Skip to content

feat(cuda-device): over-aligned element types with a checked slice view - #512

Merged
nihalpasham merged 8 commits into
NVIDIA:mainfrom
honeyspoon:up/aligned-vectors
Jul 28, 2026
Merged

nihalpasham merged 8 commits into
NVIDIA:mainfrom
honeyspoon:up/aligned-vectors

Conversation

@honeyspoon

@honeyspoon honeyspoon commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Transaction width is set by the alignment of the element type, not by how many elements a loop touches. Measured on sm_86, four safe spellings of "read four adjacent f32":

element types LDG STG
F32x4 → F32x4 (align 16) LDG.E.128 ×1 STG.E.128 ×1
same payload at align 4 LDG.E ×4 STG.E ×4
&[f32] → F32x4 LDG.E ×4 STG.E.128 ×1
&[f32] → f32 LDG.E ×4 STG.E ×1

Row three is the load-bearing one: a single kernel with scalar loads and a wide store, differing only in the types at each end.

So reaching a wide access means choosing an element type, and the obstacle is that buffers arrive flat. Copying into an aligned buffer defeats the purpose. This adds the types plus a view — check alignment and length once, then accesses through it are wide.

let quads: &[F32x4] = vector::as_vectors(input).ok_or(Unaligned)?;

Seven types covering the 64- and 128-bit widths for f32, f64, u32, u16.

Refuses rather than truncates

10 f32 viewed as F32x4 is an error, not two vectors and a dropped tail. A misaligned base is likewise refused — that is the case the check exists for: a sub-slice starting at an odd element has the right length and the wrong address.

Vector is unsafe because a wrong LANES would make the length check admit an out-of-bounds view. A test asserts the layout each unsafe impl claims, so the invariant is checked rather than trusted.

The caveat, documented rather than left to be found

Alignment is necessary but not sufficient for a wide load. With the type 16-byte aligned throughout, only how the value is consumed changes it:

never decomposed                 LDG.E.128   STG.E.128
lanes read, whole value stored   LDG.E x4    STG.E.128
lanes read, scalar stored        LDG.E x4    STG.E

Touching individual lanes lets the optimiser split the local apart and load them separately regardless of alignment; the store side has no such condition.

So these buy width on paths that move data — staging global to shared, copying, packing — and not on paths doing immediate elementwise arithmetic. The module says so up front, because "just use an aligned type" only half holds.

Pairs with #513

Aligned types are only reachable if a buffer can be one. #513 adds the length-adjusting cast that makes that possible without every producer and consumer agreeing at once. Either can land alone; together they are the usable form.

8 tests, clippy --all-targets clean.

Memory transaction width is set by the alignment of the element type, not by
how many elements a loop touches. Measured on sm_86, a 16-byte-aligned quad of
f32 compiles to one LDG.E.128 plus one STG.E.128, while the same four values at
natural alignment compile to four scalar accesses.

So reaching a wide access means choosing an element type, and the obstacle is
that buffers arrive flat. Copying into an aligned buffer defeats the purpose.
This adds the element types plus a view: check alignment and length once at the
boundary, then accesses through it are wide.

    let quads: &[F32x4] = vector::as_vectors(input).ok_or(Unaligned)?;

Seven types covering the 64- and 128-bit widths for f32, f64, u32, and u16. The
`Vector` trait is unsafe because a wrong `LANES` would make the length check
admit an out-of-bounds view; a test asserts the layout each `unsafe impl`
claims, so the invariant is checked rather than trusted.

Refuses rather than truncates: 10 f32 viewed as F32x4 is an error, not two
vectors and a dropped tail. A misaligned base is likewise refused, which is the
case the check exists for - a sub-slice starting at an odd element has the right
length and the wrong address.

One measured caveat, documented rather than left to be discovered: alignment is
necessary but not sufficient for a wide *load*. With the type 16-byte aligned
throughout, only how the value is consumed changes it:

    never decomposed                 LDG.E.128   STG.E.128
    lanes read, whole value stored   LDG.E x4    STG.E.128
    lanes read, scalar stored        LDG.E x4    STG.E

Touching individual lanes lets the optimiser split the local apart and load
them separately regardless of alignment; the store side has no such condition.
So these buy width on paths that move data - staging global to shared, copying,
packing - and not on paths doing immediate elementwise arithmetic. Saying that
up front avoids shipping advice that only half holds.

Signed-off-by: abder <[email protected]>
The misaligned-offset loop only ever saw tails whose length was not a
multiple of 4 (offsets 1..7 into a 16-element slice), so every iteration
hit the length-based `continue` and the alignment rejection in
`as_vectors` was never actually exercised. Take a 12-element window at
each misaligned offset instead: the length divides exactly, so the only
possible ground for rejection is the base address.
A literal `&[]` has a dangling base aligned only for the scalar, so it
failed the vector alignment check and returned `None`, while an aligned
empty sub-slice of a real buffer returned `Some` empty view. Make every
empty input yield `Some` empty view: nothing will be accessed, so there
is no alignment to violate. The empty case short-circuits before
`from_raw_parts`, which requires a vector-aligned base even at length
zero. Documented on `as_vectors`/`as_vectors_mut` and pinned by a test;
`is_viewable` agrees because it shares `vector_len`.
`vector_len` computed the view length from `LANES` while the actual byte
extent is governed by `size_of::<V>()`; a malformed `Vector` impl (for
example padding introduced by an over-wide `align`) would make the two
disagree and every index through the view would silently read the wrong
bytes. Assert `size_of::<V>() == LANES * size_of::<Elem>()` in an inline
`const` block, so instantiating any view path for a malformed `V` fails
the build (post-monomorphization) instead.
… element type

`validate_ptr_to_array_constant_type` restricted promoted pointer-to-array
initializers to primitive scalars and nested arrays of those, so a promoted
empty-slice constant like `Some(&[])` with a struct element type (rustc
promotes `&[]` to `&[T; 0]`) failed device codegen with "Array constant
element type is not supported". A zero-length array has no element values:
its initializer is empty and nothing can ever be read through it, so the
element-type restriction is vacuous. Accept it and let the existing
byte-image lowering emit the `[0 x i8]` global.

Exercised by the vectorization example, whose in-kernel
`vector::as_vectors::<F32x4>` path monomorphizes `Some(&[])` for a struct
vector type.
…it transactions

Add a kernel that takes a flat `&[f32]` parameter, views it as `F32x4`
quads with `cuda_device::vector::as_vectors` (and the output via
`as_vectors_mut`), and copies whole quads. The host launches it on flat
`f32` buffers, checks the round trip, and asserts the kernel body contains
a single 128-bit global vector load and store. llc's spelling of the
128-bit transaction varies by version (`v4.f32` on older llc, `v2.b64` on
llc-21/22), so either form is accepted; both are one 128-bit access. The
example is in the smoketest standard category, so the check runs in CI.
`cuda-core` does not depend on `cuda-device`, so the vector types carry no
`DeviceCopy` impl and the orphan rule stops downstream crates from adding
one; a `DeviceBuffer<F32x4>` cannot be filled from host values of these
types. Spell out the intended flow in the module docs: keep host buffers
flat and take the view inside the kernel with `as_vectors`, or reinterpret
once at the boundary with `DeviceBuffer::cast_chunks` and a host-defined
over-aligned element.
cuda-device now spells grouped scalars three ways for three jobs:
`vector` (over-aligned memory elements for wide transactions),
`CuSimd` (multi-register value groups with copy semantics), and
`f16x2`/`bf16x2` (packed 16-bit ALU pairs). Point each module's docs at
the other two so a reader landing on any spelling finds the right one
for their use case. Verified with RUSTDOCFLAGS="-D warnings".
@nihalpasham nihalpasham added enhancement New feature or request host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) labels Jul 28, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks,

Landing with maintainer commits on top:

  • the misalignment test now properly exercises the alignment rejection,
  • empty slices get uniform Some-empty-view semantics,
  • the Vector size contract is checked at compile time, and
  • the module docs cover the host-side story (flat buffers + in-kernel view, or DeviceBuffer::cast_chunks from feat(device_buffer): add cast_chunks for a length-adjusting reinterpret #513)
  • plus cross-references to CuSimd/f16x2.
  • wiring the PTX check into CI exposed a compiler gap - promoted &[] of a struct element type - fixed in mir-importer;
  • the vectorization example now proves the in-kernel as_vectors::<F32x4> path emits single 128-bit global load/store,

Validated end-to-end on an RTX 5090 (sm_120): where llc-21/22 spells the access ld/st.global.v2.b64. cuda-device and mir-importer tests plus clippy -D warnings are all clean. Closes no open issue.

Merging

@nihalpasham
nihalpasham merged commit e95835c into NVIDIA:main Jul 28, 2026
33 checks passed
@honeyspoon
honeyspoon deleted the up/aligned-vectors branch July 28, 2026 14:02
@honeyspoon

Copy link
Copy Markdown
Contributor Author

Follow-up on the SROA finding this PR's module docs record — the one that alignment is necessary but not sufficient for a wide load, because touching individual lanes lets the optimiser split the value apart.

That is confirmed and unchanged. But inventorying CCCL 13.2.27's headers turned up the route around it, which I had wrongly written off as a dead end. CUB does not try to keep the loaded value whole; it changes the layout. From cub/block/block_load.cuh on BLOCK_LOAD_VECTORIZE:

A striped arrangement of data is read efficiently from memory and then locally transposed into a blocked arrangement.

The utilization of memory transactions (coalescing) remains high regardless of items loaded per thread.

So the width survives because the read and the arithmetic use different layouts — striped for the load, where nothing decomposes the vector, then an exchange (four of CUB's six strategies go through shared memory) into the blocked arrangement the arithmetic wants. Decomposition still happens, just on registers that never came from a wide load instruction.

That makes as_vectors and a striped/blocked exchange complementary rather than competing: as_vectors is the checked way to get a genuine LDG.E.128 if the value stays whole, which is the striped-read half of that pattern. The missing piece for decomposing kernels is the exchange, not a different alignment story.

Recording it here because this PR's docs are where the necessary-but-not-sufficient constraint is written down, and a reader reasonably concludes from them that wide loads are simply unavailable to kernels that do arithmetic. They are — via a layout change, which is a separate feature.

nihalpasham added a commit to honeyspoon/cuda-oxide that referenced this pull request Jul 29, 2026
min_extent(other) only required other to divide elems_per_block, never
that elems_per_thread divides other. That admitted shape-impossible
extents on a strided operand: plan::<f16>(TXN_128, 128) gives 8
elements per thread, yet min_extent(4) returned Some(256) even though
a row of 4 f16 (8 bytes) cannot hold one thread's 16-byte access.
CUTLASS enforces exactly this divisibility (the access width divides
the contiguous extent).

Add the missing check, returning None in the module's own no-silent-
rounding idiom, and reword the doc from the contiguous-tile model (which
would admit lcm-based extents the function refuses, e.g. other=48 at
512 elems/block) to the strided model the function actually implements.

Also carry the contributor's follow-up from PR NVIDIA#512 into the Scope
note: the width is unreachable only through a direct blocked load;
CUB's BLOCK_LOAD_VECTORIZE reaches it by loading striped with wide
loads and exchanging through shared memory into the blocked layout.
That exchange primitive does not exist in cuda-oxide yet, so the note
records the gap as a missing layout change rather than an alignment
dead end.
nihalpasham added a commit that referenced this pull request Jul 29, 2026
* feat(access): derive tile shape from a target transaction width

* fix(access): require thread-access divisibility in min_extent

min_extent(other) only required other to divide elems_per_block, never
that elems_per_thread divides other. That admitted shape-impossible
extents on a strided operand: plan::<f16>(TXN_128, 128) gives 8
elements per thread, yet min_extent(4) returned Some(256) even though
a row of 4 f16 (8 bytes) cannot hold one thread's 16-byte access.
CUTLASS enforces exactly this divisibility (the access width divides
the contiguous extent).

Add the missing check, returning None in the module's own no-silent-
rounding idiom, and reword the doc from the contiguous-tile model (which
would admit lcm-based extents the function refuses, e.g. other=48 at
512 elems/block) to the strided model the function actually implements.

Also carry the contributor's follow-up from PR #512 into the Scope
note: the width is unreachable only through a direct blocked load;
CUB's BLOCK_LOAD_VECTORIZE reaches it by loading striped with wide
loads and exchanging through shared memory into the blocked layout.
That exchange primitive does not exist in cuda-oxide yet, so the note
records the gap as a missing layout change rather than an alignment
dead end.

* feat(vectorization): derive the view-kernel shape via access::plan

Give the new access module an in-repo consumer: a const assertion in
the vectorization example derives f32x4_view_copy's shape from
access::plan::<f32>(TXN_128, N) instead of restating it by hand - one
4-element quad per thread, F32x4's 16-byte alignment, and the flat
N * 4 buffer moved in exactly one block-wide pass. A shape drift now
fails at compile time. N is hoisted to module scope so the plan and
the launch share the same thread count.

---------

Co-authored-by: abder <abder@local>
Co-authored-by: nihalpasham <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants