Repository navigation
feat(disjoint): derive multi-element and grid-stride index proofs - #571
honeyspoon wants to merge 4 commits into
Conversation
`ThreadIndex` proves only that this thread's index differs from every other
thread's, which is a proof about a single element. Processing several elements
per thread is the usual way to stop wasting bandwidth, and there was no way to
say "index raw*N through raw*N+N-1, still disjoint" - so those writes went
through `get_unchecked_mut` with the bounds argument discharged by hand. That
is 24 sites in the audit, and it is why every kernel deliberately breaks the
1:1 mapping `get_mut` assumes.
Adds `ThreadIndex::scale::<N>()`, yielding a `DisjointBlock<N>`, and
`DisjointSlice::get_block_mut`, which turns that proof into a bounds-checked
`&mut [T; N]`:
let block = thread::index_1d().scale::<4>();
if let Some(row) = output.get_block_mut(block) {
*row = [o0, o1, o2, o3];
}
The proof carries because scaling tiles the space: if every `raw` is distinct,
the ranges [raw*N, raw*N+N) are pairwise disjoint and gapless. Consuming the
witness is what keeps it sound - `ThreadIndex` is deliberately not `Copy`, so
a thread cannot hold both a block proof and the original single-element proof,
or two differently scaled blocks, and end up with two live references to the
same slot. `DisjointBlock` is likewise `!Copy`.
Only scaling is offered, not a general affine `raw*S + K`. With a
caller-chosen stride the ranges do not tile unless S == N, so two such
families over one buffer could overlap while each looked disjoint on its own.
Scaling is the case where the proof is unconditional; `offset` and `stride`
are deliberately absent rather than forgotten.
Returning `&mut [T; N]` rather than `&mut [T]` is also deliberate: the length
is static, so it is the shape the codegen can fuse into one wide access when
`[T; N]` carries the matching alignment. That makes this a safe path toward
the wide accesses gap #2 is about, rather than only a safety improvement.
`N == 0` and any overflowing multiplication yield an invalid witness rather
than a wrong one, and the bounds test uses checked addition so a tile
straddling the end of the address space cannot wrap into a passing check.
Tests assert the properties the soundness argument rests on: tiles for
distinct indices never overlap across several N, tiles are gapless, overflow
and N == 0 are rejected, and the bounds test rejects wrapping. 21 tests pass,
fmt clean, no warnings.
Signed-off-by: abder <[email protected]>
The first cut only handled the contiguous case, `[tN, tN+N)`, and left the
strided families out on the grounds that a caller-chosen stride "could
overlap". That was a hunch stated as a limitation. Working the algebra out
turns it into a theorem, and the theorem covers the strided case too.
Write the element index as a mixed-radix numeral:
index = k·(G·N) + t·N + c
digit range place value
c [0, N) 1
t [0, G) N
k [0, K) G·N
Every place value is the product of the ranges of all lower digits: 1, then
1·N, then N·G. That is exactly the condition for a positional system to be
uniquely decodable, so (k, t, c) -> index is injective with inverse
c = index mod N
t = (index div N) mod G
k = index div (G·N)
Injectivity *is* the disjointness proof: an index determines the thread that
produced it, so no index belongs to two threads.
The same algebra says why the period cannot be a parameter. Choosing S < G·N
makes the t and k digit ranges overlap and injectivity fails - with N=1, G=4,
S=2, both (k=0,t=2) and (k=1,t=0) land on element 2. So `repeat` derives
P = G·N from the launch geometry and there is deliberately no
`repeat_with_stride`. A period above G·N stays injective but leaves gaps, so
the derived value is the tight choice rather than merely a safe one; both
directions are pinned by tests.
This also explains a number the gaps document lists as hardcoded: the four
stripes at `tid*4 + k*1024` under 256 threads have G·N = 256·4 = 1024, so
1024 is the derived period, not a magic constant.
API: `DisjointBlock::repeat::<K>()` yields `DisjointTiling<N, K>`, consumed by
`DisjointSlice::for_each_tile`. The callback shape is load-bearing - a
`get_tile_mut(k)` taking k at runtime could be called twice with the same k
and hand out two &mut to one tile, since the proof covers distinct threads and
distinct passes, not repeated access to one pass. Driving the loop internally
makes single-visit structural.
Tests assert the algebra rather than the API surface: injectivity checked
against the decode inverse over several (G, N, K); an ownership map proving
tiles are pairwise disjoint and gapless; the S < G·N collision as an explicit
counterexample; and the oversized-period gap. 25 tests pass, fmt clean, no
warnings.
Signed-off-by: abder <[email protected]>
I wrote that returning `&mut [T; N]` makes this "a route to wide accesses".
Measured on sm_86, that is wrong, so it is now stated the other way round.
Four safe spellings, PTX and SASS both inspected:
element types LDG STG
F32x4 -> F32x4 (align 16) LDG.E.128 STG.E.128
Quad -> Quad (align 4) LDG.E x4 STG.E x4
&[f32] -> F32x4 LDG.E x4 STG.E.128
&[f32] -> f32 LDG.E x4 STG.E
Width is decided by the *alignment of the element type*, independently on each
side - the third row is one kernel with a scalar load and a wide store, which
pins it. A static length does nothing on its own. Since `T` is the element type
of the `DisjointSlice`, a `DisjointSlice<f32>` hands back `&mut [f32; N]` at
4-byte alignment and stays scalar.
So this method is about the disjointness proof for multi-element access, and
nothing else. The doc now points at the path that does widen: an aligned
element type plus ordinary `get_mut`.
Signed-off-by: abder <[email protected]>
CI now lints test targets (NVIDIA#486), and the counterexample wrote the colliding pair as `0 * bad_period + 2 * n` against `1 * bad_period + 0 * n`, which trips clippy::erasing_op and clippy::identity_op. The literals were carrying meaning - they are the (k, t) digit pair - so suppressing the lint would have been the wrong fix. Routed through a small `at(k, t, period, n)` instead, which keeps the pair visible at each call and makes the two assertions read as the same expression under two periods. Same assertions, same numbers. Signed-off-by: abder <[email protected]>
|
All CI jobs pass on this branch. Workflows here need maintainer approval before they start, so I ran the repository's own workflow job set against this tree myself. All 16 succeed: That covers three gates my local pre-push script does not: Also re-ran my pre-push review checklist over the diff: no em-dashes, no unescaped intra-doc brackets, SPDX headers present on new files, |
|
Closing — the design is not ready, and the reason is specific rather than a general doubt. This invented a parallel vocabulary for something #477 already established in
Two vocabularies for one idea is worse than the gap. The established pattern is a view type parameterised by extents, indexed by a bounded-index proof, returning an It also carried no measured benefit: The gap is real and now filed with worked examples, including the grid-stride-mismatch trap and the partial-tail problem: #583. Happy to attempt it again against that framing if the composition question gets an answer. |
DisjointSlice::get_muttakes aThreadIndexand yields one element. A thread that owns N contiguous elements has no way to say so, so multi-element and grid-stride kernels fall back toget_unchecked_mut.This adds two derivations, each producing a proof the next step consumes:
ThreadIndex::scale::<N>() -> DisjointBlock<'kernel, N, IndexSpace>— multiplying a disjoint index by a constant keeps it disjoint.DisjointBlock::repeat::<K>() -> DisjointTiling<'kernel, N, K>— grid-stride, period derived.DisjointSlice::get_block_mut::<N>(block) -> Option<&mut [T; N]>, plusfor_each_tile::<N, K>returning the number of passes actually visited.API decisions, and the alternatives rejected
1. New proof types, not a length on
ThreadIndexChosen:
DisjointBlock<'kernel, N, IndexSpace>andDisjointTiling<'kernel, N, K>as distinct types.Alternative: add a length parameter to
ThreadIndexand keep one type.ThreadIndexmeans "this thread owns element i". Overloading it to mean "owns a run" changes what every existing consumer can assume, andget_mutwould have to reject the run case at runtime. Separate types keep each proof exactly as strong as its name, and makeget_block_mutunable to accept a bare index by construction.2.
const Nrather than a runtime lengthChosen: const generic, so
get_block_mutreturns&mut [T; N].Alternative:
scale(n: usize)returning a slice-shaped proof.The array type is the point — it is what lets the caller index without further bounds checks and what an over-aligned element type would need. A runtime length can only give
&mut [T], which re-introduces a length the optimiser must track. Cost: the tile width must be a compile-time constant, which is true of every tiled kernel I have seen but is a real restriction; a runtime variant can be added later without changing this one.3.
repeatderives the period instead of accepting a strideChosen:
period = gridDim.x * blockDim.x * N, computed insiderepeat.Alternative:
repeat(stride: usize, passes: usize).This is the decision I would most like reviewed. A passed-in stride is the classic grid-stride bug: it silently disagrees with the launch geometry and threads overlap. Deriving it means the proof cannot be constructed wrongly. The cost is that
repeatreadsgridDim/blockDim, so it is only meaningful inside a kernel — and it forecloses deliberately non-standard strides. If you want those reachable, the shape would be a separaterepeat_with_stridemarkedunsafe, not a parameter here.4. Infallible construction,
is_valid()queried laterChosen:
scale/repeatalways return a value;is_valid()reports whether the derived range is usable, andget_block_mutreturnsNonewhen it is not.Alternative: return
Option<DisjointBlock<N>>fromscale, making an invalid proof unrepresentable.The
Optionversion is more principled and I nearly went that way. I chose infallible because the interesting failure — the tile running past the slice — depends on the slice, whichscalehas never seen, so anOptionthere would only catch overflow in the index arithmetic and give false confidence about the rest. Validity is checked once, at the point that knows the length. Happy to flip this if you would rather have the stricter constructor.5.
for_each_tiletakes a closure and returns a countChosen:
f: impl FnMut(usize, &mut [T; N]), returning passes visited.Alternative: an iterator of
&mut [T; N].An iterator is the more idiomatic Rust, but each item borrows the slice mutably, so a lending iterator is required — which means either GATs plumbing or handing out raw pointers. The closure keeps the borrow trivially sound today. The returned count matters because a grid-stride loop legitimately visits fewer than
Kpasses at the tail, and silently doing fewer is exactly the bug worth surfacing.6. Overflow is a stop, never a wrap
Every offset uses
checked_*: a pass whose offset or end would wrap breaks the loop rather than folding into a passing bounds test, andget_block_mutusesstart.checked_add(N)?so a tile straddling the end of the address space cannot alias low memory. Unusual to state, but this is index arithmetic guarding anunsafeblock, so wrap-on-overflow would be a soundness hole rather than a wrong answer.What this is not
It makes no performance claim. An earlier fork PR of mine proposed 32-bit index arithmetic on the theory that it would cut bounds-check cost; the measurement did not reproduce and I closed it. This is a different change. On the codebase that motivated it,
get_block_muton aDisjointSlice<f32>yields align-4 arrays that stay scalar, so it is instruction-neutral. The value is that a multi-element write stops needingunsafe.Gates
fmt, clippy
--workspace --all-targets -D warnings, rustdoc-D warnings, tests and doctests clean onnightly-2026-04-03. +617/−1 againstmain; the single deletion is ause crate::thread::{...}line being rewritten.The period counterexample in the tests routes through an
at(k, t, period, n)helper rather than literal0 */1 *terms, because clippy'serasing_op/identity_opreject those under-D warnings.