From a77a4756943f8b23df5691feff78b01ce823f9fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Miclu=C8=9Ba-C=C3=A2mpeanu?= Date: Wed, 30 Sep 2026 03:23:36 +0300 Subject: [PATCH 1/2] BracketGallop: return the hint after two comparisons when it is the answer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A warm-started caller (an interpolation interval lookup feeding each answer back as the next hint) hits its hint most of the time, and the two comparisons `v[hint] ≤ x < v[hint + 1]` already decide the result. The hinted bracket-gallop kernels found that width-one bracket and then still ran the bounded bisection over it, two more comparisons and loads per query. Both polarities now return early on a hit; an equal neighbour fails the second test so duplicates still go through the bisection. On a 1e5-knot vector with a correlated query walk (83 % hint hits) the hinted search goes from 6.3 to 4.7 ns per query on the CPU, and 3.3 ns with `order = Base.Order.Lt(<)`, against 3.1 ns for a hand-written interval search; in a KernelAbstractions kernel on an RTX 4080 SUPER the launch goes from 4.0 to 2.7 ms against 2.2 ms. Cold and miss paths are unchanged. Adds a randomized test set over hints in and out of range, duplicates and reverse ordering, a `warm_walk` benchmark cell, and a docstring note on the hit path and the `isless` cost. Co-Authored-By: Claude Fable 5.1 --- benchmark/benchmarks.jl | 25 +++++++++++++++++++++++++ src/kernels.jl | 26 ++++++++++++++++++++++++++ src/strategies.jl | 8 ++++++++ test/core_tests.jl | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+) diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index 3df81c9..6088bff 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -65,6 +65,31 @@ end # Batched in-place benchmarks: a small grid of (v_kind, q_kind, n, m). # Auto vs hand-picked strategies, plus the queries_sorted = true fast path. # --------------------------------------------------------------------------- +# Warm-started walk: each query's hint is the previous answer, and consecutive +# queries move by a fraction of an interval (the interpolation-lookup pattern). +# BracketGallop's hit fast path is what this cell measures; LinearScan is the +# reference for a hint that is right most of the time. +SUITE["warm_walk"] = BenchmarkGroup() +let v = _make_v(:random_sorted, 100_000), rng = StableRNG(7), nq = 4096 + xs = Vector{Float64}(undef, nq) + x = v[1] + for k in 1:nq + i = clamp(searchsortedlast(v, x), 1, length(v) - 1) + x = clamp(x + (rand(rng) < 0.01 ? (rand(rng) - 0.5) * 200 : rand(rng) * 0.35) * (v[i + 1] - v[i]), v[1], v[end]) + xs[k] = x + end + function walk(strategy, v, xs) + idx = 1; s = 0 + for x in xs + idx = searchsorted_last(strategy, v, x, idx); s += idx + end + return s + end + for (name, strategy) in (("BracketGallop", BracketGallop()), ("LinearScan", LinearScan()), ("Auto", Auto())) + SUITE["warm_walk"][name] = @benchmarkable($walk($strategy, $v, $xs)) + end +end + SUITE["batched"] = BenchmarkGroup() for v_kind in (:uniform, :logspaced, :random_sorted), q_kind in (:dense, :sparse, :clustered), diff --git a/src/kernels.jl b/src/kernels.jl index 8951beb..512aa85 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -301,16 +301,42 @@ end # Kernel: BracketGallop — bracketstrictlymonotonic + bounded binary search. # =========================================================================== +# Hit fast path. A correlated caller (interpolation interval lookup, a solver +# walking through a knot vector) passes the previous answer as the hint, and +# most of the time the answer has not moved: `v[hint] ≤ x < v[hint + 1]`. Those +# two comparisons decide it, and they are the ones the bracket expansion would +# make first anyway. Without the early return the width-one bracket still went +# through the bounded bisection — two more comparisons and loads per query, +# which measured 2× on a warm-started interval search on both CPU and GPU. +# Duplicates fall through: `x == v[hint + 1]` fails the second test, so the +# bisection still returns the last equal element. @inline function _kernel_last_bracket_gallop( v::AbstractVector, x, hint::Integer, order::Base.Order.Ordering, ) + bottom, top = firstindex(v), lastindex(v) + if bottom <= hint <= top + @inbounds if !Base.Order.lt(order, x, v[hint]) && + (hint == top || Base.Order.lt(order, x, v[hint + 1])) + return convert(keytype(v), hint) + end + end lo, hi = bracketstrictlymonotonic(v, x, hint, order) return searchsortedlast(v, x, lo, hi, order) end +# `searchsortedfirst` polarity of the same fast path: the hint is the answer +# when `v[hint - 1] < x ≤ v[hint]`; an earlier duplicate of `x` fails the first +# test and falls through to the bisection. @inline function _kernel_first_bracket_gallop( v::AbstractVector, x, hint::Integer, order::Base.Order.Ordering, ) + bottom, top = firstindex(v), lastindex(v) + if bottom <= hint <= top + @inbounds if !Base.Order.lt(order, v[hint], x) && + (hint == bottom || Base.Order.lt(order, v[hint - 1], x)) + return convert(keytype(v), hint) + end + end lo, hi = bracketstrictlymonotonic_first(v, x, hint, order) return searchsortedfirst(v, x, lo, hi, order) end diff --git a/src/strategies.jl b/src/strategies.jl index 85ed8ac..5cb3040 100644 --- a/src/strategies.jl +++ b/src/strategies.jl @@ -73,6 +73,14 @@ the hint; never worse than ~2 log₂ n comparisons. Maps to `KIND_BRACKET_GALLOP`. Falls back to [`BinaryBracket`](@ref) when no hint is supplied. + +When the hint is the answer (`v[hint] ≤ x < v[hint + 1]` for `searchsorted_last`, +`v[hint - 1] < x ≤ v[hint]` for `searchsorted_first`) the result is returned after +those two comparisons, so a caller that feeds each answer back as the next hint +pays for the bracket and the bisection only when the query leaves the interval. +For float vectors that ordering cost is then dominated by `isless` (the default +`Base.Order.Forward`), which also orders NaN and signed zeros; a vector without +NaN can pass `order = Base.Order.Lt(<)` for plain comparisons. """ struct BracketGallop <: SearchStrategy end diff --git a/test/core_tests.jl b/test/core_tests.jl index cfc8086..7f2b5ad 100644 --- a/test/core_tests.jl +++ b/test/core_tests.jl @@ -294,6 +294,38 @@ end end end +@safetestset "BracketGallop hint hit fast path" begin + using FindFirstFunctions: BracketGallop, searchsorted_last, searchsorted_first + using StableRNGs + + # The hit fast path returns the hint after two comparisons when it is the + # answer. It must agree with Base for every hint (in and out of range), for + # duplicates (an equal neighbour must fall through to the bisection), at both + # ends of the vector, and under a reverse ordering. + rng = StableRNG(2026) + for trial in 1:300 + n = rand(rng, 1:40) + v = sort!(rand(rng, Bool) ? rand(rng, n) .* 10 : round.(rand(rng, n) .* 10; digits = 0)) + for x in (v[rand(rng, 1:n)], v[rand(rng, 1:n)] + eps(10.0), rand(rng) * 12 - 1, -1.0, 11.0), + h in -2:(n + 2) + @test searchsorted_last(BracketGallop(), v, x, h) == searchsortedlast(v, x) + @test searchsorted_first(BracketGallop(), v, x, h) == searchsortedfirst(v, x) + end + v_rev = reverse(v) + for x in (v[rand(rng, 1:n)], rand(rng) * 12 - 1), h in (0, 1, (n + 1) ÷ 2, n, n + 1) + @test searchsorted_last(BracketGallop(), v_rev, x, h; order = Base.Order.Reverse) == + searchsortedlast(v_rev, x, Base.Order.Reverse) + @test searchsorted_first(BracketGallop(), v_rev, x, h; order = Base.Order.Reverse) == + searchsortedfirst(v_rev, x, Base.Order.Reverse) + end + end + + # Integer hint of a different width returns the vector's index type. + v = collect(1.0:10.0) + @test searchsorted_last(BracketGallop(), v, 3.5, Int32(3)) === 3 + @test searchsorted_first(BracketGallop(), v, 3.5, Int32(4)) === 4 +end + @safetestset "SearchStrategy dispatch (single query)" begin using FindFirstFunctions: SearchStrategy, LinearScan, BracketGallop, BinaryBracket, Auto, From 4fafcf23b2b3f2d605b5b61c4a1025d56f9500db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Miclu=C8=9Ba-C=C3=A2mpeanu?= Date: Wed, 30 Sep 2026 03:41:18 +0300 Subject: [PATCH 2/2] BracketGallop: continue the gallop from the hint's comparisons on a miss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The hit check and the bracket expansion were two stages: on a miss the expansion re-read the hint's neighbours and then handed a bracket to Base's bounded bisection, which widens it by one on each side and knows nothing about either end. The hinted kernels are now one pass: the two comparisons at the hint decide a hit, and otherwise the gallop starts from the side they established, doubling its step until it brackets the answer; a bisection that knows one end of the bracket is a valid candidate finishes. `bracketstrictlymonotonic` and its `_first` twin stay defined (the QA suite checks them) but the kernels no longer call them. Same correlated walk as the previous commit, RTX 4080 SUPER: 2.7 → 1.9 ms per launch with the default ordering, now ahead of the hand-written interval search (2.2 ms); CPU 4.7 → 3.6 ns per query, 2.4 ns with `order = Base.Order.Lt(<)`. Co-Authored-By: Claude Fable 5.1 --- src/kernels.jl | 147 +++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 123 insertions(+), 24 deletions(-) diff --git a/src/kernels.jl b/src/kernels.jl index 512aa85..7c83b71 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -301,44 +301,143 @@ end # Kernel: BracketGallop — bracketstrictlymonotonic + bounded binary search. # =========================================================================== -# Hit fast path. A correlated caller (interpolation interval lookup, a solver -# walking through a knot vector) passes the previous answer as the hint, and -# most of the time the answer has not moved: `v[hint] ≤ x < v[hint + 1]`. Those -# two comparisons decide it, and they are the ones the bracket expansion would -# make first anyway. Without the early return the width-one bracket still went -# through the bounded bisection — two more comparisons and loads per query, -# which measured 2× on a warm-started interval search on both CPU and GPU. -# Duplicates fall through: `x == v[hint + 1]` fails the second test, so the -# bisection still returns the last equal element. +# The hinted kernels are one pass each: the two comparisons at the hint decide +# a hit (a correlated caller — an interpolation interval lookup feeding each +# answer back as the next hint — hits most of the time), and on a miss the +# gallop continues from what those comparisons established instead of +# starting over, doubling its step until it brackets the answer, then a +# bisection that knows one end of the bracket is a valid candidate finishes. +# The earlier two-stage form (`bracketstrictlymonotonic` + Base's bounded +# bisection) re-read the hint's neighbours on a miss and, on a hit, ran the +# bisection over a width-one bracket — two more comparisons and loads per +# query, which measured 2× on a warm-started interval search. Duplicates are +# handled by the predicates themselves: `searchsortedlast` asks for the last +# `v[i] ≤ x`, so an equal right neighbour is not a hit and the gallop moves on. + +# Largest `i` in `[lo, hi]` with `!lt(o, x, v[i])`, given that `lo` satisfies it. +@inline function _bisect_last_from(v::AbstractVector, x, lo, hi, o::Base.Order.Ordering) + @inbounds while lo < hi + m = lo + ((hi - lo + 1) >> 1) # upper midpoint, overflow-safe + if Base.Order.lt(o, x, v[m]) + hi = m - 1 + else + lo = m + end + end + return lo +end + +# Smallest `i` in `[lo, hi]` with `!lt(o, v[i], x)`, given that `hi` satisfies it. +@inline function _bisect_first_to(v::AbstractVector, x, lo, hi, o::Base.Order.Ordering) + @inbounds while lo < hi + m = lo + ((hi - lo) >> 1) # lower midpoint, overflow-safe + if Base.Order.lt(o, v[m], x) + lo = m + 1 + else + hi = m + end + end + return hi +end + @inline function _kernel_last_bracket_gallop( v::AbstractVector, x, hint::Integer, order::Base.Order.Ordering, ) bottom, top = firstindex(v), lastindex(v) - if bottom <= hint <= top - @inbounds if !Base.Order.lt(order, x, v[hint]) && - (hint == top || Base.Order.lt(order, x, v[hint + 1])) - return convert(keytype(v), hint) + (bottom <= hint <= top) || return searchsortedlast(v, x, order) + g = convert(keytype(v), hint) + @inbounds if !Base.Order.lt(order, x, v[g]) + # v[g] ≤ x: the answer is at or after g. + g == top && return g + Base.Order.lt(order, x, v[g + 1]) && return g # hit + lo = g + 1 # v[lo] ≤ x + hi = top + u = one(lo) + while true + nxt = lo + u + nxt >= top && break # v[top] undecided; the bisection settles it + if Base.Order.lt(order, x, v[nxt]) + hi = nxt - 1 + break + end + lo = nxt + u += u end + return _bisect_last_from(v, x, lo, hi, order) + else + # x < v[g]: the answer is before g. + g == bottom && return bottom - one(g) + hi = g - 1 # x < v[hi + 1] + u = one(hi) + local lo + while true + prv = hi - u + if prv <= bottom + Base.Order.lt(order, x, v[bottom]) && return bottom - one(g) + lo = bottom + break + end + if Base.Order.lt(order, x, v[prv]) + hi = prv - 1 + u += u + else + lo = prv # v[lo] ≤ x + break + end + end + return _bisect_last_from(v, x, lo, hi, order) end - lo, hi = bracketstrictlymonotonic(v, x, hint, order) - return searchsortedlast(v, x, lo, hi, order) end -# `searchsortedfirst` polarity of the same fast path: the hint is the answer -# when `v[hint - 1] < x ≤ v[hint]`; an earlier duplicate of `x` fails the first -# test and falls through to the bisection. +# `searchsortedfirst` polarity: the hint is a hit when `v[hint - 1] < x ≤ v[hint]`; +# an earlier duplicate of `x` fails that test and the gallop moves left. @inline function _kernel_first_bracket_gallop( v::AbstractVector, x, hint::Integer, order::Base.Order.Ordering, ) bottom, top = firstindex(v), lastindex(v) - if bottom <= hint <= top - @inbounds if !Base.Order.lt(order, v[hint], x) && - (hint == bottom || Base.Order.lt(order, v[hint - 1], x)) - return convert(keytype(v), hint) + (bottom <= hint <= top) || return searchsortedfirst(v, x, order) + g = convert(keytype(v), hint) + @inbounds if !Base.Order.lt(order, v[g], x) + # x ≤ v[g]: the answer is at or before g. + g == bottom && return g + Base.Order.lt(order, v[g - 1], x) && return g # hit + hi = g - 1 # x ≤ v[hi] + lo = bottom + u = one(hi) + while true + prv = hi - u + prv <= bottom && break # v[bottom] undecided; the bisection settles it + if Base.Order.lt(order, v[prv], x) + lo = prv + 1 + break + end + hi = prv + u += u + end + return _bisect_first_to(v, x, lo, hi, order) + else + # v[g] < x: the answer is after g. + g == top && return top + one(g) + lo = g + 1 # v[lo - 1] < x + u = one(lo) + local hi + while true + nxt = lo + u + if nxt >= top + Base.Order.lt(order, v[top], x) && return top + one(g) + hi = top + break + end + if Base.Order.lt(order, v[nxt], x) + lo = nxt + 1 + u += u + else + hi = nxt # x ≤ v[hi] + break + end end + return _bisect_first_to(v, x, lo, hi, order) end - lo, hi = bracketstrictlymonotonic_first(v, x, hint, order) - return searchsortedfirst(v, x, lo, hi, order) end # ===========================================================================