Compare commits

...
Author SHA1 Message Date
grenadeandClaude Opus 5.5 7553369e47 feat(neuron): capture the native decode step as CUDA graphs (#427)
CI / Config consistency (push) Successful in 11s
CI / Classify changes (push) Successful in 17s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 20s
CI / Clippy (push) Successful in 2m44s
CI / Test (push) Successful in 6m55s
CI / CUDA type-check (push) Successful in 19m0s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
Each of the step's two segments (embedding to the PLE layer; the PLE
layer to the logits) is captured once on candle's stream after a warm
eager step has sized every buffer it touches, then replayed. Between
replays the host writes the step inputs, lets the expert tier adapt,
and adds PLE's contribution; after a replay it marks the replayed usage
copies for the next adapt. Sequence state is cleared in place, so a
graph's addresses survive a new request.

Two things capture would not take, changed:
- The expert usage copy is a kernel writing mapped pinned memory (as
  Strata's host doorbell is), not a memcpy.
- No event guards the host's read of it: an event recorded inside a
  captured step cannot be waited on from the host. Every caller adapts
  only after reading the previous step's logits, which waits for the
  whole step, so the event was redundant.

On one RTX 5090 (10 GB tier, 128 tokens of a real prompt, engine-only
with PLE eager in between): eager 30-37 ms/token, graphs 22.9 ms/token
(43.6 tok/s), against 25.7 tok/s on the candle path. Graph and eager
logits are identical at every step (KL 0, top-1 128/128).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 14:20:51 +02:00
grenadeandClaude Opus 5.5 3612a00f73 feat(neuron): native decode step for qwen4_exp, end to end (#427)
CI / Config consistency (push) Successful in 12s
CI / Classify changes (push) Successful in 20s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 18s
CI / Clippy (push) Successful in 3m6s
CI / Test (push) Successful in 7m26s
CI / Build cortex SRPM (push) Canceled after 0s
CI / Build neuron SRPM (push) Canceled after 0s
CI / Publish cortex to COPR (push) Canceled after 0s
CI / Publish neuron to COPR (push) Canceled after 0s
CI / Bump version in source (push) Canceled after 0s
CI / CUDA type-check (push) Canceled after 17m11s
`engine::decoder::NativeDecoder` runs every layer for one token over
buffers allocated once: the Q8_0 embedding (Strata's iq_embed_rows)
into the four streams, each layer's mixer (gated delta-net or dense
attention) and MoE halves ping-ponging two residual buffers, the final
mixer and a BF16 LM head (the GGUF's Q6_K, dequantised on the host:
`q6_k_to_f32`, ggml's layout, unit-tested). The token and position come
from a device buffer filled from pinned host memory at the start of the
step, so nothing takes a per-token argument.

A step is two segments around the PLE layer; between them the caller
adds PLE's contribution to the residual. PLE's n-gram gather stays on
the host for now: `Qwen4ExpForCausalLM::ple_contribution` runs the
model's own PLE block on the engine's residual.

`neuron-engine-step-probe` decodes through the engine and candle's
model side by side (shared experts, same GGUF dense weights) and can
dump each step's logits. On the first 32 tokens of a real prompt:
engine vs candle mean KL 0.0031, top-1 32/32. Against Strata on the
same prefixes, the engine is closer than candle at every one:

  prefix  KL(Strata||engine)  KL(Strata||candle)
       8              0.0020              0.0258
      16              0.0200              0.0374
      24              0.0001              0.0002
      32              0.0019              0.0086

(Random token ids give KL ~0.28 and 9/16 top-1 between engine and
candle: high-entropy distributions over gibberish, where MoE routing
near-ties, which the engine breaks Strata's way, move the output.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 14:03:14 +02:00
grenadeandClaude Opus 5.5 67dc306c04 feat(neuron): native full-attention mixer for the decode engine (#427)
CI / Config consistency (push) Successful in 11s
CI / Classify changes (push) Successful in 18s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 15s
CI / Clippy (push) Successful in 2m48s
CI / Test (push) Successful in 7m5s
CI / Build cortex SRPM (push) Canceled after 0s
CI / Build neuron SRPM (push) Canceled after 0s
CI / Publish cortex to COPR (push) Canceled after 0s
CI / Publish neuron to COPR (push) Canceled after 0s
CI / Bump version in source (push) Canceled after 0s
CI / CUDA type-check (push) Canceled after 20m46s
The mixer half of a qwen4_exp full-attention layer for one token,
within QSA's budget, where selection keeps every position and dense
attention is exact: the hyper-connection read; Q8_0 q (query and gate
interleaved per head), k and v; Strata's fused RMS norm + rotary with
the position read from device memory; K/V appended in place to a cache
allocated once; a decode attention kernel (one block per query head,
warps striding the positions with an online softmax, the length read
from the device) that applies the per-head sigmoid output gate; the
Q8_0 output projection; the hyper-connection write. The indexer's raw
key is projected and cached each step for selection to use later.

The KV append and decode attention are neuron's own kernels in the
engine shim; native_rope is vendored from Strata.

`neuron-engine-layer-probe ... attn` against candle's attention (same
GGUF Q8_0 projections, BF16): layers 3 and 47 over 24 steps of growing
context agree to 1.2-2.3%. With the engine's positions shifted by one
as a deliberate fault: 79% at the first step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 13:42:01 +02:00
grenadeandClaude Opus 5.5 390b9ae21e feat(neuron): native MoE half for the decode engine (#427)
CI / Config consistency (push) Successful in 12s
CI / Classify changes (push) Successful in 19s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 18s
CI / Clippy (push) Successful in 2m48s
CI / Test (push) Successful in 7m2s
CI / Build cortex SRPM (push) Canceled after 0s
CI / Build neuron SRPM (push) Canceled after 0s
CI / Publish cortex to COPR (push) Canceled after 0s
CI / Publish neuron to COPR (push) Canceled after 0s
CI / Bump version in source (push) Canceled after 0s
CI / CUDA type-check (push) Canceled after 8m17s
A decoder layer's MoE half for one token, over buffers allocated once:
the FFN hyper-connection read, the BF16 router and Strata's fused
top-10, the routed experts through the device-routed grouped kernel,
the shared expert (Q8_0 mmvq for its three projections, SwiGLU, and its
sigmoid scalar gate), Strata's weighted combine, and the write back.

The device-routed expert launch is now a raw-pointer core,
`GgufExpertSource::launch_routed`, over a decode workspace sized once
for the largest batch, so a captured step's addresses never move; the
candle path wraps it. `record_usage` takes a device address and
`usage_replayed` marks a replayed step's usage copies for `adapt`.

On beast, layers 0, 3 and 46 over six steps against candle's MoE block
(same GGUF experts and Q8_0 projections): the contribution agrees to
1.3-3.1% wherever the two routers pick the same ten experts. The two
steps that do not (19% and 17%) are near-ties at the tenth expert,
logits 1.78583 / 1.78532 and 0.42271 / 0.42161, which the engine's f32
activations and candle's BF16 ones resolve differently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 13:33:23 +02:00
grenadeandClaude Opus 5.5 c110505491 feat(neuron): native gated delta-net mixer for the decode engine (#427)
CI / Config consistency (push) Successful in 14s
CI / Classify changes (push) Successful in 19s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 17s
CI / Clippy (push) Successful in 2m47s
CI / Test (push) Successful in 6m56s
CI / Build cortex SRPM (push) Canceled after 0s
CI / Build neuron SRPM (push) Canceled after 0s
CI / Publish cortex to COPR (push) Canceled after 0s
CI / Publish neuron to COPR (push) Canceled after 0s
CI / Bump version in source (push) Canceled after 0s
CI / CUDA type-check (push) Canceled after 9m6s
The mixer half of a qwen4_exp linear-attention layer as ten kernel
launches over buffers allocated once: the hyper-connection read, the
Q8_0 qkv and z projections (mmvq), the fused conv + SiLU + L2 norm, the
fused alpha/beta gates, the fused delta-rule step and gated norm, the
Q8_0 output projection, and the hyper-connection write. Nothing
allocates or waits, so it can be captured.

The engine reads the GGUF in its own layout and head order, and holds
the state in Strata's layout. `engine::weights` loads tensors to the
device raw, as f32, or as BF16 rounded to nearest even (Q8_0 and f16
dequantised on the host, unit-tested on the CPU), converting what
Strata's pack converts.

`neuron-engine-layer-probe` checks it against candle's own layer on the
real checkpoint and GGUF, with candle given the same Q8_0 projections.
On beast, layers 0, 1 and 46 over 8 decode steps with carried state:
the layer's contribution agrees to 1-3% (candle runs in BF16), flat
across steps; with the engine's state reset each step as a deliberate
fault, the error is 58-83% from the second step.

The PDL hooks Strata defines beside its verify kernels are stubbed off
in the engine shim, which is the ordinary-launch path the decode
kernels take outside a verify window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 13:23:57 +02:00
grenadeandClaude Opus 5.5 9edb21ed51 feat(neuron): vendor Strata's decode kernels for the native engine (#427)
CI / Config consistency (push) Successful in 15s
CI / Classify changes (push) Successful in 20s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 21s
CI / Clippy (push) Successful in 3m7s
CI / Test (push) Successful in 8m0s
CI / CUDA type-check (push) Successful in 19m32s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
The kernels a qwen4_exp decode step needs besides the experts: the
fused gated delta-net conv/L2, alpha-beta and step-plus-norm; the
hyper-connection read and write; the fused top-10 router; the MoE
combine; activation quantisation; and the BF16 projections. All from
the same Strata revision as the expert kernels, unmodified, with the
headers they include.

engine_shim.cu gives them a C ABI that catches C++ exceptions (several
throw on bad geometry) and returns a status. build.rs now compiles the
vendored translation units in parallel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 13:02:42 +02:00
grenadeandClaude Opus 5.5 0ecf24ce6e feat(neuron): route decode MoE on the device for native experts (#425)
CI / Config consistency (push) Successful in 11s
CI / Classify changes (push) Successful in 17s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 16s
CI / Clippy (push) Successful in 2m47s
CI / Test (push) Successful in 6m35s
CI / CUDA type-check (push) Successful in 19m13s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
With NEURON_EXPERT_DEVICE_ROUTING=1, decode-sized MoE layers no longer
make a host round-trip:

- Every expert is copied at load into page-locked host memory the
  device can address (55.4 GiB for UD-IQ4_XS), and a device table holds
  each expert's address: its VRAM tier slot, or its host copy. Evicted
  slots repoint their entry, stream-ordered, before they are freed.
- The router's top-k stays on the device. A neuron kernel builds the
  grouped expert kernel's arrays from it and the table, in the host
  builder's order, and lists the misses; a gather kernel copies those
  into the arena so the expert kernel reads VRAM only.
- The tier learns between steps: each layer's ids are copied to pinned
  memory asynchronously and read the next time the layer runs, which
  admits up to NEURON_EXPERT_ADMIT_PER_LAYER (default 1) misses.
- Prompt chunks keep the host-routed path, but take their misses and
  the profile warm-up straight from the pinned store, with no staging
  pass and no file reads.

On one RTX 5090 (13 GB tier, Q8_0 dense, 2048-token chunks, event
tracking off): greedy output identical to host routing on every bench
case; no stream synchronize inside decode (Nsight); decode 25.7 / 21.3
/ 18.3 tok/s at 37 / 4k / 16k, level with the best host-routed run;
prefill 4k 366 -> 636 and 16k 255 -> 383 tok/s, first token at 4k
10.7 -> 6.5 s. Decode stays bound by ~8.7k kernel launches per token,
which is what capturing the step as a CUDA graph addresses next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 11:24:11 +02:00
grenadeandClaude Opus 5.5 3af00ae761 perf(neuron): optional switch to turn off cudarc event tracking (#422)
CI / Config consistency (push) Successful in 14s
CI / Classify changes (push) Successful in 19s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 18s
CI / Clippy (push) Successful in 2m51s
CI / Test (push) Successful in 6m31s
CI / CUDA type-check (push) Successful in 19m17s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
cudarc gives every CUDA allocation a read and a write event and waits
on them when the buffer is freed. That only matters when buffers cross
streams; a device worker's work runs on candle's single stream. Nsight
on a qwen4_exp decode token counted ~20k event creates, ~20k waits,
~14k records and ~20k destroys.

NEURON_CUDA_EVENT_TRACKING=0 disables it for the worker's context
before anything is allocated. On one RTX 5090 serving Flash-Next with
native experts (warm page cache): decode 23.1 -> 25.6 tok/s short,
19.8 -> 21.4 at 4k, 17.2 -> 18.3 at 16k. Off by default until it has
been measured on the other models neuron serves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 10:02:01 +02:00
grenadeandClaude Opus 5.5 6bd73a6ae5 feat(neuron): serve qwen4_exp dense projections from the GGUF's Q8_0 blocks (#422)
CI / Config consistency (push) Successful in 12s
CI / Classify changes (push) Successful in 17s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 17s
CI / Clippy (push) Successful in 2m48s
CI / Test (push) Successful in 6m30s
CI / CUDA type-check (push) Successful in 21m9s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
A `Proj` is either a candle `Linear` or a projection held outside
candle, and a `LinearSource` is asked for each by checkpoint name; what
it declines loads from the checkpoint as before. The GDN and MLP
loaders in qwen3_5 and qwen4_exp's attention, hyper-connections and
LM head take one.

`GgufDenseSource` (`NEURON_STRATA_DENSE=1`, with native experts) serves
them from the same GGUF: Strata's `iq_mmvq` for up to 8 rows, and
dequantize + matmul for prompt chunks. Tensors map by name; the
linear-attention value heads are stored tiled by key head (GGUF head
g*16+k is checkpoint head 3k+g), which load undoes by moving whole
quantized rows or per-row head spans, so nothing is requantized.
Types the vendored mmvq lacks (the Q6_K head) stay dense.

On one RTX 5090 with UD-IQ4_XS: live VRAM 12.0 -> 8.9 GB at equal
speed (4k decode 15.6 -> 16.6, prefill 344 -> 353 tok/s). Against
BF16 dense the next-token KL is 0.008, near the 0.005 between two
Strata runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 09:22:43 +02:00
grenadeandClaude Opus 5.5 22db152022 perf(neuron): bound QSA attention and isolate the expert tier's memory (#422)
CI / Config consistency (push) Successful in 13s
CI / Classify changes (push) Successful in 19s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 17s
CI / Clippy (push) Successful in 4m24s
CI / Test (push) Successful in 8m6s
CI / CUDA type-check (push) Successful in 20m42s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
Three changes, measured on one RTX 5090 serving Qwen3.8-Flash-Next with
UD-IQ4_XS experts and an 8 GB tier:

- Additive-mask attention (QSA once its budget binds) no longer repeats
  K/V per query head and processes queries in tiles of at most 2^26
  score elements, with the mask add and softmax in f32. Its memory is
  now bounded at any chunk size, so prompts can be read in chunks larger
  than 512. 16k decode 11.6 -> 13.9 tok/s.
- The VRAM tier's experts come from their own CUDA memory pool. Mixed
  with the forward's transients in the default pool they pinned its
  blocks: 29 GB reserved against a 21 GB live peak. Device use at the
  same settings falls from 29.7 to 24.6 GB.
- NEURON_VRAM_TRACE logs the default pool's live, peak and reserved
  bytes after each forward.

With NEURON_PREFILL_CHUNK_TOKENS=2048, 4k prefill goes from 145 to 345
tok/s and 16k from 127 to 259; 8192 reaches 461 tok/s at 4k but runs
out of memory on a 16k prompt's second chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 08:44:03 +02:00
grenadeandClaude Opus 5.5 ee8322dba8 perf(neuron): stage native experts through pinned memory (#422)
CI / Config consistency (push) Successful in 13s
CI / Classify changes (push) Successful in 17s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 20s
CI / Clippy (push) Successful in 2m48s
CI / Test (push) Successful in 6m56s
CI / CUDA type-check (push) Successful in 19m5s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
Expert blobs now reach the device through a reusable pinned buffer and
queued copies, rather than an unpinned transfer per expert.
`NEURON_EXPERT_PROFILE` fills the VRAM tier from a ranked expert profile
at load, so the first requests do not pay for its warm-up.
`NEURON_EXPERT_TIMING` reports where each layer's expert time goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-23 19:49:51 +02:00
grenadeandClaude Opus 5.5 e06b901722 feat(neuron): run routed experts on Strata's grouped kernels (#422)
CI / Config consistency (push) Successful in 18s
CI / Classify changes (push) Successful in 20s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 18s
CI / Clippy (push) Successful in 2m46s
CI / Test (push) Successful in 6m57s
CI / CUDA type-check (push) Successful in 19m11s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
With the `strata-kernels` feature, host-resident experts and
`NEURON_STRATA_EXPERT_GGUF=<first shard>`, each MoE layer groups its
routed tokens by expert and runs them in one `native_expert_grouped`
launch, reading the GGUF's own blocks. The checkpoint's expert tensors
are not loaded. Routing, the shared expert and everything else in the
layer stay in neuron.

Experts come from the byte-budgeted VRAM tier. Decode admits misses.
Prompt chunks use what is held and copy the rest into a reusable arena.

Unset, execution is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-23 18:18:10 +02:00
grenadeandClaude Opus 5.5 e956d2f0e6 feat(neuron): vendor Strata's grouped expert kernels (#422)
CI / Config consistency (push) Successful in 15s
CI / Classify changes (push) Successful in 18s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 17s
CI / Clippy (push) Successful in 2m50s
CI / Test (push) Successful in 6m56s
CI / CUDA type-check (push) Successful in 18m56s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
Adds the `strata-kernels` feature, which compiles Strata's i-quant and
grouped expert kernels into neuron unmodified, with their MIT and ggml
notices, behind a small C shim. Nothing calls them from the serving
path yet.

`neuron-strata-expert-probe` runs real GGUF experts through the kernels
and recomputes the SwiGLU on the CPU from independently dequantised
weights. On UD-IQ4_XS across the IQ3_S/IQ4_NL, IQ4_XS/Q8_0 and
IQ3_S/Q8_0 format pairs, relative error is 0.96-1.05%, which is the
expected cost of the kernels' 8-bit activations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-23 17:32:55 +02:00
grenadeandClaude Opus 5.5 0739ee5e66 feat(neuron): a byte-budgeted VRAM tier for host-resident experts (#318)
CI / Config consistency (push) Successful in 13s
CI / Classify changes (push) Successful in 19s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 19s
CI / Clippy (push) Successful in 2m46s
CI / Test (push) Successful in 6m34s
CI / CUDA type-check (push) Successful in 19m48s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
`NEURON_EXPERT_CACHE_MB=N` serves a host-resident model's routed
experts through one LRU shared by every MoE block. Decode-sized forwards
admit what they miss. Prompt chunks may use what is held but neither
admit nor reorder it: a chunk touches more experts than the tier holds,
once each, and letting that scan in evicts the set decode returns to.

The KV budget now excludes the tier's reservation, because it is read
at load before the tier has filled. Prompt chunks trim the allocator
pool, which otherwise keeps gigabytes of freed transient expert copies.

Unset, execution is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-23 16:50:46 +02:00
grenadeandClaude Opus 5.5 812746b3c7 style(neuron): use a line comment rustfmt versions format alike
CI / Config consistency (push) Successful in 13s
CI / Classify changes (push) Successful in 19s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 15s
CI / Clippy (push) Successful in 2m50s
CI / Test (push) Successful in 7m2s
CI / CUDA type-check (push) Successful in 19m21s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
The block comment's continuation line is indented differently by the
rustfmt in CI and the current stable one, so one of them always failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-23 15:40:58 +02:00
grenadeandClaude Opus 5.5 42694ad3aa feat(neuron): stream host-resident experts to the GPU for prompt chunks (#318)
CI / Config consistency (push) Successful in 14s
CI / Classify changes (push) Successful in 25s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Failing after 23s
CI / Clippy (push) Successful in 4m44s
CI / Test (push) Successful in 9m18s
CI / CUDA type-check (push) Successful in 21m35s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
A prompt chunk routes many tokens to each active expert, so computing
them row by row on the CPU is the wrong side of the trade. On
qwen4_exp at q4k, routed experts were 98.7% of the layer time of a
512-token chunk.

`NEURON_EXPERT_STREAM_MIN_ROWS=N` runs a forward of at least N rows on
the GPU from transient copies of its active experts. Unset, execution
stays on the host and nothing changes. A decode step stays below any
sensible threshold, because one token per expert does not repay the
copy.

Measured on one RTX 5090 with N=64: a 4,053-token prompt went from
18.6 to 137.3 tok/s prefill, and first token from 217 s to 29.6 s.

GPU and CPU quantised kernels round differently, so greedy text can
diverge from the host path. Keep this opt-in until the next-token
distributions have been compared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-23 14:47:58 +02:00
grenadeandClaude Opus 5.5 45c8f3a91f chore(infra): Follow the DC to office host moves
build-prerelease / Resolve version stamps + change detection (push) Successful in 21s
build-prerelease / Lint (fmt + clippy) (push) Successful in 5m23s
build-prerelease / Test (push) Successful in 18m17s
build-prerelease / Build cortex binary (push) Successful in 4m49s
build-prerelease / Build helexa-bench binary (push) Successful in 3m36s
build-prerelease / Build helexa-upstream binary (push) Successful in 2m15s
build-prerelease / Build helexa-angels binary (push) Successful in 3m28s
build-prerelease / Build helexa-router binary (push) Successful in 1m40s
build-prerelease / Build helexa-tools binary (push) Successful in 1m46s
build-prerelease / Build neuron-blackwell (push) Successful in 16m53s
build-prerelease / Build neuron-ampere (push) Successful in 24m0s
build-prerelease / Build neuron-ada (push) Successful in 3m15s
build-prerelease / Package cortex RPM (push) Successful in 58s
build-prerelease / Package helexa-upstream RPM (push) Successful in 23s
build-prerelease / Package helexa-angels RPM (push) Successful in 28s
build-prerelease / Package helexa-router RPM (push) Successful in 23s
build-prerelease / Package helexa-tools RPM (push) Successful in 26s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m32s
build-prerelease / Package helexa-neuron-ampere RPM (push) Successful in 4m23s
build-prerelease / Package helexa-neuron-blackwell RPM (push) Successful in 4m36s
build-prerelease / Package helexa-bench RPM (push) Successful in 25s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 45s
magrathea, caveman, nikola and frootmig moved from kosherinata (DC) to
hanzalova (office) on 2026-11-01 and were renamed accordingly:

  magrathea.hanzalova.internal  10.6.0.194  (postgres primary)
  caveman.hanzalova.internal    10.6.0.186  (minio, gitea)
  nikola.hanzalova.internal     10.6.0.173
  frootmig.hanzalova.internal   10.6.0.131

The old *.kosherinata.internal names remain as transitional DNS aliases
and will be removed once deploys use the new names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVkZAgsEiJaTpxRZ42Q
2026-11-02 11:22:40 +02:00
grenadeandClaude Opus 5.5 e4c476a180 Merge branch 'feat/397-replicas': music replicas and scheduled dark windows (#397)
build-prerelease / Resolve version stamps + change detection (push) Successful in 18s
build-prerelease / Build helexa-angels binary (push) Skipped
build-prerelease / Build helexa-tools binary (push) Skipped
build-prerelease / Package helexa-angels RPM (push) Skipped
build-prerelease / Package helexa-tools RPM (push) Skipped
build-prerelease / Build helexa-bench binary (push) Successful in 1m54s
build-prerelease / Build cortex binary (push) Successful in 2m39s
build-prerelease / Build helexa-upstream binary (push) Successful in 2m42s
build-prerelease / Build neuron-ada (push) Successful in 2m53s
build-prerelease / Package cortex RPM (push) Successful in 28s
build-prerelease / Package helexa-upstream RPM (push) Successful in 24s
build-prerelease / Package helexa-bench RPM (push) Successful in 57s
build-prerelease / Lint (fmt + clippy) (push) Successful in 4m1s
build-prerelease / Build helexa-router binary (push) Successful in 2m16s
build-prerelease / Package helexa-router RPM (push) Successful in 18s
build-prerelease / Test (push) Successful in 15m12s
build-prerelease / Build neuron-blackwell (push) Successful in 15m45s
build-prerelease / Build neuron-ampere (push) Successful in 20m9s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m15s
build-prerelease / Package helexa-neuron-ampere RPM (push) Successful in 3m55s
build-prerelease / Package helexa-neuron-blackwell RPM (push) Successful in 4m13s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 31s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-21 18:53:40 +03:00
grenadeandClaude Opus 5.5 b00a25e2f5 feat: one model, many cards — music replicas and scheduled dark windows (#397)
CI / Config consistency (push) Successful in 13s
CI / Classify changes (push) Successful in 19s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 14s
CI / Clippy (push) Successful in 2m46s
CI / Test (push) Successful in 6m30s
CI / CUDA type-check (push) Successful in 19m22s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
A mining rig's cards sit on PCIe x1 risers, where tensor parallelism
floods the bus, so a rig serves one independent copy of a model per
card. Solar-powered rigs also leave the mesh every evening.

neuron:
- `[harness.candle.audio] replicas = "per-device"` (or a device list, or
  `replicas` in a model's load spec) loads a copy of each music model on
  each card behind one model id. One admission controller per model has
  a slot per copy; an admitted render takes an idle copy from a
  round-robin ReplicaPool. A copy whose device fails is retired; a card
  that fails to load leaves the others serving.
- /health reports per-copy load and /models the copy count; the model's
  max_in_flight is the number of copies.
- `[availability] online = ["06:30-18:45"]` (UTC) announces the next dark
  window on /health, with a drain time `drain_secs` (default 900) ahead.

cortex:
- Hosts past their drain time take no new work or cold-loads.
- Silence inside an announced window marks the host unhealthy at once and
  is logged once on leaving and once on return, not warned every poll;
  /health reports nodes.scheduled_dark. Unannounced outages are unchanged.
- Least-busy routing weighs load as a share of the model's capacity, so
  an 8-copy rig is not ranked like a single card.
- `[audio_jobs] max_concurrent = 0`, now the default, sizes the render
  gate from the fleet's advertised music capacity (minimum 1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-21 18:17:27 +03:00
grenadeandClaude Opus 5.5 b22474c0a5 Merge branch 'feat/385-acestep-memory': ACE-Step memory layouts, VAE speed-up, planner parity
build-prerelease / Resolve version stamps + change detection (push) Successful in 18s
build-prerelease / Build cortex binary (push) Skipped
build-prerelease / Build helexa-bench binary (push) Skipped
build-prerelease / Build helexa-upstream binary (push) Skipped
build-prerelease / Build helexa-angels binary (push) Skipped
build-prerelease / Build helexa-router binary (push) Skipped
build-prerelease / Build helexa-tools binary (push) Skipped
build-prerelease / Package cortex RPM (push) Skipped
build-prerelease / Package helexa-bench RPM (push) Skipped
build-prerelease / Package helexa-upstream RPM (push) Skipped
build-prerelease / Package helexa-angels RPM (push) Skipped
build-prerelease / Package helexa-router RPM (push) Skipped
build-prerelease / Package helexa-tools RPM (push) Skipped
build-prerelease / Build neuron-ada (push) Successful in 2m49s
build-prerelease / Lint (fmt + clippy) (push) Successful in 3m10s
build-prerelease / Test (push) Successful in 11m24s
build-prerelease / Build neuron-blackwell (push) Successful in 16m21s
build-prerelease / Build neuron-ampere (push) Successful in 20m22s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m12s
build-prerelease / Package helexa-neuron-ampere RPM (push) Successful in 3m52s
build-prerelease / Package helexa-neuron-blackwell RPM (push) Successful in 4m13s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 32s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 19:19:00 +03:00
130 changed files with 28205 additions and 201 deletions
+9 -9
View File
@@ -252,7 +252,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -278,7 +278,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -302,7 +302,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -339,7 +339,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -379,7 +379,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -419,7 +419,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -459,7 +459,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -495,7 +495,7 @@ jobs:
env:
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
@@ -564,7 +564,7 @@ jobs:
runs-on: ${{ matrix.runner }}
env:
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
+1 -1
View File
@@ -25,7 +25,7 @@ env:
CARGO_INCREMENTAL: "0"
RUSTC_WRAPPER: sccache
SCCACHE_BUCKET: sccache
SCCACHE_ENDPOINT: http://caveman.kosherinata.internal:9000
SCCACHE_ENDPOINT: http://caveman.hanzalova.internal:9000
SCCACHE_REGION: auto
SCCACHE_S3_USE_SSL: "false"
AWS_ACCESS_KEY_ID: ${{ secrets.SCCACHE_S3_ACCESS_KEY }}
+35
View File
@@ -1367,5 +1367,40 @@ than upstream's own bf16 (0.32). A 180 s vocal song with the 0.6B
planner takes 44 s on a 3060 (q8, 7.1 GB peak). The 0.6B planner is a
separate repo, so name it by id: `planner = "ACE-Step/acestep-5Hz-lm-0.6B"`.
**Rigs: replicas and power schedules (#397).** A mining rig's cards sit
on PCIe x1 risers, where tensor parallelism floods the bus, so a rig
serves one independent copy of a music model per card.
`[harness.candle.audio] replicas = "per-device"` (or a device list, or a
model's own `replicas` in its load spec) loads a copy on each card behind
one model id; cortex keeps seeing one model per host. Design choices:
- **Neuron-internal dispatch, one admission controller per model** with a
slot per copy, then an idle copy from a round-robin `ReplicaPool`
(`harness/replica.rs`). Queue, fair share and the anonymous ceiling see
the whole capacity, and `/health` sums naturally: `max_in_flight` is the
copy count, with a per-copy `replicas` breakdown; `/models` reports
`replicas`. A copy whose device worker is poisoned is retired and never
handed out again; otherwise it would fail requests fastest and attract
them. One card failing to load leaves the others serving.
- **cortex weighs load as a share of capacity**, `(in_flight + queue) /
max_in_flight`, so an 8-copy rig with two renders running counts as
less busy than a single card with one.
- **The audio job gate follows the fleet**: `[audio_jobs] max_concurrent
= 0` (now the default) sums the in-flight capacity of loaded music
models on hosts taking work, minimum 1. A fixed number would leave most
of an 18-card rig idle.
Solar hosts go dark daily. `[availability] online = ["06:30-18:45"]`
(UTC) makes `/health` announce `next_dark {drain_at, starts_at,
ends_at}`. The host sets `drain_at` (`drain_secs`, default 900) because it
knows how long its jobs run. cortex stops routing and cold-loading there
from `drain_at` (`NodeState::takes_work`), marks it unhealthy at once
when it goes silent inside the window, logs the departure and return once
each at `info` instead of warning every poll, and reports
`nodes.scheduled_dark` on its `/health` (gauge
`cortex_node_scheduled_dark`). An unannounced outage is still debounced
and warned about as before. Component placement across cards (HeartMuLa's
LM on one card and codec on another) is not built yet.
**Next:** the Pascal epic #380 (rig work waits until rigs are named; the fallback if
ACE-Step cannot run on Pascal is Stable Audio and/or EzAudio).
+3 -1
View File
@@ -124,7 +124,9 @@ enabled = false
# Finished jobs and their audio are deleted after this many hours.
# retention_hours = 72
# Renders running at once across the fleet; the rest queue in cortex.
# max_concurrent = 4
# 0 follows the fleet: the in-flight capacity its loaded music models
# advertise, counting every replica on a multi-card host (minimum 1).
# max_concurrent = 0
# Dispatch attempts per job; a busy (429/503) model does not use one up.
# max_attempts = 2
# How long a job may wait on a busy model before failing, in seconds.
+6 -1
View File
@@ -48,6 +48,11 @@ pub struct AudioJobsConfig {
/// How many renders cortex runs at once across the fleet. Each one
/// occupies a neuron device for its whole duration; queued jobs wait
/// in cortex rather than piling onto neuron admission queues.
///
/// `0` (the default) follows the fleet (#397): the summed in-flight
/// capacity of the music models loaded on hosts taking work, which
/// counts every replica of a model on a multi-card host, and at least
/// one so a cold model can still be loaded.
#[serde(default = "default_audio_max_concurrent")]
pub max_concurrent: usize,
/// Dispatch attempts per job before it fails. A busy neuron (429/503)
@@ -85,7 +90,7 @@ fn default_audio_retention_hours() -> u64 {
72
}
fn default_audio_max_concurrent() -> usize {
4
0
}
fn default_audio_max_attempts() -> u32 {
2
+48
View File
@@ -75,6 +75,10 @@ pub struct HealthResponse {
/// interoperable (absent → empty → treated as no load info).
#[serde(default)]
pub models: Vec<ModelLoad>,
/// This host's next scheduled absence (#397), or the one it is in.
/// Absent for a host with no schedule.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_dark: Option<DarkWindow>,
}
/// Live admission load for one loaded model (#53).
@@ -153,6 +157,48 @@ pub struct ModelLoad {
/// sample. `#[serde(default)]` for back-compat.
#[serde(default)]
pub tok_s_decode: f64,
/// Per-replica load for a model with copies on several devices (#397).
/// The model-level fields above are their sums; this says how the
/// work is spread. Empty for an unreplicated model.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub replicas: Vec<ReplicaLoad>,
}
/// One replica of a replicated model (#397).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicaLoad {
pub device: u32,
/// Requests this replica is running.
pub in_flight: usize,
/// `false` once its device has failed; it takes no more work.
pub healthy: bool,
}
/// A window in which a host is expected to be off (#397), in unix
/// seconds. Solar-powered hosts leave the mesh on a schedule; announcing
/// it lets cortex stop sending work before the host goes, and treat its
/// absence as planned rather than as a fault.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct DarkWindow {
/// From here on the host takes no new work, so what it is running can
/// finish before it goes. The host sets it: it knows how long its work
/// takes.
pub drain_at: u64,
pub starts_at: u64,
pub ends_at: u64,
}
impl DarkWindow {
/// Whether a host announcing this window should be sent new work at
/// `now`.
pub fn takes_work_at(&self, now: u64) -> bool {
now < self.drain_at || now >= self.ends_at
}
/// Whether `now` falls in the planned absence, draining included.
pub fn expects_absence_at(&self, now: u64) -> bool {
now >= self.drain_at && now < self.ends_at
}
}
#[cfg(test)]
@@ -193,7 +239,9 @@ mod health_load_tests {
rejected_anon_yield: 0,
tok_s_prefill: 0.0,
tok_s_decode: 0.0,
replicas: vec![],
}],
next_dark: None,
};
let s = serde_json::to_string(&resp).unwrap();
let back: HealthResponse = serde_json::from_str(&s).unwrap();
+58
View File
@@ -216,6 +216,60 @@ pub struct ModelSpec {
/// `None` takes the host's setting, which is every model today.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_in_flight: Option<usize>,
/// Run an independent copy of this model on each of several devices
/// (#397), overriding the host's own setting.
///
/// Each replica has its own weights and device worker; the neuron
/// hands each admitted request to an idle one. cortex keeps seeing one
/// model per host whose capacity is the replicas' sum. Only music
/// models replicate today; anything else refuses a spec that asks.
///
/// `None` takes the host's setting.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub replicas: Option<Replicas>,
}
/// Which devices carry a copy of a replicated model (#397).
///
/// Written `"per-device"` (every device the model may use: its `devices`
/// when given, else every CUDA device on the host) or as an explicit list
/// of device indices.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ReplicasRepr", into = "ReplicasRepr")]
pub enum Replicas {
PerDevice,
Devices(Vec<u32>),
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum ReplicasRepr {
Word(String),
List(Vec<u32>),
}
impl TryFrom<ReplicasRepr> for Replicas {
type Error = String;
fn try_from(r: ReplicasRepr) -> Result<Self, String> {
match r {
ReplicasRepr::Word(w) if w == "per-device" => Ok(Replicas::PerDevice),
ReplicasRepr::Word(w) => Err(format!(
"replicas must be \"per-device\" or a list of device indices, got \"{w}\""
)),
ReplicasRepr::List(d) if d.is_empty() => Err("replicas lists no devices".to_string()),
ReplicasRepr::List(d) => Ok(Replicas::Devices(d)),
}
}
}
impl From<Replicas> for ReplicasRepr {
fn from(r: Replicas) -> Self {
match r {
Replicas::PerDevice => ReplicasRepr::Word("per-device".into()),
Replicas::Devices(d) => ReplicasRepr::List(d),
}
}
}
/// Where a sparse MoE's routed experts are held (#318).
@@ -435,6 +489,10 @@ pub struct ModelInfo {
/// budget to offer.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reasoning_budget: Vec<ReasoningBudgetRung>,
/// How many independent copies of the model this host runs (#397).
/// Absent for an unreplicated model.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub replicas: Option<usize>,
}
/// Why a loaded model can or cannot be served right now (#245).
+28
View File
@@ -50,6 +50,34 @@ pub struct NodeState {
/// neuron reports the same rungs — and duplicating it onto each
/// model entry would invite the two to disagree.
pub reasoning_budget: Vec<crate::harness::ReasoningBudgetRung>,
/// The neuron's last-announced scheduled absence (#397), from
/// `/health`. Kept while the neuron is unreachable: that is when it
/// says the silence is planned.
pub next_dark: Option<crate::discovery::DarkWindow>,
/// Whether the neuron is currently away inside its announced dark
/// window, so the poller logs the departure and return once each
/// rather than every failed poll.
pub in_scheduled_absence: bool,
}
impl NodeState {
/// Whether new work may be sent here at `now` (unix seconds): the node
/// is healthy and not draining ahead of a scheduled absence (#397).
pub fn takes_work_at(&self, now: u64) -> bool {
self.healthy && self.next_dark.is_none_or(|d| d.takes_work_at(now))
}
/// [`Self::takes_work_at`] the current time.
pub fn takes_work(&self) -> bool {
self.takes_work_at(unix_now())
}
}
/// Seconds since the unix epoch.
pub fn unix_now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
/// A model registered on a node, with its runtime status.
+81 -7
View File
@@ -42,7 +42,7 @@ use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::sync::{RwLock, Semaphore};
use tokio::sync::{Notify, RwLock};
use tokio::task::JoinHandle;
/// Path of the job collection; `{id}` and `{id}/content` hang off it.
@@ -82,8 +82,10 @@ pub struct AudioJobs {
jobs: RwLock<HashMap<String, JobRecord>>,
/// Worker tasks for jobs that are queued or running, for cancellation.
workers: Mutex<HashMap<String, JoinHandle<()>>>,
/// Bounds concurrent renders across the fleet.
slots: Arc<Semaphore>,
/// Renders running now, bounded by [`AudioJobs::render_capacity`].
running: Mutex<usize>,
/// Signalled whenever a render ends.
render_ended: Notify,
/// Rendered audio, when there is no job directory to write it to.
memory_audio: Mutex<HashMap<String, Bytes>>,
/// Client for neuron dispatches. A neuron sends nothing until the render
@@ -102,7 +104,8 @@ impl AudioJobs {
dir: std::sync::OnceLock::new(),
jobs: RwLock::new(HashMap::new()),
workers: Mutex::new(HashMap::new()),
slots: Arc::new(Semaphore::new(config.max_concurrent.max(1))),
running: Mutex::new(0),
render_ended: Notify::new(),
memory_audio: Mutex::new(HashMap::new()),
http,
}
@@ -647,9 +650,7 @@ enum Dispatch {
async fn run_job(fleet: &Arc<CortexState>, id: &str, guard: ReservationGuard) {
let jobs = &fleet.audio_jobs;
let Ok(_slot) = Arc::clone(&jobs.slots).acquire_owned().await else {
return;
};
let _slot = render_slot(fleet).await;
let Some(record) = jobs
.update(id, |r| {
if !r.job.status.is_terminal() {
@@ -710,6 +711,79 @@ async fn run_job(fleet: &Arc<CortexState>, id: &str, guard: ReservationGuard) {
fail(fleet, id, last_error).await;
}
/// A render's place in the fleet-wide bound; dropping it frees the place.
struct RenderSlot<'a>(&'a AudioJobs);
impl Drop for RenderSlot<'_> {
fn drop(&mut self) {
if let Ok(mut running) = self.0.running.lock() {
*running = running.saturating_sub(1);
}
self.0.render_ended.notify_waiters();
}
}
/// How often a job waiting for a render slot re-reads the fleet's
/// capacity, which changes as hosts come and go and models load.
const CAPACITY_RECHECK: Duration = Duration::from_secs(2);
/// Wait for a place among the renders the fleet can run at once.
async fn render_slot(fleet: &CortexState) -> RenderSlot<'_> {
let jobs = &fleet.audio_jobs;
loop {
let ended = jobs.render_ended.notified();
tokio::pin!(ended);
// Registered before the check, so a render ending in between
// still wakes this waiter.
ended.as_mut().enable();
let capacity = match jobs.config.max_concurrent {
0 => {
let nodes = fleet.nodes.read().await;
fleet_render_capacity(nodes.values(), cortex_core::node::unix_now())
}
n => n,
};
{
let mut running = jobs.running.lock().expect("render count poisoned");
if *running < capacity {
*running += 1;
return RenderSlot(jobs);
}
}
let _ = tokio::time::timeout(CAPACITY_RECHECK, ended).await;
}
}
/// Renders the fleet can run at once (#397): the in-flight capacity of
/// every music model loaded on a host taking work. A host with a copy of a
/// model on each of its cards advertises one slot per copy. At least one,
/// so a job for a model nobody has loaded can still cold-load it.
pub fn fleet_render_capacity<'a>(
nodes: impl Iterator<Item = &'a cortex_core::node::NodeState>,
now: u64,
) -> usize {
use cortex_core::node::ModelStatus;
nodes
.filter(|n| n.takes_work_at(now))
.flat_map(|n| {
n.models
.values()
.filter(|m| {
matches!(m.status, ModelStatus::Loaded | ModelStatus::Reloading)
&& m.capabilities
.iter()
.any(|c| c == cortex_core::audio::CAPABILITY)
})
.map(|m| {
n.model_load
.get(&m.id)
.map_or(1, |l| l.max_in_flight.max(1))
})
})
.sum::<usize>()
.max(1)
}
async fn dispatch_once(fleet: &Arc<CortexState>, record: &JobRecord) -> Dispatch {
let route = match crate::router::resolve(fleet, &record.job.model).await {
Ok(r) => r,
+11 -2
View File
@@ -933,7 +933,9 @@ async fn list_models(State(fleet): State<Arc<CortexState>>) -> Json<Value> {
for profile in &catalogue.models {
let mut feasible_on = Vec::new();
for node in nodes.values() {
if !node.healthy {
// A host draining ahead of its dark window (#397) offers no
// new capacity.
if !node.takes_work() {
continue;
}
let Some(disc) = node.discovery.as_ref() else {
@@ -1244,6 +1246,9 @@ async fn health(State(fleet): State<Arc<CortexState>>) -> Json<Value> {
let nodes = fleet.nodes.read().await;
let healthy_count = nodes.values().filter(|n| n.healthy).count();
let total_count = nodes.len();
// Away inside a dark window they announced (#397): reduced capacity,
// not a fault, so monitoring can tell the two apart.
let scheduled_dark = nodes.values().filter(|n| n.in_scheduled_absence).count();
// Models resident on a node that cannot currently serve them. Worth
// surfacing even when another node can pick the work up, because it
@@ -1277,7 +1282,11 @@ async fn health(State(fleet): State<Arc<CortexState>>) -> Json<Value> {
let mut body = json!({
"status": status,
"nodes": { "healthy": healthy_count, "total": total_count },
"nodes": {
"healthy": healthy_count,
"total": total_count,
"scheduled_dark": scheduled_dark,
},
});
if !unservable.is_empty() {
body["unservable"] = Value::Array(unservable);
+38 -11
View File
@@ -28,8 +28,31 @@ const CAPABILITY_RETRY: Duration = Duration::from_secs(600);
/// reach [`POLL_FAILURE_THRESHOLD`]. Below the threshold the node keeps its
/// last-known health, riding over transient misses. A successful poll resets
/// the counter (see the success arm in `poll_once`).
fn record_poll_failure(node: &mut NodeState) {
///
/// A node that is away inside the dark window it announced (#397) is a
/// planned absence, not a fault: it is marked unhealthy at once, with
/// nothing to debounce, and the departure is logged once at `info` instead
/// of a warning every poll for the length of the night.
fn record_poll_failure(node: &mut NodeState, error: &dyn std::fmt::Display) {
node.consecutive_poll_failures = node.consecutive_poll_failures.saturating_add(1);
if let Some(dark) = node
.next_dark
.filter(|d| d.expects_absence_at(cortex_core::node::unix_now()))
{
node.healthy = false;
if !node.in_scheduled_absence {
node.in_scheduled_absence = true;
tracing::info!(
node = %node.name,
until = dark.ends_at,
"neuron is away for its scheduled dark window"
);
gauge!("cortex_node_scheduled_dark", "node" => node.name.clone()).set(1.0);
}
tracing::debug!(node = %node.name, error = %error, "poll failed during scheduled dark window");
return;
}
tracing::warn!(node = %node.name, error = %error, "neuron poll failed");
if node.consecutive_poll_failures >= POLL_FAILURE_THRESHOLD {
node.healthy = false;
}
@@ -180,26 +203,27 @@ async fn poll_neuron(fleet: &CortexState, name: &str, endpoint: &str) {
node.consecutive_poll_failures = 0;
node.healthy = true;
if node.in_scheduled_absence {
node.in_scheduled_absence = false;
tracing::info!(
node = name,
"neuron is back from its scheduled dark window"
);
gauge!("cortex_node_scheduled_dark", "node" => name.to_string()).set(0.0);
}
node.last_poll = Some(Utc::now());
tracing::debug!(node = name, models = models.len(), "poll ok");
}
Err(e) => {
tracing::warn!(node = name, error = %e, "failed to parse /models response");
record_poll_failure(node);
record_poll_failure(node, &format_args!("unparseable /models response: {e}"));
}
}
}
Ok(resp) => {
tracing::warn!(
node = name,
status = %resp.status(),
"neuron returned non-success status"
);
record_poll_failure(node);
record_poll_failure(node, &format_args!("/models answered {}", resp.status()));
}
Err(e) => {
tracing::warn!(node = name, error = %e, "failed to reach neuron");
record_poll_failure(node);
record_poll_failure(node, &format_args!("unreachable: {e}"));
}
}
@@ -346,6 +370,9 @@ pub async fn poll_health(fleet: &CortexState, name: &str, endpoint: &str) {
// Per-device VRAM readings (#203) for free-fit
// cold-load placement.
node.device_health = h.devices.clone();
// The host's power schedule (#397): when to stop sending
// it work, and when its silence is planned.
node.next_dark = h.next_dark;
}
}
Err(e) => {
+25 -10
View File
@@ -152,12 +152,16 @@ pub async fn resolve(
let nodes = fleet.nodes.read().await;
// All healthy nodes with the model loaded, each with its current
// admission load (#53) so we can pick the least-busy replica (#55).
let mut loaded_candidates: Vec<(String, String, usize)> = Vec::new();
let mut loaded_candidates: Vec<(String, String, f64)> = Vec::new();
let mut unloaded_route = None;
let mut recovering_node = None;
let mut any_healthy = false;
let now = cortex_core::node::unix_now();
for node in nodes.values() {
if !node.healthy {
// A node draining ahead of its scheduled dark window (#397) is
// healthy but takes nothing new: what it is running finishes,
// and the work it would have got goes elsewhere.
if !node.takes_work_at(now) {
continue;
}
any_healthy = true;
@@ -186,13 +190,20 @@ pub async fn resolve(
continue;
}
// Least-busy score: in-flight + queued from the
// neuron's last /health (#53). Unknown load (no poll
// yet) scores 0 so the replica stays eligible.
// neuron's last /health (#53), as a share of the
// model's in-flight capacity there, so a host with
// eight replicas (#397) and two renders running
// counts as less busy than a single card with one.
// Unknown load (no poll yet) scores 0 so the
// replica stays eligible; unknown capacity (0, an
// older neuron) counts as one slot.
let score = node
.model_load
.get(model_id)
.map(|l| l.in_flight + l.queue_depth)
.unwrap_or(0);
.map(|l| {
(l.in_flight + l.queue_depth) as f64 / l.max_in_flight.max(1) as f64
})
.unwrap_or(0.0);
loaded_candidates.push((node.name.clone(), node.endpoint.clone(), score));
}
ModelStatus::Unloaded => {
@@ -229,7 +240,7 @@ pub async fn resolve(
// deterministic routing. `false` = not a cold start.
let loaded_route = loaded_candidates
.into_iter()
.min_by(|a, b| a.2.cmp(&b.2).then_with(|| a.0.cmp(&b.0)))
.min_by(|a, b| a.2.total_cmp(&b.2).then_with(|| a.0.cmp(&b.0)))
.map(|(name, endpoint, _score)| (name, endpoint, false));
(loaded_route, unloaded_route, recovering_node, any_healthy)
};
@@ -330,7 +341,7 @@ async fn loaded_location(fleet: &Arc<CortexState>, model_id: &str) -> Option<(St
let nodes = fleet.nodes.read().await;
nodes
.values()
.filter(|n| n.healthy)
.filter(|n| n.takes_work())
.find(|n| {
n.models.get(model_id).is_some_and(|m| {
matches!(m.status, ModelStatus::Loaded | ModelStatus::Reloading) && m.is_servable()
@@ -424,7 +435,8 @@ async fn pick_feasible_neuron(
let nodes = fleet.nodes.read().await;
let mut candidates: Vec<(String, String, bool, bool, bool, u64)> = Vec::new();
for node in nodes.values() {
if !node.healthy {
// Never cold-load onto a host about to go dark (#397).
if !node.takes_work() {
continue;
}
let Some(disc) = node.discovery.as_ref() else {
@@ -492,7 +504,7 @@ async fn pick_feasible_neuron(
// and retries instead of treating a 404 as a hard failure. Only when no
// neuron could *ever* satisfy the topology is it a permanent 404.
let feasible_but_unhealthy = nodes.values().any(|node| {
!node.healthy
!node.takes_work()
&& node
.discovery
.as_ref()
@@ -660,6 +672,9 @@ async fn profile_to_spec(
// decides from its own config.
expert_residency: None,
max_in_flight: None,
// Like expert residency, how many cards carry a copy is the
// host's decision (#397).
replicas: None,
}
}
+2
View File
@@ -94,6 +94,8 @@ impl CortexState {
activation: None,
model_load: HashMap::new(),
consecutive_poll_failures: 0,
next_dark: None,
in_scheduled_absence: false,
},
);
}
@@ -61,6 +61,7 @@ async fn seed_loaded(fleet: &CortexState, node: &str, in_flight: usize, queue_de
rejected_anon_yield: 0,
tok_s_prefill: 0.0,
tok_s_decode: 0.0,
replicas: vec![],
},
);
}
@@ -0,0 +1,317 @@
//! Hosts that leave the mesh on a schedule (#397).
//!
//! A solar-powered rig goes dark every evening. It announces the window
//! on `/health`, including when it stops taking new work so what it is
//! running can finish. cortex must stop routing there at that moment,
//! treat the silence that follows as planned, and pick the host up again
//! when it returns. Across the whole cycle a client sees only reduced
//! capacity, never a failed request.
//!
//! Also here: a host carrying several replicas of a model (#397) counts as
//! that much capacity, both for routing and for the audio job gate.
mod common;
use axum::Json;
use axum::Router;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use cortex_core::node::unix_now;
use serde_json::{Value, json};
use std::sync::{Arc, Mutex};
use tokio::net::TcpListener;
const MODEL: &str = "test-model";
/// A neuron whose announced schedule, load and presence the test controls.
#[derive(Default)]
struct Rig {
/// Answers 502 to everything, as a host whose power is off would fail
/// to answer at all.
gone: bool,
next_dark: Option<Value>,
in_flight: usize,
max_in_flight: usize,
/// Inference requests that reached this neuron.
served: usize,
}
type Shared = Arc<Mutex<Rig>>;
async fn spawn_rig(rig: Shared) -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let endpoint = base.clone();
let app = Router::new()
.route("/models", get(models))
.route("/health", get(health))
.route(
"/models/{id}/endpoint",
get(move |State(rig): State<Shared>, Path(_): Path<String>| {
let url = endpoint.clone();
async move {
if rig.lock().unwrap().gone {
return StatusCode::BAD_GATEWAY.into_response();
}
Json(json!({ "url": url })).into_response()
}
}),
)
.route("/v1/chat/completions", post(chat))
.with_state(rig);
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
base
}
async fn models(State(rig): State<Shared>) -> Response {
if rig.lock().unwrap().gone {
return StatusCode::BAD_GATEWAY.into_response();
}
Json(json!([{
"id": MODEL, "harness": "candle", "status": "loaded", "devices": [0],
"vram_used_mb": null
}]))
.into_response()
}
async fn health(State(rig): State<Shared>) -> Response {
let r = rig.lock().unwrap();
if r.gone {
return StatusCode::BAD_GATEWAY.into_response();
}
let mut body = json!({
"uptime_secs": 1,
"devices": [],
"models": [{
"id": MODEL,
"in_flight": r.in_flight,
"queue_depth": 0,
"max_in_flight": r.max_in_flight,
}],
});
if let Some(d) = &r.next_dark {
body["next_dark"] = d.clone();
}
Json(body).into_response()
}
async fn chat(State(rig): State<Shared>) -> Response {
let mut r = rig.lock().unwrap();
if r.gone {
return StatusCode::BAD_GATEWAY.into_response();
}
r.served += 1;
Json(json!({
"id": "chatcmpl-rig", "object": "chat.completion", "created": 1, "model": MODEL,
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"},
"finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
}))
.into_response()
}
fn dark(drain_at: u64, starts_at: u64, ends_at: u64) -> Option<Value> {
Some(json!({ "drain_at": drain_at, "starts_at": starts_at, "ends_at": ends_at }))
}
/// Send `n` requests through the gateway; every one must succeed.
async fn all_succeed(gateway: &str, n: usize) {
let client = reqwest::Client::new();
for i in 0..n {
let resp = client
.post(format!("{gateway}/v1/chat/completions"))
.json(&json!({"model": MODEL, "messages": [{"role": "user", "content": "hi"}]}))
.send()
.await
.unwrap();
assert_eq!(resp.status(), 200, "request {i} failed");
}
}
fn served(rig: &Shared) -> usize {
rig.lock().unwrap().served
}
#[tokio::test]
async fn a_host_leaving_and_returning_on_schedule_fails_no_request() {
let now = unix_now();
// The rig: eight replicas, idle, dark from tonight.
let rig: Shared = Arc::new(Mutex::new(Rig {
max_in_flight: 8,
next_dark: dark(now + 3600, now + 4500, now + 40_000),
..Default::default()
}));
// An always-on single card that is already busy.
let card: Shared = Arc::new(Mutex::new(Rig {
max_in_flight: 1,
in_flight: 1,
..Default::default()
}));
let fleet = common::two_neuron_fleet(
&spawn_rig(Arc::clone(&rig)).await,
&spawn_rig(Arc::clone(&card)).await,
)
.await;
let app = cortex_gateway::build_app(Arc::clone(&fleet));
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let gateway = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
// Daytime: the idle rig takes the work.
cortex_gateway::poller::poll_once(&fleet).await;
all_succeed(&gateway, 10).await;
assert_eq!(served(&rig), 10, "the idle rig should take the work");
// Draining: still up and polling fine, but its announced drain time has
// passed. Nothing new goes there.
rig.lock().unwrap().next_dark = dark(now - 1, now + 60, now + 40_000);
cortex_gateway::poller::poll_once(&fleet).await;
all_succeed(&gateway, 10).await;
assert_eq!(served(&rig), 10, "a draining host must get no new work");
assert_eq!(served(&card), 10);
// Dark: the rig stops answering. Its absence is planned, so it leaves
// routing at once and the gateway reports it as scheduled, not failed.
rig.lock().unwrap().gone = true;
cortex_gateway::poller::poll_once(&fleet).await;
{
let nodes = fleet.nodes.read().await;
let a = &nodes["node-a"];
assert!(!a.healthy, "a host away on schedule is out of routing");
assert!(a.in_scheduled_absence);
}
all_succeed(&gateway, 10).await;
let health: Value = reqwest::get(format!("{gateway}/health"))
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(health["nodes"]["scheduled_dark"], 1);
// Morning: the rig is back with tomorrow's window, and takes work again.
{
let mut r = rig.lock().unwrap();
r.gone = false;
r.next_dark = dark(now + 86_400, now + 87_300, now + 126_000);
}
cortex_gateway::poller::poll_once(&fleet).await;
{
let nodes = fleet.nodes.read().await;
assert!(nodes["node-a"].healthy);
assert!(!nodes["node-a"].in_scheduled_absence);
}
all_succeed(&gateway, 10).await;
assert_eq!(served(&rig), 20, "the returned rig takes work again");
assert_eq!(served(&card), 20);
}
/// An unannounced outage is still a fault: debounced, not quietly accepted.
#[tokio::test]
async fn an_unannounced_absence_is_not_treated_as_scheduled() {
let rig: Shared = Arc::new(Mutex::new(Rig {
max_in_flight: 1,
..Default::default()
}));
let card: Shared = Arc::new(Mutex::new(Rig {
max_in_flight: 1,
..Default::default()
}));
let fleet = common::two_neuron_fleet(
&spawn_rig(Arc::clone(&rig)).await,
&spawn_rig(Arc::clone(&card)).await,
)
.await;
cortex_gateway::poller::poll_once(&fleet).await;
rig.lock().unwrap().gone = true;
cortex_gateway::poller::poll_once(&fleet).await;
let nodes = fleet.nodes.read().await;
let a = &nodes["node-a"];
assert!(a.healthy, "one missed poll rides the debounce");
assert!(!a.in_scheduled_absence);
}
/// Busy-ness is a share of capacity: a rig with eight replicas and two
/// renders running is less busy than a single card running one.
#[tokio::test]
async fn routing_weighs_load_against_replica_capacity() {
let rig: Shared = Arc::new(Mutex::new(Rig {
max_in_flight: 8,
in_flight: 2,
..Default::default()
}));
let card: Shared = Arc::new(Mutex::new(Rig {
max_in_flight: 1,
in_flight: 1,
..Default::default()
}));
let fleet = common::two_neuron_fleet(
&spawn_rig(Arc::clone(&rig)).await,
&spawn_rig(Arc::clone(&card)).await,
)
.await;
cortex_gateway::poller::poll_once(&fleet).await;
let route = cortex_gateway::router::resolve(&fleet, MODEL)
.await
.expect("loaded on both");
assert_eq!(route.node_name, "node-a");
}
/// The audio job gate follows the fleet: every replica of a loaded music
/// model is a render slot, and a draining host's are not.
#[tokio::test]
async fn render_capacity_counts_replicas_on_hosts_taking_work() {
use cortex_core::discovery::{DarkWindow, ModelLoad};
use cortex_core::node::{ModelEntry, ModelStatus};
use cortex_gateway::audio_jobs::fleet_render_capacity;
let fleet = common::two_neuron_fleet("http://127.0.0.1:1", "http://127.0.0.1:2").await;
let now = unix_now();
{
let mut nodes = fleet.nodes.write().await;
for (name, slots) in [("node-a", 8), ("node-b", 1)] {
let n = nodes.get_mut(name).unwrap();
n.healthy = true;
n.models.insert(
"ACE-Step/Ace-Step1.5".into(),
ModelEntry {
id: "ACE-Step/Ace-Step1.5".into(),
status: ModelStatus::Loaded,
last_accessed: None,
vram_estimate_mb: None,
capabilities: vec![cortex_core::audio::CAPABILITY.into()],
tool_call: false,
reasoning: false,
limit: None,
servable: None,
reasoning_budget: Vec::new(),
},
);
let load: ModelLoad = serde_json::from_value(json!({
"id": "ACE-Step/Ace-Step1.5", "in_flight": 0, "queue_depth": 0,
"max_in_flight": slots
}))
.unwrap();
n.model_load.insert(load.id.clone(), load);
}
}
let nodes = fleet.nodes.read().await;
assert_eq!(fleet_render_capacity(nodes.values(), now), 9);
drop(nodes);
fleet
.nodes
.write()
.await
.get_mut("node-a")
.unwrap()
.next_dark = Some(DarkWindow {
drain_at: now - 1,
starts_at: now + 60,
ends_at: now + 600,
});
let nodes = fleet.nodes.read().await;
assert_eq!(fleet_render_capacity(nodes.values(), now), 1);
}
+2
View File
@@ -223,6 +223,7 @@ impl TargetClient {
// reconstructed spec cannot carry it either.
expert_residency: None,
max_in_flight: None,
replicas: None,
})
}
@@ -292,6 +293,7 @@ impl TargetClient {
// serviceability, and absent means "no opinion".
servable: None,
reasoning_budget: Vec::new(),
replicas: None,
})
.collect())
}
+18
View File
@@ -16,6 +16,21 @@ path = "src/main.rs"
# Not shipped in the RPM: it loads a checkpoint directly and reports
# numbers, and exists so the go/no-go gate is a measurement rather than
# an argument.
[[bin]]
name = "neuron-strata-expert-probe"
path = "src/bin/strata_expert_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-engine-layer-probe"
path = "src/bin/engine_layer_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-engine-step-probe"
path = "src/bin/engine_step_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-mtp-probe"
path = "src/bin/mtp_probe.rs"
@@ -48,6 +63,9 @@ flash-attn = [
"candle-transformers/flash-attn",
"dep:candle-flash-attn",
]
# The expert kernels vendored from Strata (`vendor/strata`, MIT). Needs
# nvcc with C++20 and `CUDA_COMPUTE_CAP`.
strata-kernels = ["cuda"]
# Reserved for GPU-only integration tests in later stages.
cuda-integration = ["cuda"]
+103
View File
@@ -54,6 +54,8 @@ fn main() {
.expect("neuron cuda build failed");
println!("cargo:rustc-link-search={}", build_dir.display());
println!("cargo:rustc-link-lib=neuroncuda");
#[cfg(feature = "strata-kernels")]
build_strata_kernels(&build_dir);
println!("cargo:rustc-link-lib=dylib=cudart");
if target.contains("msvc") {
@@ -71,6 +73,107 @@ fn main() {
}
}
/// Compile the vendored Strata expert kernels and neuron's C shim.
///
/// They need C++20 and must not get the `--use_fast_math` the kernels
/// above are built with: upstream builds this file without it, and
/// contraction would change the rounding its parity relies on.
#[cfg(feature = "strata-kernels")]
fn build_strata_kernels(build_dir: &std::path::Path) {
println!("cargo:rerun-if-changed=vendor/strata");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_shim.cu");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_probe.cu");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/engine_shim.cu");
println!("cargo:rerun-if-env-changed=CUDA_COMPUTE_CAP");
let cap = std::env::var("CUDA_COMPUTE_CAP").expect("strata-kernels needs CUDA_COMPUTE_CAP");
let root = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let vendor = root.join("vendor/strata/engine");
let mut sources = vec![
// UD-IQ4_XS has no NVFP4 experts, so upstream's stub satisfies
// the reference from the grouped dispatch.
(
"strata_nvfp4_absent.o".to_string(),
vendor.join("src/kernels/cuda/nvfp4_decode_sm120_absent.cpp"),
),
(
"strata_shim.o".to_string(),
root.join("src/cuda/strata_adapter/strata_shim.cu"),
),
(
"strata_probe.o".to_string(),
root.join("src/cuda/strata_adapter/strata_probe.cu"),
),
(
"engine_shim.o".to_string(),
root.join("src/cuda/strata_adapter/engine_shim.cu"),
),
];
// The experts, then the decode kernels the native engine (#427)
// drives: linear attention, hyper-connections, router, MoE combine,
// activation quantisation and the BF16 projections.
for kernel in [
"iq_kernels",
"native_gdn",
"native_gdn_preprocess",
"fused_gdn",
"native_gr_norm",
"native_gr_postops",
"gr",
"native_router",
"native_rope",
"native_moe",
"quantize_act",
"bf16_gemv",
"native_bf16",
] {
sources.push((
format!("strata_{kernel}.o"),
vendor.join(format!("src/kernels/cuda/{kernel}.cu")),
));
}
// Independent translation units: compile them side by side.
let objects: Vec<std::path::PathBuf> = std::thread::scope(|scope| {
let jobs: Vec<_> = sources
.iter()
.map(|(name, source)| {
let object = build_dir.join(name);
let (cap, vendor) = (&cap, &vendor);
scope.spawn(move || {
let status = Command::new("nvcc")
.args(["-O3", "-DNDEBUG", "-std=c++20"])
.arg(format!(
"--generate-code=arch=compute_{cap},code=[compute_{cap},sm_{cap}]"
))
.args(["-DSTRATA_Q6K_EXPERTS=1", "-DSTRATA_VERIFY_MAX_T=8"])
.arg(format!("-I{}", vendor.join("third_party/ggml").display()))
.arg(format!("-I{}", vendor.join("include").display()))
.args(["--compiler-options", "-fPIC", "-c"])
.arg(source)
.arg("-o")
.arg(&object)
.status()
.expect("run nvcc");
assert!(status.success(), "nvcc failed on {}", source.display());
object
})
})
.collect();
jobs.into_iter()
.map(|j| j.join().expect("nvcc thread"))
.collect()
});
let library = build_dir.join("libneuronstrata.a");
let _ = std::fs::remove_file(&library);
let status = Command::new("ar")
.arg("rcs")
.arg(&library)
.args(&objects)
.status()
.expect("run ar");
assert!(status.success(), "ar failed");
println!("cargo:rustc-link-lib=static=neuronstrata");
}
/// Emit `cargo:rustc-env=` vars consumed by `env!()` in `src/version.rs`
/// so the daemon can report its own build identity from `GET /version`.
///
+212
View File
@@ -0,0 +1,212 @@
//! A host's power schedule (#397).
//!
//! Solar-powered hosts leave the mesh on a daily schedule. The operator
//! lists the windows in which the host is powered; `/health` announces the
//! next window in which it is not, so cortex can stop sending new work
//! before the host goes and treat its absence as planned.
//!
//! ```toml
//! [availability]
//! # UTC. A window may wrap past midnight ("22:00-06:00").
//! online = ["06:30-18:45"]
//! # Take no new work this long before each dark window, so running work
//! # can finish. Longer than this host's longest job.
//! drain_secs = 900
//! ```
//!
//! With no `online` windows the host is always on and announces nothing.
use cortex_core::discovery::DarkWindow;
use serde::{Deserialize, Serialize};
const DAY: u64 = 24 * 60 * 60;
/// `[availability]` in neuron.toml.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AvailabilityConfig {
/// Daily windows, in UTC, in which this host is powered:
/// `"HH:MM-HH:MM"`. Empty means always on.
#[serde(default)]
pub online: Vec<String>,
/// How long before each dark window the host stops taking new work,
/// in seconds. It should exceed the host's longest job.
#[serde(default = "default_drain_secs")]
pub drain_secs: u64,
}
impl Default for AvailabilityConfig {
fn default() -> Self {
Self {
online: Vec::new(),
drain_secs: default_drain_secs(),
}
}
}
/// Fifteen minutes: a 600 s song on the slowest card that serves one.
fn default_drain_secs() -> u64 {
900
}
/// Parsed online windows, as `[start, end)` seconds past UTC midnight.
/// A window that wraps past midnight is split in two.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Schedule {
online: Vec<(u64, u64)>,
drain_secs: u64,
}
impl Schedule {
/// `None` when the config lists no windows: an always-on host.
pub fn from_config(cfg: &AvailabilityConfig) -> anyhow::Result<Option<Self>> {
if cfg.online.is_empty() {
return Ok(None);
}
let mut online = Vec::new();
for w in &cfg.online {
let (a, b) = w
.split_once('-')
.ok_or_else(|| anyhow::anyhow!("availability window '{w}' is not HH:MM-HH:MM"))?;
let (start, end) = (time_of_day(a.trim(), w)?, time_of_day(b.trim(), w)?);
anyhow::ensure!(start != end, "availability window '{w}' is empty");
if start < end {
online.push((start, end));
} else {
online.push((start, DAY));
online.push((0, end));
}
}
Ok(Some(Self {
online,
drain_secs: cfg.drain_secs,
}))
}
/// The dark window in progress at `now`, or else the next one; `None`
/// when the windows cover the whole day.
pub fn next_dark(&self, now: u64) -> Option<DarkWindow> {
// Lay the online windows out over yesterday, today and the next
// two days; the gaps between them are the dark windows. Three days
// ahead is enough because a dark window is shorter than a day.
let midnight = now - now % DAY;
let mut on: Vec<(u64, u64)> = (0..4)
.flat_map(|d| {
let base = midnight - DAY + d * DAY;
self.online.iter().map(move |&(s, e)| (base + s, base + e))
})
.collect();
on.sort_unstable();
let mut merged: Vec<(u64, u64)> = Vec::new();
for (s, e) in on {
match merged.last_mut() {
Some(last) if s <= last.1 => last.1 = last.1.max(e),
_ => merged.push((s, e)),
}
}
merged
.windows(2)
.map(|w| DarkWindow {
drain_at: w[0].1.saturating_sub(self.drain_secs),
starts_at: w[0].1,
ends_at: w[1].0,
})
.find(|d| d.ends_at > now)
}
}
fn time_of_day(hhmm: &str, window: &str) -> anyhow::Result<u64> {
let bad = || anyhow::anyhow!("availability window '{window}' has a bad time '{hhmm}'");
let (h, m) = hhmm.split_once(':').ok_or_else(bad)?;
let (h, m): (u64, u64) = (h.parse().map_err(|_| bad())?, m.parse().map_err(|_| bad())?);
// 24:00 is the end of the day, so a window can run to midnight.
anyhow::ensure!(m < 60 && (h < 24 || (h == 24 && m == 0)), bad());
Ok(h * 3600 + m * 60)
}
#[cfg(test)]
mod tests {
use super::*;
fn schedule(windows: &[&str]) -> Schedule {
Schedule::from_config(&AvailabilityConfig {
online: windows.iter().map(|w| w.to_string()).collect(),
drain_secs: 600,
})
.unwrap()
.unwrap()
}
/// 2026-10-21 00:00 UTC.
const MIDNIGHT: u64 = 1_792_540_800;
const fn at(h: u64, m: u64) -> u64 {
MIDNIGHT + h * 3600 + m * 60
}
#[test]
fn a_day_host_announces_tonight_while_it_is_up() {
let s = schedule(&["06:30-18:45"]);
let dark = s.next_dark(at(12, 0)).unwrap();
assert_eq!(dark.starts_at, at(18, 45));
assert_eq!(dark.ends_at, at(24 + 6, 30));
assert_eq!(dark.drain_at, at(18, 35));
assert!(dark.takes_work_at(at(18, 34)));
assert!(!dark.takes_work_at(at(18, 35)));
assert!(dark.takes_work_at(at(24 + 6, 30)));
}
#[test]
fn inside_the_dark_window_it_reports_the_one_in_progress() {
let s = schedule(&["06:30-18:45"]);
// Before dawn: the window that began yesterday evening.
let dark = s.next_dark(at(3, 0)).unwrap();
assert_eq!(dark.starts_at, at(18, 45) - DAY);
assert_eq!(dark.ends_at, at(6, 30));
}
#[test]
fn a_window_may_wrap_past_midnight() {
let s = schedule(&["22:00-06:00"]);
let dark = s.next_dark(at(23, 0)).unwrap();
assert_eq!(
(dark.starts_at, dark.ends_at),
(at(24 + 6, 0), at(24 + 22, 0))
);
}
#[test]
fn overlapping_and_adjacent_windows_merge() {
let s = schedule(&["06:00-12:00", "11:00-14:00", "14:00-18:00"]);
let dark = s.next_dark(at(9, 0)).unwrap();
assert_eq!((dark.starts_at, dark.ends_at), (at(18, 0), at(24 + 6, 0)));
}
#[test]
fn a_whole_day_is_never_dark() {
assert_eq!(schedule(&["00:00-24:00"]).next_dark(at(5, 0)), None);
}
#[test]
fn no_windows_is_an_always_on_host() {
assert_eq!(
Schedule::from_config(&AvailabilityConfig::default()).unwrap(),
None
);
}
#[test]
fn malformed_windows_are_config_errors() {
for w in [
"0630-1845",
"06:30",
"25:00-26:00",
"06:60-07:00",
"08:00-08:00",
] {
let cfg = AvailabilityConfig {
online: vec![w.into()],
..Default::default()
};
assert!(Schedule::from_config(&cfg).is_err(), "{w} accepted");
}
}
}
+420
View File
@@ -0,0 +1,420 @@
//! Checks a native engine layer (#427) against candle's own, on the real
//! checkpoint and GGUF.
//!
//! ```sh
//! neuron-engine-layer-probe GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [LAYER] [STEPS] [gdn|attn|moe]
//! ```
//!
//! `gdn` (default) runs the mixer half of linear-attention layer `LAYER`
//! (default 0); `moe` runs the MoE half of any layer, and needs
//! `NEURON_EXPERT_DEVICE_ROUTING=1` (it pins every expert in host memory);
//! `attn` runs the mixer half of full-attention layer `LAYER` (3, 7, ...),
//! the context growing by one each step.
//! Either runs for `STEPS` decode tokens (default 8), carrying state, through both paths
//! from the same input: each step's residual is a real token embedding
//! repeated over the streams. Candle runs in BF16 (as served; its conv
//! kernel takes nothing wider) with the same GGUF Q8_0
//! projections the engine reads, so what differs is the engine's own
//! arithmetic and its BF16 hyper-connection and gate weights. Prints, per
//! step, the relative error of the layer's contribution (`out - in`).
use std::path::Path;
use anyhow::{Context, Result, bail};
use candle_core::cuda_backend::cudarc::driver::DevicePtr;
use candle_core::{DType, Device, IndexOp, Storage, Tensor};
use candle_nn::var_builder::ShardedSafeTensors;
use neuron::harness::arch::qwen3_5::proj::LinearSource;
use neuron::harness::arch::qwen4_exp::config::Config;
use neuron::harness::arch::qwen4_exp::engine::gdn;
use neuron::harness::arch::qwen4_exp::engine::weights::Gguf;
use neuron::harness::arch::qwen4_exp::gguf_dense::{GgufDenseSource, Heads};
use neuron::harness::arch::qwen4_exp::hyper::HyperConnection;
use neuron::harness::arch::qwen4_exp::linear_attn;
fn address(t: &Tensor) -> Result<u64> {
let (storage, layout) = t.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
bail!("expected a CUDA tensor");
};
let slice = storage.as_cuda_slice::<f32>()?;
Ok(slice.device_ptr(slice.stream()).0 + (layout.start_offset() * 4) as u64)
}
fn rel(a: &[f32], b: &[f32]) -> f64 {
let (mut num, mut den) = (0f64, 0f64);
for (x, y) in a.iter().zip(b) {
num += f64::from(x - y).powi(2);
den += f64::from(*y).powi(2);
}
(num / den.max(1e-30)).sqrt()
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
bail!(
"usage: {} GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [LAYER] [STEPS]",
args[0]
);
}
let (gguf_path, hf) = (Path::new(&args[1]), Path::new(&args[2]));
let layer: usize = args.get(3).map_or(Ok(0), |v| v.parse())?;
let steps: usize = args.get(4).map_or(Ok(8), |v| v.parse())?;
let mode = args.get(5).map_or("gdn", String::as_str);
let device = Device::new_cuda(0)?;
let cuda = device.as_cuda_device()?.clone();
let cfg = Config::from_config_json(
&std::fs::read_to_string(hf.join("config.json")).context("read config.json")?,
)?;
let text = &cfg.text_config;
let shapes = gdn::shapes(text)?;
// ---- candle, in f32, with the GGUF's Q8_0 projections.
let mut paths: Vec<_> = std::fs::read_dir(hf)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|x| x == "safetensors"))
.collect();
paths.sort();
// SAFETY: the checkpoint is not modified while mapped.
let vb = unsafe { ShardedSafeTensors::var_builder(&paths, DType::BF16, &device)? };
let dense = GgufDenseSource::open(
gguf_path,
&device,
Heads {
key_heads: text.linear_num_key_heads,
value_heads: text.linear_num_value_heads,
head_dim: text.linear_value_head_dim,
},
text.linear_num_key_heads * text.linear_key_head_dim,
)?;
let source: Option<&dyn LinearSource> = Some(&dense);
let lvb = vb.pp(format!("model.language_model.layers.{layer}"));
if mode == "attn" {
let embed = vb
.pp("model.language_model.embed_tokens")
.get((text.vocab_size, text.hidden_size), "weight")?;
return run_attn(gguf_path, &device, text, &lvb, source, &embed, layer, steps);
}
if mode == "moe" {
let embed = vb
.pp("model.language_model.embed_tokens")
.get((text.vocab_size, text.hidden_size), "weight")?;
return run_moe(gguf_path, &device, text, &lvb, dense, &embed, layer, steps);
}
let hc = HyperConnection::load(
&lvb.pp("attn_hyper_connection"),
text.hidden_size,
text.hc_count,
text.hc_lowrank,
text.rms_norm_eps,
true,
source,
)?;
let mut net = linear_attn::load(text, &lvb.pp("linear_attn"), source)?;
let embed = vb
.pp("model.language_model.embed_tokens")
.get((text.vocab_size, text.hidden_size), "weight")?;
// ---- the engine.
gdn::configure();
let gguf = Gguf::open(gguf_path, &cuda)?;
let weights = gdn::GdnWeights::load(&gguf, layer, &shapes)?;
let mut state = gdn::GdnState::zeroed(&cuda, &shapes)?;
let mut scratch = gdn::GdnScratch::new(&cuda, &shapes)?;
let out = cuda.alloc_zeros::<f32>(shapes.hc * shapes.n_embd)?;
let stream = cuda.cuda_stream().cu_stream() as *mut std::ffi::c_void;
// A deliberate fault, to show the probe can see one: the engine's
// state is reset every step while candle's carries on.
let fault = std::env::var_os("PROBE_FAULT_RESET_STATE").is_some();
let mut worst = 0f64;
for step in 0..steps {
if fault {
state = gdn::GdnState::zeroed(&cuda, &shapes)?;
}
let token = (1000 + 7919 * step) % text.vocab_size;
let h = embed
.i(token)?
.reshape((1, 1, text.hidden_size))?
.repeat((1, 1, text.hc_count))?;
let h = h.contiguous()?;
let split = hc.split(&h)?;
let inject = split
.inject
.as_ref()
.context("a decoder hyper-connection injects")?;
let mixed = net.forward(&split.input)?;
let want = hc.combine(&split.residual, &mixed, inject)?;
let h32 = h.to_dtype(DType::F32)?.contiguous()?;
gdn::forward(
&weights,
&mut state,
&mut scratch,
&shapes,
address(&h32)?,
out.device_ptr(out.stream()).0,
stream,
)?;
cuda.cuda_stream().synchronize()?;
let input: Vec<f32> = h32.flatten_all()?.to_vec1()?;
let want: Vec<f32> = want.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
let got = cuda.clone_dtoh(&out)?;
let delta = |r: &[f32]| -> Vec<f32> { r.iter().zip(&input).map(|(a, b)| a - b).collect() };
let err = rel(&delta(&got), &delta(&want));
worst = worst.max(err);
println!(
"layer {layer} step {step} token {token}: contribution rel err {err:.3e}, |out-in| {:.3e}",
delta(&want)
.iter()
.map(|v| f64::from(*v).powi(2))
.sum::<f64>()
.sqrt()
);
}
println!("layer {layer}: worst {worst:.3e} over {steps} steps");
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_moe(
gguf_path: &Path,
device: &Device,
text: &neuron::harness::arch::qwen4_exp::config::TextConfig,
lvb: &candle_nn::var_builder::ShardedVarBuilder,
dense: GgufDenseSource,
embed: &Tensor,
layer: usize,
steps: usize,
) -> Result<()> {
use neuron::harness::arch::qwen4_exp::engine::moe;
use neuron::harness::arch::qwen4_exp::native_experts::{GgufExpertSource, NativeExpertFactory};
use std::sync::Arc;
if std::env::var("NEURON_EXPERT_DEVICE_ROUTING").as_deref() != Ok("1") {
bail!("the moe probe needs NEURON_EXPERT_DEVICE_ROUTING=1");
}
let cuda = device.as_cuda_device()?.clone();
let shapes = gdn::shapes(text)?;
let mshapes = moe::shapes(text)?;
// No tier: every expert is read from the pinned host store by both
// paths alike, and neither admits anything.
let experts = Arc::new(GgufExpertSource::open(
gguf_path,
device,
text.num_hidden_layers,
text.num_experts,
text.hidden_size,
text.moe_intermediate_size,
None,
)?);
let dense: Arc<dyn LinearSource> = Arc::new(dense);
let opts = neuron::harness::arch::qwen4_exp::LoadOptions {
quant: None,
safetensors_paths: &[],
isq_cache: None,
experts_onto: &Device::Cpu,
experts_vb: None,
expert_tier: None,
external_experts: Some(Arc::new(NativeExpertFactory(experts.clone()))),
dense: Some(dense.clone()),
};
let hc = HyperConnection::load(
&lvb.pp("mlp_hyper_connection"),
text.hidden_size,
text.hc_count,
text.hc_lowrank,
text.rms_norm_eps,
true,
Some(dense.as_ref()),
)?;
let block = neuron::harness::arch::qwen4_exp::moe::load(text, &lvb.pp("mlp"), &opts)?;
let router_w = lvb
.pp("mlp")
.pp("gate")
.get((text.num_experts, text.hidden_size), "weight")?;
gdn::configure();
let gguf = Gguf::open(gguf_path, &cuda)?;
let weights = moe::MoeWeights::load(&gguf, layer, &shapes, &mshapes)?;
let mut scratch = moe::MoeScratch::new(&cuda, &shapes, &mshapes)?;
let out = cuda.alloc_zeros::<f32>(shapes.hc * shapes.n_embd)?;
let stream = cuda.cuda_stream().cu_stream() as *mut std::ffi::c_void;
let fault = std::env::var_os("PROBE_FAULT_SKIP_SHARED").is_some();
let mut worst = 0f64;
for step in 0..steps {
let token = (1000 + 7919 * step) % text.vocab_size;
let h = embed
.i(token)?
.reshape((1, 1, text.hidden_size))?
.repeat((1, 1, text.hc_count))?
.contiguous()?;
let split = hc.split(&h)?;
let inject = split
.inject
.as_ref()
.context("a decoder hyper-connection injects")?;
let mixed = candle_core::Module::forward(&block, &split.input)?;
let want = hc.combine(&split.residual, &mixed, inject)?;
let h32 = h.to_dtype(DType::F32)?.contiguous()?;
moe::forward(
&weights,
&experts,
layer,
&mut scratch,
&shapes,
&mshapes,
address(&h32)?,
out.device_ptr(out.stream()).0,
stream,
)?;
cuda.cuda_stream().synchronize()?;
let input: Vec<f32> = h32.flatten_all()?.to_vec1()?;
let want: Vec<f32> = want.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
let got = cuda.clone_dtoh(&out)?;
let delta = |r: &[f32]| -> Vec<f32> { r.iter().zip(&input).map(|(a, b)| a - b).collect() };
let (mut d_got, d_want) = (delta(&got), delta(&want));
if fault {
// A deliberate fault: drop a tenth of the contribution.
d_got.iter_mut().for_each(|v| *v *= 0.9);
}
let err = rel(&d_got, &d_want);
worst = worst.max(err);
// Which experts each path chose: the engine's from its own
// router, candle's recomputed from the same input and weight in
// candle's arithmetic (BF16 input, f32 softmax, descending sort).
let (mut ids, logits) = scratch.routed(&cuda)?;
ids.sort_unstable();
let probs = candle_nn::ops::softmax_last_dim(
&split
.input
.reshape(((), text.hidden_size))?
.matmul(&router_w.t()?)?
.to_dtype(DType::F32)?,
)?;
let order: Vec<u32> = probs.arg_sort_last_dim(false)?.flatten_all()?.to_vec1()?;
let mut cids: Vec<i32> = order[..mshapes.k].iter().map(|&e| e as i32).collect();
cids.sort_unstable();
if ids != cids {
let mut sorted = logits.clone();
sorted.sort_by(|a, b| b.total_cmp(a));
println!(
" routing differs: engine {ids:?} candle {cids:?}; engine logits at ranks 10/11: {:.5} / {:.5}",
sorted[mshapes.k - 1],
sorted[mshapes.k]
);
}
println!(
"layer {layer} moe step {step} token {token}: contribution rel err {err:.3e}, |out-in| {:.3e}",
d_want
.iter()
.map(|v| f64::from(*v).powi(2))
.sum::<f64>()
.sqrt()
);
}
println!("layer {layer} moe: worst {worst:.3e} over {steps} steps");
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_attn(
gguf_path: &Path,
device: &Device,
text: &neuron::harness::arch::qwen4_exp::config::TextConfig,
lvb: &candle_nn::var_builder::ShardedVarBuilder,
source: Option<&dyn LinearSource>,
embed: &Tensor,
layer: usize,
steps: usize,
) -> Result<()> {
use neuron::harness::arch::qwen4_exp::engine::attn;
use neuron::harness::arch::qwen4_exp::full_attn::Attention;
use std::sync::Arc;
let cuda = device.as_cuda_device()?.clone();
let shapes = gdn::shapes(text)?;
let ashapes = attn::shapes(text, steps.max(16))?;
let rotary = Arc::new(neuron::harness::arch::qwen4_exp::model::rotary_for(
text,
DType::BF16,
device,
)?);
let hc = HyperConnection::load(
&lvb.pp("attn_hyper_connection"),
text.hidden_size,
text.hc_count,
text.hc_lowrank,
text.rms_norm_eps,
true,
source,
)?;
let mut candle_attn = Attention::load(text, rotary.clone(), &lvb.pp("self_attn"), source)?;
gdn::configure();
let gguf = Gguf::open(gguf_path, &cuda)?;
let weights = attn::AttnWeights::load(&gguf, layer, &shapes, &ashapes)?;
let mut cache = attn::AttnCache::new(&cuda, &ashapes)?;
let mut scratch = attn::AttnScratch::new(&cuda, &shapes, &ashapes)?;
let mut positions = cuda.alloc_zeros::<i32>(32)?;
let out = cuda.alloc_zeros::<f32>(shapes.hc * shapes.n_embd)?;
let stream = cuda.cuda_stream().cu_stream() as *mut std::ffi::c_void;
let mut worst = 0f64;
for step in 0..steps {
let token = (1000 + 7919 * step) % text.vocab_size;
let h = embed
.i(token)?
.reshape((1, 1, text.hidden_size))?
.repeat((1, 1, text.hc_count))?
.contiguous()?;
let split = hc.split(&h)?;
let inject = split
.inject
.as_ref()
.context("a decoder hyper-connection injects")?;
let (cos, sin) = rotary.plain_cos_sin(step, 1)?;
let mixed = candle_attn.forward(&split.input, None, &cos, &sin, step)?;
let want = hc.combine(&split.residual, &mixed, inject)?;
// A deliberate fault: positions one ahead of candle's.
let shift = i32::from(std::env::var_os("PROBE_FAULT_POSITION").is_some());
cuda.memcpy_htod(&[step as i32 + shift; 32], &mut positions)?;
let h32 = h.to_dtype(DType::F32)?.contiguous()?;
attn::forward(
&weights,
&mut cache,
&mut scratch,
&shapes,
&ashapes,
positions.device_ptr(positions.stream()).0,
address(&h32)?,
out.device_ptr(out.stream()).0,
stream,
)?;
cuda.cuda_stream().synchronize()?;
let input: Vec<f32> = h32.flatten_all()?.to_vec1()?;
let want: Vec<f32> = want.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
let got = cuda.clone_dtoh(&out)?;
let delta = |r: &[f32]| -> Vec<f32> { r.iter().zip(&input).map(|(a, b)| a - b).collect() };
let err = rel(&delta(&got), &delta(&want));
worst = worst.max(err);
println!(
"layer {layer} attn step {step} token {token}: contribution rel err {err:.3e}, |out-in| {:.3e}",
delta(&want)
.iter()
.map(|v| f64::from(*v).powi(2))
.sum::<f64>()
.sqrt()
);
}
println!("layer {layer} attn: worst {worst:.3e} over {steps} steps");
Ok(())
}
+326
View File
@@ -0,0 +1,326 @@
//! Checks the native decode step (#427) end to end against candle's
//! model, on the real checkpoint and GGUF.
//!
//! ```sh
//! NEURON_EXPERT_DEVICE_ROUTING=1 neuron-engine-step-probe GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [STEPS]
//! ```
//!
//! Decodes a fixed token sequence from position 0 through both, one token
//! at a time, and compares each step's next-token distribution: KL from
//! candle's to the engine's, and whether the top token agrees. Both share
//! one expert source (and its VRAM tier, if NEURON_EXPERT_CACHE_MB is set) and the
//! GGUF's Q8_0 dense projections; candle runs in BF16 as served. The
//! engine takes PLE's contribution from candle's own PLE block, run on the
//! engine's residual, and candle's state is restored around that so its
//! own forward sees each token once.
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use candle_core::cuda_backend::cudarc::driver::DevicePtr;
use candle_core::{CudaStorage, DType, Device, Storage, Tensor};
use candle_nn::var_builder::ShardedSafeTensors;
use neuron::harness::arch::qwen3_5::proj::LinearSource;
use neuron::harness::arch::qwen4_exp::config::Config;
use neuron::harness::arch::qwen4_exp::engine::decoder::NativeDecoder;
use neuron::harness::arch::qwen4_exp::engine::weights::Gguf;
use neuron::harness::arch::qwen4_exp::gguf_dense::{GgufDenseSource, Heads};
use neuron::harness::arch::qwen4_exp::model::Qwen4ExpForCausalLM;
use neuron::harness::arch::qwen4_exp::native_experts::{GgufExpertSource, NativeExpertFactory};
fn softmax(x: &[f32]) -> Vec<f64> {
let m = x.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let e: Vec<f64> = x.iter().map(|&v| f64::from(v - m).exp()).collect();
let z: f64 = e.iter().sum();
e.into_iter().map(|v| v / z).collect()
}
fn argmax(x: &[f32]) -> usize {
x.iter()
.enumerate()
.max_by(|a, b| a.1.total_cmp(b.1))
.map_or(0, |(i, _)| i)
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
bail!(
"usage: {} GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [STEPS]",
args[0]
);
}
if std::env::var("NEURON_EXPERT_DEVICE_ROUTING").as_deref() != Ok("1") {
bail!("needs NEURON_EXPERT_DEVICE_ROUTING=1");
}
let (gguf_path, hf) = (Path::new(&args[1]), Path::new(&args[2]));
let steps: usize = args.get(3).map_or(Ok(16), |v| v.parse())?;
let device = Device::new_cuda(0)?;
let cuda = device.as_cuda_device()?.clone();
let cfg = Config::from_config_json(
&std::fs::read_to_string(hf.join("config.json")).context("read config.json")?,
)?;
let text = &cfg.text_config;
let experts = Arc::new(GgufExpertSource::open(
gguf_path,
&device,
text.num_hidden_layers,
text.num_experts,
text.hidden_size,
text.moe_intermediate_size,
// NEURON_EXPERT_CACHE_MB, as served: a VRAM tier (filled from
// NEURON_EXPERT_PROFILE) changes where experts are read, not what
// they compute.
neuron::harness::arch::qwen3_5::expert_tier::configured_budget_mb(),
)?);
let dense: Arc<dyn LinearSource> = Arc::new(GgufDenseSource::open(
gguf_path,
&device,
Heads {
key_heads: text.linear_num_key_heads,
value_heads: text.linear_num_value_heads,
head_dim: text.linear_value_head_dim,
},
text.linear_num_key_heads * text.linear_key_head_dim,
)?);
let mut paths: Vec<_> = std::fs::read_dir(hf)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|x| x == "safetensors"))
.collect();
paths.sort();
// SAFETY: the checkpoint is not modified while mapped.
let vb = unsafe { ShardedSafeTensors::var_builder(&paths, DType::BF16, &device)? };
let mut model = Qwen4ExpForCausalLM::load(
&cfg,
DType::BF16,
&device,
&vb,
&neuron::harness::arch::qwen4_exp::LoadOptions {
quant: None,
safetensors_paths: &paths,
isq_cache: None,
experts_onto: &Device::Cpu,
experts_vb: None,
expert_tier: None,
external_experts: Some(Arc::new(NativeExpertFactory(experts.clone()))),
dense: Some(dense),
},
)?;
let gguf = Gguf::open(gguf_path, &cuda)?;
let mut engine = NativeDecoder::load(&gguf, text, experts.clone(), steps.max(16))?;
let wide = text.hidden_size * text.hc_count;
// PROBE_TOKENS: a comma-separated id file (a real prompt); else a
// fixed synthetic sequence. PROBE_DUMP_DIR: each step's logits as
// e<pos>.f32 (engine) and c<pos>.f32 (candle), for comparing both
// against another engine on the same prefix.
let tokens: Vec<u32> = match std::env::var_os("PROBE_TOKENS") {
Some(path) => std::fs::read_to_string(path)?
.trim()
.split(',')
.take(steps)
.map(|t| t.trim().parse())
.collect::<Result<_, _>>()?,
None => (0..steps)
.map(|i| (1000 + 7919 * i) as u32 % 150_000)
.collect(),
};
let dump = std::env::var_os("PROBE_DUMP_DIR").map(std::path::PathBuf::from);
let write = |name: String, values: &[f32]| -> Result<()> {
if let Some(dir) = &dump {
let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
std::fs::write(dir.join(name), bytes)?;
}
Ok(())
};
if let Some(n) = std::env::var("PROBE_TIMING")
.ok()
.and_then(|v| v.parse::<usize>().ok())
{
return time_steps(
&mut engine,
&mut model,
&cuda,
&tokens,
n.min(tokens.len()),
wide,
);
}
let (mut kl_sum, mut agree, mut worst, mut kl_head_sum) = (0f64, 0usize, 0f64, 0f64);
let lm_head = vb
.pp("lm_head")
.get((text.vocab_size, text.hidden_size), "weight")?;
for (pos, &token) in tokens.iter().enumerate() {
let ids = Tensor::new(&[[token]], &device)?;
let snapshot = model.snapshot_kv_cache()?;
engine.set_step(token, pos)?;
engine.segment_head()?;
// SAFETY: written in full by the copy below.
let mut copy = unsafe { cuda.alloc::<f32>(wide)? };
cuda.memcpy_dtod(engine.residual(), &mut copy)?;
let residual = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(copy, cuda.clone())),
(1, 1, wide),
));
if let Some(ple) = model.ple_contribution(&ids, &residual)? {
let ple = ple.to_dtype(DType::F32)?.contiguous()?;
let (storage, layout) = ple.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
bail!("PLE ran off the GPU");
};
let slice = storage.as_cuda_slice::<f32>()?;
engine.add_to_residual(
slice.device_ptr(slice.stream()).0 + (layout.start_offset() * 4) as u64,
)?;
}
engine.segment_tail()?;
let got = engine.logits()?;
// The engine's final hidden state through candle's own BF16 head:
// separates the Q6_K head from everything before it.
// SAFETY: written in full by the copy below.
let mut mixed = unsafe { cuda.alloc::<f32>(text.hidden_size)? };
cuda.memcpy_dtod(engine.mixed(), &mut mixed)?;
let mixed = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(mixed, cuda.clone())),
(1, text.hidden_size),
));
let via_head: Vec<f32> = mixed
.to_dtype(DType::BF16)?
.matmul(&lm_head.t()?)?
.to_dtype(DType::F32)?
.flatten_all()?
.to_vec1()?;
model.restore_kv_cache(&snapshot)?;
let want: Vec<f32> = model
.forward(&ids, pos)?
.to_dtype(DType::F32)?
.flatten_all()?
.to_vec1()?;
let kl_of = |p: &[f64], q: &[f64]| -> f64 {
p.iter()
.zip(q)
.filter(|(a, _)| **a > 0.0)
.map(|(a, b)| a * (a / b.max(1e-30)).ln())
.sum()
};
write(format!("e{pos}.f32"), &got)?;
write(format!("c{pos}.f32"), &want)?;
let p = softmax(&want);
let kl = kl_of(&p, &softmax(&got));
let kl_head = kl_of(&p, &softmax(&via_head));
kl_head_sum += kl_head;
let same = argmax(&want) == argmax(&got);
kl_sum += kl;
agree += usize::from(same);
worst = worst.max(kl);
println!(
"pos {pos} token {token}: KL {kl:.4e} (BF16 head {kl_head:.4e}) top1 candle {} engine {} {}",
argmax(&want),
argmax(&got),
if same { "same" } else { "DIFFERENT" }
);
}
println!(
"{steps} steps: mean KL {:.4e} (through candle's BF16 head {:.4e}), worst {worst:.4e}, top-1 agree {agree}/{steps}",
kl_sum / steps as f64,
kl_head_sum / steps as f64
);
Ok(())
}
/// Engine-only decode timing: the same tokens eagerly, then with each
/// segment replayed from its graph. Per step: write the inputs, adapt the
/// tier, segment one, PLE (eager, on the host-gathered n-grams), segment
/// two, read the logits.
fn time_steps(
engine: &mut NativeDecoder,
model: &mut Qwen4ExpForCausalLM,
cuda: &candle_core::CudaDevice,
tokens: &[u32],
n: usize,
wide: usize,
) -> Result<()> {
let device = Device::Cuda(cuda.clone());
let mut eager_logits: Vec<Vec<f32>> = Vec::new();
for graphs in [false, true] {
engine.reset()?;
model.clear_kv_cache()?;
let mut times = Vec::with_capacity(n);
let mut first = Vec::new();
let (mut worst_kl, mut agree) = (0f64, 0usize);
for (pos, &token) in tokens.iter().take(n).enumerate() {
let started = std::time::Instant::now();
let ids = Tensor::new(&[[token]], &device)?;
engine.set_step(token, pos)?;
engine.adapt()?;
if graphs {
engine.run_head()?;
} else {
engine.segment_head()?;
}
// SAFETY: written in full by the copy below.
let mut copy = unsafe { cuda.alloc::<f32>(wide)? };
cuda.memcpy_dtod(engine.residual(), &mut copy)?;
let residual = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(copy, cuda.clone())),
(1, 1, wide),
));
if let Some(ple) = model.ple_contribution(&ids, &residual)? {
let ple = ple.to_dtype(DType::F32)?.contiguous()?;
let (storage, layout) = ple.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
bail!("PLE ran off the GPU");
};
let slice = storage.as_cuda_slice::<f32>()?;
engine.add_to_residual(
slice.device_ptr(slice.stream()).0 + (layout.start_offset() * 4) as u64,
)?;
}
if graphs {
engine.run_tail()?;
} else {
engine.segment_tail()?;
}
let logits = engine.logits()?;
times.push(started.elapsed().as_secs_f64() * 1e3);
if graphs {
let (p, q) = (softmax(&eager_logits[pos]), softmax(&logits));
let kl: f64 = p
.iter()
.zip(&q)
.filter(|(a, _)| **a > 0.0)
.map(|(a, b)| a * (a / b.max(1e-30)).ln())
.sum();
worst_kl = worst_kl.max(kl);
agree += usize::from(argmax(&eager_logits[pos]) == argmax(&logits));
} else {
eager_logits.push(logits.clone());
}
if pos == 0 {
first = logits;
}
}
let steady: Vec<f64> = times.iter().skip(3).copied().collect();
let mean = steady.iter().sum::<f64>() / steady.len().max(1) as f64;
println!(
"{}: {n} tokens, steady {mean:.2} ms/token ({:.1} tok/s); first-step top-1 {}",
if graphs { "graphs" } else { "eager " },
1e3 / mean,
argmax(&first)
);
if graphs {
println!(
"graphs vs eager over {n} steps: worst KL {worst_kl:.3e}, top-1 agree {agree}/{n}"
);
}
}
Ok(())
}
@@ -0,0 +1,54 @@
//! Checks the vendored Strata expert kernels against real GGUF weights.
//!
//! ```sh
//! neuron-strata-expert-probe SHARD GU_TYPE DOWN_TYPE GATE_OFF UP_OFF DOWN_OFF [EXPERT] [TOKENS]
//! ```
//!
//! Offsets are the absolute file offsets of the layer's fused tensors.
use std::ffi::CString;
use neuron::cuda::strata::neuron_strata_expert_probe;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 7 {
eprintln!(
"usage: {} SHARD GU DOWN GATE_OFF UP_OFF DOWN_OFF [EXPERT] [TOKENS]",
args[0]
);
std::process::exit(64);
}
let int = |i: usize, default: u64| -> u64 {
args.get(i)
.map(|v| v.parse().expect("integer argument"))
.unwrap_or(default)
};
let path = CString::new(args[1].as_str()).expect("path");
let (mut error, mut ms) = (f64::NAN, f64::NAN);
let (expert, tokens) = (int(7, 0) as i32, int(8, 8) as i32);
// SAFETY: the path is NUL-terminated and both out-pointers are live
// for the call; the probe owns every device allocation it makes.
let rc = unsafe {
neuron_strata_expert_probe(
path.as_ptr(),
int(2, 0) as i32,
int(3, 0) as i32,
int(4, 0),
int(5, 0),
int(6, 0),
expert,
tokens,
&mut error,
&mut ms,
)
};
if rc != 0 {
eprintln!("probe failed: code {rc}");
std::process::exit(rc);
}
println!(
"gu={} down={} expert={expert} tokens={tokens} relative_error={error:.5} kernel_ms={ms:.3}",
args[2], args[3]
);
}
+12
View File
@@ -60,6 +60,10 @@ pub struct NeuronConfig {
/// don't prevent the rest of the fleet from starting.
#[serde(default)]
pub default_models: Vec<ModelSpec>,
/// When this host is powered (#397), for hosts that leave the mesh
/// on a schedule.
#[serde(default)]
pub availability: crate::availability::AvailabilityConfig,
}
/// Settings for individual harness implementations. Each harness owns
@@ -184,6 +188,13 @@ pub struct AudioConfig {
/// the model's own limit.
#[serde(default)]
pub max_duration_secs: Option<f64>,
/// Load a copy of each music model on several devices (#397):
/// `"per-device"` for every card, or a list of device indices. One
/// render runs on each copy at once, so a rig of identical cards
/// serves as many songs in parallel as it has cards. A model's own
/// `replicas` in its load spec wins.
#[serde(default)]
pub replicas: Option<cortex_core::harness::Replicas>,
}
/// Per-component placement (#385): `"gpu"` (the model's device, the
@@ -594,6 +605,7 @@ impl Default for NeuronConfig {
harnesses: vec![],
harness: HarnessSettings::default(),
default_models: vec![],
availability: Default::default(),
}
}
}
+2
View File
@@ -13,3 +13,5 @@
pub mod ffi;
#[cfg(feature = "cuda")]
pub mod gdn;
#[cfg(feature = "strata-kernels")]
pub mod strata;
+316
View File
@@ -0,0 +1,316 @@
//! FFI to the expert kernels vendored from Strata (`vendor/strata`).
//!
//! Pointers are device addresses unless a parameter says otherwise, and
//! `stream` is a CUDA stream handle (null for the default stream).
use std::ffi::{c_char, c_void};
unsafe extern "C" {
/// Parity of two real experts against a CPU recomputation. Returns 0
/// on success.
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_expert_probe(
path: *const c_char,
gu: i32,
down: i32,
gate_off: u64,
up_off: u64,
down_off: u64,
first_expert: i32,
tokens: i32,
relative_error: *mut f64,
kernel_ms: *mut f64,
) -> i32;
pub fn neuron_strata_pinned_alloc(bytes: usize) -> *mut c_void;
pub fn neuron_strata_pinned_free(p: *mut c_void);
/// Queues a copy on `stream`. `pinned_src` must stay unchanged until
/// the stream has passed it. Returns the CUDA status.
pub fn neuron_strata_copy_to_device(
dst: *mut c_void,
pinned_src: *const c_void,
bytes: usize,
stream: *mut c_void,
) -> i32;
/// Page-locked host memory mapped into the device's address space,
/// or null. Freed with `neuron_strata_pinned_free`.
pub fn neuron_strata_host_alloc_mapped(bytes: usize) -> *mut c_void;
/// The device address of mapped host memory, or 0.
pub fn neuron_strata_host_device_ptr(host: *mut c_void) -> u64;
/// Queues `*entry = value` on `stream`. Returns the CUDA status.
pub fn neuron_strata_table_set(entry: *mut u64, value: u64, stream: *mut c_void) -> i32;
/// Builds the grouped expert kernel's arrays from one layer's
/// routing (`ids`, `w`: rows x k) and its expert address table.
/// Experts whose entry equals `host_table`'s are given arena slots
/// and listed in `miss_src`; a null `host_table` disables that.
/// Returns the CUDA status, or -1 for too many experts.
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_route_groups(
ids: *const u32,
w: *const f32,
rows: i32,
k: i32,
table: *const u64,
host_table: *const u64,
arena: u64,
blob_bytes: u64,
n_experts: i32,
grp_ptr: *mut u64,
grp_start: *mut i32,
n_groups: *mut i32,
ent_dst: *mut i32,
ent_tok: *mut i32,
w_out: *mut f32,
miss_src: *mut u64,
n_miss: *mut i32,
stream: *mut c_void,
) -> i32;
/// Copies the first `*n_miss` of `src`'s blobs (`bytes` each) to
/// consecutive slots at `dst`; `cap` bounds the launch.
pub fn neuron_strata_gather_blobs(
src: *const u64,
n_miss: *const i32,
cap: i32,
dst: u64,
bytes: u64,
stream: *mut c_void,
) -> i32;
/// `cudaGetLastError`: the error of the most recent failing call,
/// cleared by reading.
pub fn neuron_strata_last_error() -> i32;
/// Queues a kernel copying `n` 32-bit words (`dst` may be the device
/// address of mapped pinned host memory).
pub fn neuron_strata_copy_words(
dst: *mut u32,
src: *const u32,
n: i32,
stream: *mut c_void,
) -> i32;
/// Queues a device-to-host copy into pinned memory.
pub fn neuron_strata_copy_to_host(
pinned_dst: *mut c_void,
src: *const c_void,
bytes: usize,
stream: *mut c_void,
) -> i32;
pub fn neuron_strata_event_new() -> *mut c_void;
pub fn neuron_strata_event_record(event: *mut c_void, stream: *mut c_void) -> i32;
pub fn neuron_strata_event_sync(event: *mut c_void) -> i32;
pub fn neuron_strata_event_free(event: *mut c_void);
pub fn neuron_strata_expert_supported(gu_type: i32, d_type: i32, n_embd: i64, n_ff: i64)
-> i32;
pub fn neuron_strata_row_bytes(ggml_type: i32, n: i64) -> usize;
pub fn neuron_strata_expert_bytes(gu_type: i32, d_type: i32, n_embd: i64, n_ff: i64) -> usize;
pub fn neuron_strata_expert_scratch_bytes(cap_entries: i64, n_ff: i64) -> usize;
pub fn neuron_strata_quantize_q8_1(
x: *const f32,
n_rows: i64,
n_cols: i64,
y: *mut c_void,
stream: *mut c_void,
);
/// Whether `neuron_strata_mmvq` takes weights of `ggml_type`.
pub fn neuron_strata_mmvq_supported(ggml_type: i32) -> i32;
/// `y[c][r] = W[r] . x[c]` for `ncols` q8_1 activation rows.
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_mmvq(
ggml_type: i32,
w: *const c_void,
x_q8_1: *const c_void,
y: *mut f32,
n_in: i32,
n_out: i32,
ncols: i32,
stream: *mut c_void,
);
pub fn neuron_strata_dequant_f32(
ggml_type: i32,
src: *const c_void,
n: i64,
dst: *mut f32,
stream: *mut c_void,
);
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_expert_grouped(
gu_type: i32,
d_type: i32,
n_embd: i64,
n_ff: i64,
grp_ptr: *const u64,
grp_start: *const i32,
n_groups: *const i32,
ent_dst: *const i32,
ent_tok: *const i32,
cap_groups: i64,
cap_entries: i64,
x_q8_1: *const c_void,
scratch: *mut c_void,
out: *mut f32,
stream: *mut c_void,
);
// ---- the native decode engine's kernels (#427): see engine_shim.cu.
// Each returns 0, a CUDA error code, or -1 with a message from
// `neuron_engine_last_error`.
pub fn neuron_engine_last_error() -> *const c_char;
pub fn neuron_engine_configure();
pub fn neuron_gr_workspace_bytes(n_embd: i64, hc: i64, hc_lr: i64) -> usize;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gr_read(
residual: *const f32,
w_norm: *const f32,
w_down: *const u16,
w_up: *const u16,
w_inject: *const u16,
eps: f32,
n_embd: i64,
hc: i64,
hc_lr: i64,
workspace: *mut c_void,
mixed: *mut f32,
inject: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gr_write(
residual: *const f32,
block_out: *const f32,
inject: *const f32,
n_embd: i64,
hc: i64,
hc_lr: i64,
residual_out: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_conv_l2(
history: *mut f32,
qkv: *const f32,
conv_w: *const f32,
h: *mut f32,
channels: i32,
qk_heads: i32,
eps: f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_ab(
x: *const f32,
w_alpha: *const u16,
w_beta: *const u16,
dt: *const f32,
ssm_a: *const f32,
gate: *mut f32,
beta: *mut f32,
n_embd: i32,
h_v: i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_step_norm(
state: *mut f32,
q: *const f32,
k: *const f32,
v: *const f32,
gate: *const f32,
beta: *const f32,
z: *const f32,
gamma: *const f32,
eps: f32,
y: *mut f32,
h_k: i32,
h_v: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_bf16_gemv(
x: *const f32,
w: *const u16,
y: *mut f32,
n_in: i64,
n_out: i64,
stream: *mut c_void,
) -> i32;
pub fn neuron_router_top10(
logits: *const f32,
ids: *mut i32,
weights: *mut f32,
stream: *mut c_void,
) -> i32;
pub fn neuron_moe_combine(
parts: *const f32,
weights: *const f32,
shared: *const f32,
output: *mut f32,
n_embd: i64,
k: i64,
stream: *mut c_void,
) -> i32;
pub fn neuron_swiglu(
gate: *const f32,
up: *const f32,
out: *mut f32,
n: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_scale_by_sigmoid(
x: *mut f32,
gate: *const f32,
n: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_append_rows(
src_a: *const f32,
src_b: *const f32,
dst_a: *mut f32,
dst_b: *mut f32,
pos: *const i32,
width: i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_decode_attn(
q: *const f32,
kc: *const f32,
vc: *const f32,
pos: *const i32,
heads: i32,
kv_heads: i32,
head_dim: i32,
scale: f32,
gate: *const f32,
gate_stride: i32,
out: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_norm_rope(
x: *const f32,
in_stride: i32,
gamma: *const f32,
out: *mut f32,
rows: i32,
head_dim: i32,
n_rot: i32,
eps: f32,
positions: *const i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_embed_rows(
ggml_type: i32,
table: *const c_void,
row_bytes: usize,
tokens: *const i32,
n_tok: i64,
n_embd: i64,
out: *mut f32,
stream: *mut c_void,
) -> i32;
pub fn neuron_repeat_row(
src: *const f32,
dst: *mut f32,
n: i32,
times: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_add_inplace(x: *mut f32, y: *const f32, n: i32, stream: *mut c_void) -> i32;
}
@@ -0,0 +1,307 @@
// C ABI over the vendored Strata decode kernels the native qwen4_exp
// engine drives (#427): linear attention, the hyper-connection, the
// router, the MoE combine and the BF16 projections.
//
// Several of these throw on invalid geometry. An exception must not
// unwind into Rust, so every entry point catches and returns a status:
// 0 on success, otherwise a CUDA error code or -1 for a thrown error,
// whose message `neuron_engine_last_error` returns.
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <exception>
#include <stdexcept>
#include <string>
#include <cuda_runtime.h>
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/fused_gdn.hpp"
#include "strata/kernels/gr.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/native_gdn.hpp"
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/native_router.hpp"
#include "strata/kernels/pdl.hpp"
namespace k = strata::kernels;
// Programmatic dependent launch is defined upstream in verify_kernels.cu,
// with the verify-window machinery the engine does not use. With
// `pdl_scope()` off, `launch_pdl` takes its ordinary launch, which is all
// the decode kernels need; PDL comes in with the verify windows (#313).
namespace strata::kernels {
bool& pdl_scope() {
static thread_local bool on = false;
return on;
}
bool pdl_supported() { return false; }
bool pdl_launch_ok(const void*, cudaStream_t) { return false; }
} // namespace strata::kernels
namespace {
thread_local std::string g_last_error;
template <typename F>
int guarded(F&& f) {
try {
f();
} catch (const std::exception& e) {
g_last_error = e.what();
return -1;
} catch (...) {
g_last_error = "unknown exception";
return -1;
}
const cudaError_t status = cudaGetLastError();
if (status != cudaSuccess) {
g_last_error = cudaGetErrorString(status);
return (int) status;
}
return 0;
}
// The shared expert's elementwise steps, which upstream fuses into code
// the engine does not vendor: SiLU(gate) * up, and scaling the expert's
// output by the sigmoid of its one-scalar gate.
__global__ void swiglu_kernel(const float* gate, const float* up, float* out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
const float g = gate[i];
out[i] = g / (1.0f + expf(-g)) * up[i];
}
}
__global__ void scale_by_sigmoid_kernel(float* x, const float* gate, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] *= 1.0f / (1.0f + expf(-gate[0]));
}
// ---- dense decode attention over a cache allocated once (#427).
//
// The cache is `[position][kv_head][head_dim]` f32. The current position
// lives in device memory (`pos[0]`), so nothing here takes a per-token
// argument and the step can be captured.
// Writes one token's rows (`width` floats each, `src_b` optional) into
// `dst_a[pos * width]` and `dst_b[pos * width]`.
__global__ void append_rows_kernel(const float* src_a, const float* src_b, float* dst_a, float* dst_b,
const int* pos, int width) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= width) return;
const size_t at = (size_t) pos[0] * width + i;
dst_a[at] = src_a[i];
if (src_b != nullptr) dst_b[at] = src_b[i];
}
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
// One block of 8 warps per query head, D = 256 (8 values per lane). Each
// warp takes positions w, w + 8, ... up to pos[0], keeping an online
// softmax; the warps' partial results are merged at the end. The output
// is multiplied by sigmoid(gate) (Qwen's per-head output gate), the gate
// row of head h at `gate[h * gate_stride]`.
template <int D>
__global__ void __launch_bounds__(256) decode_attn_kernel(const float* q, const float* kc, const float* vc,
const int* pos, int kv_heads, int group, float scale,
const float* gate, int gate_stride, float* out) {
constexpr int PER = D / 32;
constexpr int WARPS = 8;
const int h = blockIdx.x, kvh = h / group;
const int warp = threadIdx.x / 32, lane = threadIdx.x % 32;
const int n = pos[0] + 1;
float qv[PER], acc[PER];
#pragma unroll
for (int i = 0; i < PER; ++i) {
qv[i] = q[(size_t) h * D + lane * PER + i];
acc[i] = 0.0f;
}
float m = -INFINITY, l = 0.0f;
for (int p = warp; p < n; p += WARPS) {
const float* kr = kc + ((size_t) p * kv_heads + kvh) * D + lane * PER;
float dot = 0.0f;
#pragma unroll
for (int i = 0; i < PER; ++i) dot += qv[i] * kr[i];
const float sc = warp_sum(dot) * scale;
const float m_new = fmaxf(m, sc);
const float corr = expf(m - m_new), e = expf(sc - m_new);
l = l * corr + e;
const float* vr = vc + ((size_t) p * kv_heads + kvh) * D + lane * PER;
#pragma unroll
for (int i = 0; i < PER; ++i) acc[i] = acc[i] * corr + e * vr[i];
m = m_new;
}
__shared__ float s_m[WARPS], s_l[WARPS];
__shared__ float s_acc[WARPS][D];
if (lane == 0) {
s_m[warp] = m;
s_l[warp] = l;
}
#pragma unroll
for (int i = 0; i < PER; ++i) s_acc[warp][lane * PER + i] = acc[i];
__syncthreads();
float mx = -INFINITY;
#pragma unroll
for (int w = 0; w < WARPS; ++w) mx = fmaxf(mx, s_m[w]);
float total = 0.0f;
#pragma unroll
for (int w = 0; w < WARPS; ++w) total += s_m[w] == -INFINITY ? 0.0f : s_l[w] * expf(s_m[w] - mx);
for (int d = threadIdx.x; d < D; d += blockDim.x) {
float v = 0.0f;
#pragma unroll
for (int w = 0; w < WARPS; ++w)
if (s_m[w] != -INFINITY) v += s_acc[w][d] * expf(s_m[w] - mx);
const float g = gate[(size_t) h * gate_stride + d];
out[(size_t) h * D + d] = v / total * (1.0f / (1.0f + expf(-g)));
}
}
// `dst` = `times` copies of the `n`-float row `src` (the embedding into
// every residual stream).
__global__ void repeat_row_kernel(const float* src, float* dst, int n, int times) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n * times) dst[i] = src[i % n];
}
__global__ void add_inplace_kernel(float* x, const float* y, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] += y[i];
}
k::GrShapes gr_shapes(int64_t n_embd, int64_t hc, int64_t hc_lr) {
k::GrShapes s;
s.n_embd = n_embd;
s.hc = hc;
s.hc_lr = hc_lr;
return s;
}
} // namespace
extern "C" {
const char* neuron_engine_last_error() { return g_last_error.c_str(); }
/// Selects the pinned single-token FP32 contract for the hyper-connection
/// and GDN kernels, as Strata's decode does. Call before any capture.
void neuron_engine_configure() {
k::gr_set_native_mmvf(true);
k::native_gdn_set_enabled(true);
k::native_router_set_enabled(true);
k::native_moe_combine_set_enabled(true);
}
size_t neuron_gr_workspace_bytes(int64_t n_embd, int64_t hc, int64_t hc_lr) {
return k::gr_workspace_bytes(gr_shapes(n_embd, hc, hc_lr));
}
int neuron_gr_read(const float* residual, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, int64_t n_embd, int64_t hc, int64_t hc_lr, void* workspace,
float* mixed, float* inject, void* stream) {
return guarded([&] {
const k::GrShapes s = gr_shapes(n_embd, hc, hc_lr);
k::GrWorkspace ws;
k::gr_workspace_init(s, workspace, ws);
k::gr_read(residual, w_norm, w_down, w_up, w_inject, eps, s, ws, mixed, inject, stream);
});
}
int neuron_gr_write(const float* residual, const float* block_out, const float* inject, int64_t n_embd, int64_t hc,
int64_t hc_lr, float* residual_out, void* stream) {
return guarded([&] {
k::gr_write(residual, block_out, inject, gr_shapes(n_embd, hc, hc_lr), residual_out, stream);
});
}
int neuron_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
float eps, void* stream) {
return guarded([&] { k::fused_gdn_conv_l2(history, qkv, conv_w, h, channels, qk_heads, eps, stream); });
}
int neuron_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt,
const float* ssm_a, float* gate, float* beta, int n_embd, int h_v, void* stream) {
return guarded([&] { k::fused_gdn_ab(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, stream); });
}
int neuron_gdn_step_norm(float* state, const float* q, const float* k_, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
void* stream) {
return guarded(
[&] { k::fused_gdn_step_norm(state, q, k_, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream); });
}
int neuron_bf16_gemv(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream) {
return guarded([&] { k::bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); });
}
int neuron_router_top10(const float* logits, int32_t* ids, float* weights, void* stream) {
return guarded([&] { k::native_router_top10(logits, ids, weights, stream); });
}
int neuron_moe_combine(const float* parts, const float* weights, const float* shared, float* output, int64_t n_embd,
int64_t k_, void* stream) {
return guarded([&] { k::native_moe_combine(parts, weights, shared, output, n_embd, k_, stream); });
}
int neuron_append_rows(const float* src_a, const float* src_b, float* dst_a, float* dst_b, const int* pos, int width,
void* stream) {
return guarded([&] {
append_rows_kernel<<<(width + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(src_a, src_b, dst_a,
dst_b, pos, width);
});
}
int neuron_decode_attn(const float* q, const float* kc, const float* vc, const int* pos, int heads, int kv_heads,
int head_dim, float scale, const float* gate, int gate_stride, float* out, void* stream) {
return guarded([&] {
if (head_dim != 256 || heads % kv_heads != 0) throw std::invalid_argument("decode attention: head_dim 256 only");
decode_attn_kernel<256><<<heads, 256, 0, static_cast<cudaStream_t>(stream)>>>(
q, kc, vc, pos, kv_heads, heads / kv_heads, scale, gate, gate_stride, out);
});
}
int neuron_norm_rope(const float* x, int in_stride, const float* gamma, float* out, int rows, int head_dim, int n_rot,
float eps, const int* positions, void* stream) {
return guarded([&] {
const k::RopeScaling scaling{};
k::native_qsa_rms_norm_rope(x, in_stride, gamma, out, rows, head_dim, n_rot, eps, scaling, positions, stream);
});
}
int neuron_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,
int64_t n_embd, float* out, void* stream) {
return guarded([&] { k::iq_embed_rows(ggml_type, table, row_bytes, tokens, n_tok, n_embd, out, stream); });
}
int neuron_repeat_row(const float* src, float* dst, int n, int times, void* stream) {
return guarded([&] {
repeat_row_kernel<<<(n * times + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(src, dst, n, times);
});
}
int neuron_add_inplace(float* x, const float* y, int n, void* stream) {
return guarded([&] {
add_inplace_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(x, y, n);
});
}
int neuron_swiglu(const float* gate, const float* up, float* out, int n, void* stream) {
return guarded([&] {
swiglu_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(gate, up, out, n);
});
}
int neuron_scale_by_sigmoid(float* x, const float* gate, int n, void* stream) {
return guarded([&] {
scale_by_sigmoid_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(x, gate, n);
});
}
} // extern "C"
@@ -0,0 +1,164 @@
// Parity probe for the vendored expert kernels on real GGUF weights.
//
// Runs two experts over random activations through the grouped kernels,
// then recomputes the SwiGLU on the CPU from independently dequantised
// weights. The kernels read 8-bit activations, so a small error is
// expected; a wrong layout or block format produces a large one.
#include <cuda_runtime.h>
#include <fcntl.h>
#include <unistd.h>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
#include "strata/kernels/iq_kernels.hpp"
namespace k = strata::kernels;
namespace {
constexpr int64_t kEmbd = 2560;
constexpr int64_t kFf = 640;
constexpr size_t kQ81Block = 36; // fp16 scale, fp16 sum, 32 int8 values
template <typename T>
T* device_alloc(size_t count) {
T* p = nullptr;
if (cudaMalloc(&p, count * sizeof(T)) != cudaSuccess) return nullptr;
return p;
}
bool read_at(int fd, uint8_t* dst, size_t bytes, uint64_t offset) {
size_t done = 0;
while (done < bytes) {
const ssize_t n = pread(fd, dst + done, bytes - done, offset + done);
if (n <= 0) return false;
done += static_cast<size_t>(n);
}
return true;
}
std::vector<float> dequant(int type, const uint8_t* device_src, int64_t n) {
float* d = device_alloc<float>(n);
std::vector<float> host(n);
k::iq_dequant_f32(type, device_src, n, d, nullptr);
cudaMemcpy(host.data(), d, n * sizeof(float), cudaMemcpyDeviceToHost);
cudaFree(d);
return host;
}
float silu(float x) { return x / (1.0f + std::exp(-x)); }
} // namespace
extern "C" int neuron_strata_expert_probe(const char* path, int gu, int dn, uint64_t gate_off, uint64_t up_off,
uint64_t down_off, int first_expert, int tokens, double* relative_error,
double* kernel_ms) {
if (!k::native_expert_supported(gu, dn, kEmbd, kFf) || tokens < 1) return 2;
const k::NativeExpertLayout L = k::native_expert_layout(gu, dn, kEmbd, kFf);
const size_t gate_bytes = kFf * L.gu_row, down_bytes = kEmbd * L.d_row;
const int fd = open(path, O_RDONLY);
if (fd < 0) return 3;
constexpr int groups = 2;
std::vector<uint8_t> blobs(groups * L.bytes);
for (int g = 0; g < groups; ++g) {
const uint64_t e = first_expert + g;
uint8_t* blob = blobs.data() + g * L.bytes;
if (!read_at(fd, blob, gate_bytes, gate_off + e * gate_bytes) ||
!read_at(fd, blob + L.up_off, gate_bytes, up_off + e * gate_bytes) ||
!read_at(fd, blob + L.down_off, down_bytes, down_off + e * down_bytes)) {
close(fd);
return 4;
}
}
close(fd);
std::mt19937 rng(1234);
std::uniform_real_distribution<float> dist(-2.0f, 2.0f);
std::vector<float> x(tokens * kEmbd);
for (float& v : x) v = dist(rng);
const int64_t entries = groups * tokens;
auto* d_blobs = device_alloc<uint8_t>(blobs.size());
auto* d_x = device_alloc<float>(x.size());
auto* d_q = device_alloc<uint8_t>(tokens * (kEmbd / 32) * kQ81Block);
auto* d_ptr = device_alloc<unsigned long long>(groups);
auto* d_start = device_alloc<int32_t>(groups + 1);
auto* d_n = device_alloc<int32_t>(1);
auto* d_dst = device_alloc<int32_t>(entries);
auto* d_tok = device_alloc<int32_t>(entries);
auto* d_out = device_alloc<float>(entries * kEmbd);
auto* d_scratch = device_alloc<uint8_t>(k::native_expert_scratch_bytes(entries, kFf));
if (!d_blobs || !d_x || !d_q || !d_ptr || !d_start || !d_n || !d_dst || !d_tok || !d_out || !d_scratch) return 5;
std::vector<unsigned long long> ptrs(groups);
std::vector<int32_t> start(groups + 1), dst(entries), tok(entries);
for (int g = 0; g < groups; ++g) {
ptrs[g] = reinterpret_cast<unsigned long long>(d_blobs + g * L.bytes);
start[g] = g * tokens;
for (int t = 0; t < tokens; ++t) {
dst[g * tokens + t] = g * tokens + t;
tok[g * tokens + t] = t;
}
}
start[groups] = entries;
const int32_t n_groups = groups;
cudaMemcpy(d_blobs, blobs.data(), blobs.size(), cudaMemcpyHostToDevice);
cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_ptr, ptrs.data(), groups * sizeof(unsigned long long), cudaMemcpyHostToDevice);
cudaMemcpy(d_start, start.data(), start.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
cudaMemcpy(d_n, &n_groups, sizeof(int32_t), cudaMemcpyHostToDevice);
cudaMemcpy(d_dst, dst.data(), dst.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
cudaMemcpy(d_tok, tok.data(), tok.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
k::quantize_q8_1_rows(d_x, tokens, kEmbd, d_q, nullptr);
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
k::native_expert_grouped(L, d_ptr, d_start, d_n, d_dst, d_tok, groups, entries, d_q, d_scratch, d_out, nullptr);
if (cudaDeviceSynchronize() != cudaSuccess) return 6;
*kernel_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
std::vector<float> out(entries * kEmbd);
cudaMemcpy(out.data(), d_out, out.size() * sizeof(float), cudaMemcpyDeviceToHost);
double err = 0.0, norm = 0.0;
std::vector<float> h(kFf);
for (int g = 0; g < groups; ++g) {
const uint8_t* blob = d_blobs + g * L.bytes;
const auto gate = dequant(L.gu_type, blob, kFf * kEmbd);
const auto up = dequant(L.gu_type, blob + L.up_off, kFf * kEmbd);
const auto down = dequant(L.d_type, blob + L.down_off, kEmbd * kFf);
for (int t = 0; t < tokens; ++t) {
const float* xt = x.data() + t * kEmbd;
for (int64_t r = 0; r < kFf; ++r) {
float a = 0.0f, b = 0.0f;
for (int64_t c = 0; c < kEmbd; ++c) {
a += gate[r * kEmbd + c] * xt[c];
b += up[r * kEmbd + c] * xt[c];
}
h[r] = silu(a) * b;
}
const float* got = out.data() + (g * tokens + t) * kEmbd;
for (int64_t r = 0; r < kEmbd; ++r) {
float y = 0.0f;
for (int64_t c = 0; c < kFf; ++c) y += down[r * kFf + c] * h[c];
err += (double(got[r]) - y) * (double(got[r]) - y);
norm += double(y) * y;
}
}
}
*relative_error = std::sqrt(err / norm);
for (void* p : {static_cast<void*>(d_blobs), static_cast<void*>(d_x), static_cast<void*>(d_q),
static_cast<void*>(d_ptr), static_cast<void*>(d_start), static_cast<void*>(d_n),
static_cast<void*>(d_dst), static_cast<void*>(d_tok), static_cast<void*>(d_out),
static_cast<void*>(d_scratch)}) {
cudaFree(p);
}
return 0;
}
@@ -0,0 +1,241 @@
// C ABI over the vendored Strata expert kernels (`vendor/strata`).
//
// Rust cannot name the C++ layout struct or its default arguments, so
// every call here takes the expert's formats and rebuilds the layout.
#include <cstddef>
#include <cstdint>
#include <cuda_runtime.h>
#include "strata/kernels/iq_kernels.hpp"
namespace k = strata::kernels;
namespace {
__global__ void table_set_kernel(unsigned long long* entry, unsigned long long value) { *entry = value; }
// Turns one layer's routing, `ids`/`w` (rows x k, row-major), into the
// grouped kernel's arrays. Groups are the routed experts in ascending id,
// entries within a group in ascending token, and each token's k outputs
// are ranked by ascending expert id: the order the host-side builder
// uses, so the arithmetic downstream is unchanged.
constexpr int kMaxExperts = 1024;
// An expert whose table entry is its host copy is a miss: it gets the
// next arena slot, and `miss_src` records where the gather copies it
// from. With `host_table` null every expert is read where the table says.
__global__ void route_groups_kernel(const uint32_t* ids, const float* w, int rows, int k,
const unsigned long long* table, const unsigned long long* host_table,
unsigned long long arena, unsigned long long blob_bytes, int n_experts,
unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups,
int32_t* ent_dst, int32_t* ent_tok, float* w_out, unsigned long long* miss_src,
int32_t* n_miss) {
__shared__ int counts[kMaxExperts];
__shared__ int base[kMaxExperts];
const int entries = rows * k;
for (int i = threadIdx.x; i < n_experts; i += blockDim.x) counts[i] = 0;
__syncthreads();
for (int e = threadIdx.x; e < entries; e += blockDim.x) {
const uint32_t x = ids[e];
if (x < (uint32_t) n_experts) atomicAdd(&counts[x], 1);
}
__syncthreads();
if (threadIdx.x == 0) {
int g = 0, off = 0, m = 0;
for (int x = 0; x < n_experts; ++x) {
const int c = counts[x];
base[x] = off;
if (c > 0) {
const unsigned long long at = table[x];
if (host_table != nullptr && at == host_table[x]) {
grp_ptr[g] = arena + (unsigned long long) m * blob_bytes;
miss_src[m] = at;
++m;
} else {
grp_ptr[g] = at;
}
grp_start[g] = off;
++g;
off += c;
}
}
grp_start[g] = off;
*n_groups = g;
if (n_miss != nullptr) *n_miss = m;
}
__syncthreads();
for (int e = threadIdx.x; e < entries; e += blockDim.x) {
const int t = e / k;
const uint32_t x = ids[e];
if (x >= (uint32_t) n_experts) continue;
int pos = base[x];
for (int tt = 0; tt < t; ++tt)
for (int jj = 0; jj < k; ++jj) pos += ids[tt * k + jj] == x;
int r = 0;
for (int jj = 0; jj < k; ++jj) r += ids[t * k + jj] < x;
const int dst = t * k + r;
ent_dst[pos] = dst;
ent_tok[pos] = t;
w_out[dst] = w[e];
}
}
// Copies blob `blockIdx.x` of the miss list into the arena, the grid's
// y dimension splitting each blob. Blocks past `*n_miss` do nothing, so
// the launch has a fixed shape whatever the routing was.
constexpr int kGatherSplit = 16;
__global__ void gather_blobs_kernel(const unsigned long long* src, const int32_t* n_miss, unsigned long long dst,
unsigned long long bytes) {
const int m = blockIdx.x;
if (m >= *n_miss) return;
const unsigned long long chunk = ((bytes + kGatherSplit - 1) / kGatherSplit + 15) & ~15ull;
const unsigned long long lo = (unsigned long long) blockIdx.y * chunk;
if (lo >= bytes) return;
const unsigned long long hi = lo + chunk < bytes ? lo + chunk : bytes;
const uint8_t* from = (const uint8_t*) src[m];
uint8_t* to = (uint8_t*) (dst + (unsigned long long) m * bytes);
const bool aligned = ((((unsigned long long) from) | ((unsigned long long) to) | lo) & 15) == 0;
unsigned long long tail = lo;
if (aligned) {
const unsigned long long words = (hi - lo) / 16;
for (unsigned long long i = threadIdx.x; i < words; i += blockDim.x)
*(uint4*) (to + lo + i * 16) = *(const uint4*) (from + lo + i * 16);
tail = lo + words * 16;
}
for (unsigned long long t = tail + threadIdx.x; t < hi; t += blockDim.x) to[t] = from[t];
}
// Copies `n` 32-bit words, e.g. into mapped pinned host memory: a kernel
// rather than a memcpy so the copy captures like any other launch.
__global__ void copy_words_kernel(uint32_t* dst, const uint32_t* src, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) dst[i] = src[i];
}
} // namespace
extern "C" {
int neuron_strata_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
return k::native_expert_supported(gu_type, d_type, n_embd, n_ff) ? 1 : 0;
}
size_t neuron_strata_row_bytes(int ggml_type, int64_t n) { return k::iq_row_bytes(ggml_type, n); }
size_t neuron_strata_expert_bytes(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
return k::native_expert_layout(gu_type, d_type, n_embd, n_ff).bytes;
}
size_t neuron_strata_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff) {
return k::native_expert_scratch_bytes(cap_entries, n_ff);
}
void neuron_strata_quantize_q8_1(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
k::quantize_q8_1_rows(x, n_rows, n_cols, y, stream);
}
int neuron_strata_mmvq_supported(int ggml_type) {
switch (ggml_type) {
// iq_kernels.cu's STRATA_MMVQ_FMTS.
case 16: case 17: case 18: case 20: case 21: case 22: case 23: case 29: case 42:
case 10: case 11: case 12: case 13: case 7: case 6: case 2: case 3: case 8: case 40:
case 144: case 145: case 146: case 147: case 148: case 149:
return 1;
default:
return 0;
}
}
void neuron_strata_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
void* stream) {
k::iq_mmvq(ggml_type, w, x_q8_1, y, n_in, n_out, ncols, stream);
}
void neuron_strata_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream) {
k::iq_dequant_f32(ggml_type, src, n, dst, stream);
}
void neuron_strata_expert_grouped(int gu_type, int d_type, int64_t n_embd, int64_t n_ff,
const unsigned long long* grp_ptr, const int32_t* grp_start,
const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok,
int64_t cap_groups, int64_t cap_entries, const void* x_q8_1, void* scratch,
float* out, void* stream) {
const k::NativeExpertLayout layout = k::native_expert_layout(gu_type, d_type, n_embd, n_ff);
k::native_expert_grouped(layout, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, cap_groups, cap_entries, x_q8_1,
scratch, out, stream);
}
void* neuron_strata_pinned_alloc(size_t bytes) {
void* p = nullptr;
return cudaHostAlloc(&p, bytes, cudaHostAllocDefault) == cudaSuccess ? p : nullptr;
}
void neuron_strata_pinned_free(void* p) { cudaFreeHost(p); }
int neuron_strata_copy_to_device(void* dst, const void* pinned_src, size_t bytes, void* stream) {
return cudaMemcpyAsync(dst, pinned_src, bytes, cudaMemcpyHostToDevice, static_cast<cudaStream_t>(stream));
}
void* neuron_strata_host_alloc_mapped(size_t bytes) {
void* p = nullptr;
return cudaHostAlloc(&p, bytes, cudaHostAllocMapped | cudaHostAllocPortable) == cudaSuccess ? p : nullptr;
}
unsigned long long neuron_strata_host_device_ptr(void* host) {
void* d = nullptr;
return cudaHostGetDevicePointer(&d, host, 0) == cudaSuccess ? (unsigned long long) d : 0ull;
}
int neuron_strata_table_set(unsigned long long* entry, unsigned long long value, void* stream) {
table_set_kernel<<<1, 1, 0, static_cast<cudaStream_t>(stream)>>>(entry, value);
return cudaGetLastError();
}
int neuron_strata_route_groups(const uint32_t* ids, const float* w, int rows, int k, const unsigned long long* table,
const unsigned long long* host_table, unsigned long long arena,
unsigned long long blob_bytes, int n_experts, unsigned long long* grp_ptr,
int32_t* grp_start, int32_t* n_groups, int32_t* ent_dst, int32_t* ent_tok, float* w_out,
unsigned long long* miss_src, int32_t* n_miss, void* stream) {
if (n_experts > kMaxExperts) return -1;
route_groups_kernel<<<1, 256, 0, static_cast<cudaStream_t>(stream)>>>(
ids, w, rows, k, table, host_table, arena, blob_bytes, n_experts, grp_ptr, grp_start, n_groups, ent_dst,
ent_tok, w_out, miss_src, n_miss);
return cudaGetLastError();
}
int neuron_strata_gather_blobs(const unsigned long long* src, const int32_t* n_miss, int cap, unsigned long long dst,
unsigned long long bytes, void* stream) {
if (cap <= 0) return 0;
gather_blobs_kernel<<<dim3((unsigned) cap, kGatherSplit), 256, 0, static_cast<cudaStream_t>(stream)>>>(
src, n_miss, dst, bytes);
return cudaGetLastError();
}
int neuron_strata_last_error() { return cudaGetLastError(); }
int neuron_strata_copy_words(uint32_t* dst, const uint32_t* src, int n, void* stream) {
copy_words_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(dst, src, n);
return cudaGetLastError();
}
int neuron_strata_copy_to_host(void* pinned_dst, const void* src, size_t bytes, void* stream) {
return cudaMemcpyAsync(pinned_dst, src, bytes, cudaMemcpyDeviceToHost, static_cast<cudaStream_t>(stream));
}
void* neuron_strata_event_new() {
cudaEvent_t e = nullptr;
return cudaEventCreateWithFlags(&e, cudaEventDisableTiming) == cudaSuccess ? (void*) e : nullptr;
}
int neuron_strata_event_record(void* event, void* stream) {
return cudaEventRecord(static_cast<cudaEvent_t>(event), static_cast<cudaStream_t>(stream));
}
int neuron_strata_event_sync(void* event) { return cudaEventSynchronize(static_cast<cudaEvent_t>(event)); }
void neuron_strata_event_free(void* event) { cudaEventDestroy(static_cast<cudaEvent_t>(event)); }
} // extern "C"
@@ -0,0 +1,357 @@
//! A byte-budgeted VRAM tier for host-resident routed experts (#318).
//!
//! A model whose experts exceed VRAM keeps all of them in host memory.
//! Routing is skewed, so a modest share of them serves most tokens, and
//! each expert held on the device is one the CPU does not have to
//! compute. The tier is shared by every MoE block of a model because the
//! budget is a property of the card and heat varies between layers.
//!
//! Slots are sized in bytes rather than counted: expert sizes differ
//! between layers and quantisation types, and a slot count sized for the
//! largest wastes VRAM on the rest.
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
/// The VRAM budget from `NEURON_EXPERT_CACHE_MB`, when one is set.
pub fn configured_budget_mb() -> Option<u64> {
std::env::var("NEURON_EXPERT_CACHE_MB")
.ok()
.and_then(|v| v.parse().ok())
.filter(|&mb| mb > 0)
}
/// `(block, expert)`. Blocks are numbered as they register.
type Key = (u32, u32);
struct Entry<T> {
value: Arc<T>,
bytes: u64,
stamp: u64,
}
/// Least-recently-used map with a byte budget.
struct ByteLru<T> {
capacity: u64,
used: u64,
clock: u64,
entries: HashMap<Key, Entry<T>>,
by_age: BTreeMap<u64, Key>,
}
impl<T> ByteLru<T> {
fn new(capacity: u64) -> Self {
Self {
capacity,
used: 0,
clock: 0,
entries: HashMap::new(),
by_age: BTreeMap::new(),
}
}
fn tick(&mut self) -> u64 {
self.clock += 1;
self.clock
}
fn get(&mut self, key: Key) -> Option<Arc<T>> {
let stamp = self.tick();
let entry = self.entries.get_mut(&key)?;
self.by_age.remove(&entry.stamp);
entry.stamp = stamp;
self.by_age.insert(stamp, key);
Some(entry.value.clone())
}
/// Bytes that must be released before `bytes` more can be held.
/// Returns how many entries were evicted.
fn make_room(&mut self, bytes: u64) -> u64 {
let mut evicted = 0;
while self.used + bytes > self.capacity {
let Some((_, key)) = self.by_age.pop_first() else {
break;
};
if let Some(entry) = self.entries.remove(&key) {
self.used -= entry.bytes;
evicted += 1;
}
}
evicted
}
fn insert(&mut self, key: Key, value: Arc<T>, bytes: u64) {
let stamp = self.tick();
self.used += bytes;
self.by_age.insert(stamp, key);
self.entries.insert(
key,
Entry {
value,
bytes,
stamp,
},
);
}
}
/// Cumulative counters, for measurement.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TierStats {
pub hits: u64,
pub misses: u64,
pub evictions: u64,
/// Lookups that may not admit: a prompt chunk's.
pub prompt_hits: u64,
pub prompt_misses: u64,
pub used_bytes: u64,
pub entries: u64,
}
struct State<T> {
lru: ByteLru<T>,
hits: u64,
misses: u64,
evictions: u64,
prompt_hits: u64,
prompt_misses: u64,
next_block: u32,
}
/// The tier itself. `T` is the device-resident expert.
pub struct ExpertTier<T> {
state: Mutex<State<T>>,
}
impl<T> ExpertTier<T> {
pub fn new(capacity_bytes: u64) -> Arc<Self> {
Arc::new(Self {
state: Mutex::new(State {
lru: ByteLru::new(capacity_bytes),
hits: 0,
misses: 0,
evictions: 0,
prompt_hits: 0,
prompt_misses: 0,
next_block: 0,
}),
})
}
/// A number identifying one MoE block's experts within the tier.
pub fn register_block(&self) -> u32 {
let mut state = self.state.lock().expect("expert tier lock");
let block = state.next_block;
state.next_block += 1;
block
}
/// The expert, from the tier or from `load`.
///
/// Room is made *before* `load` runs, so the outgoing expert's VRAM
/// is available to the incoming one. An expert larger than the whole
/// budget is returned without being retained.
pub fn get_or_load<E>(
&self,
block: u32,
expert: u32,
bytes: u64,
load: impl FnOnce() -> Result<T, E>,
) -> Result<Arc<T>, E> {
let key = (block, expert);
let retain = {
let mut state = self.state.lock().expect("expert tier lock");
if let Some(value) = state.lru.get(key) {
state.hits += 1;
return Ok(value);
}
state.misses += 1;
let retain = bytes <= state.lru.capacity;
if retain {
let evicted = state.lru.make_room(bytes);
state.evictions += evicted;
}
retain
};
let value = Arc::new(load()?);
if retain {
let mut state = self.state.lock().expect("expert tier lock");
state.lru.insert(key, value.clone(), bytes);
}
Ok(value)
}
/// Counts a use of the expert and refreshes it if held. Returns
/// whether it was held. A caller that admits on a budget uses this
/// for the uses it will not admit, so they still count as misses.
pub fn touch(&self, block: u32, expert: u32) -> bool {
let mut state = self.state.lock().expect("expert tier lock");
let held = state.lru.get((block, expert)).is_some();
if held {
state.hits += 1;
} else {
state.misses += 1;
}
held
}
/// The expert if it is held, without admitting it or refreshing it.
///
/// A prompt chunk touches more experts than the tier holds, once
/// each. Letting that scan admit or reorder would replace the set
/// decode keeps returning to with experts it may never use again.
pub fn peek(&self, block: u32, expert: u32) -> Option<Arc<T>> {
let mut state = self.state.lock().expect("expert tier lock");
let value = state
.lru
.entries
.get(&(block, expert))
.map(|entry| entry.value.clone());
if value.is_some() {
state.prompt_hits += 1;
} else {
state.prompt_misses += 1;
}
value
}
/// The byte budget.
pub fn capacity_bytes(&self) -> u64 {
self.state.lock().expect("expert tier lock").lru.capacity
}
pub fn stats(&self) -> TierStats {
let state = self.state.lock().expect("expert tier lock");
TierStats {
hits: state.hits,
misses: state.misses,
evictions: state.evictions,
prompt_hits: state.prompt_hits,
prompt_misses: state.prompt_misses,
used_bytes: state.lru.used,
entries: state.lru.entries.len() as u64,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn fetch(tier: &ExpertTier<u32>, expert: u32, bytes: u64, loads: &Cell<u32>) -> u32 {
*tier
.get_or_load::<()>(0, expert, bytes, || {
loads.set(loads.get() + 1);
Ok(expert)
})
.unwrap()
}
#[test]
fn a_hit_does_not_load_again() {
let tier = ExpertTier::new(100);
let loads = Cell::new(0);
assert_eq!(fetch(&tier, 7, 10, &loads), 7);
assert_eq!(fetch(&tier, 7, 10, &loads), 7);
assert_eq!(loads.get(), 1);
let stats = tier.stats();
assert_eq!((stats.hits, stats.misses, stats.used_bytes), (1, 1, 10));
}
#[test]
fn the_least_recently_used_expert_is_evicted() {
let tier = ExpertTier::new(30);
let loads = Cell::new(0);
fetch(&tier, 1, 10, &loads);
fetch(&tier, 2, 10, &loads);
fetch(&tier, 3, 10, &loads);
// Touching 1 leaves 2 as the oldest.
fetch(&tier, 1, 10, &loads);
fetch(&tier, 4, 10, &loads);
assert_eq!(loads.get(), 4);
fetch(&tier, 1, 10, &loads);
assert_eq!(loads.get(), 4, "1 was recently used and must survive");
fetch(&tier, 2, 10, &loads);
assert_eq!(loads.get(), 5, "2 was the oldest and must have gone");
}
#[test]
fn the_budget_is_in_bytes_and_is_never_exceeded() {
let tier = ExpertTier::new(50);
let loads = Cell::new(0);
for (expert, bytes) in [(1, 20), (2, 20), (3, 30), (4, 5), (5, 45)] {
fetch(&tier, expert, bytes, &loads);
assert!(tier.stats().used_bytes <= 50);
}
assert_eq!(tier.stats().used_bytes, 50);
}
#[test]
fn an_expert_larger_than_the_budget_is_served_but_not_kept() {
let tier = ExpertTier::new(10);
let loads = Cell::new(0);
fetch(&tier, 1, 5, &loads);
assert_eq!(fetch(&tier, 2, 11, &loads), 2);
let stats = tier.stats();
assert_eq!((stats.used_bytes, stats.entries), (5, 1));
fetch(&tier, 1, 5, &loads);
assert_eq!(loads.get(), 2, "the oversized expert must not evict 1");
}
#[test]
fn blocks_do_not_share_experts() {
let tier: Arc<ExpertTier<u32>> = ExpertTier::new(100);
let (a, b) = (tier.register_block(), tier.register_block());
assert_ne!(a, b);
let first = tier.get_or_load::<()>(a, 3, 10, || Ok(30)).unwrap();
let second = tier.get_or_load::<()>(b, 3, 10, || Ok(40)).unwrap();
assert_eq!((*first, *second), (30, 40));
}
#[test]
fn a_prompt_scan_neither_admits_nor_reorders() {
let tier = ExpertTier::new(20);
let loads = Cell::new(0);
fetch(&tier, 1, 10, &loads);
fetch(&tier, 2, 10, &loads);
// Peeking at 1 must not make it newer than 2.
assert_eq!(tier.peek(0, 1).as_deref(), Some(&1));
assert!(tier.peek(0, 9).is_none());
let stats = tier.stats();
assert_eq!(
(stats.prompt_hits, stats.prompt_misses, stats.entries),
(1, 1, 2)
);
fetch(&tier, 3, 10, &loads);
assert!(tier.peek(0, 1).is_none(), "1 was still the oldest");
assert!(tier.peek(0, 2).is_some());
}
/// A touch refreshes what is held, so it survives the next eviction,
/// and counts what is not as a miss without admitting it.
#[test]
fn a_touch_refreshes_without_admitting() {
let tier = ExpertTier::new(20);
let loads = Cell::new(0);
fetch(&tier, 1, 10, &loads);
fetch(&tier, 2, 10, &loads);
assert!(tier.touch(0, 1));
assert!(!tier.touch(0, 9));
fetch(&tier, 3, 10, &loads);
assert!(tier.peek(0, 1).is_some(), "the touch made 1 newer than 2");
assert!(tier.peek(0, 2).is_none());
assert!(tier.peek(0, 9).is_none(), "a touch never admits");
assert_eq!(loads.get(), 3);
let stats = tier.stats();
assert_eq!((stats.hits, stats.misses), (1, 4));
}
#[test]
fn a_failed_load_retains_nothing() {
let tier: Arc<ExpertTier<u32>> = ExpertTier::new(100);
assert!(tier.get_or_load(0, 1, 10, || Err("oom")).is_err());
let stats = tier.stats();
assert_eq!((stats.used_bytes, stats.entries), (0, 0));
}
}
@@ -154,6 +154,10 @@ pub(crate) fn attention_context(
}
}
if let AttnMask::Additive(m) = attn_mask {
return masked_attention(q, k, v, m, num_kv_groups, scale);
}
// Eager fallback: materialise GQA-repeated K/V and the score matrix.
let k = repeat_kv(k.clone(), num_kv_groups)?.contiguous()?;
let v = repeat_kv(v.clone(), num_kv_groups)?.contiguous()?;
@@ -165,6 +169,77 @@ pub(crate) fn attention_context(
probs.matmul(&v)
}
/// Score elements one query tile may hold: 2^26, about 0.75 GB across
/// the bf16 scores and the f32 softmax. A tile is as many queries as fit.
const SCORE_TILE_ELEMENTS: usize = 1 << 26;
/// Attention under an arbitrary additive mask, `(B, 1, L, S)` — the
/// path every [`AttnMask::Additive`] takes.
///
/// Equal to plain eager attention, with two changes
/// that bound its memory so long prompts can be read in large chunks:
///
/// - GQA without copying K/V: each KV head's query heads are folded
/// into the row axis, so the matmul reads the shared K/V once rather
/// than a 12x repeat of the whole cache.
/// - Queries are processed in tiles sized to [`SCORE_TILE_ELEMENTS`],
/// so a chunk of `L` queries over `S` positions never holds the full
/// `heads * L * S` scores.
///
/// The mask add and softmax run in f32, as the reference does.
fn masked_attention(
q: &Tensor,
k: &Tensor,
v: &Tensor,
mask: &Tensor,
num_kv_groups: usize,
scale: f64,
) -> candle_core::Result<Tensor> {
masked_attention_tiled(q, k, v, mask, num_kv_groups, scale, SCORE_TILE_ELEMENTS)
}
fn masked_attention_tiled(
q: &Tensor,
k: &Tensor,
v: &Tensor,
mask: &Tensor,
num_kv_groups: usize,
scale: f64,
tile_elements: usize,
) -> candle_core::Result<Tensor> {
let (b, heads, l, d) = q.dims4()?;
let (_, kv_heads, s, _) = k.dims4()?;
let kt = k.transpose(2, 3)?.contiguous()?;
let v = v.contiguous()?;
let tile = (tile_elements / (heads * s).max(1)).clamp(1, l);
let mut out = Vec::with_capacity(l.div_ceil(tile));
let mut start = 0;
while start < l {
let t = tile.min(l - start);
// (B, H, t, D) -> (B, Hkv, G * t, D): head h = kv * G + g.
let qt =
q.narrow(2, start, t)?
.contiguous()?
.reshape((b, kv_heads, num_kv_groups * t, d))?;
let scores = (qt.matmul(&kt)? * scale)?
.to_dtype(candle_core::DType::F32)?
.reshape((b, kv_heads, num_kv_groups, t, s))?;
let m = mask
.narrow(2, start, t)?
.to_dtype(candle_core::DType::F32)?
.unsqueeze(1)?;
let probs = candle_nn::ops::softmax_last_dim(&scores.broadcast_add(&m)?)?
.to_dtype(q.dtype())?
.reshape((b, kv_heads, num_kv_groups * t, s))?;
out.push(probs.matmul(&v)?.reshape((b, heads, t, d))?);
start += t;
}
if out.len() == 1 {
return Ok(out.remove(0));
}
Tensor::cat(&out, 2)
}
pub struct Qwen3_5Attention {
q_proj: Linear,
k_proj: Linear,
@@ -334,3 +409,94 @@ fn load_linear_no_bias(
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Linear::new(weight, None))
}
#[cfg(test)]
mod tests {
use super::*;
use candle_core::Device;
/// Plain eager attention: K/V repeated per query head, one score
/// matrix, f32 throughout. Independent of the code under test.
fn reference(
q: &Tensor,
k: &Tensor,
v: &Tensor,
mask: &Tensor,
groups: usize,
scale: f64,
) -> Vec<f32> {
let k = repeat_kv(k.clone(), groups).unwrap();
let v = repeat_kv(v.clone(), groups).unwrap();
let scores = (q.matmul(&k.transpose(2, 3).unwrap()).unwrap() * scale)
.unwrap()
.broadcast_add(mask)
.unwrap();
candle_nn::ops::softmax_last_dim(&scores)
.unwrap()
.matmul(&v.contiguous().unwrap())
.unwrap()
.flatten_all()
.unwrap()
.to_vec1()
.unwrap()
}
/// The tiled, copy-free GQA attention equals plain eager attention
/// under an arbitrary mask, for every tile size: one query per tile,
/// a ragged tail, and the whole chunk at once. Each KV head and each
/// row's mask differ, so a wrong head fold or a misaligned mask tile
/// changes the answer.
#[test]
fn masked_attention_matches_eager_attention_at_any_tile() {
let dev = Device::Cpu;
let (heads, kv_heads, l, s, d) = (4, 2, 5, 7, 8);
let values = |n: usize, seed: u32| -> Vec<f32> {
(0..n)
.map(|i| {
let x = (i as u32).wrapping_mul(2_654_435_761).wrapping_add(seed);
((x >> 8) % 1000) as f32 / 500.0 - 1.0
})
.collect()
};
let q = Tensor::from_vec(values(heads * l * d, 1), (1, heads, l, d), &dev).unwrap();
let k = Tensor::from_vec(values(kv_heads * s * d, 2), (1, kv_heads, s, d), &dev).unwrap();
let v = Tensor::from_vec(values(kv_heads * s * d, 3), (1, kv_heads, s, d), &dev).unwrap();
// Row i sees an irregular subset that always includes position i.
let mut mask = vec![f32::NEG_INFINITY; l * s];
for i in 0..l {
for p in 0..s {
if p == i || (p * 3 + i) % 4 == 0 {
mask[i * s + p] = 0.0;
}
}
}
let mask = Tensor::from_vec(mask, (1, 1, l, s), &dev).unwrap();
let scale = 0.35;
let want = reference(&q, &k, &v, &mask, 2, scale);
for tile_queries in [1, 2, l] {
let got: Vec<f32> =
masked_attention_tiled(&q, &k, &v, &mask, 2, scale, tile_queries * heads * s)
.unwrap()
.flatten_all()
.unwrap()
.to_vec1()
.unwrap();
for (g, w) in got.iter().zip(&want) {
assert!(
(g - w).abs() < 1e-5,
"tile of {tile_queries}: got {got:?} want {want:?}"
);
}
}
// And the dispatcher routes an additive mask here.
let routed: Vec<f32> = attention_context(&q, &k, &v, AttnMask::Additive(&mask), 2, scale)
.unwrap()
.flatten_all()
.unwrap()
.to_vec1()
.unwrap();
for (g, w) in routed.iter().zip(&want) {
assert!((g - w).abs() < 1e-5);
}
}
}
@@ -67,6 +67,7 @@ use candle_nn::var_builder::ShardedVarBuilder;
#[cfg(test)]
use super::RopeParameters;
use super::TextConfig;
use super::proj::{LinearSource, Proj, load_proj};
use super::rmsnorm::{OutputGate, Qwen3_5RmsNormGated, l2norm};
/// Per-rank, per-layer state for the linear-attention block.
@@ -81,11 +82,11 @@ pub struct GatedDeltaNetState {
pub struct GatedDeltaNet {
// Projections.
in_proj_qkv: Linear,
in_proj_z: Linear,
in_proj_qkv: Proj,
in_proj_z: Proj,
in_proj_b: Linear,
in_proj_a: Linear,
out_proj: Linear,
out_proj: Proj,
// Depthwise causal Conv1d weight; shape (conv_dim, 1, kernel_size).
// No bias (Python sets bias=False).
@@ -170,6 +171,16 @@ impl GatedDeltaNet {
}
pub fn load_with_params(cfg: GatedDeltaNetParams, vb: &ShardedVarBuilder) -> Result<Self> {
Self::load_with_source(cfg, vb, None)
}
/// As [`Self::load_with_params`], taking `in_proj_qkv`, `in_proj_z`
/// and `out_proj` from `source` where it has them.
pub fn load_with_source(
cfg: GatedDeltaNetParams,
vb: &ShardedVarBuilder,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let num_v_heads = cfg.num_value_heads;
let num_k_heads = cfg.num_key_heads;
let head_k_dim = cfg.key_head_dim;
@@ -216,20 +227,20 @@ impl GatedDeltaNet {
split_fused_qkvz(&qkvz, num_k_heads, num_v_heads, head_k_dim, head_v_dim)?;
let (b_w, a_w) = split_fused_ba(&ba, num_k_heads, num_v_heads)?;
(
Linear::new(qkv_w, None),
Linear::new(z_w, None),
Linear::new(qkv_w, None).into(),
Linear::new(z_w, None).into(),
Linear::new(b_w, None),
Linear::new(a_w, None),
)
} else {
(
load_linear_no_bias(vb, "in_proj_qkv", cfg.hidden_size, conv_dim)?,
load_linear_no_bias(vb, "in_proj_z", cfg.hidden_size, value_dim)?,
load_proj(vb, "in_proj_qkv", cfg.hidden_size, conv_dim, source)?,
load_proj(vb, "in_proj_z", cfg.hidden_size, value_dim, source)?,
load_linear_no_bias(vb, "in_proj_b", cfg.hidden_size, num_v_heads)?,
load_linear_no_bias(vb, "in_proj_a", cfg.hidden_size, num_v_heads)?,
)
};
let out_proj = load_linear_no_bias(vb, "out_proj", value_dim, cfg.hidden_size)?;
let out_proj = load_proj(vb, "out_proj", value_dim, cfg.hidden_size, source)?;
// ----- Conv1d weight (depthwise, bias=False). -----
let conv1d_weight = vb
@@ -1435,11 +1446,11 @@ mod tests {
let value_dim = cfg.linear_value_head_dim * cfg.linear_num_value_heads;
let conv_dim = key_dim * 2 + value_dim;
let mut net = GatedDeltaNet {
in_proj_qkv: Linear::new(zeros(&[conv_dim, cfg.hidden_size]), None),
in_proj_z: Linear::new(zeros(&[value_dim, cfg.hidden_size]), None),
in_proj_qkv: Linear::new(zeros(&[conv_dim, cfg.hidden_size]), None).into(),
in_proj_z: Linear::new(zeros(&[value_dim, cfg.hidden_size]), None).into(),
in_proj_b: Linear::new(zeros(&[cfg.linear_num_value_heads, cfg.hidden_size]), None),
in_proj_a: Linear::new(zeros(&[cfg.linear_num_value_heads, cfg.hidden_size]), None),
out_proj: Linear::new(zeros(&[cfg.hidden_size, value_dim]), None),
out_proj: Linear::new(zeros(&[cfg.hidden_size, value_dim]), None).into(),
conv1d_weight: zeros(&[conv_dim, 1, cfg.linear_conv_kernel_dim]),
dt_bias: zeros(&[cfg.linear_num_value_heads]),
a_log: zeros(&[cfg.linear_num_value_heads]),
+27 -25
View File
@@ -3,17 +3,17 @@
//! Identical to plain Qwen3's MLP: `down(silu(gate(x)) * up(x))` with
//! no bias on any of the three projections.
use anyhow::{Context, Result};
use anyhow::Result;
use candle_core::{Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
use super::TextConfig;
use super::proj::{LinearSource, Proj, load_proj};
pub struct Qwen3_5MLP {
gate_proj: Linear,
up_proj: Linear,
down_proj: Linear,
gate_proj: Proj,
up_proj: Proj,
down_proj: Proj,
}
impl Qwen3_5MLP {
@@ -25,11 +25,15 @@ impl Qwen3_5MLP {
/// test that proves banking neutral still needs it, to express the
/// same weights in the layout it is being compared against.
#[cfg(test)]
pub(crate) fn from_weights(gate_proj: Linear, up_proj: Linear, down_proj: Linear) -> Self {
pub(crate) fn from_weights(
gate_proj: candle_nn::Linear,
up_proj: candle_nn::Linear,
down_proj: candle_nn::Linear,
) -> Self {
Self {
gate_proj,
up_proj,
down_proj,
gate_proj: gate_proj.into(),
up_proj: up_proj.into(),
down_proj: down_proj.into(),
}
}
@@ -46,9 +50,20 @@ impl Qwen3_5MLP {
hidden: usize,
intermediate: usize,
) -> Result<Self> {
let gate_proj = load_linear_no_bias(vb, "gate_proj", hidden, intermediate)?;
let up_proj = load_linear_no_bias(vb, "up_proj", hidden, intermediate)?;
let down_proj = load_linear_no_bias(vb, "down_proj", intermediate, hidden)?;
Self::load_with_source(vb, hidden, intermediate, None)
}
/// As [`Self::load_with_dims`], taking projections from `source`
/// where it has them.
pub fn load_with_source(
vb: &ShardedVarBuilder,
hidden: usize,
intermediate: usize,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let gate_proj = load_proj(vb, "gate_proj", hidden, intermediate, source)?;
let up_proj = load_proj(vb, "up_proj", hidden, intermediate, source)?;
let down_proj = load_proj(vb, "down_proj", intermediate, hidden, source)?;
Ok(Self {
gate_proj,
up_proj,
@@ -64,16 +79,3 @@ impl Module for Qwen3_5MLP {
self.down_proj.forward(&(lhs * rhs)?)
}
}
fn load_linear_no_bias(
vb: &ShardedVarBuilder,
name: &str,
in_dim: usize,
out_dim: usize,
) -> Result<Linear> {
let weight = vb
.pp(name)
.get((out_dim, in_dim), "weight")
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Linear::new(weight, None))
}
@@ -73,11 +73,13 @@ use serde::Deserialize;
use std::sync::Arc;
pub mod decoder;
pub mod expert_tier;
pub mod full_attn;
pub mod linear_attn;
pub mod mlp;
pub mod moe;
pub mod mtp;
pub mod proj;
pub mod rmsnorm;
pub mod rope;
pub mod vision;
+375 -26
View File
@@ -29,7 +29,7 @@
//! replaces the loop behind the same `forward` signature.
use anyhow::{Context, Result};
use candle_core::quantized::{GgmlDType, QMatMul, QTensor};
use candle_core::quantized::{GgmlDType, QMatMul, QStorage, QTensor};
use candle_core::{DType, Device, IndexOp, Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
@@ -70,6 +70,11 @@ pub(crate) enum Experts {
/// dropped once its 512 experts are quantised, so the full 241.6 GB
/// never exists at once.
Quantized(Vec<QuantizedExpert>),
/// Weights and execution live outside candle.
External {
count: usize,
inner: Box<dyn ExternalExperts>,
},
Banked {
/// `(num_experts, 2 * intermediate, hidden)` — gate rows first,
/// then up. Reversing them computes `silu(up) * gate`, which is
@@ -81,8 +86,50 @@ pub(crate) enum Experts {
},
}
/// Routed experts executed outside candle.
///
/// Routing stays with the block. `xs` is `(tokens, hidden)`;
/// `tokens_for[e]` and `weights_for[e]` are expert `e`'s rows and mixing
/// weights. Returns the weighted sum of each token's `k` experts,
/// `(tokens, hidden)`.
pub trait ExternalExperts: Send + Sync {
fn forward(
&self,
xs: &Tensor,
tokens_for: &[Vec<u32>],
weights_for: &[Vec<f32>],
k: usize,
) -> candle_core::Result<Tensor>;
/// Whether [`Self::forward_device`] takes a forward of `rows` rows.
fn routes_on_device(&self, _rows: usize) -> bool {
false
}
/// The same, from routing left on the device: `ids` is `(rows, k)`
/// u32 and `weights` `(rows, k)` f32, both where `xs` is. Saves the
/// host round-trip a per-expert token list costs (#425).
fn forward_device(
&self,
_xs: &Tensor,
_ids: &Tensor,
_weights: &Tensor,
_k: usize,
) -> candle_core::Result<Tensor> {
candle_core::bail!("these experts do not take device routing")
}
}
/// Supplies each MoE layer's [`ExternalExperts`] at load.
pub trait ExternalExpertSource: Send + Sync {
fn block(&self, layer: usize) -> Result<Box<dyn ExternalExperts>>;
}
/// The VRAM tier as host-resident quantised experts use it (#318).
pub type DeviceExpertTier = super::expert_tier::ExpertTier<QuantizedExpert>;
/// One expert's three projections, quantised.
pub(crate) struct QuantizedExpert {
pub struct QuantizedExpert {
gate: QMatMul,
up: QMatMul,
down: QMatMul,
@@ -100,6 +147,76 @@ impl QuantizedExpert {
_ => None,
}
}
/// Bytes of quantised weights, for the tier's budget.
fn storage_bytes(&self) -> u64 {
[&self.gate, &self.up, &self.down]
.into_iter()
.map(|m| match m {
QMatMul::QTensor(t) => t.storage_size_in_bytes() as u64,
_ => 0,
})
.sum()
}
/// A copy of this expert on `device`.
fn on_device(&self, device: &Device) -> candle_core::Result<Self> {
Ok(Self {
gate: quantized_on(&self.gate, device)?,
up: quantized_on(&self.up, device)?,
down: quantized_on(&self.down, device)?,
})
}
/// The SwiGLU on `xs`, which must be on this expert's device. The
/// kernels accumulate in f32; the result returns in `xs`'s dtype.
fn forward_here(&self, xs: &Tensor) -> candle_core::Result<Tensor> {
let dtype = xs.dtype();
let xs32 = xs.to_dtype(DType::F32)?;
let lhs = candle_nn::ops::silu(&self.gate.forward(&xs32)?)?;
let rhs = self.up.forward(&xs32)?;
self.down.forward(&(lhs * rhs)?)?.to_dtype(dtype)
}
}
/// Rows at which host-resident experts run on the GPU instead (#318).
///
/// A prompt chunk routes many tokens to each active expert, so moving
/// the expert's weights once is cheaper than computing every row on the
/// CPU. A decode step routes one token to ten experts, where the copy
/// would cost more than the arithmetic. Unset leaves execution on the
/// host.
fn expert_stream_min_rows() -> Option<usize> {
static MIN_ROWS: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
*MIN_ROWS.get_or_init(|| {
std::env::var("NEURON_EXPERT_STREAM_MIN_ROWS")
.ok()
.and_then(|v| v.parse().ok())
.filter(|&rows| rows > 0)
})
}
/// The most rows a forward may have and still admit experts to the VRAM
/// tier. Decode windows are below it; prompt chunks are not.
pub(crate) const TIER_ADMIT_MAX_ROWS: usize = 16;
/// Whether a prompt chunk may have left transient expert copies in the
/// allocator pool, which holds freed VRAM until it is trimmed.
pub(crate) fn prompt_chunk_streams_experts(rows: usize) -> bool {
rows > TIER_ADMIT_MAX_ROWS
&& (expert_stream_min_rows().is_some()
|| super::expert_tier::configured_budget_mb().is_some())
}
/// A transient copy of a quantised projection on `device`.
fn quantized_on(m: &QMatMul, device: &Device) -> candle_core::Result<QMatMul> {
match m {
QMatMul::QTensor(t) => {
let storage = QStorage::from_data(t.data()?, device, t.dtype())?;
QMatMul::from_qtensor(QTensor::new(storage, t.shape().clone())?)
}
_ => candle_core::bail!("only a quantised expert can be streamed"),
}
}
/// The quantisation type actually usable for rows of `row` elements.
@@ -173,6 +290,7 @@ impl Experts {
Experts::PerExpert(v) => v.len(),
Experts::Banked { gate_up, .. } => gate_up.dims()[0],
Experts::Quantized(v) => v.len(),
Experts::External { count, .. } => *count,
}
}
@@ -325,6 +443,9 @@ impl Experts {
pub(crate) fn forward_one(&self, e: usize, xs: &Tensor) -> candle_core::Result<Tensor> {
match self {
Experts::PerExpert(v) => v[e].forward(xs),
Experts::External { .. } => {
candle_core::bail!("external experts run per layer, not per expert")
}
Experts::Banked {
gate_up,
down,
@@ -364,6 +485,41 @@ impl Experts {
}
}
}
/// Expert `e` computed on `xs`'s device from a transient copy of
/// its weights. Layouts that are not quantised run as usual.
pub(crate) fn forward_streamed(&self, e: usize, xs: &Tensor) -> candle_core::Result<Tensor> {
let Experts::Quantized(v) = self else {
return self.forward_one(e, xs);
};
v[e].on_device(xs.device())?.forward_here(xs)
}
/// Expert `e` computed on `xs`'s device from the VRAM tier, loading
/// it there if it is not already held.
pub(crate) fn forward_tiered(
&self,
e: usize,
xs: &Tensor,
tier: &DeviceExpertTier,
block: u32,
admit: bool,
) -> candle_core::Result<Tensor> {
let Experts::Quantized(v) = self else {
return self.forward_one(e, xs);
};
let q = &v[e];
if !admit {
return match tier.peek(block, e as u32) {
Some(resident) => resident.forward_here(xs),
None => q.on_device(xs.device())?.forward_here(xs),
};
}
let resident = tier.get_or_load(block, e as u32, q.storage_bytes(), || {
q.on_device(xs.device())
})?;
resident.forward_here(xs)
}
}
pub struct Qwen3_5MoeBlock {
@@ -380,6 +536,8 @@ pub struct Qwen3_5MoeBlock {
shared_expert_gate: Option<Linear>,
num_experts_per_tok: usize,
norm_topk_prob: bool,
/// The model's VRAM tier and this block's number in it (#318).
tier: Option<(std::sync::Arc<DeviceExpertTier>, u32)>,
}
impl Qwen3_5MoeBlock {
@@ -406,9 +564,19 @@ impl Qwen3_5MoeBlock {
shared_expert_gate,
num_experts_per_tok,
norm_topk_prob,
tier: None,
}
}
/// Serve this block's host-resident experts through `tier`.
pub(crate) fn with_tier(mut self, tier: Option<std::sync::Arc<DeviceExpertTier>>) -> Self {
self.tier = tier.map(|t| {
let block = t.register_block();
(t, block)
});
self
}
pub fn load(cfg: &TextConfig, vb: &ShardedVarBuilder) -> Result<Self> {
anyhow::ensure!(
cfg.num_experts > 0 && cfg.num_experts_per_tok > 0 && cfg.moe_intermediate_size > 0,
@@ -465,6 +633,7 @@ impl Qwen3_5MoeBlock {
shared_expert_gate,
num_experts_per_tok: cfg.num_experts_per_tok,
norm_topk_prob: cfg.norm_topk_prob,
tier: None,
})
}
}
@@ -486,21 +655,7 @@ pub(crate) fn route_scatter(
norm_topk_prob: bool,
) -> candle_core::Result<ExpertAssignments> {
let n_tokens = xs_flat.dim(0)?;
// Router probabilities in f32 (reference uses float softmax
// regardless of activations dtype).
let router_logits = gate.forward(xs_flat)?;
let probs = candle_nn::ops::softmax_last_dim(&router_logits.to_dtype(DType::F32)?)?;
// Top-k selection: descending argsort, take the first k. The
// renormalisation (iff norm_topk_prob) divides by the sum of
// the selected global-softmax values.
let sorted = probs.arg_sort_last_dim(false)?;
let topk_idx = sorted.narrow(1, 0, num_experts_per_tok)?.contiguous()?;
let mut topk_w = probs.gather(&topk_idx, 1)?;
if norm_topk_prob {
let denom = topk_w.sum_keepdim(1)?;
topk_w = topk_w.broadcast_div(&denom)?;
}
let (topk_idx, topk_w) = route_topk(gate, xs_flat, num_experts_per_tok, norm_topk_prob)?;
// Host-side scatter: token row lists per expert. Cheap relative
// to the expert GEMMs; replaced by grouped-GEMM in slice 4.
@@ -518,11 +673,54 @@ pub(crate) fn route_scatter(
Ok((tokens_for, weights_for))
}
/// The router's top-k, left where the activations are: ids `(rows, k)`
/// u32 and weights `(rows, k)` f32.
pub(crate) fn route_topk(
gate: &Linear,
xs_flat: &Tensor,
num_experts_per_tok: usize,
norm_topk_prob: bool,
) -> candle_core::Result<(Tensor, Tensor)> {
// Router probabilities in f32 (reference uses float softmax
// regardless of activations dtype).
let router_logits = gate.forward(xs_flat)?;
let probs = candle_nn::ops::softmax_last_dim(&router_logits.to_dtype(DType::F32)?)?;
// Top-k selection: descending argsort, take the first k. The
// renormalisation (iff norm_topk_prob) divides by the sum of
// the selected global-softmax values.
let sorted = probs.arg_sort_last_dim(false)?;
let topk_idx = sorted.narrow(1, 0, num_experts_per_tok)?.contiguous()?;
let mut topk_w = probs.gather(&topk_idx, 1)?;
if norm_topk_prob {
let denom = topk_w.sum_keepdim(1)?;
topk_w = topk_w.broadcast_div(&denom)?;
}
Ok((topk_idx, topk_w))
}
impl Module for Qwen3_5MoeBlock {
fn forward(&self, xs: &Tensor) -> candle_core::Result<Tensor> {
let (b, l, hidden) = xs.dims3()?;
let xs_flat = xs.reshape(((), hidden))?;
if let Experts::External { inner, .. } = &self.experts
&& inner.routes_on_device(xs_flat.dim(0)?)
{
let (ids, weights) = route_topk(
&self.gate,
&xs_flat,
self.num_experts_per_tok,
self.norm_topk_prob,
)?;
let ys = inner
.forward_device(&xs_flat, &ids, &weights, self.num_experts_per_tok)?
.to_dtype(xs.dtype())?;
return self
.add_shared_expert(ys, &xs_flat)?
.reshape((b, l, hidden));
}
// Routing stays where the activations are: it is one small
// matmul against `gate` and a host-side top-k, and the router
// is device-resident even when the experts are not.
@@ -534,6 +732,20 @@ impl Module for Qwen3_5MoeBlock {
self.norm_topk_prob,
)?;
if let Experts::External { inner, .. } = &self.experts {
let ys = inner
.forward(
&xs_flat,
&tokens_for,
&weights_for,
self.num_experts_per_tok,
)?
.to_dtype(xs.dtype())?;
return self
.add_shared_expert(ys, &xs_flat)?
.reshape((b, l, hidden));
}
// Cross to the experts once for the whole layer, not once per
// expert (#318). With host-resident experts the old shape was
// 10 round trips per layer and 480 per token; this is one in
@@ -546,7 +758,17 @@ impl Module for Qwen3_5MoeBlock {
// dominates.
let home = self.experts.device();
let off_device = home.is_some();
let routed_dev = home.unwrap_or_else(|| xs.device().clone());
let host_resident = xs.device().is_cuda() && home.as_ref().is_some_and(Device::is_cpu);
let tier = self.tier.as_ref().filter(|_| host_resident);
let stream = tier.is_some()
|| host_resident
&& expert_stream_min_rows()
.is_some_and(|min_rows| xs_flat.dim(0).is_ok_and(|n| n >= min_rows));
let routed_dev = if stream {
xs.device().clone()
} else {
home.unwrap_or_else(|| xs.device().clone())
};
let xs_routed = xs_flat.to_device(&routed_dev)?;
let started = std::time::Instant::now();
@@ -557,7 +779,15 @@ impl Module for Qwen3_5MoeBlock {
}
let rows = Tensor::new(tokens_for[e].as_slice(), &routed_dev)?;
let picked = xs_routed.index_select(&rows, 0)?;
let out = self.experts.forward_one(e, &picked)?;
let out = if let Some((tier, block)) = tier {
let admit = xs_routed.dim(0)? <= TIER_ADMIT_MAX_ROWS;
self.experts
.forward_tiered(e, &picked, tier, *block, admit)?
} else if stream {
self.experts.forward_streamed(e, &picked)?
} else {
self.experts.forward_one(e, &picked)?
};
let w = Tensor::new(weights_for[e].as_slice(), &routed_dev)?
.to_dtype(out.dtype())?
.reshape(((), 1))?;
@@ -575,18 +805,32 @@ impl Module for Qwen3_5MoeBlock {
expert_ms = started.elapsed().as_secs_f64() * 1e3,
rows = xs_routed.dims()[0],
active = tokens_for.iter().filter(|t| !t.is_empty()).count(),
stream,
tier_hits = tier.map_or(0, |(t, _)| t.stats().hits),
tier_misses = tier.map_or(0, |(t, _)| t.stats().misses),
tier_prompt_hits = tier.map_or(0, |(t, _)| t.stats().prompt_hits),
tier_prompt_misses = tier.map_or(0, |(t, _)| t.stats().prompt_misses),
tier_mb = tier.map_or(0, |(t, _)| t.stats().used_bytes >> 20),
"moe: routed experts (#318)"
);
}
let mut ys = ys.to_device(xs.device())?;
let ys = ys.to_device(xs.device())?;
self.add_shared_expert(ys, &xs_flat)?
.reshape((b, l, hidden))
}
}
if let (Some(shared), Some(gate)) = (&self.shared_expert, &self.shared_expert_gate) {
let mix = candle_nn::ops::sigmoid(&gate.forward(&xs_flat)?)?;
let shared_out = shared.forward(&xs_flat)?.broadcast_mul(&mix)?;
ys = (ys + shared_out)?;
impl Qwen3_5MoeBlock {
/// Adds the sigmoid-gated shared expert, when the model has one.
fn add_shared_expert(&self, ys: Tensor, xs_flat: &Tensor) -> candle_core::Result<Tensor> {
match (&self.shared_expert, &self.shared_expert_gate) {
(Some(shared), Some(gate)) => {
let mix = candle_nn::ops::sigmoid(&gate.forward(xs_flat)?)?;
let shared_out = shared.forward(xs_flat)?.broadcast_mul(&mix)?;
ys + shared_out
}
_ => Ok(ys),
}
ys.reshape((b, l, hidden))
}
}
@@ -623,6 +867,7 @@ mod tests {
shared_expert_gate: Some(Linear::new(randn(&[1, hidden]), None)),
num_experts_per_tok: top_k,
norm_topk_prob: true,
tier: None,
};
let (b, l) = (2, 3);
@@ -708,6 +953,7 @@ mod tests {
shared_expert_gate: None,
num_experts_per_tok: 1,
norm_topk_prob: false,
tier: None,
};
let xs = randn(&[1, 1, hidden]);
let got: Vec<f32> = block
@@ -898,6 +1144,109 @@ mod tests {
}
}
/// The streamed path must run the same arithmetic as the resident
/// one. A CPU test host cannot exercise the transfer, so this pins
/// the transient copy and the dtype round trip.
#[test]
fn streamed_expert_matches_the_resident_forward() {
let (n_experts, hidden, inter) = (2usize, 2560usize, 640usize);
let gate_up = randn(&[n_experts, inter * 2, hidden]);
let down = randn(&[n_experts, hidden, inter]);
let experts =
Experts::quantize_banked_onto(&gate_up, &down, inter, GgmlDType::Q4K, &Device::Cpu)
.unwrap();
let xs = randn(&[3, hidden]);
for e in 0..n_experts {
let resident: Vec<Vec<f32>> = experts.forward_one(e, &xs).unwrap().to_vec2().unwrap();
let streamed: Vec<Vec<f32>> =
experts.forward_streamed(e, &xs).unwrap().to_vec2().unwrap();
assert_eq!(resident, streamed, "expert {e}");
}
}
/// External experts receive the block's routing and their result is
/// mixed with the shared expert exactly as resident experts' is.
#[test]
fn external_experts_receive_the_routing_and_join_the_shared_expert() {
struct Fixed;
impl ExternalExperts for Fixed {
fn forward(
&self,
xs: &Tensor,
tokens_for: &[Vec<u32>],
weights_for: &[Vec<f32>],
k: usize,
) -> candle_core::Result<Tensor> {
let routed: usize = tokens_for.iter().map(Vec::len).sum();
assert_eq!(routed, xs.dim(0)? * k);
assert_eq!(tokens_for.len(), 6);
for (t, w) in tokens_for.iter().zip(weights_for) {
assert_eq!(t.len(), w.len());
}
xs.ones_like()
}
}
let (hidden, inter, n_exp, top_k) = (8, 4, 6, 2);
let shared = rand_mlp(hidden, inter);
let shared_gate = Linear::new(randn(&[1, hidden]), None);
let xs = randn(&[1, 3, hidden]);
let flat = xs.reshape(((), hidden)).unwrap();
let mix = candle_nn::ops::sigmoid(&shared_gate.forward(&flat).unwrap()).unwrap();
let expected = (shared.forward(&flat).unwrap().broadcast_mul(&mix).unwrap()
+ flat.ones_like().unwrap())
.unwrap();
let block = Qwen3_5MoeBlock {
gate: Linear::new(randn(&[n_exp, hidden]), None),
experts: Experts::External {
count: n_exp,
inner: Box::new(Fixed),
},
shared_expert: Some(shared),
shared_expert_gate: Some(shared_gate),
num_experts_per_tok: top_k,
norm_topk_prob: true,
tier: None,
};
let got: Vec<Vec<f32>> = block
.forward(&xs)
.unwrap()
.reshape(((), hidden))
.unwrap()
.to_vec2()
.unwrap();
let want: Vec<Vec<f32>> = expected.to_vec2().unwrap();
assert_eq!(got, want);
}
/// The tiered path runs the same arithmetic as the resident one,
/// and a second use of an expert comes from the tier.
#[test]
fn tiered_expert_matches_the_resident_forward() {
let (n_experts, hidden, inter) = (2usize, 2560usize, 640usize);
let gate_up = randn(&[n_experts, inter * 2, hidden]);
let down = randn(&[n_experts, hidden, inter]);
let experts =
Experts::quantize_banked_onto(&gate_up, &down, inter, GgmlDType::Q4K, &Device::Cpu)
.unwrap();
let tier = DeviceExpertTier::new(1 << 30);
let block = tier.register_block();
let xs = randn(&[3, hidden]);
for e in 0..n_experts {
let resident: Vec<Vec<f32>> = experts.forward_one(e, &xs).unwrap().to_vec2().unwrap();
for _ in 0..2 {
let tiered: Vec<Vec<f32>> = experts
.forward_tiered(e, &xs, &tier, block, true)
.unwrap()
.to_vec2()
.unwrap();
assert_eq!(resident, tiered, "expert {e}");
}
}
let stats = tier.stats();
assert_eq!((stats.misses, stats.hits, stats.entries), (2, 2, 2));
assert!(stats.used_bytes > 0);
}
/// Host-resident experts compute the same function as device-
/// resident ones (#318).
///
@@ -0,0 +1,157 @@
//! A bias-free projection that is either a dense candle [`Linear`] or a
//! weight held in another format and run by its own kernels.
//!
//! The second form exists so a model can take its dense weights from a
//! quantized file (a GGUF's Q8_0 blocks, say) while keeping the
//! checkpoint's names and the rest of its load path. A [`LinearSource`]
//! is asked for each projection by its checkpoint name; when it has one,
//! the dense tensor is never read.
use std::sync::Arc;
use anyhow::{Context, Result};
use candle_core::{Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
/// `y = x W^T` for a weight held outside candle.
pub trait ExternalLinear: Send + Sync {
/// `x` is `(.., in_dim)`; the result is `(.., out_dim)` in `x`'s dtype.
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor>;
}
/// Supplies projections by checkpoint name, e.g.
/// `model.language_model.layers.3.self_attn.q_proj.weight`.
pub trait LinearSource: Send + Sync {
/// The projection, or `None` to load the checkpoint's own tensor.
/// `(out_dim, in_dim)` is the shape the checkpoint would have.
fn linear(
&self,
name: &str,
in_dim: usize,
out_dim: usize,
) -> Result<Option<Arc<dyn ExternalLinear>>>;
}
#[derive(Clone)]
pub enum Proj {
Dense(Linear),
External(Arc<dyn ExternalLinear>),
}
impl Module for Proj {
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
match self {
Self::Dense(linear) => linear.forward(x),
Self::External(linear) => linear.forward(x),
}
}
}
impl From<Linear> for Proj {
fn from(linear: Linear) -> Self {
Self::Dense(linear)
}
}
/// `{prefix}.{name}.weight`, from `source` when it has it, else from the
/// checkpoint.
pub fn load_proj(
vb: &ShardedVarBuilder,
name: &str,
in_dim: usize,
out_dim: usize,
source: Option<&dyn LinearSource>,
) -> Result<Proj> {
if let Some(source) = source {
let prefix = vb.prefix();
let full = if prefix.is_empty() {
format!("{name}.weight")
} else {
format!("{prefix}.{name}.weight")
};
if let Some(linear) = source.linear(&full, in_dim, out_dim)? {
return Ok(Proj::External(linear));
}
}
let weight = vb
.pp(name)
.get((out_dim, in_dim), "weight")
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Proj::Dense(Linear::new(weight, None)))
}
#[cfg(test)]
mod tests {
use super::*;
use candle_core::{DType, Device};
use std::collections::HashMap;
use std::sync::Mutex;
struct Doubling;
impl ExternalLinear for Doubling {
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
x * 2.0
}
}
/// Records the names it is asked for and serves only one of them.
struct OneName(Mutex<Vec<String>>);
impl LinearSource for OneName {
fn linear(
&self,
name: &str,
_in_dim: usize,
_out_dim: usize,
) -> Result<Option<Arc<dyn ExternalLinear>>> {
self.0.lock().unwrap().push(name.to_string());
Ok(
(name == "a.b.served.weight")
.then(|| Arc::new(Doubling) as Arc<dyn ExternalLinear>),
)
}
}
/// The source is asked by the full checkpoint name; what it serves
/// replaces the tensor, which is never read (the checkpoint here has
/// none for it), and what it declines comes from the checkpoint.
#[test]
fn a_source_is_asked_by_full_name_and_the_checkpoint_fills_the_rest() {
let dev = Device::Cpu;
let mut tensors = HashMap::new();
tensors.insert(
"a.b.kept.weight".to_string(),
Tensor::ones((2, 2), DType::F32, &dev).unwrap(),
);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("model.safetensors");
candle_core::safetensors::save(&tensors, &path).unwrap();
let vb = unsafe {
candle_nn::var_builder::ShardedSafeTensors::var_builder(&[&path], DType::F32, &dev)
.unwrap()
}
.pp("a")
.pp("b");
let source = OneName(Mutex::new(Vec::new()));
let x = Tensor::new(&[[1f32, 3.]], &dev).unwrap();
let served = load_proj(&vb, "served", 2, 2, Some(&source)).unwrap();
assert!(matches!(served, Proj::External(_)));
assert_eq!(
served.forward(&x).unwrap().to_vec2::<f32>().unwrap(),
[[2., 6.]]
);
let kept = load_proj(&vb, "kept", 2, 2, Some(&source)).unwrap();
assert!(matches!(kept, Proj::Dense(_)));
assert_eq!(
kept.forward(&x).unwrap().to_vec2::<f32>().unwrap(),
[[4., 4.]]
);
assert_eq!(
*source.0.lock().unwrap(),
["a.b.served.weight", "a.b.kept.weight"]
);
}
}
@@ -110,12 +110,17 @@ impl DecoderLayer {
opts: &super::LoadOptions<'_>,
) -> Result<Self> {
let mixer = match layer_type {
"full_attention" => {
Mixer::Full(Box::new(Attention::load(cfg, rotary, &vb.pp("self_attn"))?))
}
"linear_attention" => {
Mixer::Linear(Box::new(linear_attn::load(cfg, &vb.pp("linear_attn"))?))
}
"full_attention" => Mixer::Full(Box::new(Attention::load(
cfg,
rotary,
&vb.pp("self_attn"),
opts.dense.as_deref(),
)?)),
"linear_attention" => Mixer::Linear(Box::new(linear_attn::load(
cfg,
&vb.pp("linear_attn"),
opts.dense.as_deref(),
)?)),
other => anyhow::bail!(
"unknown layer_type '{other}' (expected 'full_attention' or \
'linear_attention')"
@@ -132,6 +137,7 @@ impl DecoderLayer {
// Decoder hyper-connections always scatter back; only
// the top-level mixer does not.
true,
opts.dense.as_deref(),
)
};
@@ -205,6 +211,16 @@ impl DecoderLayer {
through(mlp_hc, &h, |x| Ok(mlp.forward(x)?))
}
/// This layer's PLE contribution for residual `h` and gathered
/// n-gram embedding `e`, or `None` when it carries no PLE block. The
/// native engine (#427) adds it to its own residual.
pub fn ple_contribution(&mut self, h: &Tensor, e: &Tensor) -> Result<Option<Tensor>> {
match &mut self.ple {
Some(block) => Ok(Some(block.forward(h, e)?)),
None => Ok(None),
}
}
pub fn clear_kv_cache(&mut self) -> Result<()> {
match &mut self.mixer {
Mixer::Full(attn) => attn.clear_kv_cache(),
@@ -0,0 +1,390 @@
//! A full-attention layer's mixer half, native, for contexts within the
//! QSA budget.
//!
//! One decode token: the attention hyper-connection's read; the Q8_0
//! q (query and output gate interleaved per head), k and v projections;
//! RMS norm and rotary on q and k with the position read from device
//! memory; the K/V append into a cache allocated once; dense decode
//! attention over every cached position, with the per-head sigmoid
//! output gate; the Q8_0 output projection; the hyper-connection's write.
//!
//! Dense is exact while the context fits QSA's budget (2,048 tokens),
//! where the selection keeps every position. The indexer's raw key is
//! still projected and cached each step, so selection can take over
//! beyond the budget without rebuilding that cache.
use std::ffi::c_void;
use anyhow::{Result, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use super::gdn::{GdnShapes, check};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
const Q8_1_BLOCK_VALUES: usize = 32;
const Q8_1_BLOCK_BYTES: usize = 36;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
#[derive(Debug, Clone, Copy)]
pub struct AttnShapes {
pub heads: usize,
pub kv_heads: usize,
pub head_dim: usize,
pub n_rot: usize,
pub index_dim: usize,
/// Positions the cache holds.
pub max_len: usize,
}
impl AttnShapes {
fn q_width(&self) -> usize {
self.heads * self.head_dim
}
fn kv_width(&self) -> usize {
self.kv_heads * self.head_dim
}
}
pub struct AttnWeights {
hc_norm: DeviceTensor,
hc_down: DeviceTensor,
hc_up: DeviceTensor,
hc_inject: DeviceTensor,
q: DeviceTensor,
k: DeviceTensor,
v: DeviceTensor,
o: DeviceTensor,
q_norm: DeviceTensor,
k_norm: DeviceTensor,
index_k: DeviceTensor,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl AttnWeights {
pub fn load(gguf: &Gguf, layer: usize, s: &GdnShapes, a: &AttnShapes) -> Result<Self> {
let name = |t: &str| format!("blk.{layer}.{t}");
let projection = |t: &str, n_in: usize, n_out: usize| -> Result<DeviceTensor> {
let w = gguf.upload_raw(&name(t), row_bytes)?;
ensure!(
w.dims == [n_in as u64, n_out as u64],
"{} is {:?}, expected [{n_in}, {n_out}]",
name(t),
w.dims
);
// SAFETY: a pure function of its argument.
ensure!(
unsafe { ffi::neuron_strata_mmvq_supported(w.ggml_type as i32) } != 0,
"{}: no mmvq for type {}",
name(t),
w.ggml_type
);
Ok(w)
};
let wide = s.hc * s.n_embd;
let w = Self {
hc_norm: gguf.upload_f32(&name("hc_attn_norm.weight"))?,
hc_down: gguf.upload_bf16(&name("hc_attn_down.weight"))?,
hc_up: gguf.upload_bf16(&name("hc_attn_up.weight"))?,
hc_inject: gguf.upload_bf16(&name("hc_attn_inject.weight"))?,
q: projection("attn_q.weight", s.n_embd, 2 * a.q_width())?,
k: projection("attn_k.weight", s.n_embd, a.kv_width())?,
v: projection("attn_v.weight", s.n_embd, a.kv_width())?,
o: projection("attn_output.weight", a.q_width(), s.n_embd)?,
q_norm: gguf.upload_f32(&name("attn_q_norm.weight"))?,
k_norm: gguf.upload_f32(&name("attn_k_norm.weight"))?,
index_k: gguf.upload_bf16(&name("indexer.k_proj.weight"))?,
};
for (t, want) in [
(&w.hc_norm, wide),
(&w.hc_down, s.hc_lr * wide),
(&w.hc_up, wide * s.hc_lr),
(&w.hc_inject, s.hc * wide),
(&w.q_norm, a.head_dim),
(&w.k_norm, a.head_dim),
(&w.index_k, a.index_dim * s.n_embd),
] {
ensure!(
t.values() == want,
"layer {layer}: a tensor has {} values, expected {want}",
t.values()
);
}
Ok(w)
}
}
/// A sequence's caches for one full-attention layer.
pub struct AttnCache {
k: CudaSlice<f32>,
v: CudaSlice<f32>,
/// The indexer's raw (unnormalised, unrotated) keys.
index_keys: CudaSlice<f32>,
}
impl AttnCache {
/// Zeroes the caches in place: a captured step keeps its addresses.
pub fn clear(&mut self, device: &CudaDevice) -> Result<()> {
let stream = device.cuda_stream();
stream.memset_zeros(&mut self.k)?;
stream.memset_zeros(&mut self.v)?;
stream.memset_zeros(&mut self.index_keys)?;
Ok(())
}
pub fn new(device: &CudaDevice, a: &AttnShapes) -> Result<Self> {
Ok(Self {
k: device.alloc_zeros::<f32>(a.max_len * a.kv_width())?,
v: device.alloc_zeros::<f32>(a.max_len * a.kv_width())?,
index_keys: device.alloc_zeros::<f32>(a.max_len * a.index_dim)?,
})
}
}
pub struct AttnScratch {
gr: CudaSlice<u8>,
mixed: CudaSlice<f32>,
inject: CudaSlice<f32>,
x_q8: CudaSlice<u8>,
q_raw: CudaSlice<f32>,
q: CudaSlice<f32>,
k_raw: CudaSlice<f32>,
k: CudaSlice<f32>,
v: CudaSlice<f32>,
index_key: CudaSlice<f32>,
ctx: CudaSlice<f32>,
ctx_q8: CudaSlice<u8>,
out: CudaSlice<f32>,
}
impl AttnScratch {
pub fn new(device: &CudaDevice, s: &GdnShapes, a: &AttnShapes) -> Result<Self> {
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
let q8 = |n: usize| n / Q8_1_BLOCK_VALUES * Q8_1_BLOCK_BYTES;
Ok(Self {
gr: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
inject: device.alloc_zeros::<f32>(s.hc)?,
x_q8: device.alloc_zeros::<u8>(q8(s.n_embd))?,
q_raw: device.alloc_zeros::<f32>(2 * a.q_width())?,
q: device.alloc_zeros::<f32>(a.q_width())?,
k_raw: device.alloc_zeros::<f32>(a.kv_width())?,
k: device.alloc_zeros::<f32>(a.kv_width())?,
v: device.alloc_zeros::<f32>(a.kv_width())?,
index_key: device.alloc_zeros::<f32>(a.index_dim)?,
ctx: device.alloc_zeros::<f32>(a.q_width())?,
ctx_q8: device.alloc_zeros::<u8>(q8(a.q_width()))?,
out: device.alloc_zeros::<f32>(s.n_embd)?,
})
}
}
fn mmvq(w: &DeviceTensor, x_q8: u64, y: u64, stream: *mut c_void) {
// SAFETY: `w` is `dims[1]` rows of `dims[0]`, `x_q8` holds `dims[0]`
// values in q8_1 and `y` has room for `dims[1]` floats.
unsafe {
ffi::neuron_strata_mmvq(
w.ggml_type as i32,
w.address() as *const c_void,
x_q8 as *const c_void,
y as *mut f32,
w.dims[0] as i32,
w.dims[1] as i32,
1,
stream,
)
}
}
fn quantize(x: u64, n: usize, q8: u64, stream: *mut c_void) {
// SAFETY: `x` holds `n` floats and `q8` room for their q8_1 blocks.
unsafe {
ffi::neuron_strata_quantize_q8_1(x as *const f32, 1, n as i64, q8 as *mut c_void, stream)
}
}
/// The mixer half of one full-attention layer, for one token at the
/// position in `positions[0]` (a device array of at least `heads` equal
/// entries: the rotary reads one per row).
#[allow(clippy::too_many_arguments)]
pub fn forward(
w: &AttnWeights,
cache: &mut AttnCache,
sc: &mut AttnScratch,
s: &GdnShapes,
a: &AttnShapes,
positions: u64,
residual: u64,
residual_out: u64,
stream: *mut c_void,
) -> Result<()> {
let (n_embd, hc, hc_lr) = (s.n_embd as i64, s.hc as i64, s.hc_lr as i64);
let pos = positions as *const i32;
// SAFETY (all calls below): every pointer is a live device buffer of
// the size its kernel reads or writes, as allocated in `AttnScratch`,
// `AttnCache` and `AttnWeights`; `positions` holds at least `heads`
// entries; every launch is on `stream`.
unsafe {
check(
ffi::neuron_gr_read(
residual as *const f32,
w.hc_norm.address() as *const f32,
w.hc_down.address() as *const u16,
w.hc_up.address() as *const u16,
w.hc_inject.address() as *const u16,
s.eps,
n_embd,
hc,
hc_lr,
address(&sc.gr) as *mut c_void,
address(&sc.mixed) as *mut f32,
address(&sc.inject) as *mut f32,
stream,
),
"attn gr_read",
)?;
}
quantize(address(&sc.mixed), s.n_embd, address(&sc.x_q8), stream);
mmvq(&w.q, address(&sc.x_q8), address(&sc.q_raw), stream);
mmvq(&w.k, address(&sc.x_q8), address(&sc.k_raw), stream);
mmvq(&w.v, address(&sc.x_q8), address(&sc.v), stream);
// SAFETY: as above.
unsafe {
// q rows are [query | gate] per head: read the query half.
check(
ffi::neuron_norm_rope(
address(&sc.q_raw) as *const f32,
(2 * a.head_dim) as i32,
w.q_norm.address() as *const f32,
address(&sc.q) as *mut f32,
a.heads as i32,
a.head_dim as i32,
a.n_rot as i32,
s.eps,
pos,
stream,
),
"q norm + rope",
)?;
check(
ffi::neuron_norm_rope(
address(&sc.k_raw) as *const f32,
a.head_dim as i32,
w.k_norm.address() as *const f32,
address(&sc.k) as *mut f32,
a.kv_heads as i32,
a.head_dim as i32,
a.n_rot as i32,
s.eps,
pos,
stream,
),
"k norm + rope",
)?;
check(
ffi::neuron_bf16_gemv(
address(&sc.mixed) as *const f32,
w.index_k.address() as *const u16,
address(&sc.index_key) as *mut f32,
n_embd,
a.index_dim as i64,
stream,
),
"indexer key",
)?;
check(
ffi::neuron_append_rows(
address(&sc.k) as *const f32,
address(&sc.v) as *const f32,
address(&cache.k) as *mut f32,
address(&cache.v) as *mut f32,
pos,
a.kv_width() as i32,
stream,
),
"kv append",
)?;
check(
ffi::neuron_append_rows(
address(&sc.index_key) as *const f32,
std::ptr::null(),
address(&cache.index_keys) as *mut f32,
std::ptr::null_mut(),
pos,
a.index_dim as i32,
stream,
),
"indexer key append",
)?;
check(
ffi::neuron_decode_attn(
address(&sc.q) as *const f32,
address(&cache.k) as *const f32,
address(&cache.v) as *const f32,
pos,
a.heads as i32,
a.kv_heads as i32,
a.head_dim as i32,
1.0 / (a.head_dim as f32).sqrt(),
(address(&sc.q_raw) + (a.head_dim * 4) as u64) as *const f32,
(2 * a.head_dim) as i32,
address(&sc.ctx) as *mut f32,
stream,
),
"decode attention",
)?;
}
quantize(address(&sc.ctx), a.q_width(), address(&sc.ctx_q8), stream);
mmvq(&w.o, address(&sc.ctx_q8), address(&sc.out), stream);
// SAFETY: as above.
unsafe {
check(
ffi::neuron_gr_write(
residual as *const f32,
address(&sc.out) as *const f32,
address(&sc.inject) as *const f32,
n_embd,
hc,
hc_lr,
residual_out as *mut f32,
stream,
),
"attn gr_write",
)?;
}
Ok(())
}
/// The attention shapes of a qwen4_exp config, with a cache of
/// `max_len` positions.
pub fn shapes(cfg: &super::super::config::TextConfig, max_len: usize) -> Result<AttnShapes> {
let n_rot =
(cfg.head_dim as f64 * f64::from(cfg.rope_parameters.partial_rotary_factor)) as usize;
let a = AttnShapes {
heads: cfg.num_attention_heads,
kv_heads: cfg.num_key_value_heads,
head_dim: cfg.head_dim,
n_rot,
index_dim: cfg.indexer_head_dim,
max_len,
};
ensure!(
a.head_dim == 256 && n_rot == 64,
"native attention is built for 256-wide heads, 64 rotated"
);
ensure!(
a.heads.is_multiple_of(a.kv_heads),
"query heads must be a multiple of kv heads"
);
Ok(a)
}
@@ -0,0 +1,477 @@
//! The native decode step (#427): every layer of the model for one token,
//! over buffers allocated once.
//!
//! A step is two segments around the PLE layer: `[embedding, layers
//! before PLE]`, then (after the caller adds PLE's contribution to the
//! residual) `[layers from PLE on, the final mixer, the LM head]`. Each
//! segment is fixed work over fixed addresses, with the token and
//! position read from a device buffer filled from pinned host memory at
//! the start of the step, so each can be captured as a CUDA graph and
//! replayed. PLE's n-gram gather stays on the host for now.
use std::ffi::c_void;
use std::sync::Arc;
use anyhow::{Context, Result, bail, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaGraph, CudaSlice, DevicePtr, sys};
use super::attn::{self, AttnCache, AttnScratch, AttnShapes, AttnWeights};
use super::gdn::{self, GdnScratch, GdnShapes, GdnState, GdnWeights, check};
use super::moe::{self, MoeScratch, MoeShapes, MoeWeights};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
use crate::harness::arch::qwen4_exp::config::TextConfig;
use crate::harness::arch::qwen4_exp::native_experts::GgufExpertSource;
/// Positions are written for every query-head row the rotary reads.
const POSITION_SLOTS: usize = 32;
/// The step buffer: `POSITION_SLOTS` positions, then the token id.
const STEP_SLOTS: usize = POSITION_SLOTS + 1;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
enum Mixer {
Linear(GdnWeights, GdnState),
Full(AttnWeights, AttnCache),
}
struct Layer {
mixer: Mixer,
moe: MoeWeights,
}
/// Pinned host memory the step inputs are copied from.
struct HostStep(*mut i32);
// SAFETY: plain host memory, written by the device worker between steps.
unsafe impl Send for HostStep {}
impl Drop for HostStep {
fn drop(&mut self) {
// SAFETY: allocated by `neuron_strata_pinned_alloc`, freed once.
unsafe { ffi::neuron_strata_pinned_free(self.0.cast()) };
}
}
/// A captured segment.
struct Graph(CudaGraph);
// SAFETY: a graph is launched only from the device worker that owns the
// decoder, on the stream it was captured on.
unsafe impl Send for Graph {}
pub struct NativeDecoder {
/// Captured segments, once a warm step has run.
head_graph: Option<Graph>,
tail_graph: Option<Graph>,
warmed: bool,
device: CudaDevice,
s: GdnShapes,
a: AttnShapes,
m: MoeShapes,
layers: Vec<Layer>,
ple_layer: usize,
experts: Arc<GgufExpertSource>,
gdn_sc: GdnScratch,
attn_sc: AttnScratch,
moe_sc: MoeScratch,
embed: DeviceTensor,
embed_row: CudaSlice<f32>,
mixer_norm: DeviceTensor,
mixer_down: DeviceTensor,
mixer_up: DeviceTensor,
mixer_ws: CudaSlice<u8>,
mixed: CudaSlice<f32>,
unused_inject: CudaSlice<f32>,
head: DeviceTensor,
logits: CudaSlice<f32>,
/// The residual and its other half: every half-layer reads one and
/// writes the other, so each layer starts and ends in `residual[0]`.
residual: [CudaSlice<f32>; 2],
step: CudaSlice<i32>,
host_step: HostStep,
vocab: usize,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl NativeDecoder {
/// Loads every layer from the GGUF. `experts` must route on the
/// device; `max_len` sizes the attention caches.
pub fn load(
gguf: &Gguf,
cfg: &TextConfig,
experts: Arc<GgufExpertSource>,
max_len: usize,
) -> Result<Self> {
gdn::configure();
let device = gguf.device().clone();
let s = gdn::shapes(cfg)?;
let a = attn::shapes(cfg, max_len)?;
let m = moe::shapes(cfg)?;
ensure!(
a.heads <= POSITION_SLOTS,
"more query heads than position slots"
);
let ple_layers = cfg.ple_layers();
ensure!(
ple_layers.len() == 1,
"the engine expects exactly one PLE layer"
);
let mut layers = Vec::with_capacity(cfg.num_hidden_layers);
for (i, kind) in cfg
.layer_types
.iter()
.enumerate()
.take(cfg.num_hidden_layers)
{
let mixer = match kind.as_str() {
"linear_attention" => Mixer::Linear(
GdnWeights::load(gguf, i, &s)?,
GdnState::zeroed(&device, &s)?,
),
"full_attention" => Mixer::Full(
AttnWeights::load(gguf, i, &s, &a)?,
AttnCache::new(&device, &a)?,
),
other => bail!("layer {i}: unknown layer type {other}"),
};
layers.push(Layer {
mixer,
moe: MoeWeights::load(gguf, i, &s, &m)?,
});
}
let embed = gguf.upload_raw("token_embd.weight", row_bytes)?;
ensure!(
embed.dims == [s.n_embd as u64, cfg.vocab_size as u64],
"token_embd is {:?}",
embed.dims
);
let head = gguf.upload_bf16("output.weight")?;
ensure!(
head.dims == [s.n_embd as u64, cfg.vocab_size as u64],
"output is {:?}",
head.dims
);
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
// SAFETY: returns null or STEP_SLOTS i32 of pinned host memory.
let host = unsafe { ffi::neuron_strata_pinned_alloc(STEP_SLOTS * 4) }.cast::<i32>();
ensure!(!host.is_null(), "cannot pin the step buffer");
let wide = s.hc * s.n_embd;
Ok(Self {
head_graph: None,
tail_graph: None,
warmed: false,
gdn_sc: GdnScratch::new(&device, &s)?,
attn_sc: AttnScratch::new(&device, &s, &a)?,
moe_sc: MoeScratch::new(&device, &s, &m)?,
embed,
embed_row: device.alloc_zeros::<f32>(s.n_embd)?,
mixer_norm: gguf.upload_f32("output_hc_norm.weight")?,
mixer_down: gguf.upload_bf16("output_hc_down.weight")?,
mixer_up: gguf.upload_bf16("output_hc_up.weight")?,
mixer_ws: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
unused_inject: device.alloc_zeros::<f32>(s.hc)?,
head,
logits: device.alloc_zeros::<f32>(cfg.vocab_size)?,
residual: [
device.alloc_zeros::<f32>(wide)?,
device.alloc_zeros::<f32>(wide)?,
],
step: device.alloc_zeros::<i32>(STEP_SLOTS)?,
host_step: HostStep(host),
vocab: cfg.vocab_size,
ple_layer: ple_layers[0],
device,
s,
a,
m,
layers,
experts,
})
}
pub fn stream(&self) -> *mut c_void {
self.device.cuda_stream().cu_stream() as *mut c_void
}
/// The residual between the segments, `hc * n_embd` f32.
pub fn residual(&self) -> &CudaSlice<f32> {
&self.residual[0]
}
pub fn shapes(&self) -> (GdnShapes, AttnShapes, MoeShapes) {
(self.s, self.a, self.m)
}
/// Writes the step's inputs to the pinned buffer. Must come before
/// `segment_head` and after the previous step's logits were read.
pub fn set_step(&mut self, token: u32, pos: usize) -> Result<()> {
ensure!(
pos < self.a.max_len,
"position {pos} is past the {}-position cache",
self.a.max_len
);
// SAFETY: the buffer holds STEP_SLOTS i32, and no copy from it is
// in flight (the previous step's logits were read).
let host = unsafe { std::slice::from_raw_parts_mut(self.host_step.0, STEP_SLOTS) };
host[..POSITION_SLOTS].fill(pos as i32);
host[POSITION_SLOTS] = token as i32;
Ok(())
}
/// The host-side tier work between steps: what the experts learned
/// from the last step, and admissions.
pub fn adapt(&self) -> Result<()> {
for l in 0..self.layers.len() {
self.experts.adapt(l)?;
}
Ok(())
}
/// After a replay: the usage copies it made are this step's.
pub fn usage_replayed(&self) {
for l in 0..self.layers.len() {
self.experts.usage_replayed(l);
}
}
fn run_layer(&mut self, i: usize) -> Result<()> {
let stream = self.stream();
let (r0, r1) = (address(&self.residual[0]), address(&self.residual[1]));
let positions = address(&self.step);
let layer = &mut self.layers[i];
match &mut layer.mixer {
Mixer::Linear(w, state) => {
gdn::forward(w, state, &mut self.gdn_sc, &self.s, r0, r1, stream)?
}
Mixer::Full(w, cache) => attn::forward(
w,
cache,
&mut self.attn_sc,
&self.s,
&self.a,
positions,
r0,
r1,
stream,
)?,
}
moe::forward(
&layer.moe,
&self.experts,
i,
&mut self.moe_sc,
&self.s,
&self.m,
r1,
r0,
stream,
)
}
/// Segment one: the step inputs, the embedding into every stream,
/// and the layers before the PLE layer. Leaves the residual for the
/// caller to add PLE's contribution to.
pub fn segment_head(&mut self) -> Result<()> {
let stream = self.stream();
// SAFETY: the pinned source holds STEP_SLOTS i32 and the device
// buffer as many; both live as long as `self`.
let status = unsafe {
ffi::neuron_strata_copy_to_device(
address(&self.step) as *mut c_void,
self.host_step.0.cast(),
STEP_SLOTS * 4,
stream,
)
};
ensure!(
status == 0,
"step input copy failed with CUDA status {status}"
);
let (n_embd, hc) = (self.s.n_embd, self.s.hc);
let token = address(&self.step) + (POSITION_SLOTS * 4) as u64;
// SAFETY: the table holds `vocab` rows; `token` is one device id;
// the outputs are sized for one row and `hc` copies of it.
unsafe {
check(
ffi::neuron_embed_rows(
self.embed.ggml_type as i32,
self.embed.address() as *const c_void,
row_bytes(self.embed.ggml_type, n_embd as u64),
token as *const i32,
1,
n_embd as i64,
address(&self.embed_row) as *mut f32,
stream,
),
"embedding",
)?;
check(
ffi::neuron_repeat_row(
address(&self.embed_row) as *const f32,
address(&self.residual[0]) as *mut f32,
n_embd as i32,
hc as i32,
stream,
),
"embedding into the streams",
)?;
}
for i in 0..self.ple_layer {
self.run_layer(i).with_context(|| format!("layer {i}"))?;
}
Ok(())
}
/// Segment one, from its graph: captured on first use after a warm
/// eager step (which sizes every buffer the segment touches), then
/// replayed. The first call of all runs it eagerly.
pub fn run_head(&mut self) -> Result<()> {
self.run_captured(true)
}
/// Segment two, as [`Self::run_head`].
pub fn run_tail(&mut self) -> Result<()> {
self.run_captured(false)
}
fn run_captured(&mut self, head: bool) -> Result<()> {
if !self.warmed {
if head {
self.segment_head()?;
} else {
self.segment_tail()?;
self.warmed = true;
}
return Ok(());
}
let has = if head {
self.head_graph.is_some()
} else {
self.tail_graph.is_some()
};
if !has {
let stream = self.device.cuda_stream();
stream.begin_capture(sys::CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_THREAD_LOCAL)?;
let ran = if head {
self.segment_head()
} else {
self.segment_tail()
};
let graph = stream.end_capture(
sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH,
);
ran.context("while capturing")?;
let graph = graph?.context("capture produced no graph")?;
if head {
self.head_graph = Some(Graph(graph));
} else {
self.tail_graph = Some(Graph(graph));
}
}
let graph = if head {
&self.head_graph
} else {
&self.tail_graph
};
graph.as_ref().expect("captured above").0.launch()?;
if !head {
self.usage_replayed();
}
Ok(())
}
/// Adds `contribution` (`hc * n_embd` f32 on the device) to the
/// residual: the PLE layer's addition before its attention half.
pub fn add_to_residual(&mut self, contribution: u64) -> Result<()> {
let n = (self.s.hc * self.s.n_embd) as i32;
// SAFETY: both buffers hold `n` floats.
unsafe {
check(
ffi::neuron_add_inplace(
address(&self.residual[0]) as *mut f32,
contribution as *const f32,
n,
self.stream(),
),
"ple add",
)
}
}
/// Segment two: the layers from the PLE layer on, the final mixer and
/// the LM head, into the logits buffer.
pub fn segment_tail(&mut self) -> Result<()> {
for i in self.ple_layer..self.layers.len() {
self.run_layer(i).with_context(|| format!("layer {i}"))?;
}
let stream = self.stream();
let s = self.s;
// SAFETY: as in the layers; a null injection is the final
// mixer's, which collapses the streams without a write-back.
unsafe {
check(
ffi::neuron_gr_read(
address(&self.residual[0]) as *const f32,
self.mixer_norm.address() as *const f32,
self.mixer_down.address() as *const u16,
self.mixer_up.address() as *const u16,
std::ptr::null(),
s.eps,
s.n_embd as i64,
s.hc as i64,
s.hc_lr as i64,
address(&self.mixer_ws) as *mut c_void,
address(&self.mixed) as *mut f32,
address(&self.unused_inject) as *mut f32,
stream,
),
"final mixer",
)?;
check(
ffi::neuron_bf16_gemv(
address(&self.mixed) as *const f32,
self.head.address() as *const u16,
address(&self.logits) as *mut f32,
s.n_embd as i64,
self.vocab as i64,
stream,
),
"lm head",
)?;
}
Ok(())
}
/// The final mixer's output of the last step, `n_embd` f32: what the
/// LM head reads.
pub fn mixed(&self) -> &CudaSlice<f32> {
&self.mixed
}
/// The logits of the last step (waits for it).
pub fn logits(&self) -> Result<Vec<f32>> {
Ok(self.device.clone_dtoh(&self.logits)?)
}
/// Clears every sequence state, in place, for a new request.
pub fn reset(&mut self) -> Result<()> {
for layer in &mut self.layers {
match &mut layer.mixer {
Mixer::Linear(_, state) => state.clear(&self.device)?,
Mixer::Full(_, cache) => cache.clear(&self.device)?,
}
}
Ok(())
}
}
@@ -0,0 +1,373 @@
//! A linear-attention (gated delta-net) layer's mixer half, native.
//!
//! One decode token: the attention hyper-connection reads the four
//! residual streams into the mixer's input, the gated delta-net runs on
//! it, and the hyper-connection writes the result back. The MoE half of
//! the layer is separate. Ten kernel launches, against ~180 candle ops:
//!
//! 1. `gr_read`: stream norm, down/up bottleneck, gated mean, injection.
//! 2. quantize the mixer input to q8_1 for the Q8_0 projections.
//! 3. `qkv = attn_qkv @ x` (mmvq).
//! 4. causal conv + SiLU over all channels, L2 norm of the q and k heads.
//! 5. alpha/beta projections (BF16) with their softplus/sigmoid gates.
//! 6. `z = attn_gate @ x` (mmvq).
//! 7. the delta-rule step and the gated RMS norm of its readout.
//! 8. quantize that readout; 9. `out = ssm_out @ y` (mmvq).
//! 10. `gr_write`: the output added back to every stream, gated.
//!
//! Everything is in the GGUF's own layout (value heads tiled by key
//! head) and the state in Strata's: recurrent `[row][head][col]` f32,
//! conv history `[channel][3]` f32.
use std::ffi::{CStr, c_void};
use anyhow::{Result, bail, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
const Q8_1_BLOCK_VALUES: usize = 32;
const Q8_1_BLOCK_BYTES: usize = 36;
const STATE_SIZE: usize = 128;
const CONV_HISTORY: usize = 3;
/// Turns a kernel status into an error naming the step.
pub(crate) fn check(status: i32, what: &str) -> Result<()> {
if status == 0 {
return Ok(());
}
// SAFETY: returns a NUL-terminated string owned by the shim.
let message = unsafe { CStr::from_ptr(ffi::neuron_engine_last_error()) }.to_string_lossy();
bail!("{what} failed (status {status}): {message}")
}
/// Selects the kernel contracts Strata's decode uses. Idempotent.
pub fn configure() {
static ONCE: std::sync::Once = std::sync::Once::new();
// SAFETY: sets process-wide kernel selections before any launch.
ONCE.call_once(|| unsafe { ffi::neuron_engine_configure() });
}
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
/// Shapes of the hyper-connection and the gated delta-net.
#[derive(Debug, Clone, Copy)]
pub struct GdnShapes {
pub n_embd: usize,
pub hc: usize,
pub hc_lr: usize,
pub k_heads: usize,
pub v_heads: usize,
pub eps: f32,
}
impl GdnShapes {
fn qk(&self) -> usize {
self.k_heads * STATE_SIZE
}
fn value(&self) -> usize {
self.v_heads * STATE_SIZE
}
fn channels(&self) -> usize {
2 * self.qk() + self.value()
}
}
/// One layer's weights for the mixer half.
pub struct GdnWeights {
hc_norm: DeviceTensor,
hc_down: DeviceTensor,
hc_up: DeviceTensor,
hc_inject: DeviceTensor,
qkv: DeviceTensor,
gate: DeviceTensor,
out: DeviceTensor,
alpha: DeviceTensor,
beta: DeviceTensor,
conv: DeviceTensor,
norm: DeviceTensor,
dt: DeviceTensor,
ssm_a: DeviceTensor,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl GdnWeights {
pub fn load(gguf: &Gguf, layer: usize, s: &GdnShapes) -> Result<Self> {
let name = |t: &str| format!("blk.{layer}.{t}");
let projection = |t: &str, n_in: usize, n_out: usize| -> Result<DeviceTensor> {
let w = gguf.upload_raw(&name(t), row_bytes)?;
ensure!(
w.dims == [n_in as u64, n_out as u64],
"{} is {:?}, expected [{n_in}, {n_out}]",
name(t),
w.dims
);
// SAFETY: a pure function of its argument.
ensure!(
unsafe { ffi::neuron_strata_mmvq_supported(w.ggml_type as i32) } != 0,
"{}: no mmvq for type {}",
name(t),
w.ggml_type
);
Ok(w)
};
let wide = s.hc * s.n_embd;
let weights = Self {
hc_norm: gguf.upload_f32(&name("hc_attn_norm.weight"))?,
hc_down: gguf.upload_bf16(&name("hc_attn_down.weight"))?,
hc_up: gguf.upload_bf16(&name("hc_attn_up.weight"))?,
hc_inject: gguf.upload_bf16(&name("hc_attn_inject.weight"))?,
qkv: projection("attn_qkv.weight", s.n_embd, s.channels())?,
gate: projection("attn_gate.weight", s.n_embd, s.value())?,
out: projection("ssm_out.weight", s.value(), s.n_embd)?,
alpha: gguf.upload_bf16(&name("ssm_alpha.weight"))?,
beta: gguf.upload_bf16(&name("ssm_beta.weight"))?,
conv: gguf.upload_f32(&name("ssm_conv1d.weight"))?,
norm: gguf.upload_f32(&name("ssm_norm.weight"))?,
dt: gguf.upload_f32(&name("ssm_dt.bias"))?,
ssm_a: gguf.upload_f32(&name("ssm_a"))?,
};
for (t, want) in [
(&weights.hc_norm, wide),
(&weights.hc_down, s.hc_lr * wide),
(&weights.hc_up, wide * s.hc_lr),
(&weights.hc_inject, s.hc * wide),
(&weights.alpha, s.v_heads * s.n_embd),
(&weights.beta, s.v_heads * s.n_embd),
(&weights.conv, s.channels() * (CONV_HISTORY + 1)),
(&weights.norm, STATE_SIZE),
(&weights.dt, s.v_heads),
(&weights.ssm_a, s.v_heads),
] {
ensure!(
t.values() == want,
"layer {layer}: a tensor has {} values, expected {want}",
t.values()
);
}
Ok(weights)
}
}
/// A sequence's recurrent and conv state for one layer.
pub struct GdnState {
pub recurrent: CudaSlice<f32>,
pub conv: CudaSlice<f32>,
}
impl GdnState {
/// Zeroes the state in place: a captured step keeps its addresses.
pub fn clear(&mut self, device: &CudaDevice) -> Result<()> {
let stream = device.cuda_stream();
stream.memset_zeros(&mut self.recurrent)?;
stream.memset_zeros(&mut self.conv)?;
Ok(())
}
pub fn zeroed(device: &CudaDevice, s: &GdnShapes) -> Result<Self> {
Ok(Self {
recurrent: device.alloc_zeros::<f32>(STATE_SIZE * s.v_heads * STATE_SIZE)?,
conv: device.alloc_zeros::<f32>(s.channels() * CONV_HISTORY)?,
})
}
}
/// Intermediate buffers, shared by every layer of a step.
pub struct GdnScratch {
gr: CudaSlice<u8>,
mixed: CudaSlice<f32>,
inject: CudaSlice<f32>,
x_q8: CudaSlice<u8>,
qkv: CudaSlice<f32>,
h: CudaSlice<f32>,
z: CudaSlice<f32>,
gate: CudaSlice<f32>,
beta: CudaSlice<f32>,
y: CudaSlice<f32>,
y_q8: CudaSlice<u8>,
out: CudaSlice<f32>,
}
impl GdnScratch {
pub fn new(device: &CudaDevice, s: &GdnShapes) -> Result<Self> {
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
let q8 = |n: usize| n / Q8_1_BLOCK_VALUES * Q8_1_BLOCK_BYTES;
Ok(Self {
gr: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
inject: device.alloc_zeros::<f32>(s.hc)?,
x_q8: device.alloc_zeros::<u8>(q8(s.n_embd))?,
qkv: device.alloc_zeros::<f32>(s.channels())?,
h: device.alloc_zeros::<f32>(s.channels())?,
z: device.alloc_zeros::<f32>(s.value())?,
gate: device.alloc_zeros::<f32>(s.v_heads)?,
beta: device.alloc_zeros::<f32>(s.v_heads)?,
y: device.alloc_zeros::<f32>(s.value())?,
y_q8: device.alloc_zeros::<u8>(q8(s.value()))?,
out: device.alloc_zeros::<f32>(s.n_embd)?,
})
}
}
/// `y = W x` for a quantized `W` and an f32 `x` already in q8_1.
fn mmvq(w: &DeviceTensor, x_q8: u64, y: u64, stream: *mut c_void) {
// SAFETY: `w` is `dims[1]` rows of `dims[0]`, `x_q8` holds `dims[0]`
// values in q8_1 and `y` has room for `dims[1]` floats.
unsafe {
ffi::neuron_strata_mmvq(
w.ggml_type as i32,
w.address() as *const c_void,
x_q8 as *const c_void,
y as *mut f32,
w.dims[0] as i32,
w.dims[1] as i32,
1,
stream,
)
}
}
fn quantize(x: u64, n: usize, q8: u64, stream: *mut c_void) {
// SAFETY: `x` holds `n` floats and `q8` room for their q8_1 blocks.
unsafe {
ffi::neuron_strata_quantize_q8_1(x as *const f32, 1, n as i64, q8 as *mut c_void, stream)
}
}
/// The mixer half of one linear-attention layer, for one token:
/// `residual_out = residual + gated(gdn(gr_read(residual)))`.
///
/// `residual` and `residual_out` are `hc * n_embd` f32 device buffers and
/// may not alias. Nothing allocates or waits, so this can be captured.
pub fn forward(
w: &GdnWeights,
state: &mut GdnState,
sc: &mut GdnScratch,
s: &GdnShapes,
residual: u64,
residual_out: u64,
stream: *mut c_void,
) -> Result<()> {
let (n_embd, hc, hc_lr) = (s.n_embd as i64, s.hc as i64, s.hc_lr as i64);
let qk = s.qk() as u64 * 4;
// SAFETY (all calls below): every pointer is a live device buffer of
// the size its kernel reads or writes, as allocated in `GdnScratch`,
// `GdnState` and `GdnWeights`, and every launch is on `stream`.
unsafe {
check(
ffi::neuron_gr_read(
residual as *const f32,
w.hc_norm.address() as *const f32,
w.hc_down.address() as *const u16,
w.hc_up.address() as *const u16,
w.hc_inject.address() as *const u16,
s.eps,
n_embd,
hc,
hc_lr,
address(&sc.gr) as *mut c_void,
address(&sc.mixed) as *mut f32,
address(&sc.inject) as *mut f32,
stream,
),
"gr_read",
)?;
quantize(address(&sc.mixed), s.n_embd, address(&sc.x_q8), stream);
mmvq(&w.qkv, address(&sc.x_q8), address(&sc.qkv), stream);
check(
ffi::neuron_gdn_conv_l2(
address(&state.conv) as *mut f32,
address(&sc.qkv) as *const f32,
w.conv.address() as *const f32,
address(&sc.h) as *mut f32,
s.channels() as i32,
(2 * s.k_heads) as i32,
s.eps,
stream,
),
"gdn conv + l2",
)?;
check(
ffi::neuron_gdn_ab(
address(&sc.mixed) as *const f32,
w.alpha.address() as *const u16,
w.beta.address() as *const u16,
w.dt.address() as *const f32,
w.ssm_a.address() as *const f32,
address(&sc.gate) as *mut f32,
address(&sc.beta) as *mut f32,
s.n_embd as i32,
s.v_heads as i32,
stream,
),
"gdn alpha/beta",
)?;
mmvq(&w.gate, address(&sc.x_q8), address(&sc.z), stream);
let h = address(&sc.h);
check(
ffi::neuron_gdn_step_norm(
address(&state.recurrent) as *mut f32,
h as *const f32,
(h + qk) as *const f32,
(h + 2 * qk) as *const f32,
address(&sc.gate) as *const f32,
address(&sc.beta) as *const f32,
address(&sc.z) as *const f32,
w.norm.address() as *const f32,
s.eps,
address(&sc.y) as *mut f32,
s.k_heads as i32,
s.v_heads as i32,
stream,
),
"gdn step + norm",
)?;
quantize(address(&sc.y), s.value(), address(&sc.y_q8), stream);
mmvq(&w.out, address(&sc.y_q8), address(&sc.out), stream);
check(
ffi::neuron_gr_write(
residual as *const f32,
address(&sc.out) as *const f32,
address(&sc.inject) as *const f32,
n_embd,
hc,
hc_lr,
residual_out as *mut f32,
stream,
),
"gr_write",
)?;
}
Ok(())
}
/// The shapes of a qwen4_exp config.
pub fn shapes(cfg: &super::super::config::TextConfig) -> Result<GdnShapes> {
let s = GdnShapes {
n_embd: cfg.hidden_size,
hc: cfg.hc_count,
hc_lr: cfg.hc_lowrank,
k_heads: cfg.linear_num_key_heads,
v_heads: cfg.linear_num_value_heads,
eps: cfg.rms_norm_eps as f32,
};
ensure!(
cfg.linear_key_head_dim == STATE_SIZE && cfg.linear_value_head_dim == STATE_SIZE,
"the native gated delta-net is built for 128-wide heads"
);
ensure!(
s.v_heads.is_multiple_of(s.k_heads),
"value heads must be a multiple of key heads"
);
Ok(s)
}
@@ -0,0 +1,18 @@
//! The native qwen4_exp decode engine (#427).
//!
//! A decode step as fixed work over buffers allocated once: Strata's
//! kernels (and neuron's own) driven over device pointers, so the step can
//! be captured as one CUDA graph. Candle remains the loader for
//! everything else, the prompt path, and the parity oracle every layer
//! here is checked against.
pub mod weights;
#[cfg(feature = "strata-kernels")]
pub mod attn;
#[cfg(feature = "strata-kernels")]
pub mod decoder;
#[cfg(feature = "strata-kernels")]
pub mod gdn;
#[cfg(feature = "strata-kernels")]
pub mod moe;
@@ -0,0 +1,345 @@
//! A decoder layer's MoE half, native.
//!
//! One decode token: the FFN hyper-connection reads the streams into the
//! block's input; the router picks ten experts on the device; the routed
//! experts run on the grouped kernel through the device-routed expert
//! path (#425), misses gathered into the arena; the shared expert runs
//! beside them; the weighted combination is written back to every
//! stream through the hyper-connection. Every layer, linear or full
//! attention, has this half.
use std::ffi::c_void;
use anyhow::{Result, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use super::gdn::{GdnShapes, check};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
use crate::harness::arch::qwen4_exp::native_experts::GgufExpertSource;
const Q8_1_BLOCK_VALUES: usize = 32;
const Q8_1_BLOCK_BYTES: usize = 36;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
/// Routing and expert widths.
#[derive(Debug, Clone, Copy)]
pub struct MoeShapes {
pub experts: usize,
pub k: usize,
pub n_ff: usize,
}
pub struct MoeWeights {
hc_norm: DeviceTensor,
hc_down: DeviceTensor,
hc_up: DeviceTensor,
hc_inject: DeviceTensor,
router: DeviceTensor,
shared_gate: DeviceTensor,
shared_up: DeviceTensor,
shared_down: DeviceTensor,
shared_scale: DeviceTensor,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl MoeWeights {
pub fn load(gguf: &Gguf, layer: usize, s: &GdnShapes, m: &MoeShapes) -> Result<Self> {
let name = |t: &str| format!("blk.{layer}.{t}");
let projection = |t: &str, n_in: usize, n_out: usize| -> Result<DeviceTensor> {
let w = gguf.upload_raw(&name(t), row_bytes)?;
ensure!(
w.dims == [n_in as u64, n_out as u64],
"{} is {:?}, expected [{n_in}, {n_out}]",
name(t),
w.dims
);
// SAFETY: a pure function of its argument.
ensure!(
unsafe { ffi::neuron_strata_mmvq_supported(w.ggml_type as i32) } != 0,
"{}: no mmvq for type {}",
name(t),
w.ggml_type
);
Ok(w)
};
let wide = s.hc * s.n_embd;
let w = Self {
hc_norm: gguf.upload_f32(&name("hc_ffn_norm.weight"))?,
hc_down: gguf.upload_bf16(&name("hc_ffn_down.weight"))?,
hc_up: gguf.upload_bf16(&name("hc_ffn_up.weight"))?,
hc_inject: gguf.upload_bf16(&name("hc_ffn_inject.weight"))?,
router: gguf.upload_bf16(&name("ffn_gate_inp.weight"))?,
shared_gate: projection("ffn_gate_shexp.weight", s.n_embd, m.n_ff)?,
shared_up: projection("ffn_up_shexp.weight", s.n_embd, m.n_ff)?,
shared_down: projection("ffn_down_shexp.weight", m.n_ff, s.n_embd)?,
shared_scale: gguf.upload_bf16(&name("ffn_gate_inp_shexp.weight"))?,
};
for (t, want) in [
(&w.hc_norm, wide),
(&w.hc_down, s.hc_lr * wide),
(&w.hc_up, wide * s.hc_lr),
(&w.hc_inject, s.hc * wide),
(&w.router, m.experts * s.n_embd),
(&w.shared_scale, s.n_embd),
] {
ensure!(
t.values() == want,
"layer {layer}: a tensor has {} values, expected {want}",
t.values()
);
}
Ok(w)
}
}
pub struct MoeScratch {
gr: CudaSlice<u8>,
mixed: CudaSlice<f32>,
inject: CudaSlice<f32>,
logits: CudaSlice<f32>,
ids: CudaSlice<i32>,
weights: CudaSlice<f32>,
parts: CudaSlice<f32>,
w_route: CudaSlice<f32>,
x_q8: CudaSlice<u8>,
gate: CudaSlice<f32>,
up: CudaSlice<f32>,
h: CudaSlice<f32>,
h_q8: CudaSlice<u8>,
shared: CudaSlice<f32>,
scale: CudaSlice<f32>,
out: CudaSlice<f32>,
}
impl MoeScratch {
/// The experts the last step routed to, for inspection.
pub fn routed(&self, device: &CudaDevice) -> Result<(Vec<i32>, Vec<f32>)> {
Ok((
device.clone_dtoh(&self.ids)?,
device.clone_dtoh(&self.logits)?,
))
}
pub fn new(device: &CudaDevice, s: &GdnShapes, m: &MoeShapes) -> Result<Self> {
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
let q8 = |n: usize| n / Q8_1_BLOCK_VALUES * Q8_1_BLOCK_BYTES;
Ok(Self {
gr: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
inject: device.alloc_zeros::<f32>(s.hc)?,
logits: device.alloc_zeros::<f32>(m.experts)?,
ids: device.alloc_zeros::<i32>(m.k)?,
weights: device.alloc_zeros::<f32>(m.k)?,
parts: device.alloc_zeros::<f32>(m.k * s.n_embd)?,
w_route: device.alloc_zeros::<f32>(m.k)?,
x_q8: device.alloc_zeros::<u8>(q8(s.n_embd))?,
gate: device.alloc_zeros::<f32>(m.n_ff)?,
up: device.alloc_zeros::<f32>(m.n_ff)?,
h: device.alloc_zeros::<f32>(m.n_ff)?,
h_q8: device.alloc_zeros::<u8>(q8(m.n_ff))?,
shared: device.alloc_zeros::<f32>(s.n_embd)?,
scale: device.alloc_zeros::<f32>(1)?,
out: device.alloc_zeros::<f32>(s.n_embd)?,
})
}
}
fn mmvq(w: &DeviceTensor, x_q8: u64, y: u64, stream: *mut c_void) {
// SAFETY: `w` is `dims[1]` rows of `dims[0]`, `x_q8` holds `dims[0]`
// values in q8_1 and `y` has room for `dims[1]` floats.
unsafe {
ffi::neuron_strata_mmvq(
w.ggml_type as i32,
w.address() as *const c_void,
x_q8 as *const c_void,
y as *mut f32,
w.dims[0] as i32,
w.dims[1] as i32,
1,
stream,
)
}
}
fn quantize(x: u64, n: usize, q8: u64, stream: *mut c_void) {
// SAFETY: `x` holds `n` floats and `q8` room for their q8_1 blocks.
unsafe {
ffi::neuron_strata_quantize_q8_1(x as *const f32, 1, n as i64, q8 as *mut c_void, stream)
}
}
/// The MoE half of layer `layer`, for one token:
/// `residual_out = residual + gated(moe(gr_read(residual)))`.
///
/// The experts come from `experts`, which must route on the device. It
/// does not adapt the expert tier; the caller does that between steps.
#[allow(clippy::too_many_arguments)]
pub fn forward(
w: &MoeWeights,
experts: &GgufExpertSource,
layer: usize,
sc: &mut MoeScratch,
s: &GdnShapes,
m: &MoeShapes,
residual: u64,
residual_out: u64,
stream: *mut c_void,
) -> Result<()> {
let (n_embd, hc, hc_lr) = (s.n_embd as i64, s.hc as i64, s.hc_lr as i64);
// SAFETY (all calls below): every pointer is a live device buffer of
// the size its kernel reads or writes, as allocated in `MoeScratch`
// and `MoeWeights`, and every launch is on `stream`.
unsafe {
check(
ffi::neuron_gr_read(
residual as *const f32,
w.hc_norm.address() as *const f32,
w.hc_down.address() as *const u16,
w.hc_up.address() as *const u16,
w.hc_inject.address() as *const u16,
s.eps,
n_embd,
hc,
hc_lr,
address(&sc.gr) as *mut c_void,
address(&sc.mixed) as *mut f32,
address(&sc.inject) as *mut f32,
stream,
),
"ffn gr_read",
)?;
check(
ffi::neuron_bf16_gemv(
address(&sc.mixed) as *const f32,
w.router.address() as *const u16,
address(&sc.logits) as *mut f32,
n_embd,
m.experts as i64,
stream,
),
"router",
)?;
check(
ffi::neuron_router_top10(
address(&sc.logits) as *const f32,
address(&sc.ids) as *mut i32,
address(&sc.weights) as *mut f32,
stream,
),
"router top-10",
)?;
}
experts.launch_routed(
layer,
address(&sc.mixed),
address(&sc.ids),
address(&sc.weights),
1,
m.k,
address(&sc.parts),
address(&sc.w_route),
stream,
)?;
experts.record_usage(layer, address(&sc.ids), m.k)?;
quantize(address(&sc.mixed), s.n_embd, address(&sc.x_q8), stream);
mmvq(&w.shared_gate, address(&sc.x_q8), address(&sc.gate), stream);
mmvq(&w.shared_up, address(&sc.x_q8), address(&sc.up), stream);
// SAFETY: as above.
unsafe {
check(
ffi::neuron_swiglu(
address(&sc.gate) as *const f32,
address(&sc.up) as *const f32,
address(&sc.h) as *mut f32,
m.n_ff as i32,
stream,
),
"shared swiglu",
)?;
}
quantize(address(&sc.h), m.n_ff, address(&sc.h_q8), stream);
mmvq(
&w.shared_down,
address(&sc.h_q8),
address(&sc.shared),
stream,
);
// SAFETY: as above.
unsafe {
check(
ffi::neuron_bf16_gemv(
address(&sc.mixed) as *const f32,
w.shared_scale.address() as *const u16,
address(&sc.scale) as *mut f32,
n_embd,
1,
stream,
),
"shared gate",
)?;
check(
ffi::neuron_scale_by_sigmoid(
address(&sc.shared) as *mut f32,
address(&sc.scale) as *const f32,
s.n_embd as i32,
stream,
),
"shared gate apply",
)?;
check(
ffi::neuron_moe_combine(
address(&sc.parts) as *const f32,
address(&sc.w_route) as *const f32,
address(&sc.shared) as *const f32,
address(&sc.out) as *mut f32,
n_embd,
m.k as i64,
stream,
),
"moe combine",
)?;
check(
ffi::neuron_gr_write(
residual as *const f32,
address(&sc.out) as *const f32,
address(&sc.inject) as *const f32,
n_embd,
hc,
hc_lr,
residual_out as *mut f32,
stream,
),
"ffn gr_write",
)?;
}
Ok(())
}
/// The MoE shapes of a qwen4_exp config.
pub fn shapes(cfg: &super::super::config::TextConfig) -> Result<MoeShapes> {
let m = MoeShapes {
experts: cfg.num_experts,
k: cfg.num_experts_per_tok,
n_ff: cfg.moe_intermediate_size,
};
ensure!(
m.experts == 512 && m.k == 10,
"the native router is built for 512 experts, top 10"
);
ensure!(
cfg.shared_expert_intermediate_size == m.n_ff,
"the shared expert is assumed as wide as a routed one"
);
Ok(m)
}
@@ -0,0 +1,346 @@
//! GGUF tensors as the native decode engine (#427) holds them.
//!
//! The engine reads the GGUF as it is stored: llama.cpp's layout and
//! head order (the linear-attention value heads tiled by key head), the
//! norm weights already `1 + w`, `ssm_a` already `-exp(A_log)`. That is
//! the form Strata's kernels take. Quantized projections stay quantized;
//! the tensors Strata's pack converts to BF16 (the hyper-connection mixes
//! and injections, the GDN alpha/beta, the routers) are converted the
//! same way here, rounding to nearest even.
/// ggml type ids the engine handles.
pub const GGML_F32: u32 = 0;
pub const GGML_F16: u32 = 1;
pub const GGML_Q8_0: u32 = 8;
pub const GGML_Q6_K: u32 = 14;
pub const GGML_BF16: u32 = 30;
const Q8_0_BLOCK_VALUES: usize = 32;
const Q8_0_BLOCK_BYTES: usize = 34;
/// IEEE half to single, subnormals included.
pub fn f16_to_f32(h: u16) -> f32 {
let sign = ((h >> 15) & 1) as u32;
let exp = ((h >> 10) & 0x1f) as u32;
let man = (h & 0x3ff) as u32;
let bits = match (exp, man) {
(0, 0) => sign << 31,
(0, _) => {
// Subnormal: renormalise.
let shift = man.leading_zeros() - 21;
let man = (man << shift) & 0x3ff;
(sign << 31) | ((113 - shift) << 23) | (man << 13)
}
(0x1f, _) => (sign << 31) | (0xff << 23) | (man << 13),
_ => (sign << 31) | ((exp + 112) << 23) | (man << 13),
};
f32::from_bits(bits)
}
/// Single to BF16 bits, round to nearest even (NaN stays NaN).
pub fn f32_to_bf16(x: f32) -> u16 {
let bits = x.to_bits();
if x.is_nan() {
return ((bits >> 16) | 0x40) as u16;
}
let round = 0x7fff + ((bits >> 16) & 1);
(bits.wrapping_add(round) >> 16) as u16
}
/// Q8_0 blocks (an f16 scale, then 32 signed bytes) to f32.
pub fn q8_0_to_f32(bytes: &[u8]) -> Vec<f32> {
let mut out = Vec::with_capacity(bytes.len() / Q8_0_BLOCK_BYTES * Q8_0_BLOCK_VALUES);
for block in bytes.as_chunks::<Q8_0_BLOCK_BYTES>().0 {
let d = f16_to_f32(u16::from_le_bytes([block[0], block[1]]));
out.extend(block[2..].iter().map(|&q| d * f32::from(q as i8)));
}
out
}
const Q6_K_BLOCK_VALUES: usize = 256;
const Q6_K_BLOCK_BYTES: usize = 210;
/// Q6_K blocks to f32, as ggml's `dequantize_row_q6_K`: per 256 values,
/// 128 bytes of low nibbles, 64 of high bit pairs, 16 signed scales and
/// an f16 scale.
pub fn q6_k_to_f32(bytes: &[u8]) -> Vec<f32> {
let mut out = Vec::with_capacity(bytes.len() / Q6_K_BLOCK_BYTES * Q6_K_BLOCK_VALUES);
for block in bytes.as_chunks::<Q6_K_BLOCK_BYTES>().0 {
let (ql, rest) = block.split_at(128);
let (qh, rest) = rest.split_at(64);
let (sc, d) = rest.split_at(16);
let d = f16_to_f32(u16::from_le_bytes([d[0], d[1]]));
let mut y = [0f32; Q6_K_BLOCK_VALUES];
for half in 0..2 {
let (ql, qh, sc) = (&ql[64 * half..], &qh[32 * half..], &sc[8 * half..]);
let y = &mut y[128 * half..];
for l in 0..32 {
let is = l / 16;
let q = |low: u8, shift: u32| -> f32 {
f32::from(((low | (((qh[l] >> shift) & 3) << 4)) as i8) - 32)
};
let s = |i: usize| f32::from(sc[i] as i8);
y[l] = d * s(is) * q(ql[l] & 0xf, 0);
y[l + 32] = d * s(is + 2) * q(ql[l + 32] & 0xf, 2);
y[l + 64] = d * s(is + 4) * q(ql[l] >> 4, 4);
y[l + 96] = d * s(is + 6) * q(ql[l + 32] >> 4, 6);
}
}
out.extend_from_slice(&y);
}
out
}
/// A tensor's values as f32, from the GGUF types the engine converts.
pub fn to_f32(bytes: &[u8], ggml_type: u32) -> Option<Vec<f32>> {
Some(match ggml_type {
GGML_F32 => bytes
.as_chunks::<4>()
.0
.iter()
.map(|&b| f32::from_le_bytes(b))
.collect(),
GGML_F16 => bytes
.as_chunks::<2>()
.0
.iter()
.map(|&b| f16_to_f32(u16::from_le_bytes(b)))
.collect(),
GGML_BF16 => bytes
.as_chunks::<2>()
.0
.iter()
.map(|&b| f32::from_bits(u32::from(u16::from_le_bytes(b)) << 16))
.collect(),
GGML_Q8_0 => q8_0_to_f32(bytes),
GGML_Q6_K => q6_k_to_f32(bytes),
_ => return None,
})
}
/// Bytes a tensor of `ggml_type` with `values` elements occupies, for
/// the types the engine reads whole.
pub fn tensor_bytes(ggml_type: u32, values: usize) -> Option<usize> {
Some(match ggml_type {
GGML_F32 => values * 4,
GGML_F16 | GGML_BF16 => values * 2,
GGML_Q8_0 if values.is_multiple_of(Q8_0_BLOCK_VALUES) => {
values / Q8_0_BLOCK_VALUES * Q8_0_BLOCK_BYTES
}
GGML_Q6_K if values.is_multiple_of(Q6_K_BLOCK_VALUES) => {
values / Q6_K_BLOCK_VALUES * Q6_K_BLOCK_BYTES
}
_ => return None,
})
}
#[cfg(feature = "strata-kernels")]
pub use device::{DeviceTensor, Gguf};
#[cfg(feature = "strata-kernels")]
mod device {
use std::fs::File;
use std::path::Path;
use anyhow::{Context, Result, bail, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use memmap2::Mmap;
use super::{GGML_BF16, GGML_F32, f32_to_bf16, tensor_bytes, to_f32};
use crate::harness::arch::qwen4_exp::gguf_index::{GgufIndex, GgufTensor};
/// A tensor on the device, in whatever form it was uploaded.
pub struct DeviceTensor {
buf: CudaSlice<u8>,
pub ggml_type: u32,
/// ggml order: `dims[0]` is the fastest-varying (the input width
/// of a projection).
pub dims: Vec<u64>,
}
impl DeviceTensor {
pub fn address(&self) -> u64 {
self.buf.device_ptr(self.buf.stream()).0
}
pub fn values(&self) -> usize {
self.dims.iter().product::<u64>() as usize
}
}
/// The GGUF's shards, mapped, and the device tensors go to.
pub struct Gguf {
pub index: GgufIndex,
maps: Vec<Mmap>,
device: CudaDevice,
}
impl Gguf {
pub fn open(first: &Path, device: &CudaDevice) -> Result<Self> {
let index = GgufIndex::open(first)?;
let mut maps = Vec::with_capacity(index.shards.len());
for path in &index.shards {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
// SAFETY: model files are not modified while serving.
maps.push(
unsafe { Mmap::map(&file) }
.with_context(|| format!("map {}", path.display()))?,
);
}
Ok(Self {
index,
maps,
device: device.clone(),
})
}
fn tensor(&self, name: &str) -> Result<&GgufTensor> {
self.index
.tensors
.get(name)
.with_context(|| format!("the GGUF has no {name}"))
}
/// The tensor's stored bytes. Only for the types whose size the
/// engine knows; quantized projections use `upload_raw`.
fn bytes(&self, name: &str, size: usize) -> Result<&[u8]> {
let t = self.tensor(name)?;
let map = &self.maps[t.shard];
let start = t.offset as usize;
ensure!(start + size <= map.len(), "{name} runs past its shard");
Ok(&map[start..start + size])
}
fn upload(&self, host: &[u8], ggml_type: u32, dims: Vec<u64>) -> Result<DeviceTensor> {
// SAFETY: written in full by the copy below.
let mut buf = unsafe { self.device.alloc::<u8>(host.len().max(1)) }?;
self.device.memcpy_htod(host, &mut buf)?;
Ok(DeviceTensor {
buf,
ggml_type,
dims,
})
}
/// The tensor as stored, for the kernels that read its format.
/// `row_bytes` gives the size of one `dims[0]`-wide row.
pub fn upload_raw(
&self,
name: &str,
row_bytes: impl Fn(u32, u64) -> usize,
) -> Result<DeviceTensor> {
let t = self.tensor(name)?;
let rows: u64 = t.dims.iter().skip(1).product();
let size = row_bytes(t.ggml_type, t.dims[0]) * rows as usize;
ensure!(size > 0, "{name}: no row size for type {}", t.ggml_type);
let host = self.bytes(name, size)?;
self.upload(host, t.ggml_type, t.dims.clone())
}
fn values_f32(&self, name: &str) -> Result<(Vec<f32>, Vec<u64>)> {
let t = self.tensor(name)?;
let n: u64 = t.dims.iter().product();
let Some(size) = tensor_bytes(t.ggml_type, n as usize) else {
bail!("{name}: the engine cannot convert type {}", t.ggml_type);
};
let values = to_f32(self.bytes(name, size)?, t.ggml_type)
.with_context(|| format!("{name}: unconvertible type {}", t.ggml_type))?;
Ok((values, t.dims.clone()))
}
/// The tensor as f32.
pub fn upload_f32(&self, name: &str) -> Result<DeviceTensor> {
let (values, dims) = self.values_f32(name)?;
let host: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
self.upload(&host, GGML_F32, dims)
}
/// The tensor as BF16, rounded to nearest even.
pub fn upload_bf16(&self, name: &str) -> Result<DeviceTensor> {
let (values, dims) = self.values_f32(name)?;
let host: Vec<u8> = values
.iter()
.flat_map(|&v| f32_to_bf16(v).to_le_bytes())
.collect();
self.upload(&host, GGML_BF16, dims)
}
pub fn device(&self) -> &CudaDevice {
&self.device
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn half_precision_converts_exactly() {
assert_eq!(f16_to_f32(0x3c00), 1.0);
assert_eq!(f16_to_f32(0xc000), -2.0);
assert_eq!(f16_to_f32(0x0000), 0.0);
assert_eq!(f16_to_f32(0x7bff), 65504.0);
// Smallest subnormal, 2^-24, and a larger one, 2^-15.
assert_eq!(f16_to_f32(0x0001), 2f32.powi(-24));
assert_eq!(f16_to_f32(0x0200), 2f32.powi(-15));
assert!(f16_to_f32(0x7c00).is_infinite());
}
/// Ties go to the even mantissa, and anything past half rounds up.
#[test]
fn bf16_rounds_to_nearest_even() {
assert_eq!(f32_to_bf16(1.0), 0x3f80);
// 1 + 2^-8 is exactly halfway between 1 and 1 + 2^-7: to even.
assert_eq!(f32_to_bf16(1.0 + 2f32.powi(-8)), 0x3f80);
// 1 + 3 * 2^-8 is halfway between 1 + 2^-7 (odd) and 1 + 2^-6.
assert_eq!(f32_to_bf16(1.0 + 3.0 * 2f32.powi(-8)), 0x3f82);
// Just past halfway rounds up.
assert_eq!(f32_to_bf16(1.0 + 2f32.powi(-8) + 2f32.powi(-20)), 0x3f81);
assert_eq!(f32_to_bf16(-2.5), 0xc020);
}
/// One Q6_K block built by hand: every 6-bit value is assembled from
/// its low nibble and high bit pair, offset by 32, and scaled by its
/// group's scale and the block scale.
#[test]
fn q6_k_assembles_six_bit_values() {
let mut block = vec![0u8; 210];
// Value 0: low nibble 5, high bits 0b10 -> 0b10_0101 = 37, -32 = 5.
block[0] = 0x05;
block[128] = 0b10;
// Value 96 (fourth quarter: ql[32]'s high nibble, qh[0] bits 6-7):
// nibble 0xf, high bits 0b01 -> 0b01_1111 = 31, -32 = -1.
block[32] = 0xf0;
block[128] |= 0b01 << 6;
// Scales: group 0 = 3, group 6 (value 96's) = -2.
block[192] = 3;
block[198] = (-2i8) as u8;
block[208..210].copy_from_slice(&0x3800u16.to_le_bytes()); // 0.5
let y = q6_k_to_f32(&block);
assert_eq!(y.len(), 256);
assert_eq!(y[0], 0.5 * 3.0 * 5.0);
// scale 0.5, group scale -2, value -1.
assert_eq!(y[96], 1.0);
// An all-zero position reads 0 - 32 = -32 times its scale.
assert_eq!(y[1], 0.5 * 3.0 * -32.0);
assert_eq!(tensor_bytes(GGML_Q6_K, 512), Some(420));
}
#[test]
fn q8_0_blocks_scale_their_bytes() {
let mut block = vec![0u8; 34];
block[..2].copy_from_slice(&0x3800u16.to_le_bytes()); // 0.5
for (i, b) in block[2..].iter_mut().enumerate() {
*b = (i as i8 - 16) as u8;
}
let values = q8_0_to_f32(&block);
assert_eq!(values.len(), 32);
assert_eq!(values[0], -8.0);
assert_eq!(values[16], 0.0);
assert_eq!(values[31], 7.5);
assert_eq!(tensor_bytes(GGML_Q8_0, 64), Some(68));
assert_eq!(tensor_bytes(GGML_Q8_0, 33), None);
}
}
@@ -26,14 +26,14 @@
//!
//! See `doc/qwen4_exp-port-spec.md` §3 and §4.
use anyhow::{Context, Result};
use anyhow::Result;
use candle_core::{Module, Tensor};
use candle_nn::Linear;
use candle_nn::kv_cache::ConcatKvCache;
use candle_nn::var_builder::ShardedVarBuilder;
use std::sync::Arc;
use crate::harness::arch::qwen3_5::full_attn::{AttnMask, attention_context};
use crate::harness::arch::qwen3_5::proj::{LinearSource, Proj, load_proj};
use crate::harness::arch::qwen3_5::rmsnorm::Qwen3_5RmsNorm;
use crate::harness::arch::qwen3_5::rope::RotaryEmbedding;
@@ -41,10 +41,10 @@ use super::config::TextConfig;
use super::qsa::Indexer;
pub struct Attention {
q_proj: Linear,
k_proj: Linear,
v_proj: Linear,
o_proj: Linear,
q_proj: Proj,
k_proj: Proj,
v_proj: Proj,
o_proj: Proj,
q_norm: Qwen3_5RmsNorm,
k_norm: Qwen3_5RmsNorm,
/// The sparse-attention side channel. Owns its own KV cache, which
@@ -66,6 +66,7 @@ impl Attention {
cfg: &TextConfig,
rotary: Arc<RotaryEmbedding>,
vb: &ShardedVarBuilder,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let head_dim = cfg.head_dim;
let num_heads = cfg.num_attention_heads;
@@ -78,10 +79,22 @@ impl Attention {
let attn_width = num_heads * head_dim;
Ok(Self {
// Doubled output: query and gate, interleaved per head.
q_proj: linear(vb, "q_proj", cfg.hidden_size, attn_width * 2)?,
k_proj: linear(vb, "k_proj", cfg.hidden_size, num_kv_heads * head_dim)?,
v_proj: linear(vb, "v_proj", cfg.hidden_size, num_kv_heads * head_dim)?,
o_proj: linear(vb, "o_proj", attn_width, cfg.hidden_size)?,
q_proj: load_proj(vb, "q_proj", cfg.hidden_size, attn_width * 2, source)?,
k_proj: load_proj(
vb,
"k_proj",
cfg.hidden_size,
num_kv_heads * head_dim,
source,
)?,
v_proj: load_proj(
vb,
"v_proj",
cfg.hidden_size,
num_kv_heads * head_dim,
source,
)?,
o_proj: load_proj(vb, "o_proj", attn_width, cfg.hidden_size, source)?,
q_norm: Qwen3_5RmsNorm::load(&vb.pp("q_norm"), head_dim, cfg.rms_norm_eps)?,
k_norm: Qwen3_5RmsNorm::load(&vb.pp("k_norm"), head_dim, cfg.rms_norm_eps)?,
// The indexer is a submodule of the attention block, not a
@@ -210,20 +223,13 @@ impl Attention {
}
}
fn linear(vb: &ShardedVarBuilder, name: &str, in_dim: usize, out_dim: usize) -> Result<Linear> {
let weight = vb
.pp(name)
.get((out_dim, in_dim), "weight")
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Linear::new(weight, None))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::harness::arch::qwen3_5::TextConfig as Qwen3_5TextConfig;
use crate::harness::arch::qwen4_exp::qsa::BlockSelector;
use candle_core::{DType, Device};
use candle_nn::Linear;
const HIDDEN: usize = 4;
const HEADS: usize = 2;
@@ -272,10 +278,10 @@ mod tests {
fn layer(budget: usize) -> Attention {
let attn_width = HEADS * HEAD_DIM;
Attention {
q_proj: from_first_column(&[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0], HIDDEN),
k_proj: from_first_column(&[0.0; HEAD_DIM], HIDDEN),
v_proj: from_first_column(&[1.0; HEAD_DIM], HIDDEN),
o_proj: eye(attn_width),
q_proj: from_first_column(&[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0], HIDDEN).into(),
k_proj: from_first_column(&[0.0; HEAD_DIM], HIDDEN).into(),
v_proj: from_first_column(&[1.0; HEAD_DIM], HIDDEN).into(),
o_proj: eye(attn_width).into(),
q_norm: Qwen3_5RmsNorm::from_weight(
Tensor::zeros(HEAD_DIM, DType::F32, &Device::Cpu).unwrap(),
1e-6,
@@ -0,0 +1,479 @@
//! Dense projections from a GGUF's quantized blocks, run on Strata's
//! kernels: a quantized matrix-vector product (`mmvq`) for decode-sized
//! inputs, and dequantize + cuBLAS for prompt chunks.
//!
//! Most of the model's dense tensors are stored as Q8_0 in the UD packs,
//! half of BF16. They map to the checkpoint by name, each in its own
//! layout, except the linear-attention value heads: llama.cpp's
//! converter stores them tiled by key head where the checkpoint groups
//! them. With `r = value_heads / key_heads`, GGUF head `g * key_heads +
//! k` holds checkpoint head `r * k + g`. That is undone at load by
//! moving whole quantized rows (or whole blocks within each row, where
//! the heads are the input dimension), so no value is requantized.
use anyhow::{Result, ensure};
/// How a GGUF tensor's value heads must move to match the checkpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Reorder {
None,
/// Output rows, after the first `skip_rows` (the q and k of a fused
/// qkv projection, which are stored in order).
Rows {
skip_rows: usize,
},
/// Input columns: within every row, per head of `head_dim` values.
Cols,
}
/// The GGUF tensor holding checkpoint tensor `name`, and its reorder.
pub(crate) fn gguf_name(name: &str) -> Option<(String, Reorder, bool)> {
// The bool says whether `skip_rows` must be filled in from the
// config: only the fused qkv knows its q and k widths.
if name == "lm_head.weight" {
return Some(("output.weight".into(), Reorder::None, false));
}
if let Some(rest) = name.strip_prefix("model.language_model.hyper_connection_mixer.") {
let gguf = match rest {
"input_mix_weight_up.weight" => "output_hc_up.weight",
"input_mix_weight_down.weight" => "output_hc_down.weight",
_ => return None,
};
return Some((gguf.into(), Reorder::None, false));
}
let rest = name.strip_prefix("model.language_model.layers.")?;
let (layer, rest) = rest.split_once('.')?;
let layer: usize = layer.parse().ok()?;
let (gguf, reorder, needs_skip) = match rest {
"linear_attn.in_proj_qkv.weight" => ("attn_qkv", Reorder::Rows { skip_rows: 0 }, true),
"linear_attn.in_proj_z.weight" => ("attn_gate", Reorder::Rows { skip_rows: 0 }, false),
"linear_attn.out_proj.weight" => ("ssm_out", Reorder::Cols, false),
"self_attn.q_proj.weight" => ("attn_q", Reorder::None, false),
"self_attn.k_proj.weight" => ("attn_k", Reorder::None, false),
"self_attn.v_proj.weight" => ("attn_v", Reorder::None, false),
"self_attn.o_proj.weight" => ("attn_output", Reorder::None, false),
"mlp.shared_expert.gate_proj.weight" => ("ffn_gate_shexp", Reorder::None, false),
"mlp.shared_expert.up_proj.weight" => ("ffn_up_shexp", Reorder::None, false),
"mlp.shared_expert.down_proj.weight" => ("ffn_down_shexp", Reorder::None, false),
"attn_hyper_connection.input_mix_weight_up.weight" => ("hc_attn_up", Reorder::None, false),
"attn_hyper_connection.input_mix_weight_down.weight" => {
("hc_attn_down", Reorder::None, false)
}
"mlp_hyper_connection.input_mix_weight_up.weight" => ("hc_ffn_up", Reorder::None, false),
"mlp_hyper_connection.input_mix_weight_down.weight" => {
("hc_ffn_down", Reorder::None, false)
}
_ => return None,
};
Some((format!("blk.{layer}.{gguf}.weight"), reorder, needs_skip))
}
/// The linear-attention head geometry the reorder needs.
#[derive(Debug, Clone, Copy)]
pub struct Heads {
pub key_heads: usize,
pub value_heads: usize,
pub head_dim: usize,
}
impl Heads {
/// The GGUF head that holds checkpoint head `h`.
fn source(&self, h: usize) -> usize {
let r = self.value_heads / self.key_heads;
(h % r) * self.key_heads + h / r
}
}
/// Reorders a tensor of `n_out` rows of `row_bytes` into the
/// checkpoint's layout. `head_bytes` is one head's span within a row
/// (only read for [`Reorder::Cols`]).
pub(crate) fn reorder(
src: &[u8],
n_out: usize,
row_bytes: usize,
head_bytes: usize,
how: Reorder,
heads: Heads,
) -> Result<Vec<u8>> {
ensure!(src.len() == n_out * row_bytes, "tensor is not n_out rows");
match how {
Reorder::None => Ok(src.to_vec()),
Reorder::Rows { skip_rows } => {
let per_head = heads.head_dim * row_bytes;
ensure!(
n_out == skip_rows + heads.value_heads * heads.head_dim,
"{n_out} rows are not {skip_rows} + {} value heads of {}",
heads.value_heads,
heads.head_dim
);
let mut out = src[..skip_rows * row_bytes].to_vec();
let base = skip_rows * row_bytes;
for h in 0..heads.value_heads {
let at = base + heads.source(h) * per_head;
out.extend_from_slice(&src[at..at + per_head]);
}
Ok(out)
}
Reorder::Cols => {
ensure!(
row_bytes == heads.value_heads * head_bytes,
"a {row_bytes}-byte row is not {} heads of {head_bytes}",
heads.value_heads
);
let mut out = Vec::with_capacity(src.len());
for row in src.chunks_exact(row_bytes) {
for h in 0..heads.value_heads {
let at = heads.source(h) * head_bytes;
out.extend_from_slice(&row[at..at + head_bytes]);
}
}
Ok(out)
}
}
}
#[cfg(feature = "strata-kernels")]
pub use kernels::GgufDenseSource;
#[cfg(feature = "strata-kernels")]
mod kernels {
use std::ffi::c_void;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, bail, ensure};
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use candle_core::{CudaDevice, CudaStorage, DType, Device, Storage, Tensor};
use memmap2::{Advice, Mmap};
use super::{Heads, gguf_name, reorder};
use crate::cuda::strata as ffi;
use crate::harness::arch::qwen3_5::proj::{ExternalLinear, LinearSource};
use crate::harness::arch::qwen4_exp::gguf_index::GgufIndex;
const Q8_1_BLOCK_BYTES: usize = 36;
/// Inputs of up to this many rows take the matrix-vector kernel;
/// larger ones dequantize the weight and use a matmul.
const MMVQ_MAX_ROWS: usize = 8;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
pub struct GgufDenseSource {
device: CudaDevice,
index: GgufIndex,
maps: Vec<Mmap>,
heads: Heads,
key_dim: usize,
}
impl GgufDenseSource {
pub fn open(first: &Path, device: &Device, heads: Heads, key_dim: usize) -> Result<Self> {
let device = device.as_cuda_device()?.clone();
let index = GgufIndex::open(first)?;
let mut maps = Vec::with_capacity(index.shards.len());
for path in &index.shards {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
// SAFETY: model files are not modified while serving.
let map = unsafe { Mmap::map(&file) }
.with_context(|| format!("map {}", path.display()))?;
map.advise(Advice::Sequential).context("advise dense map")?;
maps.push(map);
}
tracing::info!(
shards = maps.len(),
"dense projections from GGUF on native kernels"
);
Ok(Self {
device,
index,
maps,
heads,
key_dim,
})
}
}
impl LinearSource for GgufDenseSource {
fn linear(
&self,
name: &str,
in_dim: usize,
out_dim: usize,
) -> Result<Option<Arc<dyn ExternalLinear>>> {
let Some((gguf, mut how, needs_skip)) = gguf_name(name) else {
return Ok(None);
};
let Some(tensor) = self.index.tensors.get(&gguf) else {
return Ok(None);
};
let ty = tensor.ggml_type as i32;
// SAFETY: a pure function of its argument.
if unsafe { ffi::neuron_strata_mmvq_supported(ty) } == 0 {
tracing::info!(
name,
ggml_type = ty,
"no native kernel for this type; dense"
);
return Ok(None);
}
ensure!(
tensor.dims == [in_dim as u64, out_dim as u64],
"{gguf} is {:?}, the checkpoint's {name} is [{in_dim}, {out_dim}]",
tensor.dims
);
if needs_skip {
how = super::Reorder::Rows {
skip_rows: 2 * self.key_dim,
};
}
// SAFETY: pure functions of their integer arguments.
let (row_bytes, head_bytes) = unsafe {
(
ffi::neuron_strata_row_bytes(ty, in_dim as i64),
ffi::neuron_strata_row_bytes(ty, self.heads.head_dim as i64),
)
};
ensure!(row_bytes > 0, "{gguf}: no row size for type {ty}");
if how == super::Reorder::Cols && head_bytes * self.heads.value_heads != row_bytes {
bail!(
"{gguf}: type {ty} blocks do not divide a {}-wide head",
self.heads.head_dim
);
}
let start = tensor.offset as usize;
let bytes = out_dim * row_bytes;
let map = &self.maps[tensor.shard];
ensure!(start + bytes <= map.len(), "{gguf} runs past its shard");
let host = reorder(
&map[start..start + bytes],
out_dim,
row_bytes,
head_bytes,
how,
self.heads,
)
.with_context(|| format!("reorder {gguf}"))?;
// SAFETY: written in full by the copy below.
let mut weight = unsafe { self.device.alloc::<u8>(bytes) }?;
self.device.memcpy_htod(&host, &mut weight)?;
Ok(Some(Arc::new(QuantLinear {
device: self.device.clone(),
weight,
ty,
n_in: in_dim,
n_out: out_dim,
})))
}
}
struct QuantLinear {
device: CudaDevice,
weight: CudaSlice<u8>,
ty: i32,
n_in: usize,
n_out: usize,
}
impl QuantLinear {
fn stream(&self) -> *mut c_void {
self.device.cuda_stream().cu_stream() as *mut c_void
}
/// `(rows, n_in)` f32 activations to `(rows, n_out)` f32.
fn mmvq(&self, x: &Tensor, rows: usize) -> candle_core::Result<Tensor> {
let (storage, layout) = x.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
candle_core::bail!("native dense projections need activations on the GPU");
};
let x_slice = storage.as_cuda_slice::<f32>()?;
let x_ptr = (address(x_slice) as usize + layout.start_offset() * 4) as *const f32;
// SAFETY: both are written in full before they are read.
let q8 = unsafe {
self.device
.alloc::<u8>(rows * (self.n_in / 32) * Q8_1_BLOCK_BYTES)?
};
// SAFETY: as above.
let out = unsafe { self.device.alloc::<f32>(rows * self.n_out)? };
// SAFETY: every pointer is a live device allocation of the
// size the kernels read or write; the stream orders them.
unsafe {
ffi::neuron_strata_quantize_q8_1(
x_ptr,
rows as i64,
self.n_in as i64,
address(&q8) as *mut c_void,
self.stream(),
);
ffi::neuron_strata_mmvq(
self.ty,
address(&self.weight) as *const c_void,
address(&q8) as *const c_void,
address(&out) as *mut f32,
self.n_in as i32,
self.n_out as i32,
rows as i32,
self.stream(),
);
}
// `q8` is freed stream-ordered, after the kernel has read it.
drop(q8);
Ok(Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
(rows, self.n_out),
)))
}
/// The weight as a `(n_out, n_in)` tensor of `dtype`.
fn dense(&self, dtype: DType) -> candle_core::Result<Tensor> {
let n = self.n_in * self.n_out;
// SAFETY: written in full by the dequantize below.
let out = unsafe { self.device.alloc::<f32>(n)? };
// SAFETY: the weight holds `n` values of `ty`; `out` holds n.
unsafe {
ffi::neuron_strata_dequant_f32(
self.ty,
address(&self.weight) as *const c_void,
n as i64,
address(&out) as *mut f32,
self.stream(),
);
}
Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
(self.n_out, self.n_in),
))
.to_dtype(dtype)
}
}
impl ExternalLinear for QuantLinear {
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
let dims = x.dims().to_vec();
let Some((&n_in, lead)) = dims.split_last() else {
candle_core::bail!("a projection needs at least one dimension");
};
if n_in != self.n_in {
candle_core::bail!("input is {n_in} wide, the weight takes {}", self.n_in);
}
let rows: usize = lead.iter().product();
let x2 = x.reshape((rows, n_in))?;
let y = if rows <= MMVQ_MAX_ROWS {
let x32 = x2.to_dtype(DType::F32)?.contiguous()?;
self.mmvq(&x32, rows)?.to_dtype(x.dtype())?
} else {
let w = self.dense(x.dtype())?;
x2.contiguous()?.matmul(&w.t()?)?
};
let mut out_dims = lead.to_vec();
out_dims.push(self.n_out);
y.reshape(out_dims)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const HEADS: Heads = Heads {
key_heads: 2,
value_heads: 6,
head_dim: 1,
};
/// The mapping recovered from the shipped GGUF (16 key heads, 48
/// value heads): GGUF head `g * 16 + k` is checkpoint head `3k + g`.
#[test]
fn the_shipped_geometry_matches_the_measured_permutation() {
let heads = Heads {
key_heads: 16,
value_heads: 48,
head_dim: 128,
};
// Checkpoint heads 0, 1, 2 are GGUF 0, 16, 32; checkpoint 3 is 1.
assert_eq!(
(0..5).map(|h| heads.source(h)).collect::<Vec<_>>(),
[0, 16, 32, 1, 17]
);
// And measured directly: GGUF position 1 holds checkpoint head 3.
let gguf_holds: Vec<usize> = (0..48)
.map(|p| (0..48).find(|&h| heads.source(h) == p).unwrap())
.collect();
assert_eq!(&gguf_holds[..4], [0, 3, 6, 9]);
assert_eq!(gguf_holds[16], 1);
}
/// Rows after the skipped q/k move as whole heads; the skipped rows
/// keep their place.
#[test]
fn rows_move_by_head_after_the_skip() {
// Two skipped rows, then six value heads of one row each, two
// bytes per row. GGUF value position p holds head `gguf_holds[p]`.
let gguf_holds = [0u8, 3, 1, 4, 2, 5];
let mut src = vec![100, 101, 102, 103];
for h in gguf_holds {
src.extend_from_slice(&[h, h]);
}
let got = reorder(&src, 8, 2, 0, Reorder::Rows { skip_rows: 2 }, HEADS).unwrap();
assert_eq!(
got,
[100, 101, 102, 103, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
);
}
/// Columns move as whole head spans within every row.
#[test]
fn columns_move_by_head_within_each_row() {
let gguf_holds = [0u8, 3, 1, 4, 2, 5];
let mut src = Vec::new();
for row in 0..2u8 {
for h in gguf_holds {
src.extend_from_slice(&[10 * row + h, 10 * row + h]);
}
}
let got = reorder(&src, 2, 12, 2, Reorder::Cols, HEADS).unwrap();
let want: Vec<u8> = (0..2u8)
.flat_map(|row| (0..6u8).flat_map(move |h| [10 * row + h, 10 * row + h]))
.collect();
assert_eq!(got, want);
}
#[test]
fn names_map_to_their_gguf_tensors() {
assert_eq!(
gguf_name("model.language_model.layers.7.linear_attn.out_proj.weight"),
Some(("blk.7.ssm_out.weight".into(), Reorder::Cols, false))
);
assert_eq!(
gguf_name("model.language_model.layers.3.self_attn.q_proj.weight"),
Some(("blk.3.attn_q.weight".into(), Reorder::None, false))
);
assert_eq!(
gguf_name("model.language_model.layers.0.linear_attn.in_proj_qkv.weight"),
Some((
"blk.0.attn_qkv.weight".into(),
Reorder::Rows { skip_rows: 0 },
true
))
);
assert_eq!(
gguf_name("model.language_model.hyper_connection_mixer.input_mix_weight_up.weight"),
Some(("output_hc_up.weight".into(), Reorder::None, false))
);
// Unmapped names — the indexer, the MTP head — stay dense.
assert_eq!(
gguf_name("model.language_model.layers.3.self_attn.indexer.index_qk_proj.weight"),
None
);
assert_eq!(gguf_name("mtp.layers.0.self_attn.q_proj.weight"), None);
}
#[test]
fn a_tensor_of_the_wrong_size_is_refused() {
assert!(reorder(&[0; 5], 2, 2, 0, Reorder::None, HEADS).is_err());
assert!(reorder(&[0; 14], 7, 2, 0, Reorder::Rows { skip_rows: 2 }, HEADS).is_err());
}
}
@@ -0,0 +1,354 @@
//! Where each tensor of a split GGUF lies.
//!
//! A deliberately small reader: the native expert path needs names,
//! shapes, types and absolute offsets, and must accept quantisation
//! types candle's GGUF reader has no enum value for.
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail, ensure};
/// One tensor's location.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GgufTensor {
pub shard: usize,
pub offset: u64,
/// In GGUF order, innermost dimension first.
pub dims: Vec<u64>,
pub ggml_type: u32,
}
/// Every tensor of a model, across its shards.
#[derive(Debug)]
pub struct GgufIndex {
pub shards: Vec<PathBuf>,
pub tensors: HashMap<String, GgufTensor>,
}
fn read_u32(r: &mut impl Read) -> Result<u32> {
let mut b = [0; 4];
r.read_exact(&mut b)?;
Ok(u32::from_le_bytes(b))
}
fn read_u64(r: &mut impl Read) -> Result<u64> {
let mut b = [0; 8];
r.read_exact(&mut b)?;
Ok(u64::from_le_bytes(b))
}
fn read_string(r: &mut impl Read) -> Result<String> {
let len = read_u64(r)?;
ensure!(len <= 1 << 30, "implausible GGUF string length {len}");
let mut b = vec![0; len as usize];
r.read_exact(&mut b)?;
String::from_utf8(b).context("GGUF string is not UTF-8")
}
fn skip(r: &mut (impl Read + Seek), bytes: i64) -> Result<()> {
r.seek(SeekFrom::Current(bytes))?;
Ok(())
}
fn scalar_size(value_type: u32) -> Option<i64> {
match value_type {
0 | 1 | 7 => Some(1),
2 | 3 => Some(2),
4..=6 => Some(4),
10..=12 => Some(8),
_ => None,
}
}
/// Skips one value, returning it when it is an unsigned 32-bit integer
/// (the type `general.alignment` is stored as).
fn skip_value(r: &mut (impl Read + Seek), value_type: u32) -> Result<Option<u32>> {
if value_type == 4 {
return Ok(Some(read_u32(r)?));
}
if let Some(size) = scalar_size(value_type) {
skip(r, size)?;
return Ok(None);
}
match value_type {
8 => {
let len = read_u64(r)?;
skip(r, i64::try_from(len)?)?;
}
9 => {
let element = read_u32(r)?;
let count = read_u64(r)?;
if let Some(size) = scalar_size(element) {
skip(
r,
size.checked_mul(i64::try_from(count)?)
.context("GGUF array size")?,
)?;
} else if element == 8 {
for _ in 0..count {
let len = read_u64(r)?;
skip(r, i64::try_from(len)?)?;
}
} else {
bail!("unsupported GGUF array element type {element}");
}
}
other => bail!("unknown GGUF value type {other}"),
}
Ok(None)
}
fn read_shard(path: &Path, shard: usize, out: &mut HashMap<String, GgufTensor>) -> Result<()> {
let mut r =
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
let mut magic = [0; 4];
r.read_exact(&mut magic)?;
ensure!(&magic == b"GGUF", "{} is not a GGUF file", path.display());
let version = read_u32(&mut r)?;
ensure!(version == 3, "{}: GGUF version {version}", path.display());
let n_tensors = read_u64(&mut r)?;
let n_kv = read_u64(&mut r)?;
let mut alignment = 32_u64;
for _ in 0..n_kv {
let key = read_string(&mut r)?;
let value_type = read_u32(&mut r)?;
if let Some(v) = skip_value(&mut r, value_type)?
&& key == "general.alignment"
{
ensure!(v > 0 && v.is_power_of_two(), "bad GGUF alignment {v}");
alignment = u64::from(v);
}
}
let mut found = Vec::with_capacity(n_tensors as usize);
for _ in 0..n_tensors {
let name = read_string(&mut r)?;
let n_dims = read_u32(&mut r)?;
ensure!(n_dims <= 8, "{name}: {n_dims} dimensions");
let dims = (0..n_dims)
.map(|_| read_u64(&mut r))
.collect::<Result<Vec<_>>>()?;
let ggml_type = read_u32(&mut r)?;
let offset = read_u64(&mut r)?;
found.push((name, dims, ggml_type, offset));
}
let header_end = r.stream_position()?;
let data_start = header_end.div_ceil(alignment) * alignment;
for (name, dims, ggml_type, offset) in found {
out.insert(
name,
GgufTensor {
shard,
offset: data_start + offset,
dims,
ggml_type,
},
);
}
Ok(())
}
/// The sibling paths of a `name-00001-of-0000N.gguf` shard, or the file
/// itself when it is not split.
fn shard_paths(first: &Path) -> Result<Vec<PathBuf>> {
let name = first
.file_name()
.and_then(|n| n.to_str())
.context("GGUF path has no file name")?;
let Some(stem) = name.strip_suffix(".gguf") else {
bail!("{name} is not a .gguf file");
};
let parts: Vec<&str> = stem.rsplitn(4, '-').collect();
if parts.len() == 4
&& parts[1] == "of"
&& parts[0].len() == 5
&& parts[2].len() == 5
&& let Ok(total) = parts[0].parse::<usize>()
{
let dir = first.parent().unwrap_or_else(|| Path::new("."));
return Ok((1..=total)
.map(|i| dir.join(format!("{}-{i:05}-of-{total:05}.gguf", parts[3])))
.collect());
}
Ok(vec![first.to_path_buf()])
}
impl GgufIndex {
/// Reads every shard of the model whose first shard is `first`.
pub fn open(first: &Path) -> Result<Self> {
let shards = shard_paths(first)?;
let mut tensors = HashMap::new();
for (i, path) in shards.iter().enumerate() {
read_shard(path, i, &mut tensors)?;
}
Ok(Self { shards, tensors })
}
}
/// The `(layer, expert)` pairs of a Strata expert profile, hottest first.
pub fn read_expert_profile(path: &Path, layers: usize, experts: usize) -> Result<Vec<(u16, u16)>> {
let blob = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
parse_expert_profile(&blob, layers, experts)
.with_context(|| format!("parse {}", path.display()))
}
fn parse_expert_profile(blob: &[u8], layers: usize, experts: usize) -> Result<Vec<(u16, u16)>> {
const HEADER: usize = 24;
ensure!(
blob.len() >= HEADER && &blob[..4] == b"STRP",
"not an expert profile"
);
let field = |i: usize| {
u32::from_le_bytes(blob[4 + i * 4..8 + i * 4].try_into().expect("four bytes")) as usize
};
ensure!(field(0) == 1, "profile version {}", field(0));
ensure!(
(field(1), field(2)) == (layers, experts),
"profile is {}x{}, the model is {layers}x{experts}",
field(1),
field(2)
);
let count = field(4);
ensure!(count <= layers * experts, "profile ranks {count} pairs");
ensure!(blob.len() >= HEADER + count * 4, "profile is truncated");
blob[HEADER..HEADER + count * 4]
.as_chunks::<4>()
.0
.iter()
.map(|pair| {
let layer = u16::from_le_bytes([pair[0], pair[1]]);
let expert = u16::from_le_bytes([pair[2], pair[3]]);
ensure!(
(layer as usize) < layers && (expert as usize) < experts,
"pair ({layer}, {expert}) is out of range"
);
Ok((layer, expert))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn string(out: &mut Vec<u8>, s: &str) {
out.extend((s.len() as u64).to_le_bytes());
out.extend(s.as_bytes());
}
/// A GGUF with one of each key shape the skipper must cross.
fn shard(alignment: u32, tensors: &[(&str, &[u64], u32, u64)]) -> Vec<u8> {
let mut b = b"GGUF".to_vec();
b.extend(3_u32.to_le_bytes());
b.extend((tensors.len() as u64).to_le_bytes());
b.extend(4_u64.to_le_bytes());
string(&mut b, "a.string");
b.extend(8_u32.to_le_bytes());
string(&mut b, "value");
string(&mut b, "a.array");
b.extend(9_u32.to_le_bytes());
b.extend(8_u32.to_le_bytes());
b.extend(2_u64.to_le_bytes());
string(&mut b, "x");
string(&mut b, "yz");
string(&mut b, "a.numbers");
b.extend(9_u32.to_le_bytes());
b.extend(5_u32.to_le_bytes());
b.extend(3_u64.to_le_bytes());
b.extend([0_u8; 12]);
string(&mut b, "general.alignment");
b.extend(4_u32.to_le_bytes());
b.extend(alignment.to_le_bytes());
for (name, dims, ty, offset) in tensors {
string(&mut b, name);
b.extend((dims.len() as u32).to_le_bytes());
for d in *dims {
b.extend(d.to_le_bytes());
}
b.extend(ty.to_le_bytes());
b.extend(offset.to_le_bytes());
}
b
}
#[test]
fn offsets_are_absolute_and_follow_the_alignment() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("m.gguf");
let bytes = shard(64, &[("t", &[2560, 640, 512], 21, 128)]);
let data_start = (bytes.len() as u64).div_ceil(64) * 64;
File::create(&path).unwrap().write_all(&bytes).unwrap();
let index = GgufIndex::open(&path).unwrap();
assert_eq!(
index.tensors["t"],
GgufTensor {
shard: 0,
offset: data_start + 128,
dims: vec![2560, 640, 512],
ggml_type: 21,
}
);
}
#[test]
fn split_models_are_read_from_every_shard() {
let dir = tempfile::tempdir().unwrap();
for (i, name) in ["a", "b"].iter().enumerate() {
let path = dir.path().join(format!("m-Q-{:05}-of-00002.gguf", i + 1));
let bytes = shard(32, &[(name, &[1], 8, 0)]);
File::create(path).unwrap().write_all(&bytes).unwrap();
}
let index = GgufIndex::open(&dir.path().join("m-Q-00001-of-00002.gguf")).unwrap();
assert_eq!(index.shards.len(), 2);
assert_eq!((index.tensors["a"].shard, index.tensors["b"].shard), (0, 1));
}
fn profile(version: u32, layers: u32, experts: u32, pairs: &[(u16, u16)]) -> Vec<u8> {
let mut b = b"STRP".to_vec();
for v in [
version,
layers,
experts,
layers * experts,
pairs.len() as u32,
] {
b.extend(v.to_le_bytes());
}
for (l, e) in pairs {
b.extend(l.to_le_bytes());
b.extend(e.to_le_bytes());
}
b
}
#[test]
fn a_profile_keeps_its_rank_order() {
let blob = profile(1, 2, 4, &[(1, 3), (0, 2)]);
assert_eq!(
parse_expert_profile(&blob, 2, 4).unwrap(),
vec![(1, 3), (0, 2)]
);
}
#[test]
fn a_profile_for_another_shape_or_out_of_range_is_refused() {
assert!(parse_expert_profile(&profile(1, 2, 4, &[]), 3, 4).is_err());
assert!(parse_expert_profile(&profile(2, 2, 4, &[]), 2, 4).is_err());
assert!(parse_expert_profile(&profile(1, 2, 4, &[(2, 0)]), 2, 4).is_err());
let truncated = profile(1, 2, 4, &[(1, 1)]);
assert!(parse_expert_profile(&truncated[..truncated.len() - 1], 2, 4).is_err());
}
#[test]
fn a_file_that_is_not_gguf_is_refused() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("m.gguf");
File::create(&path).unwrap().write_all(b"NOPE0000").unwrap();
assert!(GgufIndex::open(&path).is_err());
}
}
@@ -40,6 +40,7 @@ use candle_core::{D, Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
use crate::harness::arch::qwen3_5::proj::{LinearSource, Proj, load_proj};
use crate::harness::arch::qwen3_5::rmsnorm::Qwen3_5RmsNorm;
/// What a hyper-connection hands its sublayer.
@@ -56,8 +57,8 @@ pub struct HyperSplit {
/// `Qwen4ExpTextGatedResidual`.
pub struct HyperConnection {
hc_norm: Qwen3_5RmsNorm,
mix_down: Linear,
mix_up: Linear,
mix_down: Proj,
mix_up: Proj,
/// Absent on the top-level `hyper_connection_mixer`, which collapses
/// the streams for the LM head instead of feeding a sublayer.
block_inject: Option<Linear>,
@@ -73,12 +74,13 @@ impl HyperConnection {
hc_lowrank: usize,
eps: f64,
use_combine: bool,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let wide = hidden_size * hc_count;
let hc_norm = Qwen3_5RmsNorm::load_grouped(&vb.pp("hc_norm"), wide, hidden_size, eps)
.with_context(|| format!("load '{}/hc_norm'", vb.prefix()))?;
let mix_down = linear(vb, "input_mix_weight_down", wide, hc_lowrank)?;
let mix_up = linear(vb, "input_mix_weight_up", hc_lowrank, wide)?;
let mix_down = load_proj(vb, "input_mix_weight_down", wide, hc_lowrank, source)?;
let mix_up = load_proj(vb, "input_mix_weight_up", hc_lowrank, wide, source)?;
let block_inject = if use_combine {
Some(linear(vb, "block_inject_weight", wide, hc_count)?)
} else {
@@ -123,8 +125,8 @@ impl HyperConnection {
1e-6,
Some(hidden_size),
),
mix_down: z(hc_lowrank, wide),
mix_up: z(wide, hc_lowrank),
mix_down: z(hc_lowrank, wide).into(),
mix_up: z(wide, hc_lowrank).into(),
block_inject: use_combine.then(|| z(hc_count, wide)),
hidden_size,
hc_count,
@@ -31,10 +31,15 @@ use crate::harness::arch::qwen3_5::linear_attn::{
};
use super::config::TextConfig;
use crate::harness::arch::qwen3_5::proj::LinearSource;
/// `vb` should be `.pp(...)`-ed to the layer's `linear_attn` prefix.
pub fn load(cfg: &TextConfig, vb: &ShardedVarBuilder) -> Result<GatedDeltaNet> {
GatedDeltaNet::load_with_params(params(cfg)?, vb)
pub fn load(
cfg: &TextConfig,
vb: &ShardedVarBuilder,
source: Option<&dyn LinearSource>,
) -> Result<GatedDeltaNet> {
GatedDeltaNet::load_with_source(params(cfg)?, vb, source)
}
/// The settings this architecture asks for, as opposed to the ones
@@ -36,12 +36,20 @@
pub mod config;
pub mod decoder;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod engine;
pub mod full_attn;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod gguf_dense;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod gguf_index;
pub mod hyper;
pub mod linear_attn;
pub mod model;
pub mod moe;
pub mod mtp;
#[cfg(feature = "strata-kernels")]
pub mod native_experts;
pub mod ple;
pub mod qsa;
@@ -87,4 +95,14 @@ pub struct LoadOptions<'a> {
/// Reading them straight into host memory removes the transit
/// rather than managing it.
pub experts_vb: Option<&'a candle_nn::var_builder::ShardedVarBuilder<'a>>,
/// VRAM tier for host-resident experts (#318). `None` computes them
/// where they live.
pub expert_tier: Option<std::sync::Arc<super::qwen3_5::moe::DeviceExpertTier>>,
/// Routed experts served outside candle. When set, the checkpoint's
/// expert tensors are not read at all.
pub external_experts: Option<std::sync::Arc<dyn super::qwen3_5::moe::ExternalExpertSource>>,
/// Dense projections served outside candle (a GGUF's quantized
/// blocks). Each is asked for by checkpoint name; what it declines
/// is read from the checkpoint.
pub dense: Option<std::sync::Arc<dyn super::qwen3_5::proj::LinearSource>>,
}
@@ -35,10 +35,11 @@
use anyhow::{Context, Result, ensure};
use candle_core::{DType, Device, IndexOp, Module, Tensor};
use candle_nn::Embedding;
use candle_nn::var_builder::ShardedVarBuilder;
use candle_nn::{Embedding, Linear};
use std::sync::Arc;
use crate::harness::arch::qwen3_5::proj::{Proj, load_proj};
use crate::harness::arch::qwen3_5::rope::RotaryEmbedding;
use super::config::{Config, TextConfig};
@@ -116,7 +117,7 @@ pub struct Qwen4ExpForCausalLM {
/// `hyper_connection_mixer` — `use_combine = false`, so it collapses
/// rather than scatters, and there is no final norm beside it.
mixer: HyperConnection,
lm_head: Linear,
lm_head: Proj,
ngram: Option<NGramEmbedding>,
rotary: Arc<RotaryEmbedding>,
hc_count: usize,
@@ -191,19 +192,24 @@ impl Qwen4ExpForCausalLM {
// No block_inject_weight in the checkpoint: this one ends
// the streams rather than feeding a sublayer.
false,
opts.dense.as_deref(),
)
.context("load hyper_connection_mixer")?;
let lm_head_weight = vb
.pp("lm_head")
.get((text.vocab_size, text.hidden_size), "weight")
.context("load 'lm_head.weight'")?;
let lm_head = load_proj(
vb,
"lm_head",
text.hidden_size,
text.vocab_size,
opts.dense.as_deref(),
)
.context("load 'lm_head.weight'")?;
Ok(Self {
embed_tokens,
layers,
mixer,
lm_head: Linear::new(lm_head_weight, None),
lm_head,
ngram,
rotary,
hc_count: text.hc_count,
@@ -232,6 +238,25 @@ impl Qwen4ExpForCausalLM {
Ok(self.lm_head.forward(&x)?)
}
/// The PLE contribution for one decode token, from the native
/// engine's residual `h` (`(1, 1, hidden * hc)`, any float dtype): the
/// n-gram rows are gathered for `input_ids` (advancing the carried
/// ids, as a forward would) and the PLE layer's block run on them.
/// `None` without PLE. Returned in `h`'s dtype.
pub fn ple_contribution(&mut self, input_ids: &Tensor, h: &Tensor) -> Result<Option<Tensor>> {
let Some(ngram) = &mut self.ngram else {
return Ok(None);
};
let e = ngram.forward(&ids_to_i64(input_ids)?, &self.device, self.dtype)?;
let hm = h.to_dtype(self.dtype)?;
for layer in &mut self.layers {
if let Some(out) = layer.ple_contribution(&hm, &e)? {
return Ok(Some(out.to_dtype(h.dtype())?));
}
}
Ok(None)
}
/// Logits for the **last** position, `(B, 1, vocab)`.
pub fn forward(&mut self, input_ids: &Tensor, offset: usize) -> Result<Tensor> {
Ok(self.forward_inner(input_ids, offset)?.0)
@@ -507,7 +532,7 @@ fn ids_to_i64(input_ids: &Tensor) -> Result<Vec<Vec<i64>>> {
/// identically to Qwen3.6 (spec §7) — so `qwen3_5`'s module is reused
/// as-is, through the parts it actually needs rather than through a
/// fabricated config.
fn rotary_for(cfg: &TextConfig, dtype: DType, device: &Device) -> Result<RotaryEmbedding> {
pub fn rotary_for(cfg: &TextConfig, dtype: DType, device: &Device) -> Result<RotaryEmbedding> {
RotaryEmbedding::from_parts(
dtype,
cfg.head_dim,
@@ -849,6 +874,9 @@ mod tests {
isq_cache: None,
experts_onto: &Device::Cpu,
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.unwrap();
@@ -99,7 +99,7 @@ pub fn load(
// A hit skips reading the fused tensors at all, which is the point:
// the cost being avoided is the 5.03 GB read *and* the ~32 s of
// quantisation, not just the latter.
let cached = match (quant, isq_cache) {
let cached = match (quant, isq_cache.filter(|_| opts.external_experts.is_none())) {
(Some(_), Some(cache)) => cache.load(&cache_key, experts_onto).and_then(|entries| {
match Experts::from_cache_entries(entries, cfg.num_experts) {
Ok(e) => Some(e),
@@ -113,7 +113,19 @@ pub fn load(
_ => None,
};
let experts = match cached {
let external = match &opts.external_experts {
Some(source) => {
let layer = layer_of(&vb.prefix())
.with_context(|| format!("no layer index in '{}'", vb.prefix()))?;
Some(Experts::External {
count: cfg.num_experts,
inner: source.block(layer)?,
})
}
None => None,
};
let experts = match external.or(cached) {
Some(experts) => experts,
None => {
let gate_up = experts_vb
@@ -151,10 +163,11 @@ pub fn load(
};
let (shared_expert, shared_expert_gate) = if cfg.shared_expert_intermediate_size > 0 {
let shared = Qwen3_5MLP::load_with_dims(
let shared = Qwen3_5MLP::load_with_source(
&vb.pp("shared_expert"),
h,
cfg.shared_expert_intermediate_size,
opts.dense.as_deref(),
)
.context("load shared_expert")?;
let gate_w = vb
@@ -173,7 +186,16 @@ pub fn load(
shared_expert_gate,
cfg.num_experts_per_tok,
cfg.norm_topk_prob,
))
)
.with_tier(opts.expert_tier.clone()))
}
/// The layer index in a tensor prefix such as
/// `model.language_model.layers.7.mlp`.
fn layer_of(prefix: &str) -> Option<usize> {
let mut parts = prefix.split('.');
parts.find(|p| *p == "layers")?;
parts.next()?.parse().ok()
}
/// Validate the fused pair before it is banked.
@@ -208,6 +230,12 @@ mod tests {
/// The loader validates the fused pair up front. Without this the
/// first token to route to a bad expert fails mid-forward, which is
/// a worse place to learn the checkpoint disagrees with the config.
#[test]
fn the_layer_index_comes_from_the_tensor_prefix() {
assert_eq!(layer_of("model.language_model.layers.17.mlp"), Some(17));
assert_eq!(layer_of("mtp.mlp"), None);
}
#[test]
fn a_fused_pair_that_disagrees_with_the_config_is_rejected() {
let dev = Device::Cpu;
@@ -124,6 +124,9 @@ impl MtpHead {
isq_cache: None,
experts_onto: vb.device(),
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.context("load mtp.layers.0")?,
@@ -134,6 +137,7 @@ impl MtpHead {
cfg.hc_lowrank,
cfg.rms_norm_eps,
false,
None,
)
.context("load mtp.hyper_connection_mixer")?,
hidden_size: h,
File diff suppressed because it is too large Load Diff
+222 -48
View File
@@ -663,27 +663,98 @@ impl LoadedImageModel {
}
}
/// A loaded ACE-Step music pipeline (#383). Every component lives in the
/// device worker's audio slab, addressed via [`Self::handle`]; this
/// async-side struct holds admission bookkeeping and the model's limits.
/// A render is one `Job::GenerateAudio` round-trip.
/// A loaded music pipeline (#383): one copy per replica device (#397).
/// Every component of a copy lives in its device worker's audio slab,
/// addressed via [`AudioReplica::handle`]; this async-side struct holds
/// admission bookkeeping and the model's limits. A render is one
/// `Job::GenerateAudio` round-trip on one replica.
pub struct LoadedAudioModel {
pub model_id: String,
pub spec: ModelSpec,
/// Every device a copy lives on.
pub devices: Vec<u32>,
pub worker: Arc<super::device_worker::DeviceWorkerHandle>,
pub handle: super::device_worker::AudioHandle,
pub replicas: Vec<AudioReplica>,
/// Which copies are idle; a render holds one for its whole duration.
pub pool: Arc<super::replica::ReplicaPool>,
/// Whether the snapshot carried a song planner.
pub has_planner: bool,
/// What a request may ask of this model; validated before admission.
pub limits: cortex_core::audio::AudioLimits,
/// Set when a render fails at the driver level: subsequent requests
/// fast-reject and `/models` reports `poisoned`.
/// Set once every replica's device has failed: requests fast-reject
/// and `/models` reports `poisoned`.
pub poisoned: Arc<AtomicBool>,
/// Admission control (#53) with `max_in_flight` forced to 1 — a render
/// saturates the device. The cortex job queue is the real backlog.
/// Admission control (#53) with one in-flight slot per replica — a
/// render saturates its device. The cortex job queue is the real
/// backlog.
pub admission: super::admission::AdmissionController,
pub inference_lock: Arc<tokio::sync::Mutex<()>>,
}
/// One copy of a music pipeline (#397).
pub struct AudioReplica {
pub device: u32,
pub worker: Arc<super::device_worker::DeviceWorkerHandle>,
pub handle: super::device_worker::AudioHandle,
}
impl LoadedAudioModel {
/// Per-replica load for `/health`; empty for a single copy, whose
/// load the model-level numbers already say.
pub fn replica_loads(&self) -> Vec<cortex_core::discovery::ReplicaLoad> {
if self.replicas.len() < 2 {
return Vec::new();
}
self.replicas
.iter()
.enumerate()
.map(|(i, r)| cortex_core::discovery::ReplicaLoad {
device: r.device,
in_flight: self.pool.in_flight(i),
healthy: self.pool.is_healthy(i),
})
.collect()
}
}
/// The devices a music model's copies go on (#397): one per entry of
/// `replicas`, or the model's single device when it is not replicated.
///
/// `"per-device"` means every device the model may use: its `devices` when
/// the spec names them, else every CUDA device on the host.
fn replica_devices(
replicas: Option<&cortex_core::harness::Replicas>,
devices: Option<&[u32]>,
device_count: fn() -> usize,
) -> Result<Vec<u32>> {
use cortex_core::harness::Replicas;
let picked = match replicas {
None => vec![devices.and_then(|d| d.first().copied()).unwrap_or(0)],
Some(Replicas::Devices(list)) => list.clone(),
Some(Replicas::PerDevice) => match devices {
Some(d) if !d.is_empty() => d.to_vec(),
_ => (0..device_count() as u32).collect(),
},
};
anyhow::ensure!(
!picked.is_empty(),
"replicas = \"per-device\" found no CUDA devices"
);
let mut seen = std::collections::HashSet::new();
for d in &picked {
anyhow::ensure!(seen.insert(*d), "replicas lists device {d} twice");
}
Ok(picked)
}
/// CUDA devices on this host; 0 without CUDA.
fn cuda_device_count() -> usize {
#[cfg(feature = "cuda")]
{
cudarc::driver::CudaContext::device_count().map_or(0, |n| n.max(0) as usize)
}
#[cfg(not(feature = "cuda"))]
{
0
}
}
/// A loaded model with its tokenizer, device placement, and architecture-
@@ -1170,8 +1241,8 @@ impl ModelArch {
/// the wrapper).
pub fn clear_kv_cache(&mut self) -> Result<()> {
match self {
ModelArch::Qwen3Quantized(_) => Ok(()), /* keeps cache by design;
* forward() handles offset */
// Keeps its cache by design: forward() handles the offset.
ModelArch::Qwen3Quantized(_) => Ok(()),
ModelArch::Qwen3Dense(m) => {
m.clear_kv_cache();
Ok(())
@@ -2996,6 +3067,9 @@ impl CandleHarness {
// choice here.
experts_onto: &device_for_load,
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.context("build qwen4_exp model")?;
@@ -3825,6 +3899,10 @@ impl CandleHarness {
kv_available_mb,
tok_s_prefill,
tok_s_decode,
replicas: match handle {
LoadedHandle::Audio(a) => a.replica_loads(),
_ => Vec::new(),
},
}
})
.collect()
@@ -3955,6 +4033,10 @@ impl Harness for CandleHarness {
reasoning: h.has_reasoning(),
preserve_thinking: h.preserve_thinking(),
servable: h.servability(&self.context_limit_cfg),
replicas: match h {
LoadedHandle::Audio(a) if a.replicas.len() > 1 => Some(a.replicas.len()),
_ => None,
},
// The rungs this model's own template accepts (#290),
// discovered at load rather than invented. Advertising a
// rung the template rejects hands callers a name that
@@ -4015,6 +4097,7 @@ impl Harness for CandleHarness {
// A recovering model is a trigger-time snapshot; it
// is not serving, so it advertises no controls.
reasoning_budget: Vec::new(),
replicas: None,
});
}
}
@@ -4409,8 +4492,18 @@ impl Harness for CandleHarness {
// Publish the KV budget while nothing is in flight (#257) —
// the only moment a free-VRAM reading is not already net of
// some running sequence's reservations.
// The expert tier fills after this reading, so what it may
// come to hold is not available to KV.
let tier_reserved_mb = if matches!(
spec.expert_residency,
Some(cortex_core::harness::ExpertResidency::Host)
) {
super::arch::qwen3_5::expert_tier::configured_budget_mb().unwrap_or(0)
} else {
0
};
let budget = kv_budget_mb(
free_mb,
free_mb.saturating_sub(tier_reserved_mb),
&self.context_limit_cfg,
prefix_cache_reserved_mb(&self.prefix_cache_cfg),
);
@@ -4418,6 +4511,7 @@ impl Harness for CandleHarness {
tracing::info!(
model = %spec.model_id,
free_at_load_mb = free_mb,
tier_reserved_mb,
kv_budget_mb = budget,
"admission: KV budget published"
);
@@ -4476,14 +4570,17 @@ impl Harness for CandleHarness {
dm.release().await;
}
LoadedHandle::Audio(audio) => {
// Drop the pipeline on the worker thread so its CUDA
// tensors release on the context that allocated them.
if let Err(e) = audio.worker.drop_audio(audio.handle).await {
tracing::warn!(
model = %model_id,
error = %e,
"audio unload: DropAudio RPC failed (pipeline may leak in worker slab)"
);
// Drop each copy on its worker thread so its CUDA tensors
// release on the context that allocated them.
for r in &audio.replicas {
if let Err(e) = r.worker.drop_audio(r.handle).await {
tracing::warn!(
model = %model_id,
device = r.device,
error = %e,
"audio unload: DropAudio RPC failed (pipeline may leak in worker slab)"
);
}
}
}
#[cfg(feature = "cuda")]
@@ -4670,18 +4767,20 @@ impl CandleHarness {
files: super::audio::AudioFiles,
limits: cortex_core::audio::AudioLimits,
) -> Result<()> {
let devices = spec.devices.clone().unwrap_or_else(|| vec![0]);
let devices = replica_devices(
spec.replicas.as_ref().or(self.audio_cfg.replicas.as_ref()),
spec.devices.as_deref(),
cuda_device_count,
)?;
let device = Self::pick_device(&devices)?;
let worker: Arc<super::device_worker::DeviceWorkerHandle> = match &device {
#[cfg(feature = "cuda")]
Device::Cuda(_) => self.ensure_device_worker(devices[0]).await?,
// On CPU builds this arm is the whole match: a song on the CPU
// takes many minutes and is not a serving target.
_ => anyhow::bail!(
if !matches!(device, Device::Cuda(_)) {
// A song on the CPU takes many minutes and is not a serving
// target.
anyhow::bail!(
"music generation requires a CUDA device; '{}' resolved to a CPU device",
spec.model_id
),
};
);
}
let has_planner =
matches!(&files, super::audio::AudioFiles::AceStep(f) if f.planner.is_some());
@@ -4699,32 +4798,62 @@ impl CandleHarness {
limits.max_duration = limits.max_duration.min(max);
limits.default_duration = limits.default_duration.min(limits.max_duration);
}
let handle = worker
.load_audio(files, spec.model_id.clone())
.await
.map_err(|e| anyhow::anyhow!("worker load_audio: {e:#}"))?;
// Every copy loads at once: each device has its own worker thread,
// and on a rig the slow part is each card's own riser.
let loads = devices.iter().map(|&d| {
let files = files.clone();
let model_id = spec.model_id.clone();
async move {
let worker = self.ensure_device_worker(d).await?;
let handle = worker
.load_audio(files, model_id)
.await
.map_err(|e| anyhow::anyhow!("worker load_audio on device {d}: {e:#}"))?;
anyhow::Ok(AudioReplica {
device: d,
worker,
handle,
})
}
});
let mut replicas = Vec::with_capacity(devices.len());
let mut first_error = None;
for (device, outcome) in devices.iter().zip(futures::future::join_all(loads).await) {
match outcome {
Ok(r) => replicas.push(r),
// One bad card must not take the rig's other copies down
// with it. The replica count on `/models` shows the loss.
Err(e) => {
tracing::warn!(model = %spec.model_id, device, error = %e, "audio replica failed to load");
first_error.get_or_insert(e);
}
}
}
if replicas.is_empty() {
return Err(first_error.unwrap_or_else(|| anyhow::anyhow!("no devices to load on")));
}
// Admission (#53) with the in-flight ceiling forced to 1: a render
// saturates the device. cortex queues jobs ahead of this.
// Admission (#53) with one in-flight slot per replica: a render
// saturates its device. cortex queues jobs ahead of this.
let admission_cfg = crate::config::AdmissionConfig {
max_in_flight: 1,
max_in_flight: replicas.len(),
..self.admission_cfg.clone()
};
let loaded = LoadedAudioModel {
model_id: spec.model_id.clone(),
spec: spec.clone(),
devices,
worker,
handle,
devices: replicas.iter().map(|r| r.device).collect(),
pool: super::replica::ReplicaPool::new(replicas.len()),
replicas,
has_planner,
limits,
poisoned: Arc::new(AtomicBool::new(false)),
admission: crate::harness::admission::AdmissionController::new(&admission_cfg),
inference_lock: Arc::new(tokio::sync::Mutex::new(())),
};
let copies = loaded.replicas.len();
let mut models = self.models.write().await;
models.insert(spec.model_id.clone(), LoadedHandle::Audio(Arc::new(loaded)));
tracing::info!(model = %spec.model_id, planner = has_planner, "audio pipeline loaded");
tracing::info!(model = %spec.model_id, planner = has_planner, replicas = copies, "audio pipeline loaded");
Ok(())
}
@@ -5367,11 +5496,28 @@ impl CandleHarness {
};
let _permit = audio.admission.enter(principal).await?;
let _guard = audio.inference_lock.lock().await;
let result = audio
.worker
.generate_audio(audio.handle, params)
.await
// Admission lets in no more renders than there are copies, so one
// is idle here unless a device has failed.
let Some(lease) = audio.pool.checkout().await else {
audio.poisoned.store(true, Ordering::Release);
return Err(InferenceError::Other(anyhow::anyhow!(
"every replica of audio model '{}' has failed; unload and reload it",
request.model
)));
};
let replica = &audio.replicas[lease.index()];
let outcome = replica.worker.generate_audio(replica.handle, params).await;
if replica.worker.is_poisoned() {
// The device is gone for good: stop handing this copy work,
// or it becomes the fastest way to fail a request.
tracing::error!(model = %request.model, device = replica.device, "audio replica's device failed; retiring it");
lease.mark_failed();
if audio.pool.healthy_count() == 0 {
audio.poisoned.store(true, Ordering::Release);
}
}
drop(lease);
let result = outcome
.map_err(|e| InferenceError::Other(anyhow::anyhow!("audio generation: {e:#}")))?;
let duration = result.duration_secs();
@@ -8664,6 +8810,34 @@ mod tests {
/// admission controller. Those are separate readers of the same
/// number, and a model bounded at 1 while an engine starts with 8
/// slots is the failure this function exists to prevent.
#[test]
fn replica_devices_follow_the_spec_then_the_host() {
use cortex_core::harness::Replicas;
fn four() -> usize {
4
}
// Unreplicated: the model's first device, as before #397.
assert_eq!(replica_devices(None, None, four).unwrap(), [0]);
assert_eq!(replica_devices(None, Some(&[2, 3]), four).unwrap(), [2]);
// Per-device: the spec's devices when it names them, else every card.
let per = Some(&Replicas::PerDevice);
assert_eq!(replica_devices(per, None, four).unwrap(), [0, 1, 2, 3]);
assert_eq!(replica_devices(per, Some(&[1, 3]), four).unwrap(), [1, 3]);
// An explicit list wins over the spec's devices.
let list = Replicas::Devices(vec![5, 6]);
assert_eq!(
replica_devices(Some(&list), Some(&[0]), four).unwrap(),
[5, 6]
);
// Nothing to load on, or a card named twice, is a config error.
fn none() -> usize {
0
}
assert!(replica_devices(per, None, none).is_err());
let twice = Replicas::Devices(vec![1, 1]);
assert!(replica_devices(Some(&twice), None, four).is_err());
}
#[test]
fn a_model_may_lower_max_in_flight_below_the_host() {
let host = crate::config::AdmissionConfig {
@@ -319,6 +319,10 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
reply,
} => {
let result = forward_logits(&mut state, handle, &tokens, offset);
trace_device_pool(&state, "forward", tokens.len());
if crate::harness::arch::qwen3_5::moe::prompt_chunk_streams_experts(tokens.len()) {
trim_device_pool(&state);
}
let _ = reply.send(result);
}
Job::AssembleKvBatch {
@@ -892,6 +896,14 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
// semantics in mod.rs for the Phase 3+ refinement.
}
/// `NEURON_CUDA_EVENT_TRACKING=0` turns cudarc's cross-stream event
/// tracking off for the worker's context. On by default until measured
/// across the fleet's models.
#[cfg(feature = "cuda")]
fn cuda_event_tracking() -> bool {
std::env::var("NEURON_CUDA_EVENT_TRACKING").map_or(true, |v| v != "0")
}
fn init_state(device_index: u32) -> DeviceWorkerState {
#[cfg(feature = "cuda")]
{
@@ -901,6 +913,23 @@ fn init_state(device_index: u32) -> DeviceWorkerState {
// CudaContext::new and Device::new_cuda end up sharing state.
let (device, ctx) = match candle_core::Device::new_cuda(device_index as usize) {
Ok(device) => match CudaContext::new(device_index as usize) {
Ok(ctx) if !cuda_event_tracking() => {
// cudarc gives every allocation two events and waits
// on them when it is freed, which only matters when
// a buffer crosses streams. All of this worker's
// work runs on candle's one stream, and the events
// cost ~74k driver calls per qwen4_exp decode token.
if let Ok(cuda) = device.as_cuda_device() {
// SAFETY: nothing has been allocated yet, and
// this context's work is on a single stream.
unsafe { cuda.disable_event_tracking() };
tracing::info!(device_index, "CUDA event tracking off");
}
if let Err(e) = ctx.bind_to_thread() {
tracing::warn!(device_index, error = ?e, "device worker: bind_to_thread failed");
}
(device, Some(ctx))
}
Ok(ctx) => {
if let Err(e) = ctx.bind_to_thread() {
tracing::warn!(
@@ -1063,6 +1092,63 @@ fn trim_device_pool(state: &DeviceWorkerState) {
);
}
/// Logs the device pool after a job when `NEURON_VRAM_TRACE` is set:
/// bytes live now, the job's peak, and bytes the pool holds from the
/// driver. The peak counter is reset, so each line covers one job.
/// Memory the driver reports used beyond `reserved` was allocated
/// outside the pool (context, library workspaces, synchronous allocs).
#[cfg(feature = "cuda")]
fn trace_device_pool(state: &DeviceWorkerState, job: &str, tokens: usize) {
use candle_core::cuda::cudarc::driver::{
result::{device, mem_pool},
sys::CUmemPool_attribute,
};
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ENABLED.get_or_init(|| std::env::var_os("NEURON_VRAM_TRACE").is_some()) {
return;
}
let Some(ctx) = state.ctx.as_ref() else {
return;
};
let Ok(pool) = (unsafe { device::get_default_mem_pool(ctx.cu_device()) }) else {
return;
};
let read = |attr: CUmemPool_attribute| -> u64 {
let mut value = 0_u64;
// SAFETY: these attributes are all cuuint64_t.
match unsafe { mem_pool::get_attribute(pool, attr, (&raw mut value).cast()) } {
Ok(()) => value >> 20,
Err(_) => 0,
}
};
let used = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_CURRENT);
let peak = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_HIGH);
let reserved = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT);
let mut zero = 0_u64;
// SAFETY: writing zero resets the high-water mark.
let _ = unsafe {
mem_pool::set_attribute(
pool,
CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_HIGH,
(&raw mut zero).cast(),
)
};
let (free, total) = query_vram(state).unwrap_or((0, 0));
tracing::info!(
device_index = state.device_index,
job,
tokens,
pool_used_mb = used,
pool_peak_mb = peak,
pool_reserved_mb = reserved,
device_used_mb = total.saturating_sub(free),
"vram trace"
);
}
#[cfg(not(feature = "cuda"))]
fn trace_device_pool(_state: &DeviceWorkerState, _job: &str, _tokens: usize) {}
#[cfg(not(feature = "cuda"))]
fn trim_device_pool(_state: &DeviceWorkerState) {}
@@ -1348,6 +1434,19 @@ fn load_dense_inner(
} else {
None
};
// A byte budget, because what else the card must hold (KV,
// activations) is the operator's trade to make.
let tier_budget = crate::harness::arch::qwen3_5::expert_tier::configured_budget_mb()
.filter(|_| experts_on_host);
let external_experts =
native_expert_source(&cfg, device, experts_on_host, tier_budget)?;
let dense = native_dense_source(&cfg, device, external_experts.is_some())?;
let expert_tier = tier_budget
.filter(|_| external_experts.is_none())
.map(|mb| {
tracing::info!(budget_mb = mb, "VRAM expert tier enabled (#318)");
crate::harness::arch::qwen3_5::moe::DeviceExpertTier::new(mb << 20)
});
let model = crate::harness::arch::qwen4_exp::model::Qwen4ExpForCausalLM::load(
&cfg,
dtype,
@@ -1358,6 +1457,9 @@ fn load_dense_inner(
safetensors_paths,
isq_cache,
experts_vb: host_vb.as_ref(),
expert_tier,
external_experts,
dense,
// Host residency (#318) is what makes a model whose
// experts exceed VRAM loadable; everything else in
// the model still lands on the device.
@@ -1379,6 +1481,83 @@ fn load_dense_inner(
}
}
/// Strata's kernels over the GGUF named by `NEURON_STRATA_EXPERT_GGUF`.
#[cfg(feature = "strata-kernels")]
fn native_expert_source(
cfg: &crate::harness::arch::qwen4_exp::config::Config,
device: &candle_core::Device,
experts_on_host: bool,
tier_budget_mb: Option<u64>,
) -> anyhow::Result<
Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::moe::ExternalExpertSource>>,
> {
use crate::harness::arch::qwen4_exp::native_experts::{GgufExpertSource, NativeExpertFactory};
let Some(path) = std::env::var_os("NEURON_STRATA_EXPERT_GGUF").filter(|_| experts_on_host)
else {
return Ok(None);
};
let text = &cfg.text_config;
let source = GgufExpertSource::open(
std::path::Path::new(&path),
device,
text.num_hidden_layers,
text.num_experts,
text.hidden_size,
text.moe_intermediate_size,
tier_budget_mb,
)?;
Ok(Some(std::sync::Arc::new(NativeExpertFactory(
std::sync::Arc::new(source),
))))
}
#[cfg(not(feature = "strata-kernels"))]
fn native_expert_source(
_cfg: &crate::harness::arch::qwen4_exp::config::Config,
_device: &candle_core::Device,
_experts_on_host: bool,
_tier_budget_mb: Option<u64>,
) -> anyhow::Result<
Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::moe::ExternalExpertSource>>,
> {
Ok(None)
}
/// The GGUF's quantized dense weights, when `NEURON_STRATA_DENSE=1`
/// and the experts already come from that GGUF.
#[cfg(feature = "strata-kernels")]
fn native_dense_source(
cfg: &crate::harness::arch::qwen4_exp::config::Config,
device: &candle_core::Device,
native_experts: bool,
) -> anyhow::Result<Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::proj::LinearSource>>> {
use crate::harness::arch::qwen4_exp::gguf_dense::{GgufDenseSource, Heads};
let text = &cfg.text_config;
let enabled = std::env::var("NEURON_STRATA_DENSE").is_ok_and(|v| v == "1");
let Some(path) =
std::env::var_os("NEURON_STRATA_EXPERT_GGUF").filter(|_| enabled && native_experts)
else {
return Ok(None);
};
let heads = Heads {
key_heads: text.linear_num_key_heads,
value_heads: text.linear_num_value_heads,
head_dim: text.linear_value_head_dim,
};
let key_dim = text.linear_num_key_heads * text.linear_key_head_dim;
let source = GgufDenseSource::open(std::path::Path::new(&path), device, heads, key_dim)?;
Ok(Some(std::sync::Arc::new(source)))
}
#[cfg(not(feature = "strata-kernels"))]
fn native_dense_source(
_cfg: &crate::harness::arch::qwen4_exp::config::Config,
_device: &candle_core::Device,
_native_experts: bool,
) -> anyhow::Result<Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::proj::LinearSource>>> {
Ok(None)
}
/// Load the leader's TP shard on the worker thread. Reads the Comm
/// directly from `state.nccl`; no cross-thread Arc<Comm> transfer.
#[cfg(feature = "cuda")]
+1
View File
@@ -20,6 +20,7 @@ pub mod preprocess;
pub(crate) mod quant;
pub mod reasoning_budget;
pub mod reasoning_effort;
pub mod replica;
pub mod sampling;
pub mod speculative;
pub mod tp;
+1
View File
@@ -490,6 +490,7 @@ mod tests {
preserve_thinking: None,
expert_residency: None,
max_in_flight: None,
replicas: None,
}
}
+225
View File
@@ -0,0 +1,225 @@
//! Copies of one model on several devices (#397).
//!
//! A mining rig carries many identical small cards on PCIe x1 risers,
//! where tensor parallelism is not viable: the throughput shape is one
//! independent copy of the model per card. The neuron keeps those copies
//! behind one model id, so cortex sees a single model whose capacity is
//! their sum.
//!
//! Admission stays per *model*: one [`AdmissionController`] with an
//! in-flight slot per replica, so the queue, the per-principal fair share
//! and the anonymous ceiling all see the model's whole capacity. An
//! admitted request then takes an idle replica from a [`ReplicaPool`].
//! Admission never lets in more requests than there are replicas, so a
//! replica is free whenever a request reaches the pool, unless one has
//! failed.
//!
//! Idle replicas are handed out round-robin (a returned replica goes to
//! the back of the line), which spreads heat and wear across the cards
//! instead of working the first one hardest.
//!
//! [`AdmissionController`]: super::admission::AdmissionController
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tokio::sync::Semaphore;
/// The idle set of a replicated model's copies.
pub struct ReplicaPool {
idle: Mutex<VecDeque<usize>>,
/// One permit per idle, healthy replica.
available: Semaphore,
healthy: Vec<AtomicBool>,
busy: Vec<AtomicUsize>,
}
impl ReplicaPool {
pub fn new(replicas: usize) -> Arc<Self> {
Arc::new(Self {
idle: Mutex::new((0..replicas).collect()),
available: Semaphore::new(replicas),
healthy: (0..replicas).map(|_| AtomicBool::new(true)).collect(),
busy: (0..replicas).map(|_| AtomicUsize::new(0)).collect(),
})
}
pub fn len(&self) -> usize {
self.healthy.len()
}
pub fn is_empty(&self) -> bool {
self.healthy.is_empty()
}
/// Wait for an idle replica. `None` once every replica has failed.
pub async fn checkout(self: &Arc<Self>) -> Option<ReplicaLease> {
let permit = self.available.acquire().await.ok()?;
permit.forget();
let index = self
.idle
.lock()
.expect("replica pool poisoned")
.pop_front()?;
self.busy[index].fetch_add(1, Ordering::AcqRel);
Some(ReplicaLease {
pool: Arc::clone(self),
index,
})
}
/// Requests replica `index` is running.
pub fn in_flight(&self, index: usize) -> usize {
self.busy[index].load(Ordering::Acquire)
}
pub fn is_healthy(&self, index: usize) -> bool {
self.healthy[index].load(Ordering::Acquire)
}
pub fn healthy_count(&self) -> usize {
self.healthy
.iter()
.filter(|h| h.load(Ordering::Acquire))
.count()
}
/// Take a replica out of service for good. It is not handed out again;
/// when it was the last one, waiters are woken with `None`.
fn retire(&self, index: usize) {
self.healthy[index].store(false, Ordering::Release);
if self.healthy_count() == 0 {
self.available.close();
}
}
}
/// A replica held for one request. Dropping it returns the replica to the
/// pool, unless it was marked failed.
pub struct ReplicaLease {
pool: Arc<ReplicaPool>,
index: usize,
}
impl ReplicaLease {
pub fn index(&self) -> usize {
self.index
}
/// The replica's device failed: never hand it out again.
pub fn mark_failed(&self) {
self.pool.retire(self.index);
}
}
impl Drop for ReplicaLease {
fn drop(&mut self) {
self.pool.busy[self.index].fetch_sub(1, Ordering::AcqRel);
if self.pool.is_healthy(self.index) {
self.pool
.idle
.lock()
.expect("replica pool poisoned")
.push_back(self.index);
self.pool.available.add_permits(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::AdmissionConfig;
use crate::harness::admission::AdmissionController;
use std::time::Duration;
/// #397's acceptance: eight replicas, sixteen concurrent requests. Every
/// replica works, none ever runs two at once, and nothing is refused.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn sixteen_requests_spread_over_eight_replicas_one_at_a_time() {
const REPLICAS: usize = 8;
let pool = ReplicaPool::new(REPLICAS);
let admission = Arc::new(AdmissionController::new(&AdmissionConfig {
max_in_flight: REPLICAS,
max_queue_depth: 16,
max_per_principal: 0,
..AdmissionConfig::default()
}));
let peak: Arc<Vec<AtomicUsize>> =
Arc::new((0..REPLICAS).map(|_| AtomicUsize::new(0)).collect());
let served: Arc<Vec<AtomicUsize>> =
Arc::new((0..REPLICAS).map(|_| AtomicUsize::new(0)).collect());
let tasks: Vec<_> = (0..16)
.map(|i| {
let (pool, admission) = (Arc::clone(&pool), Arc::clone(&admission));
let (peak, served) = (Arc::clone(&peak), Arc::clone(&served));
tokio::spawn(async move {
let principal = format!("caller-{i}");
let _permit = admission.enter(Some(&principal)).await.expect("admitted");
let lease = pool.checkout().await.expect("a replica");
let running = pool.in_flight(lease.index());
peak[lease.index()].fetch_max(running, Ordering::AcqRel);
served[lease.index()].fetch_add(1, Ordering::AcqRel);
tokio::time::sleep(Duration::from_millis(30)).await;
})
})
.collect();
for t in tasks {
t.await.expect("request task");
}
for r in 0..REPLICAS {
assert_eq!(peak[r].load(Ordering::Acquire), 1, "replica {r} peak");
assert!(
served[r].load(Ordering::Acquire) >= 1,
"replica {r} never served"
);
}
let total: usize = served.iter().map(|s| s.load(Ordering::Acquire)).sum();
assert_eq!(total, 16);
assert_eq!(admission.in_flight(), 0);
}
#[tokio::test]
async fn idle_replicas_are_handed_out_round_robin() {
let pool = ReplicaPool::new(3);
let mut order = Vec::new();
for _ in 0..6 {
let lease = pool.checkout().await.expect("a replica");
order.push(lease.index());
}
assert_eq!(order, [0, 1, 2, 0, 1, 2]);
}
#[tokio::test]
async fn a_failed_replica_is_never_handed_out_again() {
let pool = ReplicaPool::new(2);
let lease = pool.checkout().await.expect("a replica");
assert_eq!(lease.index(), 0);
lease.mark_failed();
drop(lease);
for _ in 0..4 {
assert_eq!(pool.checkout().await.expect("a replica").index(), 1);
}
assert_eq!(pool.healthy_count(), 1);
}
#[tokio::test]
async fn waiters_wake_when_the_last_replica_fails() {
let pool = ReplicaPool::new(1);
let lease = pool.checkout().await.expect("a replica");
let waiter = {
let pool = Arc::clone(&pool);
tokio::spawn(async move { pool.checkout().await.is_none() })
};
tokio::time::sleep(Duration::from_millis(20)).await;
lease.mark_failed();
drop(lease);
let woke_empty = tokio::time::timeout(Duration::from_secs(2), waiter)
.await
.expect("waiter woke")
.expect("waiter task");
assert!(woke_empty);
}
}
+19 -1
View File
@@ -10,6 +10,8 @@ const POLL_INTERVAL: Duration = Duration::from_secs(5);
pub struct HealthCache {
inner: RwLock<HealthResponse>,
has_gpus: RwLock<bool>,
/// This host's power schedule (#397); unset for an always-on host.
schedule: std::sync::OnceLock<crate::availability::Schedule>,
}
impl Default for HealthCache {
@@ -33,8 +35,11 @@ impl HealthCache {
// Per-model admission load is overlaid by the api handler
// from the candle harness (#53); the cache doesn't own it.
models: Vec::new(),
// Overlaid by the api handler from `[availability]`.
next_dark: None,
}),
has_gpus: RwLock::new(false),
schedule: std::sync::OnceLock::new(),
}
}
@@ -45,7 +50,20 @@ impl HealthCache {
/// Get a snapshot of the current health state.
pub async fn snapshot(&self) -> HealthResponse {
self.inner.read().await.clone()
let mut snapshot = self.inner.read().await.clone();
if let Some(schedule) = self.schedule.get() {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
snapshot.next_dark = schedule.next_dark(now);
}
snapshot
}
/// Announce this host's power schedule on `/health` (#397). Set once,
/// at startup.
pub fn set_schedule(&self, schedule: crate::availability::Schedule) {
let _ = self.schedule.set(schedule);
}
/// Run forever, polling nvidia-smi every 5 seconds and updating the cache.
+1
View File
@@ -1,5 +1,6 @@
pub mod activation;
pub mod api;
pub mod availability;
pub mod config;
pub mod cuda;
pub mod discovery;
+4
View File
@@ -191,6 +191,10 @@ async fn daemon(args: Args) -> Result<()> {
let shutdown_candle = candle.clone();
let health_cache = Arc::new(health::HealthCache::new());
if let Some(schedule) = neuron::availability::Schedule::from_config(&cfg.availability)? {
tracing::info!(online = ?cfg.availability.online, "power schedule (UTC)");
health_cache.set_schedule(schedule);
}
health_cache
.set_has_gpus(!discovery_result.devices.is_empty())
.await;
+4
View File
@@ -33,6 +33,7 @@ async fn test_load_default_models_skips_unknown_harness() {
preserve_thinking: None,
expert_residency: None,
max_in_flight: None,
replicas: None,
},
ModelSpec {
model_id: "model-b".into(),
@@ -44,6 +45,7 @@ async fn test_load_default_models_skips_unknown_harness() {
preserve_thinking: None,
expert_residency: None,
max_in_flight: None,
replicas: None,
},
];
@@ -107,6 +109,7 @@ async fn test_load_default_models_skipped_on_driver_mismatch() {
preserve_thinking: None,
expert_residency: None,
max_in_flight: None,
replicas: None,
}];
let activation = ActivationTracker::new(&specs);
let reason = "host NVIDIA driver/library mismatch (userspace NVML 580.159 vs loaded \
@@ -212,6 +215,7 @@ fn qwen_spec() -> ModelSpec {
preserve_thinking: None,
expert_residency: None,
max_in_flight: None,
replicas: None,
}
}
@@ -423,6 +423,9 @@ fn qwen4_exp_case(name: &str, max_abs_bound: f32) {
isq_cache: None,
experts_onto: &device,
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.expect("load the fixture through the production loader");
+1
View File
@@ -110,6 +110,7 @@ fn spec(model_id: &str, tp: Option<u32>, quant: Option<&str>) -> ModelSpec {
preserve_thinking: None,
expert_residency: None,
max_in_flight: None,
replicas: None,
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Niko1221 and the Strata contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
# Vendored from Strata
These files are an unmodified subset of [Strata](https://github.com/Niko1221/Strata)
at commit `6a6db7ff58c283cf28d2b913404b5fa31a767eaa`, kept at their upstream paths so
their relative includes work and so they can be diffed against upstream.
- Strata is MIT licensed. See `LICENSE`.
- Its quantised-block layouts and dot products derive from llama.cpp / ggml, also MIT
licensed. See `engine/third_party/ggml/LICENSE` and `VERSION.txt`.
To update, copy the same paths from a newer upstream commit and change the commit above.
Do not edit these files in place; neuron's adapter is `crates/neuron/src/cuda/strata_adapter/strata_shim.cu`.
## Decode kernels for the native engine (#427)
Added from the same Strata revision for neuron's native qwen4_exp decode
engine, unmodified: `native_gdn`, `native_gdn_preprocess`, `fused_gdn`,
`native_gr_norm`, `native_gr_postops`, `gr`, `native_router`, `native_moe`,
`quantize_act`, `bf16_gemv` and `native_bf16` (`engine/src/kernels/cuda/`),
with the headers they include. neuron calls them through
`src/cuda/strata_adapter/engine_shim.cu`.
@@ -0,0 +1,77 @@
// include/strata/artifact/model_family.hpp - which model family a GGUF holds, from its general.architecture.
//
// Strata was written for one model (Qwen3.8-Flash-Next, `qwen4exp`). Qwen3.6-35B-A3B (`qwen35moe`) is a close
// cousin (same tokenizer, the same Gated-DeltaNet + gated-attention 3:1 layer pattern, the same head dims), so the
// reader, the geometry and the layout tables know both. The ENGINE runs only the families `model_family_runs`
// names; a recognised family it does not run yet is refused with `model_family_not_supported`, not mis-run.
//
// No dependencies: the GGUF reader (the architecture guard) and the core geometry both include this.
#pragma once
#include <string>
namespace strata {
enum class ModelFamily {
Unknown = 0,
Qwen4Exp, ///< Qwen3.8-Flash-Next and its fine-tunes / pruned variants (Swift 1.5, the Coder)
Qwen35Moe, ///< Qwen3.6-35B-A3B (Unsloth's MTP GGUFs): plain pre-norm residual, dense attention, nextn MTP block
Hy4Flash, ///< Tencent Hy4-Flash 220B-A12B (LatentMoE + Hybrid MLA/IndexPool + 4-Module Engram + 5L DFly2)
Inkling2Loop, ///< Thinking Machines Inkling 2 Mini 26.4B-A3.4B/5.4B (24->48 Looped MoE + SITU + AttnRes + ShortConv + DSpark)
};
inline ModelFamily model_family_from_arch(const std::string& arch) {
if (arch == "qwen4exp") return ModelFamily::Qwen4Exp;
if (arch == "qwen35moe") return ModelFamily::Qwen35Moe;
if (arch == "hy_v4_flash") return ModelFamily::Hy4Flash;
if (arch == "inkling2" || arch == "inkling2_loop" || arch == "inkling2_loop_text") return ModelFamily::Inkling2Loop;
return ModelFamily::Unknown;
}
/// The GGUF architecture string (also the metadata key prefix: "<arch>.block_count").
inline const char* model_family_arch(ModelFamily f) {
switch (f) {
case ModelFamily::Qwen4Exp:
return "qwen4exp";
case ModelFamily::Qwen35Moe:
return "qwen35moe";
case ModelFamily::Hy4Flash:
return "hy_v4_flash";
case ModelFamily::Inkling2Loop:
return "inkling2_loop";
default:
return "";
}
}
/// The model's name for messages.
inline const char* model_family_title(ModelFamily f) {
switch (f) {
case ModelFamily::Qwen4Exp:
return "Qwen3.8-Flash-Next";
case ModelFamily::Qwen35Moe:
return "Qwen3.6-35B-A3B";
case ModelFamily::Hy4Flash:
return "Tencent Hy4-Flash";
case ModelFamily::Inkling2Loop:
return "Thinking Machines Inkling 2 Mini";
default:
return "an unknown model";
}
}
/// Whether Flash-Next's engine path runs the family. Qwen3.6 has an engine path of its own (src/qwen35), which the
/// CUDA and HIP builds of `strata` switch to at the top of main(); the Intel Arc (SYCL) build has none yet, so there
/// (and on Flash-Next's path) the family is refused with `model_family_not_supported`.
inline bool model_family_runs(ModelFamily f) { return f == ModelFamily::Qwen4Exp; }
/// The refusal for a recognised family the engine does not run (empty when it runs it).
inline std::string model_family_not_supported(ModelFamily f) {
if (model_family_runs(f)) return {};
if (f == ModelFamily::Unknown) return "this is not a model family Strata knows";
return std::string(model_family_title(f)) + " (architecture '" + model_family_arch(f) +
"') runs on the NVIDIA (CUDA) and AMD (HIP) builds of Strata; this build does not run it yet (the Intel "
"Arc / SYCL port is in development). Use a CUDA or HIP build, or a Qwen3.8-Flash-Next model file";
}
} // namespace strata
@@ -0,0 +1,21 @@
// strata/core/bw_dense_defaults.hpp - defaults of the bitwise load-ordering variants from the Blackwell Qwen speed work (BW-DENSE).
//
// Each is bitwise equal to the kernel it replaces (the screens and the engine A/Bs are in phaseA-tests/blackwell/decisions/E15.md and
// E21-small-kernel-loads.md), measured on an RTX PRO 5000 Blackwell (compute capability 12.0), so they are on there and nowhere else
// (unmeasured on other cards). STRATA_SM120_PERF=0 and STRATA_DEFAULTS=026 turn them off like the rest of the 12.0 set; an explicit variable
// (STRATA_GR_V3_PF, STRATA_SMALL_UNR) wins on any card in both directions.
#pragma once
#include "strata/core/defaults_026.hpp"
#include "strata/core/sm120_series.hpp"
namespace strata {
/// STRATA_GR_V3_PF when unset (gr_down_v3 / gr_up_v3 load-ordering variants): bits 0 (gr_down batched staging loads), 2 (gr_up batched loads) and 7 (gr_down: windows of 5+ rows
/// take 2 rows a warp with the activations read from shared memory once for both rows; bitwise the same dots, DF2-MORE: down 16.1 / 16.2 / 17.6 / 19.5 -> 13.3 / 14.1 / 14.7 / 15.6 us at T 5-8).
inline int gr_v3_pf_default(int major, int minor) { return sm12x_default(major, minor, kGb10GrV3Pf) && !qwen_defaults_026() ? 133 : 0; }
/// STRATA_SMALL_UNR when unset: bit 0 the bf16 router read, bit 1 the GDN a/b projection (constant-trip loops).
inline int small_unr_default(int major, int minor) { return sm12x_default(major, minor, kGb10SmallUnr) && !qwen_defaults_026() ? 3 : 0; }
} // namespace strata
@@ -0,0 +1,41 @@
// include/strata/core/defaults_026.hpp - STRATA_DEFAULTS=026: the master switch of the Qwen engine's 0.2.7 defaults.
//
// Every default the Qwen engine (`strata`) changed since v0.2.6 goes back to what v0.2.6 did when STRATA_DEFAULTS=026 is in the
// environment (the app's "off" for its speed switches sends it): the wide
// hyper-connection up read (STRATA_GR_UP_WIDE), the stream-split hyper-connection read (STRATA_GR_V3), the int8 prompt attention
// (STRATA_PROMPT_ATTN_IMMA), the four gfx12 decode switches of the arch table, the PLE residency policy (STRATA_PLE_AUTO_RAM), and the
// gfx12 decode miss split of 0.15 (back to 0.55). KVA is off by default in 0.2.7 and stays whatever STRATA_KVA says.
// The residency-biased routing (STRATA_ROUTE_PRIOR) was in this set in 0.2.7; it is off by default again (owner, 2026-10-29), so the master switch
// has nothing to take back there, and route_prior_default() answers 0 with the switch on or off.
// An explicit per-feature variable (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, STRATA_PLE_AUTO_RAM=1, ...) or flag (--pcie-frac, --ple-io)
// still wins over the master switch. Each rule is a pure function that takes the answer of qwen_defaults_026() as its `v026`
// argument, so a test can check both settings without touching the environment (src/core/arch_defaults_test.cpp,
// src/core/ple_residency_test.cpp).
#pragma once
#include <cstdlib>
#include <cstring>
namespace strata {
/// "026", "0.2.6" and "v0.2.6" name version 0.2.6; anything else (unset, "", "0", "027") does not.
inline bool is_026_token(const char* v) {
return v != nullptr && (std::strcmp(v, "026") == 0 || std::strcmp(v, "0.2.6") == 0 || std::strcmp(v, "v0.2.6") == 0);
}
/// STRATA_DEFAULTS=026 (read once).
inline bool qwen_defaults_026() {
static const bool on = is_026_token(std::getenv("STRATA_DEFAULTS"));
return on;
}
/// The decode miss split's start value (the share of a native pack's missing experts the CPU pool takes) when --pcie-frac is not given:
/// NVFP4 packs 0.25, other native packs 0.55 (the x16 share), and 0.15 on gfx12 (0.2.7) unless STRATA_PCIE_FRAC_DEFAULT=old or the master
/// switch is 026; a canonical pack 0.2.
inline double pcie_start_frac(bool nvfp4_pack, bool native_pack, bool gfx12_default, bool pf_old, bool v026 = false) {
if (nvfp4_pack) return 0.25;
if (!native_pack) return 0.2;
return gfx12_default && !pf_old && !v026 ? 0.15 : 0.55;
}
} // namespace strata
@@ -0,0 +1,154 @@
// strata/core/dispatch_stats.hpp - aggregate dispatch counters (BW-MEASURE, P0.2 of the Blackwell plan).
//
// Which kernel path a run really took: the dense projection kernel by type and shape, the grouped expert path, the hyper-connection
// format, the head, the all-resident or partial window graph, and why a fast path was declined. Counted where a path is CHOSEN:
// * inside a graph capture (Verifier::record_window): once per recorded window, binned by the window width T and the graph kind;
// a run's total calls = counts of that bin x how often that graph was launched (graph_launch(), one increment per launch);
// * outside a capture (the draft head, the prompt path): every call, bin "eager".
// Nothing is read back from the device and nothing runs inside a timed device region. A call costs one mutex and one hash lookup
// (tens of ns, against a kernel launch of microseconds); STRATA_DISPATCH_STATS=0 turns it off.
//
// The report is JSON, written at exit when STRATA_DISPATCH_REPORT=<path> is set (and by the CLI's --stats to stdout as "dispatch").
// Header only, standard C++17, no CUDA / HIP / SYCL / Metal types: every backend compiles it.
#pragma once
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace strata::dispatch {
struct Key {
uint16_t cat = 0, var = 0, scope = 0, t = 0, ncols = 0, pad = 0;
uint32_t n_in = 0, n_out = 0;
bool operator==(const Key& o) const { return std::memcmp(this, &o, sizeof(Key)) == 0; }
};
struct KeyHash {
size_t operator()(const Key& k) const {
uint64_t a, b;
std::memcpy(&a, reinterpret_cast<const char*>(&k), 8);
std::memcpy(&b, reinterpret_cast<const char*>(&k) + 8, 8);
uint64_t h = a * 0x9E3779B97F4A7C15ull ^ (b + 0x7F4A7C159E3779B9ull + (a << 6) + (a >> 2));
h ^= h >> 29;
return (size_t) h;
}
};
enum Cat : uint16_t { kStr = 0, kDense = 1, kExpert = 2, kHc = 3, kHead = 4, kWindow = 5 };
class Stats {
public:
// leaked on purpose: the atexit report must not run after the maps are destroyed
static Stats& get() { static Stats* s = new Stats(); return *s; }
bool on() const { return on_; }
// the current thread's bin: 0 = eager, else 1 + (T * 4 + kind) of the graph being captured
static uint16_t& scope() { thread_local uint16_t s = 0; return s; }
void count(const Key& k, uint64_t n = 1) {
if (!on_) return;
std::lock_guard<std::mutex> lk(m_);
map_[k] += n;
}
// a free-text path / reason; interned once per distinct text
void note(const char* text, uint64_t n = 1) {
if (!on_) return;
std::lock_guard<std::mutex> lk(m_);
auto it = intern_.find(text);
uint16_t id;
if (it == intern_.end()) { id = (uint16_t) names_.size(); names_.push_back(text); intern_.emplace(text, id); }
else id = it->second;
Key k; k.cat = kStr; k.var = id; k.scope = scope();
map_[k] += n;
}
void graph_launch(int T, int kind) { // kind: 0 all-resident graph, 1 doorbell (partial) graph, 2 other
if (!on_) return;
if (T < 0 || T > 63) return;
launches_[T][kind & 3].fetch_add(1, std::memory_order_relaxed);
}
void graph_capture(int T, int kind) { note_capture_(T, kind); }
std::string json() {
std::lock_guard<std::mutex> lk(m_);
std::string o = "{\n \"launches\": {";
bool first = true;
for (int t = 0; t < 64; ++t)
for (int k = 0; k < 4; ++k) {
const uint64_t n = launches_[t][k].load();
if (n == 0) continue;
char b[96];
std::snprintf(b, sizeof b, "%s\"T%d/k%d\": %llu", first ? "" : ", ", t, k, (unsigned long long) n);
o += b; first = false;
}
o += "},\n \"counts\": [\n";
first = true;
for (const auto& kv : map_) {
const Key& k = kv.first;
char b[512];
const int sc = k.scope == 0 ? -1 : (k.scope - 1) / 4, kd = k.scope == 0 ? -1 : (k.scope - 1) % 4;
if (k.cat == kStr)
std::snprintf(b, sizeof b, "%s {\"scope\": [%d, %d], \"cat\": \"str\", \"key\": \"%s\", \"n\": %llu}", first ? "" : ",\n",
sc, kd, k.var < names_.size() ? names_[k.var].c_str() : "?", (unsigned long long) kv.second);
else
std::snprintf(b, sizeof b,
"%s {\"scope\": [%d, %d], \"cat\": %u, \"var\": %u, \"type\": %u, \"ncols\": %u, \"n_in\": %u, \"n_out\": %u, \"n\": %llu}",
first ? "" : ",\n", sc, kd, k.cat, k.var, k.t, k.ncols, k.n_in, k.n_out, (unsigned long long) kv.second);
o += b; first = false;
}
o += "\n ]\n}\n";
return o;
}
void write_report() {
const char* p = std::getenv("STRATA_DISPATCH_REPORT");
if (!on_ || p == nullptr || p[0] == '\0') return;
const std::string j = json();
if (std::FILE* f = std::fopen(p, "wb")) { std::fwrite(j.data(), 1, j.size(), f); std::fclose(f); }
}
private:
Stats() {
const char* e = std::getenv("STRATA_DISPATCH_STATS");
on_ = e == nullptr || e[0] != '0';
for (auto& r : launches_) for (auto& c : r) c.store(0);
if (on_) std::atexit([] { Stats::get().write_report(); });
}
void note_capture_(int T, int kind) { note(("capture T" + std::to_string(T) + "/k" + std::to_string(kind)).c_str()); }
bool on_ = true;
std::mutex m_;
std::unordered_map<Key, uint64_t, KeyHash> map_;
std::unordered_map<std::string, uint16_t> intern_;
std::vector<std::string> names_;
std::atomic<uint64_t> launches_[64][4];
};
// RAII: while alive, this thread's counts go to the bin of a T-token graph of the given kind
struct Scope {
uint16_t prev;
Scope(int T, int kind) : prev(Stats::scope()) { Stats::scope() = (uint16_t) (1 + T * 4 + (kind & 3)); }
~Scope() { Stats::scope() = prev; }
};
// a kernel-level choice: a dense projection / expert / hc / head launch with its shape
inline void kernel(Cat cat, int variant, int type, int n_in, int n_out, int ncols) {
Stats& s = Stats::get();
if (!s.on()) return;
Key k; k.cat = cat; k.var = (uint16_t) variant; k.t = (uint16_t) type; k.ncols = (uint16_t) ncols;
k.n_in = (uint32_t) n_in; k.n_out = (uint32_t) n_out; k.scope = Stats::scope();
s.count(k);
}
inline void note(const char* text) { Stats::get().note(text); }
inline void notef(const char* fmt, long a = 0, long b = 0, long c = 0) {
Stats& s = Stats::get();
if (!s.on()) return;
char buf[200];
std::snprintf(buf, sizeof buf, fmt, a, b, c);
s.note(buf);
}
} // namespace strata::dispatch
@@ -0,0 +1,94 @@
// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only).
//
// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer
// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the
// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for:
// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that
// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's.
#pragma once
#include <cstdlib>
#if defined(__linux__) && !defined(__HIPCC__) && !defined(STRATA_GPU_METAL)
#include <dlfcn.h>
#include <string>
#endif
namespace strata {
/// nbald/volta-forever version string when running under the CUDA 13 Volta compatibility proxy (libcuda.so.1
/// exports volta_forever_version()), or "" when not loaded. Cached once per process.
inline const char* volta_forever_version() {
#if defined(__linux__) && !defined(__HIPCC__) && !defined(STRATA_GPU_METAL)
static const std::string ver = []() -> std::string {
using Fn = const char* (*)();
auto probe = [](void* handle) -> std::string {
if (!handle) return {};
void* sym = dlsym(handle, "volta_forever_version");
if (!sym) return {};
const char* s = reinterpret_cast<Fn>(sym)();
return s ? std::string(s) : std::string();
};
std::string out;
#ifdef RTLD_DEFAULT
out = probe(RTLD_DEFAULT);
if (!out.empty()) return out;
#endif
#ifdef RTLD_NOLOAD
if (void* h = dlopen("libcuda.so.1", RTLD_LAZY | RTLD_NOLOAD)) {
out = probe(h);
dlclose(h);
if (!out.empty()) return out;
}
#endif
if (void* h = dlopen("libcuda.so.1", RTLD_LAZY | RTLD_LOCAL)) {
out = probe(h);
dlclose(h);
if (!out.empty()) return out;
}
return {};
}();
return ver.c_str();
#else
return "";
#endif
}
inline bool volta_forever_active() { return volta_forever_version()[0] != '\0'; }
/// the emulated compute capability as 10 * major + minor, or 0 (off)
inline int emulated_cc() {
static const int cc = [] {
const char* e = std::getenv("STRATA_EMULATE_CC");
const int v = e ? std::atoi(e) : 0;
return v >= 75 && v < 120 ? v : 0;
}();
return cc;
}
/// Effective compute capability (10 * major + minor). STRATA_EMULATE_CC wins; otherwise under
/// nbald/volta-forever (which spoofs physical Volta 7.0 as 7.5 for CUDA 13 binaries), remap 7.5 -> 7.0.
inline int cc_of(int real_major, int real_minor, bool vf_active) {
if (const int e = emulated_cc()) return e;
if (vf_active && real_major == 7 && real_minor == 5) return 70;
return 10 * real_major + real_minor;
}
inline int cc_of(int real_major, int real_minor) {
return cc_of(real_major, real_minor, volta_forever_active());
}
inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; }
inline int cc_minor_of(int real_minor) {
if (const int e = emulated_cc()) return e % 10;
if (volta_forever_active() && real_minor == 5) return 0;
return real_minor;
}
/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100,
/// 99 KB on the other Ampere and Ada cards
inline int smem_optin_of(int real) {
switch (emulated_cc()) {
case 0: return real;
case 75: return 65536;
case 80: return 166912;
default: return real < 101376 ? real : 101376;
}
}
} // namespace strata
@@ -0,0 +1,457 @@
// include/strata/core/expert_nibble.hpp - STRATA_EXPERT_NIBBLE=1 (opt-in, default off): the gate/up experts of
// IQ2_S / IQ3_XXS / IQ3_S layers kept as 4-bit codes in their VRAM slots, for Pascal GP100 (sm_60).
//
// **WHY.** On a GP100 the decode window's gate/up expert kernels are not held by memory bandwidth: they use a small
// part of it and wait on each block's serial chain (the weights, the codebook lookups, the emulated dp4a, the
// reduction). Re-encoding each 32-weight item of these three formats as sixteen bytes of 4-bit codes (one aligned
// 16-byte load) and keeping the integer scale and the fp16 d as they are makes the slot 1.25-1.68x the GGUF bytes and
// the decode of four weights 1-4 integer instructions instead of two codebook lookups.
//
// **WHY IT IS LOSSLESS.** Their grids have only 3 (IQ2_S) or 8 (IQ3_XXS, IQ3_S) magnitudes, so each int8 weight the
// production `Split<TG>::load` decodes is one of at most 16 signed values. At every start the transcoder decodes every
// item of every converted slot with the production load, encodes it, decodes the written code again and compares; and
// the GGUF blocks are rebuilt from every slot and compared with the blob byte for byte (`check_gguf`). The decode
// kernels run the production integer chain and float tail in the production order: every gate / up value is the
// production kernel's, bit for bit. The prompt path's MMQ reads the GGUF blocks rebuilt from the slot (`gather_gguf`,
// in place of the copy it does today): the same bytes, so the same bits.
//
// **OFF IS TODAY.** Unset or 0: no layer is converted, `slot_bytes(l)` is `expert_layout().blob_bytes(l)`, nothing is
// transcoded, sealed or hashed, and none of the new branches is entered. Only a CUDA build with
// STRATA_EXPERIMENTAL_SM60 has the kernels (STRATA_EXPERT_NIBBLE_BUILT); every other build refuses the switch at start.
#pragma once
#include "strata/kernels/cpu/expert_layout.hpp"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \
!defined(STRATA_GPU_METAL)
#define STRATA_EXPERT_NIBBLE_BUILT 1
#else
#define STRATA_EXPERT_NIBBLE_BUILT 0
#endif
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_NIB_HD __host__ __device__
#else
#define STRATA_NIB_HD
#endif
namespace strata::core::nibble {
// ------------------------------------------------------------------------------------------------ the slot layout
//
// A converted layer's expert slot, in order (the host arena and the pack keep the GGUF blocks):
//
// codes kRows x kItems x 16 B row r, item k at (r * kItems + k) * 16; rows 0..kNFf-1 gate, kNFf..kRows-1 up
// scales kRows x kItems x 1 B row r, item k at kScOff + r * kItems + k (the production scale step's input)
// d kRows x kSuper x 2 B row r, superblock s at kDOff + (r * kSuper + s) * 2: the block's fp16 d, bit for bit
// ------ kGuBytes = 1,766,400 B (6900 x 256: the down part starts 256-aligned)
// down the GGUF down rows, copied verbatim from the raw blob's [down_off, bytes)
// ------ slot_bytes = round_up(kGuBytes + down bytes, kSlotAlign)
//
// One item = 32 weights of a row, one 16-byte code (four 32-bit words, see `encode_item`). Only the expert shape
// n_embd 2560, n_ff 640 is converted: every other layer keeps its GGUF blob and its kernels.
inline constexpr int64_t kNEmbd = 2560; ///< the gate/up rows' width (the activation)
inline constexpr int64_t kNFf = 640; ///< gate rows = up rows = n_ff
inline constexpr int64_t kRows = 2 * kNFf; ///< 1280: gate, then up
inline constexpr int64_t kItems = kNEmbd / 32; ///< 80 items of 32 weights per row
inline constexpr int64_t kSuper = kNEmbd / 256; ///< 10 superblocks (one fp16 d each) per row
inline constexpr uint64_t kItemBytes = 16; ///< one item's code: four words, one 16-byte load
inline constexpr uint64_t kCodesOff = 0;
inline constexpr uint64_t kUpCodesOff = (uint64_t) kNFf * kItems * kItemBytes; ///< 819,200: row kNFf
inline constexpr uint64_t kScOff = (uint64_t) kRows * kItems * kItemBytes; ///< 1,638,400
inline constexpr uint64_t kDOff = kScOff + (uint64_t) kRows * kItems; ///< 1,740,800
inline constexpr uint64_t kGuBytes = kDOff + (uint64_t) kRows * kSuper * 2; ///< 1,766,400
inline constexpr uint64_t kDownOff = kGuBytes; ///< the down rows
inline constexpr uint64_t kSlotAlign = 256; ///< every slot's size
static_assert(kGuBytes == 1766400, "the slot layout above");
static_assert(kGuBytes % kSlotAlign == 0, "the down part starts 256-aligned");
static_assert(kScOff % 16 == 0 && kDOff % 16 == 0, "each region starts 16-aligned");
/// Byte offset of row `row` (0..kRows-1; up rows are kNFf + r) item `k`'s code inside the slot.
STRATA_NIB_HD constexpr uint64_t code_off(int64_t row, int64_t k) {
return kCodesOff + ((uint64_t) row * kItems + (uint64_t) k) * kItemBytes;
}
/// Byte offset of row `row` item `k`'s scale byte.
STRATA_NIB_HD constexpr uint64_t scale_off(int64_t row, int64_t k) { return kScOff + (uint64_t) row * kItems + (uint64_t) k; }
/// Byte offset of row `row` superblock `s`'s fp16 d (s = k / 8 for item k).
STRATA_NIB_HD constexpr uint64_t d_off(int64_t row, int64_t s) { return kDOff + ((uint64_t) row * kSuper + (uint64_t) s) * 2; }
/// A converted slot's size for a raw blob whose down rows are `down_bytes` long.
STRATA_NIB_HD constexpr uint64_t slot_bytes_for(uint64_t down_bytes) {
return (kGuBytes + down_bytes + kSlotAlign - 1) / kSlotAlign * kSlotAlign;
}
// ------------------------------------------------------------------------------------------------ the formats
inline constexpr int kIQ3_XXS = 18;
inline constexpr int kIQ3_S = 21;
inline constexpr int kIQ2_S = 22;
/// Whether `gu_type` is converted (the three formats whose weights take at most 16 values).
STRATA_NIB_HD constexpr bool fmt_built(int gu_type) { return gu_type == kIQ2_S || gu_type == kIQ3_XXS || gu_type == kIQ3_S; }
/// The GGUF gate/up row bytes of `gu_type` at kNEmbd (a converted layer's raw blob must agree; 0 = not a format here).
STRATA_NIB_HD constexpr uint64_t raw_gu_row(int gu_type) {
return gu_type == kIQ2_S ? 820 : gu_type == kIQ3_XXS ? 980 : gu_type == kIQ3_S ? 1100 : 0;
}
inline const char* fmt_name(int gu_type) {
switch (gu_type) {
case kIQ3_XXS: return "IQ3_XXS";
case kIQ3_S: return "IQ3_S";
case kIQ2_S: return "IQ2_S";
default: return "?";
}
}
// ------------------------------------------------------------------------------------------------ the item code
//
// `g[32]` below is one item as the production `Split<TG>::load` leaves it: g[4 * j + b] is byte b of W.g[j]
// (j = 0..7, the dp4a order against the q8_1 block's qs words). Word m (0..3) of the 16-byte code holds W.g[2m]
// and W.g[2m + 1]:
//
// IQ2_S bits 4b..4b+3 = c(g[8m + b]), bits 16+4b.. = c(g[8m + 4 + b]), b = 0..3
// c = magnitude index of {8, 25, 43} | sign << 2: the PRMT selector into {8,25,43,0} {-8,-25,-43,0}
// IQ3_XXS same nibble positions; c = index of {4, 12, 20, 28, 36, 44, 52, 62} | sign << 3
// IQ3_S byte b = u(g[8m + b]) | u(g[8m + 4 + b]) << 4, u = (v + 15) / 2 (v odd, -15..15); v = 2u - 15
//
// The scale byte keeps the production integer scale step's input:
// IQ2_S the block's scales byte for the item: ls0 | ls1 << 4 (W.ls0, W.ls1)
// IQ3_XXS aux32 >> 28 (0..15, W.ls)
// IQ3_S 1 + 2 * nibble (1..31, W.ls)
/// Encodes one item; false when a weight is outside the format's code set (the conversion then refuses to start).
inline bool encode_item(int gu_type, const int8_t g[32], uint32_t q[4]) {
bool ok = true;
auto code = [&](int8_t v) -> uint32_t {
const int a = v < 0 ? -(int) v : (int) v;
if (gu_type == kIQ3_S) {
if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; }
return (uint32_t) (((int) v + 15) / 2);
}
if (gu_type == kIQ3_XXS) {
static constexpr int mag[8] = { 4, 12, 20, 28, 36, 44, 52, 62 };
for (uint32_t i = 0; i < 8; ++i)
if (a == mag[i]) return i | (v < 0 ? 8u : 0u);
ok = false;
return 0;
}
const uint32_t m = a == 8 ? 0u : a == 25 ? 1u : a == 43 ? 2u : 3u; // IQ2_S
if (m == 3u) { ok = false; return 0; }
return m | (v < 0 ? 4u : 0u);
};
for (int m = 0; m < 4; ++m) {
uint32_t w = 0;
for (int b = 0; b < 4; ++b) {
const uint32_t c0 = code(g[8 * m + b]), c1 = code(g[8 * m + 4 + b]);
if (gu_type == kIQ3_S) w |= (c0 | c1 << 4) << (8 * b);
else w |= c0 << (4 * b) | c1 << (16 + 4 * b);
}
q[m] = w;
}
return ok;
}
/// Decodes one item's code back to the production W.g bytes (the host reference the parity program compares with;
/// the device decoders give the same bytes). Codes outside the set decode as the PRMT does: IQ2_S index 3 -> 0.
inline void decode_item(int gu_type, const uint32_t q[4], int8_t g[32]) {
static constexpr int8_t iq2[8] = { 8, 25, 43, 0, -8, -25, -43, 0 };
static constexpr int8_t iq3[8] = { 4, 12, 20, 28, 36, 44, 52, 62 };
for (int m = 0; m < 4; ++m)
for (int b = 0; b < 4; ++b) {
uint32_t c0, c1;
if (gu_type == kIQ3_S) {
c0 = q[m] >> (8 * b) & 15u;
c1 = q[m] >> (8 * b + 4) & 15u;
} else {
c0 = q[m] >> (4 * b) & 15u;
c1 = q[m] >> (16 + 4 * b) & 15u;
}
auto val = [&](uint32_t c) -> int8_t {
if (gu_type == kIQ3_S) return (int8_t) (2 * (int) c - 15);
if (gu_type == kIQ3_XXS) return (int8_t) ((c & 8u) ? -iq3[c & 7u] : iq3[c & 7u]);
return iq2[c & 7u];
};
g[8 * m + b] = val(c0);
g[8 * m + 4 + b] = val(c1);
}
}
// ------------------------------------------------------------------------------------------------ the slot hash
//
// STRATA_EXPERT_NIBBLE_RECHECK's fingerprint of a slot: over the slot's first `hashed` bytes (kGuBytes plus the down
// rows; the alignment tail is not written and not hashed) as little-endian 32-bit words w_i, the last one
// zero-extended, H = sum_i (uint64) (w_i ^ i) * kHashMul mod 2^64. A sum, so the device's order of adding does not
// change it; the index term makes a moved word count.
inline constexpr uint64_t kHashMul = 0x9E3779B97F4A7C15ull;
/// The host reference of the slot hash (the device hash gives the same value for the same bytes).
inline uint64_t hash_host(const void* p, uint64_t bytes) {
const uint8_t* s = (const uint8_t*) p;
uint64_t h = 0;
const uint64_t n = (bytes + 3) / 4;
for (uint64_t i = 0; i < n; ++i) {
uint32_t w = 0;
const uint64_t at = 4 * i, take = bytes - at < 4 ? bytes - at : 4;
std::memcpy(&w, s + at, (size_t) take); // little-endian hosts only
h += (uint64_t) (w ^ (uint32_t) i) * kHashMul;
}
return h;
}
// ------------------------------------------------------------------------------------------------ the switches
struct Config {
bool on = false; ///< STRATA_EXPERT_NIBBLE=1
bool recheck = false; ///< STRATA_EXPERT_NIBBLE_RECHECK=1 (debug: every slot's hash per request)
std::vector<int> fmts{ kIQ2_S, kIQ3_XXS, kIQ3_S }; ///< STRATA_EXPERT_NIBBLE_FMTS (default 22,18,21)
std::vector<int64_t> skip; ///< STRATA_EXPERT_NIBBLE_SKIP: layers kept in their GGUF blocks
std::string error; ///< non-empty: a malformed value - the start is refused
};
namespace detail {
/// "a,b,c" -> integers; false on anything else (empty = an empty list).
inline bool parse_list(const char* s, std::vector<int64_t>& out) {
out.clear();
while (s != nullptr && *s != '\0') {
char* end = nullptr;
const long long v = std::strtoll(s, &end, 10);
if (end == s) return false;
out.push_back((int64_t) v);
s = end;
if (*s == ',') ++s;
else if (*s != '\0') return false;
}
return true;
}
} // namespace detail
/// The switches, read once (generate.cpp reads them before anything is allocated).
inline const Config& config() {
static const Config c = [] {
Config r;
const char* e = std::getenv("STRATA_EXPERT_NIBBLE");
if (e != nullptr && e[0] != '\0' && std::strcmp(e, "0") != 0) {
if (std::strcmp(e, "1") == 0) r.on = true;
else r.error = std::string("STRATA_EXPERT_NIBBLE=") + e + ": expected 0 or 1";
}
const char* rc = std::getenv("STRATA_EXPERT_NIBBLE_RECHECK");
r.recheck = rc != nullptr && std::strcmp(rc, "1") == 0;
std::vector<int64_t> v;
if (const char* f = std::getenv("STRATA_EXPERT_NIBBLE_FMTS"); f != nullptr && f[0] != '\0') {
if (!detail::parse_list(f, v)) {
if (r.error.empty()) r.error = std::string("STRATA_EXPERT_NIBBLE_FMTS=") + f + ": expected ggml types, e.g. 22,18,21";
} else {
r.fmts.clear();
for (const int64_t t : v) {
if (!fmt_built((int) t) && r.error.empty())
r.error = "STRATA_EXPERT_NIBBLE_FMTS: type " + std::to_string(t) +
" is not converted (22 IQ2_S, 18 IQ3_XXS, 21 IQ3_S)";
r.fmts.push_back((int) t);
}
}
}
if (const char* k = std::getenv("STRATA_EXPERT_NIBBLE_SKIP"); k != nullptr && k[0] != '\0') {
if (!detail::parse_list(k, r.skip) && r.error.empty())
r.error = std::string("STRATA_EXPERT_NIBBLE_SKIP=") + k + ": expected layer numbers, e.g. 40,44";
}
return r;
}();
return c;
}
/// With the switch on, the first environment setting it refuses, as a message (empty = none): the paths that would
/// read a converted slot as GGUF blocks, write GGUF bytes into one, or run other kernels for the converted layers
/// than the ones the 4-bit kernels are bit for bit. The command-line half (--peer-device, remote expert caches,
/// --kv-grow, --vram-elastic), the cc 6.0 check, full residency and no loan are generate.cpp's checks; the prompt
/// path's own (MMQ on every converted layer) is Prefill::nibble_prompt_check.
inline std::string env_conflicts() {
auto set = [](const char* n) -> const char* {
const char* v = std::getenv(n);
return v != nullptr && v[0] != '\0' ? v : nullptr;
};
const char* v = set("STRATA_MMQ_DIRECT");
if (v != nullptr && std::atoi(v) != 0)
return "STRATA_MMQ_DIRECT (the prompt MMQ would read a converted slot in place as GGUF blocks)";
v = set("STRATA_PREFILL_MMQ");
if (v != nullptr && std::atoi(v) == 0) return "STRATA_PREFILL_MMQ=0 (the FP16 prompt path reads GGUF blocks)";
v = set("STRATA_PF_FUSED");
if (v != nullptr && v[0] == '1') return "STRATA_PF_FUSED=1 (the fused prompt kernels read GGUF blocks)";
v = set("STRATA_FS_SLOTS");
if (v != nullptr && std::atoi(v) > 0) return "STRATA_FS_SLOTS (Foresight swaps GGUF blobs into slots)";
v = set("STRATA_EXPERT_V2");
if (v != nullptr && v[0] == '1') return "STRATA_EXPERT_V2=1 (the S26 kernels, not the CUDA layout, on IQ3_S)";
v = set("STRATA_KV_GROW");
if (v != nullptr && v[0] != '0') return "STRATA_KV_GROW (the elastic K/V moves slots at their GGUF size)";
v = set("STRATA_EXP_MODE");
if (v != nullptr && std::atoi(v) != 0 && std::atoi(v) != 8)
return "STRATA_EXP_MODE other than 0 or 8 (another layout's gate/up kernels)";
return {};
}
// ------------------------------------------------------------------------------------------------ the VRAM table
/// One layer's slots. `on` false: the GGUF blob, `slot_bytes == raw_bytes`, the production kernels.
struct LayerVram {
bool on = false;
int gu_type = -1, d_type = -1;
uint64_t down_off = 0; ///< in the slot: kDownOff when on, else the raw blob's down_off
uint64_t down_bytes = 0; ///< the down rows (raw_bytes - raw_down_off)
uint64_t hashed = 0; ///< bytes the slot hash covers: kGuBytes + down_bytes when on, else 0
uint64_t slot_bytes = 0; ///< what the expert cache allocates per slot (`open_sized`, every estimate)
// the raw blob as the arena and the pack hold it (expert_layout().fmt[l]); the transcoder reads these
uint64_t raw_bytes = 0, raw_gu_row = 0, raw_up_off = 0, raw_down_off = 0;
};
/// One layer's entry from its GGUF format and the switches (pure; `plan_layers` calls it per layer).
inline LayerVram plan_layer(int64_t l, const strata::kernels::cpu::NativeFmt& f, const Config& c) {
LayerVram v;
v.gu_type = f.gu_type;
v.d_type = f.d_type;
v.raw_bytes = f.bytes;
v.raw_gu_row = f.gu_row;
v.raw_up_off = f.up_off;
v.raw_down_off = f.down_off;
v.down_bytes = f.bytes - f.down_off;
v.down_off = f.down_off;
v.slot_bytes = f.bytes;
bool listed = false, skipped = false;
for (const int t : c.fmts) listed = listed || t == f.gu_type;
for (const int64_t s : c.skip) skipped = skipped || s == l;
// [gate | up | down] exactly, no NVFP4 tail, the down rows a whole number of 16-byte words (the gathers copy them so)
const bool shape = f.n_embd == kNEmbd && f.n_ff == kNFf && f.gu_row == raw_gu_row(f.gu_type) &&
f.up_off == (uint64_t) kNFf * f.gu_row && f.down_off == 2 * f.up_off && f.bytes > f.down_off &&
f.tail_off == 0 && (f.bytes - f.down_off) % 16 == 0;
if (c.on && c.error.empty() && listed && !skipped && fmt_built(f.gu_type) && shape) {
v.on = true;
v.down_off = kDownOff;
v.hashed = kGuBytes + v.down_bytes;
v.slot_bytes = slot_bytes_for(v.down_bytes);
}
return v;
}
/// Every layer's entry for this pack (all off for a Q2_0 pack or with the switch off). `err`: a SKIP layer out of
/// range, or the switch on with a Q2_0 pack.
inline std::vector<LayerVram> plan_layers(const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {
const Config& c = config();
std::vector<LayerVram> out((size_t) (lay.n_layers > 0 ? lay.n_layers : 0));
for (int64_t l = 0; l < (int64_t) out.size(); ++l) {
if (lay.native && (size_t) l < lay.fmt.size()) out[(size_t) l] = plan_layer(l, lay.fmt[(size_t) l], c);
else out[(size_t) l].slot_bytes = out[(size_t) l].raw_bytes = lay.blob_bytes(l);
}
if (c.on && !lay.native) err = "STRATA_EXPERT_NIBBLE needs a native pack (native_experts.txt)";
for (const int64_t s : c.skip)
if (c.on && (s < 0 || s >= lay.n_layers) && err.empty())
err = "STRATA_EXPERT_NIBBLE_SKIP: layer " + std::to_string(s) + " is not in the model";
return out;
}
namespace detail {
inline std::vector<LayerVram>& table() {
static std::vector<LayerVram> t;
return t;
}
} // namespace detail
/// generate.cpp only: the table, once, after `expert_layout_load` and BEFORE the first slot estimate (placement
/// search, can_start, the cache's auto size, every `open_sized`). Not thread-safe: set before any other thread.
inline void set_layers(std::vector<LayerVram> v) { detail::table() = std::move(v); }
/// Layer `l`'s entry (an off entry when the table is not set or `l` is outside it). Read-only after `set_layers`.
inline const LayerVram& layer(int64_t l) {
static const LayerVram off;
const auto& t = detail::table();
return l >= 0 && (size_t) l < t.size() ? t[(size_t) l] : off;
}
/// Whether any layer is converted (the switch on and the table set).
inline bool any_on() {
for (const LayerVram& v : detail::table())
if (v.on) return true;
return false;
}
/// Bytes of one of layer `l`'s VRAM slots: the converted size for a converted layer, else the layout's blob bytes
/// (exactly `expert_layout().blob_bytes(l)`: with the switch off every caller sizes what it sized before).
inline uint64_t slot_bytes(int64_t l) {
const auto& t = detail::table();
if (l >= 0 && (size_t) l < t.size()) return t[(size_t) l].slot_bytes;
return strata::kernels::cpu::expert_layout().blob_bytes(l);
}
// ------------------------------------------------------------------------------------------------ fatal paths
/// A converted layer reached a path that would compute or copy it as GGUF blocks: say where and stop. Never a
/// silent wrong answer.
[[noreturn]] inline void fatal(int64_t l, const char* where, const char* why) {
std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: layer %lld (%s, 4-bit slots) reached %s: %s - stopping\n",
(long long) l, fmt_name(layer(l).gu_type), where != nullptr ? where : "?", why != nullptr ? why : "");
std::fflush(stderr);
std::abort();
}
/// Before each raw slot copy that bypasses the ExpertCache API (the adaptive tier's copies, the elastic K/V's slot
/// moves): fatal when `l` is a converted layer. The startup refusals keep these paths off; this is the backstop
/// (with `ExpertCache::seal()` for the API's own fills).
inline void guard_raw(int64_t l, const char* where) {
if (layer(l).on) fatal(l, where, "a raw slot copy at the GGUF size");
}
// ------------------------------------------------------------------------------------------------ the decode kernels
//
// Two skeletons in the shape of native_gu_multi_kernel (16 lanes a row, a group's entries GRP_NC at a time), both bit
// for bit the production gate/up: S stages the entries' q8_1 blocks in shared memory and decodes each item where it
// is used (IQ3_S: v = 2u - 15 restored per byte, then the production apply); P loads the lane's codes, scales and d
// before staging the qs words as 16-byte rows (IQ3_S: sum = 2 dot(u, x) - 15 sum(x), the same int32). Per format the
// faster one on 4x GP100 at T = 1..6 (native_expert_bench --nibble): IQ2_S P, IQ3_XXS S, IQ3_S S.
inline constexpr int kSkelS = 0, kSkelP = 1;
STRATA_NIB_HD constexpr int gu_skeleton(int gu_type) { return gu_type == kIQ2_S ? kSkelP : kSkelS; }
// ------------------------------------------------------------------------------------------------ iq_kernels.cu
//
// Device addresses are `unsigned long long` (as native_expert_grouped's grp_ptr), streams `void*`; each returns the
// CUDA error code (0 = success) so the caller can name the layer. A build without STRATA_EXPERT_NIBBLE_BUILT
// returns cudaErrorInvalidValue (1) from each.
/// The reverse codebooks (grid magnitudes -> GGUF grid index) `check_gguf` and `gather_gguf` use, built on the CURRENT
/// device (once per device; call it at load, before any capture). Non-zero also when a grid entry is not unique.
int prepare(void* stream);
/// Converts `n` raw blobs of layer `L` (device `staging`, `L.raw_bytes` apart, as the host arena holds them) into
/// the converted slots at `slot_ptrs[0..n)` (a device array): codes, scales, d. The down rows are not touched (the
/// caller copies them to `slot + kDownOff`). Every item is decoded with the production `Split<TG>::load`, encoded,
/// decoded from the written code again and compared with W.g[0..7], the scale and d; each item that differs or holds
/// a weight outside the code set adds 1 to `*bad` (device). L.on must be true.
int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
unsigned long long* bad, void* stream);
/// The GGUF gate/up blocks rebuilt from each of the `n` (<= 64) converted slots at `slot_ptrs` and its down rows,
/// compared with the raw blobs in `staging` (`L.raw_bytes` apart) byte for byte: each 32-bit word that differs adds 1
/// to `*bad`. `prepare` first.
int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
unsigned long long* bad, void* stream);
/// The prompt path's gather of a converted layer's experts (prefill.cpp, MMQ): for q in [first, n) (n <= 16), the
/// GGUF [gate | up] blocks rebuilt from slot `slots[q]` (host array of device addresses) into gu_dst + q * gu_stride -
/// the bytes the raw blob holds, byte for byte - and its down rows copied to d_dst + q * d_stride; `zero_bytes` zeroed
/// after expert n - 1's gate/up and down (MMQ's tail). Every address, stride and size 16-byte aligned. `prepare`
/// on this device first.
int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride,
void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream);
/// The slot hash (`hash_host`'s value) of the `L.hashed` bytes at each `slot_ptrs[i]`, into device `out[0..n)`.
int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out,
void* stream);
} // namespace strata::core::nibble
@@ -0,0 +1,11 @@
// include/strata/core/geometries/flash_next.hpp - Qwen3.8-Flash-Next (qwen4exp), the shape the engine ships for.
// The values are ModelGeometry's member defaults (geometry.hpp); this header exists so that every shape is a header,
// and so that the default build is byte-for-byte the build it was before shapes were selectable.
#pragma once
namespace strata::core {
inline constexpr const char* kGeometryName = "flash_next";
inline constexpr ModelGeometry kCompiledGeometry{};
} // namespace strata::core
@@ -0,0 +1,92 @@
// include/strata/core/geometry.hpp - the model's geometry: one struct for the shape a model file declares and
// the shape the kernels are compiled for.
//
// A model file's geometry is read from its own metadata (`strata::read_geometry`, gguf_reader.hpp), and the
// engine passes that struct everywhere it needs a dimension. The CUDA/HIP kernels still fix most of these
// numbers at compile time (`constexpr int N = 2560` and the like); `kCompiledGeometry` is that shape, written
// once, and each kernel that pins a number `static_assert`s it against this struct. So a kernel and this file
// cannot drift apart without the build failing, and a model file of another shape is refused at load with the
// metadata key that differs (`strata::geometry_unsupported`) instead of mis-running.
//
// Dependency-free on purpose: the kernels include it.
#pragma once
#include "strata/artifact/model_family.hpp"
#include <cstdint>
namespace strata::core {
/// Every field is a number a kernel depends on, so a change to the compiled values is a change to a kernel
/// contract and not a tuning knob. The defaults are Qwen3.8-Flash-Next's (qwen4exp), the shape the kernels
/// are compiled for; the GGUF key each field is read from is named beside it.
struct ModelGeometry {
int64_t n_embd = 2560; ///< embedding_length
int64_t n_layers = 48; ///< block_count (the trunk; an in-file MTP block is counted in n_mtp_layers)
int64_t qsa_interval = 4; ///< full_attention_interval: every 4th layer is full attention, 3, 7, ... 47
int64_t n_vocab = 248320; ///< the length of tokenizer.ggml.tokens
double rms_eps = 1e-6; ///< attention.layer_norm_rms_epsilon
// GDN (36 layers)
int64_t ssm_state_size = 128; ///< ssm.state_size: the key head width, and the value head width
int64_t ssm_k_heads = 16; ///< ssm.group_count
int64_t ssm_v_heads = 48; ///< ssm.time_step_rank
int64_t ssm_d_conv = 4; ///< ssm.conv_kernel
int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48, derived
int64_t ssm_value_dim = 6144; ///< ssm.inner_size, 128 * 48
// QSA (12 layers)
int64_t n_head = 24; ///< attention.head_count
int64_t n_head_kv = 2; ///< attention.head_count_kv
int64_t head_dim = 256; ///< attention.key_length (= attention.value_length)
int64_t n_rot = 64; ///< rope.dimension_count: the rotated slice of head_dim and of idx_key_dim
int64_t idx_q_heads = 4; ///< attention.indexer.head_count
int64_t idx_key_dim = 128; ///< attention.indexer.key_length
int64_t idx_block = 4; ///< the non-zero attention.compress_ratios entry: one pooled key per 4 cells
int64_t idx_top_k = 2048; ///< attention.indexer.top_k: cells of selection budget
// gated residual, on every layer
int64_t hc = 4; ///< hyper_connection.count
int64_t hc_lr = 320; ///< hyper_connection.low_rank
// MoE, on every layer
int64_t n_expert = 512; ///< expert_count; pruned variants (GSQ-RCO Coder) ship fewer
int64_t n_expert_used = 10; ///< expert_used_count
int64_t n_ff = 640; ///< expert_feed_forward_length (= expert_shared_feed_forward_length)
// appended for the model families (Qwen3.6 = qwen35moe); the defaults keep Flash-Next's values
int64_t n_ff_shexp = 640; ///< the shared expert's FFN width (qwen4exp: equal to n_ff, read_geometry checks)
ModelFamily family = ModelFamily::Qwen4Exp;
int64_t n_mtp_layers = 0; ///< MTP blocks inside the model file, after the trunk (qwen35moe: blk.40)
constexpr bool has_indexer() const { return idx_q_heads > 0; } ///< false: dense attention only
constexpr bool has_hyper_connections() const { return hc > 0; } ///< false: plain pre-norm residual
constexpr int64_t hc_dim() const { return hc * n_embd; }
/// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list.
constexpr int64_t n_qsa_layers() const { return n_layers / qsa_interval; }
constexpr int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); }
};
} // namespace strata::core
// The shape the kernels are compiled for: `kCompiledGeometry`, defined by the geometry header chosen at configure
// time (`-DSTRATA_GEOMETRY=<name>` selects include/strata/core/geometries/<name>.hpp, `-DSTRATA_GEOMETRY_FILE=<path>`
// takes any header; cmake/strata_geometry.cmake writes geometry_selected.hpp into the build tree for either). With
// neither option the build uses Flash-Next's header and adds no compile flag. A kernel that fixes a dimension at
// compile time asserts it against `kCompiledGeometry`; geometry_checks.hpp holds the constraints every shape must meet.
#if __has_include("strata/core/geometry_selected.hpp")
#include "strata/core/geometry_selected.hpp"
#else
#include "strata/core/geometries/flash_next.hpp"
#endif
#include "strata/core/geometry_checks.hpp"
namespace strata::core {
/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval
/// = 4` and an explicit `attention.compress_ratios` array - and `read_geometry` checks that the two agree.
inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) {
return layer % g.qsa_interval == g.qsa_interval - 1;
}
} // namespace strata::core
@@ -0,0 +1,52 @@
// include/strata/core/geometry_checks.hpp - what every compiled shape must satisfy.
//
// The kernels are written for a family of shapes, not for one number each: some values are the same in every Qwen
// model of this layer design (the GDN state width, the attention head width, the conv width) and are held fixed
// here; the others have to be divisible or within a range the tiles, the shared-memory plans and the register
// arrays were written for. A geometry header that breaks one of these fails the build with the line below that
// names the field, instead of compiling a kernel that mis-runs. Included by geometry.hpp, after the header.
#pragma once
#include "strata/core/geometry.hpp"
namespace strata::core::geometry_checks {
inline constexpr const ModelGeometry& g = kCompiledGeometry;
// ---- held fixed: the same in every published Qwen3-Next / 3.5 / 3.6 config and in Flash-Next; the kernels unroll them
static_assert(g.ssm_state_size == 128, "geometry: ssm.state_size must be 128 (GDN kernels: 4 rows per lane, 128-thread blocks, 32x32 state tiles)");
static_assert(g.ssm_k_heads == 16, "geometry: ssm.group_count must be 16 (GDN key heads)");
static_assert(g.ssm_d_conv == 4, "geometry: ssm.conv_kernel must be 4 (3 history taps and 4 weights are unrolled)");
static_assert(g.head_dim == 256, "geometry: attention.key_length must be 256 (attention kernels: thread per dim, 4 warps x 64)");
static_assert(g.n_rot == 64, "geometry: rope.dimension_count must be 64");
static_assert(g.qsa_interval == 4, "geometry: full_attention_interval must be 4");
static_assert(g.hc == 4, "geometry: hyper_connection.count must be 4 (register and shared arrays hold 4 streams)");
static_assert(g.idx_q_heads == 4 && g.idx_key_dim == 128,
"geometry: the indexer must be 4 heads x 128 (one float4 per lane, one warp per head)");
static_assert(g.idx_block == 4, "geometry: the indexer pooling block must be 4 cells");
// ---- ranges and divisibility the tiles were written for
static_assert(g.n_embd % 256 == 0 && g.n_embd >= 1024 && g.n_embd <= 4096,
"geometry: embedding_length must be a multiple of 256 within 1024..4096 (K-quant rows, 8x512 partial sums, 4096-half shared staging)");
static_assert(g.n_ff % 64 == 0 && g.n_ff >= 256 && g.n_ff <= 1100,
"geometry: expert_feed_forward_length must be a multiple of 64 within 256..1100 (Q2 blobs, 64-wide act groups, 1024-byte act buffer)");
static_assert(g.n_ff_shexp == g.n_ff, "geometry: the shared expert must be as wide as the routed experts");
static_assert(g.hc_lr % 64 == 0 && g.hc_lr / 8 >= 32 && g.hc_lr / 8 <= 64 && g.hc_lr % 8 == 0,
"geometry: hyper_connection.low_rank must be a multiple of 64 with 32 <= low_rank/8 <= 64 (fused_gr lane rule)");
static_assert(g.n_head_kv >= 1 && g.n_head % g.n_head_kv == 0 && g.n_head / g.n_head_kv <= 16,
"geometry: attention.head_count / head_count_kv must be a whole number <= 16 (one M16 tile of query heads)");
static_assert(g.ssm_v_heads % g.ssm_k_heads == 0 && g.ssm_v_heads / g.ssm_k_heads >= 1 && g.ssm_v_heads / g.ssm_k_heads <= 4,
"geometry: ssm.time_step_rank must be 1..4 times ssm.group_count");
static_assert(g.n_expert % 32 == 0 && g.n_expert >= 32 && g.n_expert <= 512,
"geometry: expert_count must be a multiple of 32 up to 512 (router: one lane per 32 experts)");
static_assert(g.n_expert_used >= 1 && g.n_expert_used <= 16 && g.n_expert_used <= g.n_expert,
"geometry: expert_used_count must be 1..16");
static_assert(g.n_layers % g.qsa_interval == 0 && g.n_layers >= g.qsa_interval,
"geometry: block_count must be a multiple of full_attention_interval");
// ---- derived fields written out in the header must agree
static_assert(g.ssm_conv_channels == 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_state_size * g.ssm_v_heads,
"geometry: ssm_conv_channels must be 2*state*k_heads + state*v_heads");
static_assert(g.ssm_value_dim == g.ssm_state_size * g.ssm_v_heads, "geometry: ssm_value_dim must be state*v_heads");
} // namespace strata::core::geometry_checks
@@ -0,0 +1,221 @@
// strata/core/sm120_series.hpp - bitwise kernel switches that are ON by default on a compute capability 12.0 card
// (RTX 50 series / RTX PRO Blackwell workstation cards).
//
// 147-verify measured these exact switches on an RTX PRO 5000 Blackwell 72 GB (IQ3_S, every expert in VRAM): together
// a verify round of 4 tokens 13.70 -> 12.23 ms with the same text (notes-147-l620.md). Each one is bitwise equal to
// the kernels it replaces (their own parity tests and the identity gate), so only the speed changes:
// STRATA_SIDE_MIXER=2 the mixer's input-only work on branches of the verify graph
// STRATA_ATTN_DAILY=1 the Daily's decode attention (attn_chunk_kernel_pre75 + merge v2)
// STRATA_GR_UP75=1 the hyper-connection up projection with its rows' loads hoisted
// STRATA_GR_DOWN_TG=1 the hyper-connection down projection with one token a block row (T times the blocks); =2 (token
// pairs) on a 12.0 card with fewer than 80 SMs
// STRATA_GU_SWIGLU=1 gate/up, SwiGLU and the q8_1 blocks of the routed experts in one launch
// STRATA_GR_UP_WIDE=1 the hyper-connection up projection with one warp a row (1,280 blocks instead of 160; +1.9%
// story / +0.7% code decode on the RTX PRO 5000, 5 pairs, token ids identical; bitwise)
// and one that rounds differently (KL-checked, the AMD gfx12 rule): STRATA_PF_FUSED (the native packs' prompt experts on the
// fused int8 kernels, IQ2_S / IQ3_XXS / IQ3_S / IQ4_XS gate/up only, 12.0 cards with 80+ SMs only; =0 keeps MMQ, =1 takes every
// covered format on any card).
//
// STRATA_SM120_PERF=0 turns the whole set off on a 12.0 card (the defaults every other card has).
// Each switch's own variable still wins in both directions (=0 off, =1 / =2 on), on any card, as before.
// Nothing here changes a card that is not a 12.0, except the two switches the GB10 (sm_121) measured as well (kGb10AttnDaily, kGb10GrDownTg below;
// STRATA_SM121_PERF=0 or STRATA_DEFAULTS=026 give the GB10 its earlier defaults back); an sm_100 card keeps its defaults.
#pragma once
#include "strata/core/defaults_026.hpp"
#include "strata/core/emulate.hpp"
#include <cstdlib>
namespace strata {
/// STRATA_SM120_PERF (read once): unset or anything but "0" = on
inline bool sm120_series() {
static const bool on = [] {
const char* e = std::getenv("STRATA_SM120_PERF");
return e == nullptr || std::atoi(e) != 0;
}();
return on;
}
/// the device (raw cudaDevAttrComputeCapabilityMajor / Minor) is a 12.0 card, or emulates one (STRATA_EMULATE_CC=120)
inline bool is_sm120(int major, int minor) { return cc_major_of(major) == 12 && cc_minor_of(minor) == 0; }
/// STRATA_PLE_BATCH (the prompt path's batched PLE post-ops) when the user set nothing. ON everywhere except one toolchain: an engine built with CUDA 12.8
/// (CUDART_VERSION 12080..12089) running on a compute capability 12.0 card faults in the prompt path with it ("an illegal memory access", first error in the
/// native PLE postops launch; RTX PRO 6000, driver 580, srv118; issues #220, #224; CMake already warns for a CUDA < 13.0 sm_120 build). The same source built
/// with CUDA 13.0 (the released cuda13 package) and 13.2 runs it at every prompt length, and it is worth ~23% of the prompt speed there, so it stays on there.
/// `cudart_version`: CUDART_VERSION of the toolkit the engine was built with (0 in a HIP build); `hip`: a HIP build (a gfx12 card reports 12.0 as well).
inline bool ple_batch_default(int cudart_version, bool hip, int major, int minor) {
const bool cuda_12_8 = !hip && cudart_version >= 12080 && cudart_version < 12090;
return !(cuda_12_8 && is_sm120(major, minor));
}
/// The decision: STRATA_PLE_BATCH wins in both directions (text that reads as 0 is off, anything else on, as before); unset is ple_batch_default.
inline bool ple_batch_resolve(const char* env, int cudart_version, bool hip, int major, int minor) {
if (env != nullptr) return std::atoi(env) != 0;
return ple_batch_default(cudart_version, hip, major, minor);
}
/// the default of a bitwise switch of the set: on for a 12.0 card unless STRATA_SM120_PERF=0
inline bool sm120_default(int major, int minor) { return is_sm120(major, minor) && sm120_series(); }
/// the device is a GB10 (NVIDIA DGX Spark, compute capability 12.1, or emulates one)
inline bool is_sm121(int major, int minor) { return cc_major_of(major) == 12 && cc_minor_of(minor) == 1; }
/// STRATA_SM121_PERF (read once): unset or anything but "0" = on. The GB10 table of nv_defaults.cpp reads the same variable.
inline bool sm121_series() {
static const bool on = [] {
const char* e = std::getenv("STRATA_SM121_PERF");
return e == nullptr || std::atoi(e) != 0;
}();
return on;
}
/// The default of a bitwise switch of the 12.0 set that was ALSO measured on a GB10 (BW-7, phaseA-tests/bw/RESULTS-BW-B.md): on for a 12.0 card unless
/// STRATA_SM120_PERF=0, and on for a GB10 when `gb10_measured` (the caller's constant: the switch won there and passed its gate) unless
/// STRATA_SM121_PERF=0 or STRATA_DEFAULTS=026 (the same off switches as the GB10 table of nv_defaults.cpp). `v026`: qwen_defaults_026().
inline bool sm12x_default_v(int major, int minor, bool gb10_measured, bool v026) {
return sm120_default(major, minor) || (gb10_measured && is_sm121(major, minor) && sm121_series() && !v026);
}
inline bool sm12x_default(int major, int minor, bool gb10_measured) { return sm12x_default_v(major, minor, gb10_measured, qwen_defaults_026()); }
/// Which switches of the 12.0 set are on for a GB10 (compute capability 12.1, DGX Spark) as well. BW-7, 11-19, a rented GB10 (IQ3_S, all 24,576 experts resident,
/// DFlash2 Q4_0 drafter, --spec 6, fixed draft-cost table, fresh engine per start, arms interleaved, 4 requests x 300 tokens per kind a start, token ids identical to
/// the default's); numbers and gates in phaseA-tests/bw/RESULTS-BW-B.md. Each constant is one measured verdict, so a later measurement flips one line.
/// Decode against the GB10 default (3 paired rounds, median; chat / code / json / agent):
/// STRATA_ATTN_DAILY +0.3 / +0.9 / +0.7 / +1.2 % (json, agent 3 of 3 pairs) -> ON
/// STRATA_GR_DOWN_TG -0.1 / +0.7 / +1.1 / +0.9 % (json, agent 3 of 3 pairs; token pairs, the GB10 has 48 SMs) -> ON
/// STRATA_GU_SWIGLU -0.2 / -1.0 / 0.0 / +0.1 %, STRATA_GR_UP75 -0.7 / -0.2 / -0.4 / -0.6 %, STRATA_GR_UP_WIDE -0.4 / -0.3 / -0.1 / -0.2 %,
/// STRATA_SMALL_UNR +0.1 / -0.9 / +0.2 / 0.0 %, STRATA_DF_PDL +0.1 / -0.6 / 0.0 / +0.3 %: level or slower here (inside the 0.2-1 % scatter) -> stay off
/// STRATA_GR_V3 (another summation order, KL-gated; text changes) and STRATA_GR_V3_PF (E15, acts only with GR_V3): mixed, E15 itself level (v3 with / without PF
/// chat +1.0 %, code -0.9 %, json -0.4 %, agent -0.5 %) -> stay off
constexpr bool kGb10GuSwiglu = false; ///< STRATA_GU_SWIGLU
constexpr bool kGb10AttnDaily = true; ///< STRATA_ATTN_DAILY
constexpr bool kGb10GrUp75 = false; ///< STRATA_GR_UP75
constexpr bool kGb10GrDownTg = true; ///< STRATA_GR_DOWN_TG
constexpr bool kGb10GrUpWide = false; ///< STRATA_GR_UP_WIDE
constexpr bool kGb10SmallUnr = false; ///< STRATA_SMALL_UNR
constexpr bool kGb10DfPdl = false; ///< STRATA_DF_PDL
constexpr bool kGb10GrV3Pf = false; ///< STRATA_GR_V3_PF (E15: the v3 HC read's load ordering; bitwise, but it only acts when the v3 read runs)
constexpr bool kGb10GrV3 = false; ///< STRATA_GR_V3 (the stream-split HC read: another summation order, KL-gated)
// ---- 0.2.7 defaults of the CUDA speed work (pure rules; the engine reads the device and calls these; tests in arch_defaults_test)
// `hip`: a HIP build, where a gfx1200 / gfx1201 reports compute capability 12.0 as well and none of these is measured or wanted.
// `v026`: STRATA_DEFAULTS=026 (defaults_026.hpp qwen_defaults_026()): every one of these is then off, as in v0.2.6. An explicit variable
// (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, ...) is decided by the caller before it asks the rule, so it still wins.
// `total_bytes`: the card's memory (cudaDeviceProp::totalGlobalMem); `integrated`: a GPU that shares the PC's memory.
constexpr double kSmallCardGiB = 13.0; // "a 12 GB card": 12 GB cards report 11.6 - 12.0 GiB, 16 GB ones 15.6 - 16.0
/// The residency-bias bonus the user can ask for on a discrete CUDA card of 13 GiB or less (STRATA_ROUTE_PRIOR=1.5; the app's Expert-settings row
/// "Faster answers on 12 GB NVIDIA cards" writes it): THE one place the value lives. 1.5 since the owner decision of 2026-10-26 (2.0 had real defects in
/// the copy and code check on the RTX 3060 12 GB with IQ3_XXS; none in 19 tasks at 1.5 or 1.0). Speed against off: story +15%, code +37%.
/// It was the default on those cards in 0.2.7 only. Owner decision of 2026-10-29: OFF by default again (#4402: repetition loops and weaker results in long
/// agent sessions; our own 0.2.7 agent check passed 4.5 of 10 tasks with it on against 5.6 with it off). It stays an opt-in.
constexpr float kRoutePriorSmallCard = 1.5f;
/// STRATA_ROUTE_PRIOR when the user set nothing: 0 on every card (residency-biased routing changes which experts run, so it is only on when asked for:
/// STRATA_ROUTE_PRIOR=1.5, or the Expert-settings row). The same answer as v0.2.6 and as 0.2.7 with STRATA_ROUTE_PRIOR=0 or STRATA_DEFAULTS=026.
/// The arguments are kept so a caller and the table test (arch_defaults_test) still ask the same question per card; none of them changes the answer.
inline float route_prior_default(bool /*hip*/, bool /*integrated*/, double /*total_bytes*/, bool /*v026*/ = false) { return 0.0f; }
/// The lambda the engine uses given the text of STRATA_ROUTE_PRIOR (nullptr = unset): any set value is the user's own and wins on every card
/// (atof; "0" and text that reads as 0 are off; "1.5" is what the Expert-settings row writes), unset is route_prior_default (0).
inline float route_prior_resolve(const char* env, bool hip, bool integrated, double total_bytes, bool v026 = false) {
return env != nullptr ? (float) std::atof(env) : route_prior_default(hip, integrated, total_bytes, v026);
}
/// The window warm-up before READY (generate.cpp, lane DRAFT-COSTS): one dummy window per width on token id 1, whose misses page that token's experts into the GPU expert
/// cache. "Speed only" while routing ignores residency; with STRATA_ROUTE_PRIOR on, the first request is routed towards what is resident, so the dummy token's experts bend its
/// answer (#6171: P(<|im_end|>) summed over the 8 digits of a long passkey answer 4.8 - 7.4 % in the first request after a start against 1.4 - 1.7 % with the warm-up off or the prior off;
/// 8 starts per arm, RTX 3090, IQ4_XS). warm_env is STRATA_WINDOW_WARM (nullptr unset): "0" off, "1" on whatever the prior says; unset: on, except while the prior is on (prior > 0).
/// The cost of skipping it is the graph build of a width that the policy first picks inside a request (tens of ms, once).
inline bool window_warm_on(const char* warm_env, float prior) {
if (warm_env != nullptr && warm_env[0] == '0') return false;
if (warm_env != nullptr && warm_env[0] == '1') return true;
return !(prior > 0.0f);
}
/// STRATA_GR_V3 (the stream-split hyper-connection read, another summation order) when the user set nothing: ON for a discrete compute capability
/// 12.0 card (STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB, CUDA builds only. Measured: RTX PRO 5000 72 GB +1.2% decode clean,
/// -3.0% / -5.9% on 2x RTX A4000 (sm_86), +1.0% / -3.4% on an RTX 3060 (sm_86): so not those; a 12 GB sm_120 card is unmeasured.
inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, double total_bytes, bool v026 = false) {
return !v026 && !hip && ((!integrated && sm120_default(major, minor) && total_bytes / 1073741824.0 > kSmallCardGiB) || (kGb10GrV3 && is_sm121(major, minor) && sm121_series()));
}
/// STRATA_PROMPT_ATTN_IMMA (the prompt attention on int8 tensor cores, another summation order) when the user set nothing: ON for every CUDA card of
/// compute capability 8.0 or newer (the int8 m16n8k32 MMA), not Turing / Volta / Pascal, not HIP. `cc` = 10 * major + minor as the engine
/// resolves it (an emulated or forced Turing counts as 75). Measured on sm_120 (RTX PRO 5000) and sm_86 (2x RTX A4000): +1.1 .. +1.8% prompt.
inline bool prompt_attn_imma_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc >= 80; }
/// STRATA_MMVQ_IL_89 (#3453: the decode kernel row tables of an Ada card, the cells where an RTX 4070 and an RTX 4080 agreed; bitwise the same
/// output, only the rows-a-warp split differs) when the user set nothing: ON for compute capability 8.9 only (owner decision, 26 October: not yet
/// measured on an Ada card by us), off under STRATA_DEFAULTS=026 and in HIP builds. `cc` = 10 * major + minor as the engine resolves it.
inline bool mmvq_il_89_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc == 89; }
/// The two sm_80-only defaults of 0.2.7 (#3779: the wide dense dequant and the MMVQ-IL sm_80 tables, both bitwise the old output, measured on a
/// CMP 170HX only) given the text of their variable (nullptr = unset): "1" on and "0" off win, unset is on unless STRATA_DEFAULTS=026.
inline bool sm80_default_on(const char* env, bool v026 = false) {
if (env != nullptr && env[0] == '1') return true;
if (env != nullptr && env[0] == '0') return false;
return !v026;
}
/// The answer for STRATA_MMVQ_IL_89 given the variable's text (nullptr = unset): "1" on and "0" off win over everything, anything else (unset,
/// empty, other text) is the rule above.
inline bool mmvq_il_89_resolve(const char* env, bool hip, int cc, bool v026 = false) {
if (env != nullptr && env[0] == '1') return true;
if (env != nullptr && env[0] == '0') return false;
return mmvq_il_89_default(hip, cc, v026);
}
/// STRATA_GR_UP_WIDE (the hyper-connection up projection, one warp a row; bitwise the old kernel) when the user set nothing: ON for a compute
/// capability 12.0 card (STRATA_SM120_PERF=0 turns the set off), CUDA builds only.
inline bool gr_up_wide_default(bool hip, int major, int minor, bool v026 = false) { return !v026 && !hip && sm12x_default_v(major, minor, kGb10GrUpWide, v026); }
/// STRATA_PREFILL_LAYER_MAJOR (#3976: the layer-major prompt walk, which reads each layer's streamed experts once per super-chunk instead of once
/// per chunk; another summation order of the routed experts, so KL-checked, not bitwise) when the user set nothing: OFF everywhere (owner's yes 2026-11-02).
/// It was ON for a CUDA layer split (`stages` = the number of GPUs the prompt path runs on, 2 or more; measured 2026-10-24 on 2x RTX A4000 with IQ3_XXS and
/// streamed experts only), but on 2x RTX A6000 (IQ3_S, MTP, three residency levels) the chunk-major path reads a 32K prompt 37-55% sooner and is level at 8K
/// (DF2-MGPU, boston). The one place the walk wins by default is the single-card small-cache rule (small_card_prompt_path below), which sets
/// STRATA_PREFILL_LAYER_MAJOR=1 itself. STRATA_PREFILL_LAYER_MAJOR=1 still turns it on, "0" off, by hand, on any build that has it. The parameters stay so that
/// the callers and the resolve rule below keep their shape. The engine adds its own per-prompt declines (image prompts, KVA, a batch read that yields,
/// a peer GPU, no VRAM for a super-chunk): those read the chunk-major path as before.
inline bool prefill_layer_major_default(bool /*hip*/, int /*stages*/, bool /*v026*/ = false) { return false; }
/// The answer for STRATA_PREFILL_LAYER_MAJOR given the variable's text (nullptr = unset): any text that starts a number other than 0 is on, "0" (or any
/// text that reads as 0) is off, both win over everything; unset or empty is the rule above. An explicit "1" is honoured on one GPU too (the
/// opt-in of the first ports); a HIP build still declines at run time.
inline bool prefill_layer_major_resolve(const char* env, bool hip, int stages, bool v026 = false) {
if (env != nullptr && env[0] != '\0') return std::atoi(env) != 0;
return prefill_layer_major_default(hip, stages, v026);
}
/// The small-card prompt path (owner's yes 2026-11-02; DF2-MEM, phaseA-tests/blackwell/RESULTS-DF2MEM.md sections 5-10). On one CUDA card whose expert
/// cache is small, the default prompt path has to read prompts in chunks below 8,192 tokens and streams every expert again for every chunk; reading them
/// with the unfused experts (STRATA_PF_FUSED=0) and, from two chunks on, the layer-major walk (each layer's experts once per super-chunk) is faster:
/// IQ3_S on an RTX PRO 5000 with the cache held to ~1.3K / ~1.6K / ~1.9K engine slots (default chunks 2048 / 3840 / 5888): time to first token of a 20K / 32K
/// prompt -44% / -50%, -41% / -42%, -14% / -12% (and -26% on a real 12 GB RTX 5070 at 20K); from a default chunk of 8,192 on (2.3K slots and up) the default
/// path wins and the same change costs +1..+25%. Not bitwise (first-token KL against the FP16 prompt path 0.012-0.018 for every path including the default;
/// top-1 47 of 48), hence the owner's yes. `default_chunk` is the chunk the DEFAULT path got from the cache sizing (0: none, e.g. no borrowing or an explicit
/// --prefill). One GPU, CUDA, a native (IQ) pack only (what was measured), not under STRATA_DEFAULTS=026. The user's own variables win both ways:
/// `fused_env_set` (STRATA_PF_FUSED named, either value) leaves the expert path alone and with it the walk (a fused layout declines it anyway);
/// `lm_env_set` (STRATA_PREFILL_LAYER_MAJOR named) leaves the walk alone.
struct SmallCardPromptPath {
bool fused_off = false; ///< read the prompt with the unfused experts (STRATA_PF_FUSED=0 as far as the engine is concerned)
bool layer_major = false; ///< and take the layer-major walk for a prompt of two chunks or more (STRATA_PREFILL_LAYER_MAJOR=1)
bool any() const { return fused_off || layer_major; }
};
inline constexpr long long kSmallCardChunkBelow = 8192;
inline SmallCardPromptPath small_card_prompt_path(long long default_chunk, bool hip, int stages, bool native_pack, bool v026, bool fused_env_set,
bool lm_env_set) {
SmallCardPromptPath r;
if (hip || v026 || !native_pack || stages > 1 || default_chunk <= 0 || default_chunk >= kSmallCardChunkBelow) return r;
if (fused_env_set) return r;
r.fused_off = true;
r.layer_major = !lm_env_set;
return r;
}
} // namespace strata
@@ -0,0 +1,46 @@
// strata/core/sm75_series.hpp - the Turing (RTX 20, compute capability 7.5) kernel series: one opt-in switch.
//
// The Turing kernels of PRs #2069-#2072, #2081, #2091-#2093, #2145-#2146, #2220-#2223, #1821 were measured on one RTX
// 2080 Ti (and a CMP 50HX) and are bitwise equal to the kernels they replace. We have no sm_75 card to confirm them, so
// they are ON ONLY WHEN ASKED FOR:
//
// STRATA_SM75_PERF=1 turns on every bitwise Turing kernel of the series on a compute capability 7.5 card.
//
// Each kernel keeps the author's own switch, which wins over STRATA_SM75_PERF in both directions (=0 off, =1 on, on any
// card where the PR said so for tests). Nothing here changes a card that is not a 7.5: the check is the card's compute
// capability (STRATA_EMULATE_CC=75 counts, so a 75-virtual build on an sm_86 card runs the series for tests).
//
// The numerics-changing Turing options are NOT part of this switch and keep their own explicit opt-ins:
// STRATA_SELECT_SIMT=1|2 (FP32 tiled block scorer), STRATA_PA_V2T=1 (v2 prompt attention), STRATA_PF_FUSED_SM75=1
// (fused int8 prompt experts), STRATA_BF16_TC=1 (FP16 tensor-core projections).
#pragma once
#include "strata/core/emulate.hpp"
#include <cstdlib>
namespace strata {
/// STRATA_SM75_PERF=1 (read once)
inline bool sm75_series() {
static const bool on = [] {
const char* e = std::getenv("STRATA_SM75_PERF");
return e != nullptr && std::atoi(e) != 0;
}();
return on;
}
/// the device (raw cudaDevAttrComputeCapabilityMajor / Minor) is a Turing card, or emulates one (STRATA_EMULATE_CC=75)
inline bool is_sm75(int major, int minor) { return cc_of(major, minor) == 75; }
/// the default of a bitwise Turing kernel switch: on for a Turing card when STRATA_SM75_PERF=1
inline bool sm75_default(int major, int minor) { return is_sm75(major, minor) && sm75_series(); }
/// a Turing switch with its own variable: `name` set means 0 off / anything else on (Turing only); unset follows the series
inline bool sm75_switch(const char* name, int major, int minor) {
if (!is_sm75(major, minor)) return false;
const char* v = std::getenv(name);
return v != nullptr ? std::atoi(v) != 0 : sm75_series();
}
} // namespace strata
@@ -0,0 +1,61 @@
// include/strata/kernels/bf16_bits.hpp - the bf16 conversions, written out, as bits.
//
// bf16 is the TOP HALF of an f32, so `f32_from_bf16` is a shift and needs no rounding at all. The forward
// direction does: ggml's `ggml_compute_fp32_to_bf16` adds `((i >> 16) & 1) + 0x7FFF` and truncates 16 bits.
//
// **THE `& 1` IS ON BIT 16**, the lowest KEPT bit, which is what makes an exact tie round to EVEN. Using bit
// 15 there is a plausible mistake: it differs only on exact ties, i.e. almost never on real data, which is
// exactly why it would survive any amount of end-to-end testing. `ref/quant.py` documents the same rule for
// the same reason.
//
// WHY THIS IS SEPARATE FROM `f16_bits.hpp`: fp16 and bf16 are not two spellings of one idea. fp16 has 5
// exponent bits and 10 mantissa bits; bf16 has 8 and 7. A conversion routine written for one and reused for
// the other is wrong in a way that produces plausible numbers - bf16's 2^-9 relative precision looks like a
// small fp16 error and is not small at all next to fp16's 2^-11.
//
// `gr.cu` carried a private copy of `f32_to_bf16_bits` until this header existed. It now includes this.
#pragma once
#include <cstdint>
#include <cstring>
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_BF16_HD __host__ __device__
#else
#define STRATA_BF16_HD
#endif
namespace strata::kernels {
/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16.
///
/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone
/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so
/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the
/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input,
/// infinities included, rounds exactly as before.
STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {
uint32_t i;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&i, &f, 4);
#else
std::memcpy(&i, &f, 4);
#endif
if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u);
i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
return (uint16_t) (i >> 16);
}
/// bf16 bits -> f32. Exact, and no rounding: the low 16 bits of an f32 are simply zero.
STRATA_BF16_HD inline float f32_from_bf16(uint16_t h) {
const uint32_t i = (uint32_t) h << 16;
float f;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&f, &i, 4);
#else
std::memcpy(&f, &i, 4);
#endif
return f;
}
} // namespace strata::kernels
@@ -0,0 +1,70 @@
// include/strata/kernels/bf16_gemv.hpp - the GEMV for a BF16 weight, P2.S5.
//
// WHY THIS EXISTS WHEN `s_gemv` ALREADY DOES. `s_gemv` decodes the S-family canonical forms (S2/S4/S8) from
// `codes` + `scales`, and a BF16 weight is not one of them - it has no codes and no scales, it is a plain
// 16-bit matrix. Six tensors per layer are in that state:
//
// ssm_alpha.weight, ssm_beta.weight GDN, [n_embd, 48]
// indexer.q_proj.weight, indexer.k_proj.weight QSA, [n_embd, 512] and [n_embd, 128]
// ple_value.weight layer 1, [n_embd, n_embd]
// ffn_gate_inp.weight handled inside `router_top10`
//
// The original entry points take BF16 activation bits for the historical CPU-derived contract. The explicit
// FP32 entry point below follows the pinned CUDA single-token MMVF contract. See docs/activation-contract.md
// for why activation precision depends on backend and batch geometry rather than weight type alone.
#pragma once
#include <cstdint>
namespace strata::kernels {
/// `y[o] = sum_i f32(x[i]) * f32(w[o*n_in + i])`, with both sides bf16-valued so every product is exact in
/// f32 and only the summation order differs.
///
/// THE WEIGHT LAYOUT IS THE MANIFEST'S: shape [n_in, n_out] with ne0 = n_in CONTIGUOUS, so row `o` is a
/// contiguous run of `n_in` bf16 values. That is the same convention `s_gemv` uses, and it is what
/// `strata::core::WeightRef::ne0/ne1` already report.
void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream);
/// TWO weight matrices from ONE kernel (llama.cpp's `*_mul_mat_multi` shape): `y1 = w1 @ x`, `y2 = w2 @ x`.
/// One warp computes row o of both matrices with two accumulators over one lane-strided pass, so each output
/// is bitwise what `bf16_gemv` produced for that matrix wherever `bf16_gemv` used its warp kernel
/// (`n_out >= 64`); a matrix below that threshold falls back to the plain call to keep the naive kernel's
/// summation order. `n_out1` or `n_out2` may be 0 for a one-sided call.
void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2,
float* y2, int64_t n_out2, int64_t n_in, void* stream);
/// The row-split variant, for the same reason `s_gemv_split` exists: with one thread per output row the
/// parallelism IS the output width, and `ssm_alpha` has 48 of them over 48 SMs. One warp per row, lanes
/// striding the reduction axis - which is also what makes the access pattern coalesced in this layout.
///
/// NOT bit-identical to `bf16_gemv`: the partial sums are added in a different order. Both are kept and both
/// are tested, because the naive one is the reference the split one is checked against.
void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out,
int threads_per_row, void* stream);
/// Single-token, contiguous 2D BF16-weight/F32-activation MMVF from the pinned llama.cpp CUDA path.
/// Preserves pair accumulation, adaptive block size and warp-XOR reduction order. This is a separate
/// opt-in entry point; the legacy BF16-activation kernels above retain their behavior.
/// `w[o*n_in+i]` is BF16 bits; x/y are F32. n_in must be positive and even, n_out positive, both <= INT_MAX.
/// x must be 8-byte aligned, w 4-byte aligned, and y 4-byte aligned. Throws on invalid geometry/pointers.
/// The device buffers must not overlap; allocation bounds remain the caller's responsibility.
/// No allocations or synchronization, including when stream is null (the CUDA default stream).
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
int64_t n_in, int64_t n_out, void* stream);
/// `ncols` columns at once: x is [ncols][n_in], y is [ncols][n_out]; each column bitwise equal to a
/// `bf16_gemv_fp32_mmvf` call on it.
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
void* stream);
/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch,
/// the weight read once, every output bit-identical to its own single-row call.
void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
int64_t n_in, int64_t n_out, int n_tok, void* stream);
/// S26 STRATA_LFUSE: bf16_gemv_fp32_mmvf_multi(x, ldx, w, y, ldy, n_in, n_out, n_tok) plus the 1-row
/// bf16_gemv_fp32_mmvf_multi(x, ldx, w_aux, y_aux, ldy_aux, n_in, 1, n_tok) in ONE launch, every output bitwise the
/// two calls'. Returns false (nothing launched) unless the rows path applies (STRATA_MMVF_ROWS=1, n_out >= 64, 2-8 rows).
bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux,
int64_t ldy_aux, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,207 @@
// include/strata/kernels/cpu/expert.hpp - P2.S3: the CPU expert path.
//
// This is the Q2_0 expert kernel promoted out of `bench/micro/cpu_s2.cpp`, which is the instrument that
// measured `c` (Memory/LEDGER.md L9/L10: 15.03 ms for one token's full routed set on 6 cores, DRAM-bound at
// 44.14 GB/s) and whose P0.T2 parity passes at 1.461e-06.
//
// IT IS THE SAME CODE, NOT A COPY. Keeping a second implementation next to a validated one is how a project
// ends up with two answers and no way to say which is right, so `cpu_s2.cpp` is expected to become a thin
// benchmark over these functions. (Until it is, the two exist side by side and this header says so.)
//
// WHAT MAKES IT FAST, and each of the three was paid for once:
//
// * `vpdpbusd` (AVX512-VNNI) does four int8 MACs per instruction. The scalar loop it replaces ran at
// 9.89 GB/s on one core; VNNI is the reason the 6-core figure is 42.55 GB/s.
// * `vpmultishiftqb` (AVX512-VBMI) unpacks the 2-bit codes eight at a time. Its ARGUMENT ORDER is
// (control, data) and was determined empirically - the Intel guide states the opposite, and following the
// guide produced 43 of 64 wrong codes.
// * The row accumulator stays a FLOAT VECTOR and is reduced ONCE at the end of the row. Reducing per
// 64-weight block cost more than the dot products themselves: it made the kernel compute-bound at
// 21 GB/s instead of DRAM-bound at 32.
//
// THE CONTRACT THAT MATTERS, because collapsing it is invisible and cannot match ggml's logits: one Q2_0
// WEIGHT block is QK=64 weights with one fp16 scale, while one ACTIVATION chunk is QKA=32 elements with
// its OWN scale. So a weight block spans TWO activation chunks with two different scales. Using one scale
// per weight block is the natural-looking mistake.
#pragma once
#include "strata/core/geometry.hpp"
#include <cstdint>
#include <cstddef>
namespace strata::kernels::cpu {
// ---- geometry, all of it fixed by the artifact (tools/verify_q2_0_geometry.py: 202/202 tensors at QK=64) ----
inline constexpr int H = strata::core::kCompiledGeometry.n_embd; // 2560 in Flash-Next
inline constexpr int FF = strata::core::kCompiledGeometry.n_ff; // expert intermediate width, 640
inline constexpr int NE = strata::core::kCompiledGeometry.n_expert; // routed experts per layer, 512
static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff,
"the CPU expert path is compiled for core/geometry.hpp");
inline constexpr int QK = 64; // QK2_0: weights per fp16 scale
inline constexpr int QKA = 32; // QK8_1/QK8_0: ACTIVATION elements per scale
inline constexpr int BB = 18; // bytes per 64-weight Q2_0 block: 2 fp16-scale + 16 codes
inline constexpr int MAXC = H / QKA; // 80 activation chunks across the widest reduction
inline constexpr int ROW_GU = H * 2 / 8; // 640 B of codes per gate/up row
inline constexpr int ROW_D = FF * 2 / 8; // 160 B of codes per down row
inline constexpr int SC_GU = H / QK; // 40 weight blocks per gate/up row
inline constexpr int SC_D = FF / QK; // 10 weight blocks per down row
inline constexpr size_t BLOB = 3ull * (H * FF * BB / QK); // 1,382,400
// ---- the blob's internal layout (one expert) ----
inline constexpr size_t O_GU_CODES = 0;
inline constexpr size_t O_D_CODES = 2ull * FF * ROW_GU;
inline constexpr size_t O_GU_SCALES = O_D_CODES + 1ull * H * ROW_D;
inline constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2;
/// One activation in Strata's planar storage: `QKA` elements per chunk.
/// The default legacy quantizer uses FP32 scales and half-away rounding. It is
/// not the pinned ggml CPU Q8_0 contract; expert_set_oracle_q8_0 selects that
/// experimental contract (FP16-rounded scales and x86 nearest-even codes).
///
/// The historical function name `act_quant_q8_1` does not describe a native
/// ggml block layout. One 64-weight block always spans two 32-element chunks.
///
/// `hx[k] = scale[k] * sum[k]` is the weight-independent correction the Q2_0 identity needs
/// (`sum (c-1) d_w xhat d_x = d_w (d_x*sum(c*xhat) - d_x*sum(xhat))`), precomputed once per layer rather than
/// once per row: 640 rows would otherwise recompute it 640 times.
struct ActQ {
alignas(64) int8_t q[H];
float scale[MAXC];
int32_t sum[MAXC];
float hx[MAXC];
int nchunks;
/// The AVX-2 "bit-plane" image of `q` (src/kernels/cpu/q2_avx2.cpp explains it), filled only by
/// `act_quant_q8_1_avx2` with STRATA_Q2_BITPLANE=1 and read only by `q2_0_gguf_rows_multi_avx2`. Per pair p of 64-value blocks:
/// `qp[128p + 32k + 16h + i] = q[128p + 64h + 4i + k]`, `psum[8p + 4h + m]` = the sum of q[128p + 64h + 16m ..
/// + 16), `pscale[8p + 2c + e] = scale[4p + c]`. `bp_pairs` is 0 when the image is absent (n % 128 != 0).
alignas(32) int8_t qp[H];
alignas(32) int32_t psum[H / 16];
alignas(32) float pscale[H / 16];
int bp_pairs = 0;
};
/// Per-worker scratch. Owned by the caller and passed in, so the token path performs NO allocations
/// (P2.T10) - the kernel itself allocates nothing.
struct ExpertScratch {
ActQ a1;
ActQ a2;
alignas(64) float ff[FF];
};
/// Runtime CPU feature check. The kernel uses AVX512-VNNI + AVX512-VBMI + AVX512VL, and code compiled with
/// `/arch:AVX512` can emit AVX-512 anywhere in its translation unit, so a machine without them must be
/// REFUSED rather than silently run. `s2_expert_scalar` is the fallback and exists for tests.
struct CpuFeatures {
bool avx512f = false;
bool avx512bw = false;
bool avx512vl = false;
bool avx512_vnni = false;
bool avx512_vbmi = false;
bool usable() const { return avx512f && avx512bw && avx512vl && avx512_vnni && avx512_vbmi; }
/// A one-line description of what is missing, or "ok".
const char* reason() const;
};
CpuFeatures cpu_features();
/// Exits with a clear message if the CPU cannot run `s2_expert_vnni`. Called once at startup, so a user on an
/// older CPU learns why at second zero instead of seeing an illegal instruction at token 4000.
void cpu_require_expert_support();
/// Select the pinned x86 Q8_0 activation contract at BOTH expert quantization
/// boundaries and the pinned generic CPU Q2_0 dot reduction in all projections.
/// Default false preserves the legacy quantizer and eight-lane FP32 reduction.
/// Configure before starting worker threads and do not change during a request.
/// GPU expert-cache parity is not established for this mode; the driver must
/// reject combining it with that cache. No allocation occurs in either mode.
void expert_set_oracle_q8_0(bool enabled);
/// `x` -> `a` in the configured contract. The function name is historical;
/// `n` must be a multiple of QKA and at most H. No allocation occurs.
void act_quant_q8_1(const float* x, int n, ActQ& a);
/// One expert: `out(H) = down( swiglu( gate(x), up(x) ) )`, all three projections Q2_0,
/// with the configured activation and dot contracts at both quantization boundaries.
///
/// `blob` is one 1,382,400-byte expert in the pack's layout; `x` is the H-wide input; `out` is H-wide.
void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws);
/// The same, with the activation ALREADY quantized in the configured contract.
/// Workers may share this read-only activation; each must own its scratch/output.
///
/// This split exists for the pool. A layer runs TEN experts against ONE activation, so quantizing inside
/// `s2_expert_vnni` would do the same 2560-element conversion ten times per layer per token - 480 redundant
/// conversions per token. P2.S3's work item is `(blob, x-hat quantized, block sums, weight, out)`, and this
/// is the entry point that matches it.
void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws);
/// Plan v0.3 P6: ONE expert applied to up to MAXT tokens that were all routed to it (a speculative verify
/// window routes ~1.5 tokens to each distinct expert). The 1.38 MB blob is read and its 2-bit codes unpacked
/// ONCE per block for all tokens; only the VNNI dot and the accumulation run per token. Every token's output
/// is bitwise equal to `s2_expert_vnni_q` on that token (same operation order per token). Legacy activation
/// contract only; with `expert_set_oracle_q8_0(true)` it falls back to one `s2_expert_vnni_q` per token.
inline constexpr int MAXT = 8;
/// Plan v0.3 P4: the expert in row ranges, so several threads can share one expert. `s2_expert_gu_rows` writes
/// ff[r] = silu(gate_r . x) * (up_r . x) for r in [r0, r1) (of FF); `s2_expert_down_rows` writes out[r] for r in
/// [r0, r1) (of H) from the intermediate's quantized image. Together with `act_quant_q8_1(ff, FF, a2)` in
/// between they are exactly `s2_expert_vnni_q`, row for row (same `row_dot`), so the result is bitwise the same.
bool expert_oracle_q8_0_enabled();
void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1);
void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1);
/// Plan v0.3 P6: the row-range kernels for up to MAXT tokens routed to the same expert (legacy contract only).
/// Each token's rows are bitwise the single-token `s2_expert_gu_rows` / `s2_expert_down_rows`.
void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0,
int r1);
void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0,
int r1);
struct ExpertScratchMulti {
ActQ a2[MAXT];
alignas(64) float ff[MAXT][FF];
ExpertScratch single; // the oracle-contract fallback
};
void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out,
ExpertScratchMulti& ws);
/// The scalar transcription of ggml's formula - NOT a second opinion, but the ORACLE the VNNI path is checked
/// against, and the only path available on a CPU without AVX-512.
///
/// `quant_acts` makes the oracle consume the SAME INT8 activation values the VNNI path uses, **at BOTH
/// stages**. With it OFF the oracle is exact-FP32-activation and the gap between them IS the activation
/// contract; with it ON the two differ only by FP32 evaluation order, so a small gap there proves the kernel
/// itself correct. That separation is the whole point of P0.T2 and it is why this parameter exists rather
/// than two functions.
///
/// CORRECTION TO THE ORIGINAL: `bench/micro/cpu_s2.cpp`'s comment says "at both stages" but its code
/// quantizes only the intermediate, leaving the gate/up projections on raw f32 `x`. That is invisible when
/// the caller passes an already-quantized input - which the engine does - and shows up as a ~1.2% gap when it
/// does not, which reads as a kernel bug and is not one. This version quantizes both.
/// Plan v0.3 P6: rows [r0, r1) of a Q2_0 matrix in the GGUF block layout (18 bytes per 64 weights, `row_bytes`
/// per row, `nblocks` blocks each) against `nt` activations: out[t][r].
void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
/// The same two for CPUs without AVX-512 (src/kernels/cpu/q2_avx2.cpp, compiled for AVX2 only).
void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
/// STRATA_Q2_BITPLANE=1 (read once): the AVX-2 Q2_0 kernel reads the bit-plane image instead of the legacy one.
bool q2_bitplane_enabled();
/// The pre-bit-plane AVX-2 kernel (the default), kept for A/B and parity.
void q2_0_gguf_rows_multi_avx2_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
/// The same rows with AVX-VNNI on or off, not as cpu_avxvnni_ok() says (tests and benches; on only where it holds).
void q2_0_gguf_rows_multi_avx2_v(bool vnni, const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a,
int nt, float* const* out, int r0, int r1);
void act_quant_q8_1_avx2(const float* x, int n, ActQ& a);
/// The same for CPUs with AVX but no AVX2 (src/kernels/cpu/q2_avx1.cpp, the third rung of q2_rows_any /
/// act_quant_any, issue #1699): same arithmetic, 128-bit integer lanes, mul+add instead of FMA (last bits),
/// software fp16 conversion. Called only behind cpu_avx1_ok() && !cpu_avx2_ok().
void q2_0_gguf_rows_multi_avx1(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
void q2_0_gguf_rows_multi_avx1_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
void act_quant_q8_1_avx1(const float* x, int n, ActQ& a);
void s2_expert_scalar(const uint8_t* blob, const float* x, float* out, bool quant_acts);
} // namespace strata::kernels::cpu
@@ -0,0 +1,115 @@
// include/strata/kernels/cpu/expert_layout.hpp - plan v0.3 P6: where each routed expert lives in experts.bin.
//
// A Q2_0 pack (tools/strata_pack.py) has one blob size for every layer, `BLOB`, in the Strata expert form. A
// native pack (tools/iq_pack.py, the IQ2_XS / IQ3_XXS files) keeps each expert's raw GGUF slices, so the blob
// size and the formats change from layer to layer; `native_experts.txt` says how. Everything that touches an
// expert blob - the arena, the VRAM tier, the prompt path, the CPU pool, the GPU window - asks this table.
#pragma once
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/cpu/native_expert.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace strata::kernels::cpu {
struct ExpertLayout {
bool native = false;
int64_t n_layers = 0, n_expert = NE;
std::vector<NativeFmt> fmt; ///< per layer (native packs)
std::vector<uint64_t> offset, bytes; ///< per layer: where its 512 blobs start, bytes per blob
/// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in their GGUF files, so the
/// arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown).
std::vector<uint64_t> gguf_off;
/// Per layer PER ROLE (3 x n_layers, `3 * layer + role`, matching `gguf_off`), the GGUF file - a name beside
/// the --native shard - that holds that role's tensor. Empty = the --native shard itself. Per role because a
/// shard boundary can fall inside a layer: Unsloth's UD-Q4_K_XL has layer 11's down in shard 2 and its gate
/// and up in shard 3 (native_experts.txt v4, the `gate,up,down` shard column).
std::vector<std::string> gguf_file;
int version = 0; ///< native_experts.txt's header version (0 = none given)
uint64_t max_blob = BLOB;
uint64_t total = 0; ///< experts.bin size
uint64_t blob_bytes(int64_t layer) const { return native ? bytes[(size_t) layer] : (uint64_t) BLOB; }
uint64_t layer_offset(int64_t layer) const {
return native ? offset[(size_t) layer] : (uint64_t) layer * (uint64_t) n_expert * (uint64_t) BLOB;
}
uint64_t blob_offset(int64_t layer, int64_t expert) const {
return layer_offset(layer) + (uint64_t) expert * blob_bytes(layer);
}
};
/// Plan v0.3 P6: whether this CPU (and its OS) runs the AVX-512 kernels (F, BW, VL, VNNI, VBMI). Probed in a
/// file compiled without AVX-512, so asking is safe everywhere; STRATA_FORCE_AVX2=1 answers no (for tests).
bool cpu_avx512_ok();
/// The same probes with VBMI required only (the multishift unpack and other byte-permute shuffles): a CPU may run
/// every other feature the kernels use and miss it (Cascade Lake Xeon).
bool cpu_vbmi_ok();
/// AVX-512F + DQ + BW + VL + VNNI, VBMI NOT required: the dpbusd row dots, the q8 quantizer and the dq/bw arithmetic
/// need no byte-permute shuffles (the q2 unpack's op has a substitute in expert.cpp). A CPU this answers yes on
/// used to run every expert through the AVX-2 fallback. Without VBMI, STRATA_VNNI_TIER=1 opts in; unset keeps
/// the AVX-2 rows' rounding. STRATA_FORCE_AVX2 and STRATA_FORCE_ISA still cap this probe.
bool cpu_vnni_ok();
/// Scattered pieces: the copy above is a declaration only (defined in expert.cpp, the AVX-512 TU, because it reads
/// its STRATA_CPU_YMM switch): whether the 512-bit q2 row dot may run at all (VNNI and not the YMM env).
bool q2_rows_512_ok();
/// Whether this CPU runs AVX-512F + AVX-512BW + AVX-512VL + AVX-512DQ (e.g. Skylake-X i9-9920X) for iq_avx512.cpp.
bool cpu_avx512bw_ok();
/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel
/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it.
bool cpu_avx2_ok();
/// Whether this CPU (and its OS) runs AVX (Sandy Bridge and newer): the AVX1 router dot (kq_avx1.cpp) and ggml-cpu in
/// a STRATA_ISA_FLOOR=avx build. The other expert rows then run on ggml-cpu (experimental, slow).
bool cpu_avx1_ok();
/// SSE4.2 + POPCNT: ggml-cpu in a STRATA_ISA_FLOOR=none build.
bool cpu_sse42_ok();
/// STRATA_FORCE_ISA=avx2|avx|sse caps the probes above (3 = no cap, 2 = AVX2, 1 = AVX, 0 = SSE4.2), so the older-CPU
/// paths run on any PC: tests and the experimental builds' checks. ggml-cpu keeps what it was compiled for.
int cpu_isa_cap();
/// The experimental older-CPU build this engine is ("avx", "sse4.2"), or "" for the normal build (AVX2 floor).
const char* isa_floor_build();
/// STRATA_IQ256_GATHER, the AVX-2 i-quant kernels' gathered grid decode (iq_avx2.cpp): -1 unset (auto, see
/// cpu_gather_fast_here), 0 the scalar decode on every core, 1 the gathered one on every core.
int iq256_gather_setting();
/// Whether this CPU's performance cores gather the IQ grid entries faster than they assemble them from scalar loads:
/// an Intel CPU with AVX-VNNI, i.e. Alder Lake / Sapphire Rapids or newer, and not one of the E-core-only parts.
/// The older Intel cores gather slowly (Haswell, Broadwell) or under the Downfall (GDS) microcode (Skylake to Tiger
/// Lake), AMD Zen 2/3 gather slowly, and Zen 4/5 run the AVX-512 kernels. STRATA_FORCE_ISA answers no.
bool cpu_gather_fast();
/// cpu_gather_fast() and the CALLING THREAD runs on a performance core: CPUID 1Ah core type 40h on a hybrid CPU (its
/// E-cores, 20h, gather slower than they assemble). Probed once per thread: the pool pins each worker to one core.
bool cpu_gather_fast_here();
/// Whether the AVX-2 expert kernels take their AVX-VNNI forms (vpdpwssd / vpdpbusd: Alder Lake, Sapphire Rapids and
/// later, P- and E-cores alike; the same integer sums): cpu_avx2_ok() and CPUID 7.1:EAX[4], not capped by
/// STRATA_FORCE_ISA, and not an older-CPU build (STRATA_ISA_FLOOR, which stays on its floor and AVX2).
/// STRATA_NO_AVXVNNI=1 answers no.
bool cpu_avxvnni_ok();
/// Whether a native pack's layer of this ggml type runs on Strata's own Q2_0 kernels (AVX-512 / AVX2, and the AVX1
/// rung of q2_rows_any / act_quant_any on a CPU with AVX but no AVX2: Sandy / Ivy Bridge). Only a CPU without AVX
/// (STRATA_ISA_FLOOR=none) takes ggml-cpu's own Q2_0 vec_dot, which on an i7-3770 took 0.98 ms per expert at one
/// token against 0.52 ms for the AVX1 rows (0.42 with STRATA_Q2_BITPLANE=1; kq_cpu_bench --pairs q2_0/q2_0).
inline bool q2_native_kernels(int type) { return type == 42 && (cpu_avx2_ok() || cpu_avx1_ok()); }
/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none.
std::string cpu_name();
/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has.
void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
int r0, int r1);
void act_quant_any(const float* x, int n, ActQ& a);
/// The same dispatch, always the pre-bit-plane kernel (tests and A/B; the bit-plane switch off by construction).
void q2_rows_any_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
int r0, int r1);
/// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack).
const ExpertLayout& expert_layout();
/// Reads `<pack_dir>/native_experts.txt` when it exists (a native pack), else sets the canonical layout.
/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it).
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);
/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`,
/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte).
/// v5 = v4 plus `hadamard.txt` beside it: Hadamard-folded experts (hadamard.hpp), written only for such models,
/// so an engine that cannot rotate the activations refuses the pack instead of running it wrong.
inline constexpr int kExpertLayoutVersion = 5;
} // namespace strata::kernels::cpu
@@ -0,0 +1,88 @@
// include/strata/kernels/cpu/native_expert.hpp - plan v0.3 P6: one routed expert in its GGUF form on the CPU.
//
// The IQ2_XS / IQ3_XXS model files keep their experts in i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS,
// IQ3_S gate/up; Q2_0 or IQ4_NL down) whose values cannot be re-expressed in the Q2_0 pack form. A native expert
// blob is the three GGUF slices back to back, [gate rows | up rows | down rows]. Activations use the weight type's
// ggml `vec_dot_type`; dispatch selects a format-specific kernel or ggml's per-token dot. The arithmetic mode
// controls whether grouping tokens may change the selected row arithmetic.
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include "strata/core/geometry.hpp"
namespace strata::kernels::cpu {
/// Bytes of the quantized activation of a row of `n` values: the larger of Q8_K (292 bytes per 256) and a 32-block
/// format at 36 bytes per 32 (Q8_1 and friends).
constexpr size_t native_act_bytes_for(int64_t n) {
const size_t q8k = (size_t) (n / 256) * 292, q81 = (size_t) (n / 32) * 36;
return q8k > q81 ? q8k : q81;
}
/// Bytes of the largest quantized activation any native layer uses (2560 values as Q8_K: 10 x 292); never below the
/// 4096 of the Flash-Next engine, and it grows with the compiled hidden size (4096 values need 4672).
inline constexpr size_t kNativeActBytes =
native_act_bytes_for(strata::core::kCompiledGeometry.n_embd) > 4096 ? native_act_bytes_for(strata::core::kCompiledGeometry.n_embd) : 4096;
/// Bytes of the largest quantized down activation (640 values as Q8_0: 20 x 34, or Q8_K 3 x 292); never below 1024,
/// and it grows with the compiled expert width (1024 values as Q8_K need 1168).
inline constexpr size_t kNativeHBytes =
native_act_bytes_for(strata::core::kCompiledGeometry.n_ff) > 1024 ? native_act_bytes_for(strata::core::kCompiledGeometry.n_ff) : 1024;
/// Arithmetic fixed for one pool batch. WindowInvariant preserves the legacy singleton result at every width.
enum class NativeArithmetic { Default, WindowInvariant };
/// One layer's native expert geometry.
struct NativeFmt {
int gu_type = -1, d_type = -1; ///< ggml types of gate/up and of down
int gu_act = -1, d_act = -1; ///< their vec_dot_type (the activation formats)
int64_t n_embd = 0, n_ff = 0;
size_t gu_row = 0, d_row = 0; ///< bytes per weight row
size_t up_off = 0, down_off = 0; ///< inside the blob
size_t bytes = 0; ///< the whole blob
size_t act_bytes = 0, h_bytes = 0; ///< quantized activation sizes (n_embd of gu_act, n_ff of d_act)
/// NVFP4 (ggml type 40) only: the blob ends with {s_gate, s_up, s_down, 0} at this offset, the per-expert
/// weight_scale_2 the block format has no room for (tools/iq_pack.py). 0 = no tail. Each scale goes on its own
/// projection's FP32 output: gate * s_gate, up * s_up, down * s_down. Do not fold s_down into up: the hidden
/// drops to ~1e-5 and its q8 block scale becomes an FP16 subnormal (expert error 2-12% instead of 1.1%).
size_t tail_off = 0;
/// prism.hadamard (hadamard.hpp): the experts of this layer are stored in a rotated basis, and
/// native_quant_act / native_quant_h apply y = H_block (signs * x) before quantizing. had_block 0 = none.
int had_block = 0;
bool had_gu = false, had_d = false;
int layer = -1; ///< the layer this format belongs to (set by expert_layout_load; STRATA_ACT_DUMP only)
const float* gu_signs = nullptr; ///< n_embd signs for x (nullptr: identity)
const float* d_signs = nullptr; ///< n_ff signs for h (nullptr: identity)
};
constexpr int kNvfp4Type = 40;
constexpr size_t kNvfp4Tail = 16;
/// Whether this build has the ggml-cpu path.
bool native_experts_available() noexcept;
/// Fills `f` for a layer; false (with a reason) when ggml-cpu has no dot product for a type.
bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err);
/// x (n_embd floats) -> the gate/up activation (act_bytes), rotated first when the layer is Hadamard-folded.
void native_quant_act(const NativeFmt& f, const float* x, void* dst);
/// h (n_ff floats) -> the down activation (h_bytes), rotated first when the layer is Hadamard-folded.
void native_quant_h(const NativeFmt& f, const float* h, void* dst);
/// From how many tokens native_gu_rows gives this gate/up type to a multi-token kernel (#152; ggml-cpu's per-token dot
/// below that). 1: a token's rows are the same alone and in any group.
int native_gu_mt_min(int gu_type);
/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]) for rows r in [r0, r1), `nt` tokens.
void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff,
int r0, int r1);
/// out[t][r] = down_r . hq[t] for rows r in [r0, r1).
void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out,
int r0, int r1);
/// Same per-token result as the corresponding legacy nt=1 call on this build and CPU.
/// Kernels that already satisfy this contract retain their grouped execution.
void native_gu_rows_invariant(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt,
float* const* ff, int r0, int r1);
void native_down_rows_invariant(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt,
float* const* out, int r0, int r1);
} // namespace strata::kernels::cpu
@@ -0,0 +1,55 @@
// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have.
//
// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time
// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is
// missing exactly two things the i-quant kernels rely on:
//
// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). The reference for its
// fallback is llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), since the kernels in this directory are
// transcribed from llama.cpp's vecdotq.cuh and that wrapper's operands are the same sites: it reinterprets
// the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a` does for these calls. The
// fallback below computes exactly that with four PTX `vmad` byte-select instructions, so it is bit-exact
// rather than merely close (tools/sm60_dp4a_check.cu checks it against the byte-wise form).
// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that
// spins without it is correct, merely busier.
//
// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX
// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is
// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is
// HIP's own `__nanosleep`.
#pragma once
#include <cstdint>
#if defined(STRATA_HIP_GFX906)
#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)
#endif
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
// PTX vmad with byte selectors: compiles to four VMAD.S8.S8 (cuobjdump -sass), no byte extraction.
// Bit-exact with the byte-wise form it replaces: 1.07e9 cases (edge bytes, every per-lane byte pair, random),
// 0 mismatches, ~2.2x faster in isolation on a Tesla P100 (tools/sm60_dp4a_check.cu).
int r = c;
asm("vmad.s32.s32.s32 %0, %1.b0, %2.b0, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b1, %2.b1, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b2, %2.b2, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b3, %2.b3, %0;"
// The first instruction writes r before the remaining instructions
// have read a/b. Equal-valued operands must not share its register.
: "+&r"(r) : "r"(a), "r"(b));
return r;
}
#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c))
#else
#define STRATA_DP4A(a, b, c) __dp4a((a), (b), (c))
#endif
/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a
/// contract, and only pre-Volta CUDA has no `__nanosleep` at all.
__device__ __forceinline__ void strata_spin_pause() {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700
// sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed.
#else
__nanosleep(100);
#endif
}
@@ -0,0 +1,104 @@
// include/strata/kernels/f16_bits.hpp - the fp16 conversions, written out, as bits.
//
// WHY THIS IS NOT `__float2half`. Round 193 found `__float2half` producing 0x2600 for a value whose correct
// fp16 encoding is 0x26DB, and 0x3C01 for a value that is exactly 1.0 - i.e. wrong bits, not a rounding
// difference. The cause was never isolated (it is either `__float2half` itself or `__half_as_ushort`), so
// `src/kernels/cuda/quantize_act.cu` replaced it with the version below, which then came out byte-exact over
// all 20,480 blocks of the fixture. `shared_expert.cu` carries the same function privately for the same
// reason. Three copies of a converter whose failure mode is silent wrong bits is two copies too many, so the
// copy lives here and the kernel and its TEST both include it - with the test checking it against vectors
// generated by numpy's float16 (an oracle that shares no code with this), which is what neither private copy
// had.
//
// The rounding is ROUND-TO-NEAREST-EVEN, which is what numpy's `.astype(np.float16)` does and what IEEE-754
// specifies for the default mode. The three interesting regimes are all handled explicitly and all three are
// covered by the test's oracle vectors:
//
// * normal - exponent fits, mantissa is rounded from 13 surviving bits with a sticky remainder
// * subnormal - the implicit 1 is restored and the result is shifted right, so the rounding point MOVES
// * overflow - exp >= 31 saturates to inf (0x7C00) and keeps the sign; a NaN input stays a NaN
//
// `f32_from_f16` deliberately does NOT round: it is used to compare against a reference that holds the same
// bits, so it only has to be exact.
#pragma once
#include <cstdint>
#include <cstring>
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_HD __host__ __device__
#else
#define STRATA_HD
#endif
namespace strata::kernels {
/// Round-to-nearest-even f32 -> fp16, returned as raw bits.
STRATA_HD inline uint16_t f16_from_f32(float f) {
uint32_t x;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&x, &f, 4);
#else
std::memcpy(&x, &f, 4);
#endif
const uint32_t sign = (x >> 16) & 0x8000u;
const uint32_t rawexp = (x >> 23) & 0xFFu;
int exp = (int) rawexp - 127 + 15;
uint32_t man = x & 0x7FFFFFu;
// TWO different things reach here and they must not be conflated: an f32 inf/NaN (raw exponent 255) stays
// an inf/NaN, and a FINITE value too large for fp16 (1e30) SATURATES TO INF. The version of this function
// in quantize_act.cu and shared_expert.cu tests `if (exp >= 31) return sign | 0x7C00 | (man ? 0x200 : 0)`
// and therefore returns a NaN for every overflowing finite value - which their own fixtures cannot see,
// because all of their values are O(1). Round 198's numpy oracle caught it here on the first run (1e30,
// 65536, 1e45: numpy says inf, the conflated test said NaN).
if (rawexp == 0xFFu) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u)); // inf, or a quiet/NaN
if (exp >= 31) return (uint16_t) (sign | 0x7C00u); // finite overflow -> inf
if (exp <= 0) {
if (exp < -10) return (uint16_t) sign; // underflows to a signed zero
man |= 0x800000u; // restore the implicit 1
const uint32_t sh = (uint32_t) (14 - exp);
uint32_t h = (man >> sh) & 0x3FFu;
const uint32_t rem = man & ((1u << sh) - 1u);
if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h;
return (uint16_t) (sign | h);
}
uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13));
const uint32_t rem = man & 0x1FFFu;
if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; // the carry may bump the exponent
return h;
}
/// Exact fp16 bits -> f32. No rounding, no exceptions: every one of the 65,536 inputs maps to a value f32
/// represents exactly, including the subnormals (which is why the `ex == 0` case cannot be skipped).
STRATA_HD inline float f32_from_f16(uint16_t h) {
const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
const uint32_t ex = (h >> 10) & 0x1Fu, man = h & 0x3FFu;
uint32_t out;
if (ex == 0) {
// Subnormal or zero. The value is `man * 2^-24`, so after `s` left shifts the leading 1 reaches bit
// 10 and the value is `(1 + frac) * 2^(-14-s)`: the f32 exponent field is 113 - s and `frac` is the low
// ten bits. Flushing these to zero - which the two private copies of this function in the tree do -
// maps 0x0001 to 0.0 instead of 2^-24, a 100% relative error on any KL-quant scale that lands here.
if (man == 0) {
out = sign;
} else {
uint32_t m = man;
int s = 0;
while ((m & 0x400u) == 0) { m <<= 1; ++s; }
out = sign | ((uint32_t) (113 - s) << 23) | ((m & 0x3FFu) << 13);
}
} else if (ex == 31) {
out = sign | 0x7F800000u | (man << 13);
} else {
out = sign | ((ex - 15 + 127) << 23) | (man << 13);
}
float f;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&f, &out, 4);
#else
std::memcpy(&f, &out, 4);
#endif
return f;
}
} // namespace strata::kernels
@@ -0,0 +1,41 @@
// include/strata/kernels/fused_gdn.hpp - plan v0.3 P3: the gated delta-net step and its output norm in ONE kernel.
//
// The native step (after llama.cpp's gated_delta_net.cu) gives each warp one (head, column) and strides its 32
// lanes over the 128 ROWS of the state, which is stored `[row][head][col]`: every lane's load is 24.5 KB from its
// neighbour's, so each 32 B sector delivers 4 useful bytes - 47.6 us per layer for 6.3 MB of state traffic. Here a
// block owns one whole head, its 512 threads are (row group of 32, column), and a row's 128 columns are one
// contiguous 512 B load. With the head in one block, the per-head RMS norm, the norm weight and the sigmoid(z)
// gate of `gdn_out_norm` run in the same kernel.
//
// S <- g S + k (beta (v - g S^T k))^T (g = exp(gate[head]), per value head; q/k shared by h_v / h_k heads)
// o = (S^T q) / sqrt(128)
// y = rmsnorm(o) * gamma * sigmoid(z)
#pragma once
#include <cstdint>
namespace strata::kernels {
/// The 4-tap causal conv + SiLU over all `channels` (history is `[channel][3]`, updated), then the L2 norm of
/// each of the first `qk_heads` 128-channel heads (q then k), eps as the native `l2_norm` (x / sqrt(sum + eps)).
/// One block per 128-channel head; replaces conv_silu + two l2_norm launches.
void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
float eps, void* stream);
/// alpha and beta, both `(h_v, n_embd)` BF16 against the FP32 activation, with their epilogues:
/// gate = softplus(alpha + dt) * ssm_a, beta = sigmoid(beta). One warp per row; replaces two MMVF launches and
/// two elementwise kernels.
void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
float* gate, float* beta, int n_embd, int h_v, void* stream);
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
void* stream);
/// The same step with the SiLU output gate, y = rmsnorm(o) * gamma * silu(z): Qwen3.6-35B-A3B's (qwen35moe) GDN
/// (CUDA / HIP; the SYCL port has no qwen35moe path).
void fused_gdn_step_norm_silu(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k,
int h_v, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,97 @@
// include/strata/kernels/gdn.hpp - the gated delta-net (GDN) layer's non-projection parts, P2.S2.
//
// Transcribed from `ref/gdn.py`, which is itself transcribed from `build_layer_attn_linear` and
// `build_delta_net_autoregressive`. The projections (`wqkv`, `wqkv_gate`, `ssm_out`) are the existing
// `s_gemv`/`s2_gemv` kernels; what lives here is everything BETWEEN them.
//
// Geometry of the real artifact (48 layers are GDN, 12 are QSA):
//
// S = state_size = 128 head_k_dim == head_v_dim
// h_k = 16 k/q heads h_v = 48 v heads (idx[h] = h % h_k)
// C = 2*128*16 + 128*48 = 10240 channels d_conv = 4
//
// STATE LAYOUT. This is the one place the kernels deliberately differ from the reference, and the reason is
// coalescing. `ref/gdn.py` carries the state as (S, S, H_v) = (i, j, h); here it is **(S, H_v, S)** =
// (i, h, j), so that for a fixed i a warp walking consecutive j reads CONTIGUOUS memory. The state is a
// runtime buffer, not a weight, so this costs nothing to choose - but it must be said, because the two
// layouts index the same three numbers and a mismatch is silent.
//
// WHAT MAKES THE RECURRENCE PARALLEL, and it is worth stating because it is not obvious:
//
// dec = exp(gate) (h_v,)
// st = state * dec
// sk[h,j] = sum_i st[i,j,h] * k[idx[h]][i]
// d[h,j] = (v[h,j] - sk[h,j]) * beta[h]
// st[i,j,h] += k[idx[h]][i] * d[h,j]
// o[h,j] = sum_i st[i,j,h] * q[idx[h]][i]
//
// Every line touches ONLY the (j, h) column. Nothing couples one column to another, so one thread can own a
// column for the whole step and no barrier is needed anywhere in the recurrence. (The decay must still be
// applied BEFORE the rank-1 update - `ref/gdn.py` PROPERTY 5 pins that, and the test re-pins it here.)
#pragma once
#include <cstdint>
namespace strata::kernels {
/// Geometry of one GDN layer. The real artifact: S = 128, h_k = 16, h_v = 48.
struct GdnShapes {
int64_t S = 0; ///< head dim, and the state's contracted axis
int64_t h_k = 0; ///< key/query heads (q and k are (h_k, S))
int64_t h_v = 0; ///< value heads (v, z, o are (h_v, S)); h_v must be a multiple of h_k
};
/// One step of the delta-rule recurrence, IN PLACE on `state`.
///
/// state (S, h_v, S) f32, j fastest, updated in place
/// q, k (h_k, S) already L2-normalised, and q ALREADY SCALED by 1/sqrt(S) - the two llama.cpp paths
/// apply that scale in different places, so the caller owns it
/// v (h_v, S)
/// gate (h_v,) the PRE-exp value; `dec = exp(gate)` is formed here
/// beta (h_v,)
/// o (h_v, S)
///
/// The head pairing is `h % h_k` (MODULO), not `h / (h_v/h_k)` (INTERLEAVE). `ref/gdn.py` PROPERTY 8 and 11
/// pin this and the test re-pins it, because both conventions produce well-formed output.
void gdn_step(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, float* o, const GdnShapes& s, void* stream);
/// `ggml_ssm_conv` with the carried state prepended. Updates `conv_state` in place.
///
/// conv_state (d_conv-1, channels) the previous d_conv-1 input columns, OLDEST FIRST
/// x (channels,) the new column
/// kW (channels, d_conv) the weight in GGML-NATIVE layout: `kW[c*d_conv + i]` is tap i of
/// channel c. The manifest gives `ssm_conv1d.weight` ne = [4, 10240],
/// i.e. ne0 = d_conv is the FAST axis, which is this and NOT the
/// reference's row-major (d_conv, channels).
/// out (channels,)
///
/// out[c] = sum_{i<d_conv} inp[i][c] * kW[c*d_conv + i], inp = [conv_state | x]
///
/// `kernel[0]` reads the OLDEST state row and the new input lands in the LAST state row.
void gdn_conv_step(float* conv_state, const float* x, const float* kW, float* out, int64_t channels,
int64_t d_conv, void* stream);
/// `build_gdn_l2_norm`: `x / sqrt(sum(x^2) + eps)`, over the LAST axis.
///
/// The `+ eps` is an absolute floor on the SQUARED NORM, not on the mean - so the sum is formed first and
/// there is NO division by the width. The plausible wrong reading (`x / sqrt(mean(x^2) + eps)`) differs by
/// sqrt(S) = 11.3x here, which is why the test asserts the two are distinguishable.
void gdn_l2_norm(float* x, int64_t rows, int64_t cols, float eps, void* stream);
/// `beta = sigmoid(beta)`, in place over `h_v` values.
///
/// **`gdn_step` DOES NOT DO THIS AND THE LAYER MUST.** `build_layer_attn_linear` L889 is
/// `beta = ggml_sigmoid(beta)` and the step kernel's contract is `d = (v - sk) * beta`, so what it receives has
/// to be a fraction. Passing the raw `ssm_beta @ cur` leaves the delta-net write strength unbounded and signed.
/// `ref/gdn.py` and `ref/model.py` both sigmoid it; this call is what makes the C++ agree with them.
void gdn_beta_gate(float* beta, int64_t h_v, void* stream);
/// The layer's closing norm: `y = rms_norm(o, eps) * ssm_norm * sigmoid(z)`.
///
/// Note SIGMOID, not SiLU - qwen3.5 used SiLU and this artifact does not, and `ref/gdn.py` says so outright.
/// The norm is over the LAST axis: one RMS per head, so it is per-ROW here and not over the whole (h_v, S).
void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S,
float eps, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,44 @@
// include/strata/kernels/gfx_arch.hpp - which AMD architecture names the gfx11 matrix-core code (and the gfx12 native
// prompt-expert kernels) was built for.
//
// The WMMA kernels select their intrinsic with `#if defined(__gfx1100__) || ... || defined(__gfx1151__)`: a gfx11 part
// outside that list (gfx1152, ...) gets an empty or trapping body. The runtime gates therefore match the SAME
// list, not the "gfx11" prefix, so such a part falls back to hipBLASLt / the portable kernels instead of launching code
// that is not there. Pure string matching (no HIP headers), usable from host code of any build.
#pragma once
#include <cstddef>
#include <cstring>
namespace strata::kernels {
/// `gcn` is hipDeviceProp_t::gcnArchName ("gfx1151", or "gfx1151:sramecc-:xnack-"): true when it is exactly `name`.
inline bool gfx_arch_is(const char* gcn, const char* name) {
if (gcn == nullptr) return false;
const std::size_t n = std::strlen(name);
return std::strncmp(gcn, name, n) == 0 && (gcn[n] == '\0' || gcn[n] == ':');
}
/// Discrete RDNA3 desktop / workstation GPUs (RX 7900 XTX / XT / GRE / W7900 = gfx1100,
/// RX 7800 XT / 7700 XT = gfx1101, RX 7600 / 7600 XT = gfx1102).
inline bool gfx_arch_is_discrete_rdna3(const char* gcn) {
return gfx_arch_is(gcn, "gfx1100") || gfx_arch_is(gcn, "gfx1101") || gfx_arch_is(gcn, "gfx1102");
}
/// The gfx11 targets the matrix-core kernels (prompt GEMM / attention / scorer / fused experts) are compiled for.
inline bool gfx_arch_is_gfx11_wmma(const char* gcn) {
return gfx_arch_is(gcn, "gfx1100") || gfx_arch_is(gcn, "gfx1101") || gfx_arch_is(gcn, "gfx1102") || gfx_arch_is(gcn, "gfx1103") ||
gfx_arch_is(gcn, "gfx1150") || gfx_arch_is(gcn, "gfx1151");
}
/// The gfx12 (RDNA4) targets the gfx12 matrix-core kernels are compiled for (`#if defined(__gfx1200__) ||
/// defined(__gfx1201__)`): the R9700 / 9070 (XT) are gfx1201, the 9060 (XT) gfx1200.
inline bool gfx_arch_is_gfx12_wmma(const char* gcn) { return gfx_arch_is(gcn, "gfx1200") || gfx_arch_is(gcn, "gfx1201"); }
/// Strix Halo (Ryzen AI Max, RDNA3.5): the part the gfx1151 defaults (docs/STRIX_HALO.md) are measured on.
inline bool gfx_arch_is_gfx1151(const char* gcn) { return gfx_arch_is(gcn, "gfx1151"); }
/// RDNA4 (Radeon AI PRO R9700 = gfx1201, RX 9070 / 9070 XT = gfx1201, RX 9060 = gfx1200).
inline bool gfx_arch_is_gfx12(const char* gcn) { return gfx_arch_is(gcn, "gfx1200") || gfx_arch_is(gcn, "gfx1201"); }
} // namespace strata::kernels
@@ -0,0 +1,132 @@
// include/strata/kernels/gr.hpp - the gated residual (hyper-connection), P2.S2.
//
// `ref/gr.py::gr_read` / `gr_write`, which are transcribed from
// `llama_model_qwen4exp::graph::build_hc_mix` / `build_hc_combine` (qwen4exp.cpp L267-350 at 3cf03257).
//
// The residual is a STACK of `hc` streams, each `n_embd` wide - not one vector with a gate. `gr_read`
// collapses the stack to the one vector the mixer consumes and produces a per-stream injection; `gr_write`
// puts the mixer's output back into every stream, weighted per stream.
//
// WEIGHTS ARE BF16, stored as the high 16 bits of an f32 in a `uint16_t`. That is not a shortcut: every one
// of these tensors has source type BF16 in the pack (288 of the shard's 483 BF16 tensors are `hc_*`), so the
// pack's 32-bit promotion is lossless padding and re-rounding to 16 bits costs nothing. It is also worth
// 1.374 GiB of the 5.305 GiB dense file, which is the difference between the dense weights fitting in VRAM
// beside the expert cache and not fitting at all.
//
// The default activation contract is the historical BF16-rounded reference. The opt-in FP32 contract
// matches the pinned llama.cpp CUDA single-token BF16 MMVF input precision: BF16 weights multiply FP32
// activations. The CPU oracle and some batched CUDA paths instead round activations to BF16. Therefore
// activation precision must be pinned with the oracle backend and batch geometry, not inferred from weights.
#pragma once
#include <cstdint>
#include <cstddef>
namespace strata::kernels {
/// Select the activation precision for subsequent gr_read launches (default: false/BF16).
/// Configure before creating/capturing a session, and do not mutate concurrently with gr_read.
/// A captured graph retains the kernel variants chosen at capture; changing this flag cannot alter it.
/// This changes activation precision only; the existing FP32 reduction trees remain unchanged.
void gr_set_fp32_activations(bool enabled);
/// Select pinned single-token BF16/F32 MMVF projections for subsequent gr_read launches (default false).
/// This implies FP32 activations regardless of gr_set_fp32_activations. Configure before session capture;
/// a captured graph retains its selected kernels. Requires even hc*n_embd and hc_lr, as MMVF reads pairs.
/// This also selects pinned weighted F32 RMSNorm and nonlinear/combine arithmetic.
/// Layer reads use fused HC pre; the final mixer (null w_inject) retains its unfused graph order.
/// Subsequent gr_write calls select pinned sigmoid/scatter arithmetic under the same setting.
void gr_set_native_mmvf(bool enabled);
/// Whether gr_write currently uses the native write (native_gr_post).
bool gr_native_mmvf_enabled();
/// Geometry of the hyper-connection. The real model: n_embd = 2560, hc = 4, hc_lr = 320.
struct GrShapes {
int64_t n_embd = 0; ///< width of one residual stream
int64_t hc = 0; ///< number of streams in the stack
int64_t hc_lr = 0; ///< rank of the down/up bottleneck
};
/// Scratch for `gr_read`. EXPLICIT and caller-owned, because P2.T10 requires ZERO token-path allocations:
/// a hidden `cudaMalloc` on first use would satisfy every test here and fail the memory test in P2.S10.
///
/// **IT MUST BE DEVICE MEMORY.** `gr_workspace_init` takes a raw pointer and does no checking, so handing it
/// a host buffer produces device kernels writing to a truncated host address - an illegal access whose
/// reported fault address is the low 32 bits of a host pointer, which reads as a wild pointer rather than as
/// the mistake it is. That cost one round in `gr_parity`;
///
/// xn hc*n_embd floats the unrounded activated streams (the gated mean needs the unrounded value)
/// xq hc*n_embd uint16 bf16(xn), used by the default activation contract
/// lq hc_lr uint16 bf16(lo), used by the default activation contract
/// gated hc*n_embd floats xn * sigmoid(gate), before the mean over streams
/// lo hc_lr floats SiLU bottleneck, used by the FP32 activation contract
///
/// `cudaMalloc(gr_workspace_bytes(s))`, then `gr_workspace_init(s, ptr, ws)` to carve it.
struct GrWorkspace {
float* xn = nullptr;
uint16_t* xq = nullptr;
uint16_t* lq = nullptr;
float* gated = nullptr;
float* lo = nullptr;
/// Set by `gr_workspace_init`. `gr_read` CHECKS it, so an under-sized buffer is a loud failure at the
/// first call instead of silent corruption - which is what a mis-ordered region table used to produce.
size_t bytes = 0;
};
/// Carves `base` (which must be DEVICE memory, or null to size only) into `out` and returns the bytes needed.
/// 16-byte aligned between regions.
size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out);
inline size_t gr_workspace_bytes(const GrShapes& s) { GrWorkspace w; return gr_workspace_init(s, nullptr, w); }
/// `build_hc_mix`. ONE token: `R` is (hc, n_embd) with n_embd fastest, i.e. stream c starts at c*n_embd.
///
/// w_norm (hc*n_embd) per-stream RMSNorm gamma, STORED AS (1 + w) by the converter
/// w_down (hc_lr, hc*n_embd) MANIFEST LAYOUT - row k is contiguous, `w_down[k*hc*n_embd + i]`
/// w_up (hc*n_embd, hc_lr) MANIFEST LAYOUT - row i is contiguous, `w_up[i*hc_lr + k]`
/// w_inject (hc, hc*n_embd) null for the FINAL mixer, which has no write-back to gate
///
/// mixed (n_embd) = mean over streams of xn * sigmoid(bf16(lo) @ w_up.T)
/// inject (hc) = bf16(xn) @ w_inject.T, or untouched when w_inject is null
///
/// `lo = silu((bf16(xn) @ w_down.T) / hc)` - the division by hc is INSIDE the silu, which is easy to read
/// past and changes the result materially.
/// With gr_set_fp32_activations(true), replace bf16(xn) and bf16(lo) by xn and lo respectively.
///
/// **NO PERMUTATION: both matrices are taken exactly as the manifest stores them**, so the loader does nothing
/// to them. Both are coalesced because each projection assigns ONE WARP PER OUTPUT ROW and strides the
/// reduction axis across its 32 lanes: for a fixed output, consecutive lanes touch consecutive addresses in
/// either orientation. An earlier version assigned one THREAD per row, which is coalesced with itself and 32
/// transactions away from its warp neighbours - see the history below.
///
/// **HISTORY, because this kernel was the engine's worst and the reason is instructive.** The first version
/// was launched `<<<1, 256>>>` with `xn`/`xq` in shared memory, and at the real geometry it cost **2.67 ms per
/// call, 96 calls per token = 262 ms/token, about 3.8 tok/s, 134x off the 643 GB/s memory floor.** The cause
/// was isolated by elimination: NOT memory latency (four independent accumulator chains made it 17% SLOWER),
/// NOT the SM clock (`nvidia-smi` reported 2917 MHz and 99% utilisation throughout), and only partly
/// coalescing (transposing one of the two matrices gave 31% and transposing the other gave nothing). It was
/// ISSUE THROUGHPUT - ~8.4M iterations of 6-8 instructions issued by ONE of 48 SMs.
///
/// This version splits the work the way the shapes want: `hc` blocks for the per-stream norm, one warp per
/// row for each of the two projections, and one block-tile for the mean. The transposes are gone because the
/// warp-per-row mapping makes them unnecessary.
void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed,
float* inject, void* stream);
void gr_read_multi(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws,
float* xn_multi, float* lo_multi, float* gated_multi, float* mixed, float* inject,
int n_tok, void* stream);
/// `build_hc_combine`. `R_out[i] = R[i] + block_out[d] * w[c]` with `w[c] = 2*sigmoid(inject[c]/hc)`.
///
/// The `2*sigmoid` is what CENTRES the gate on 1, so a zero injection is a plain residual add - the source
/// comment says so outright and `gr_write`'s test asserts it. Note the block output is added to EVERY stream
/// identically; only the weight is per-stream.
void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
void* stream);
void gr_write_multi(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
int n_tok, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,135 @@
// include/strata/kernels/i8_expert_rule.hpp - when a prompt layer's expert groups take our own int8 dot-product kernels (native_expert_i8,
// src/kernels/cuda/i8_expert.cuh) in place of MMQ.
//
// STRATA_EXPERT_I8 = 1 asks for them on any card, 0 turns them off, unset (or empty) leaves the card class to decide: on the HIP cards gfx1030 / gfx1031 /
// gfx1032 (RDNA2: no matrix cores, the byte dot product `v_dot4_i32_i8` only) the covered formats take them by default. Measured on the RX 6700 XT
// (gfx1031, one MoE layer of Flash-Next's shape, tokens 2,048 / 8,192 / 20,000): 1.10 - 1.35 times MMQ for the IQ2_S / IQ2_XXS packs with a Q2_0 down and
// for the IQ3_S / IQ3_XXS packs with an IQ4_NL down (par/RESULTS-OWN-I8.md). gfx1034 / 1035 / 1036 were not compiled or timed: they stay on MMQ.
//
// Both kinds of call keep the size floor: a launch of experts averaging fewer than kI8MinGroupEntries entries stays on today's path (no timing below
// 2,048 tokens exists on this class; the P100 / V100 numbers say the grouped / MMQ kernels win at 300 tokens). Pure functions: no GPU and no
// environment read here (the caller passes the variable's text and the device's gcnArchName), so the rule is unit-tested without a card.
#pragma once
#include <cstddef>
#include <cstdint>
#include "strata/kernels/gfx_arch.hpp"
namespace strata::kernels {
/// Groups (a launch of up to 16 experts) averaging fewer entries than this keep today's path.
inline constexpr int64_t kI8MinGroupEntries = 256;
/// The RDNA2 parts that take the int8 kernels by default. `gcn` is hipDeviceProp_t::gcnArchName (a CUDA card has none: nullptr or "").
inline bool gfx_arch_is_gfx103x_i8(const char* gcn) {
return gfx_arch_is(gcn, "gfx1030") || gfx_arch_is(gcn, "gfx1031") || gfx_arch_is(gcn, "gfx1032");
}
/// STRATA_EXPERT_I8 read as a state: 1 = on (any non-empty text that does not start with '0'), 0 = off (starts with '0'), -1 = not set (null or empty).
inline int i8_switch_parse(const char* text) {
return text == nullptr || text[0] == '\0' ? -1 : (text[0] == '0' ? 0 : 1);
}
/// A build without llama.cpp's MMQ (-DSTRATA_MMQ=OFF, or HIP without STRATA_PREFILL_MMQ; prefill.cpp's STRATA_PF_OWN_ONLY): the int8 kernels are the default prompt-expert kernels on every
/// card that covers the layer's formats, because MMQ is what they replace; without them the layer runs each expert on the FP16 path (4 - 5 times slower on an RX 6700 XT). `state` is
/// i8_switch_parse's answer; a value the user set (0 or 1) is kept, an unset switch reads as 1 in such a build. "Default on" is not "forced": see i8_order_allows.
inline int i8_switch_effective(int state, bool mmq_free) { return state == -1 && mmq_free ? 1 : state; }
/// Does the build / card class alone (switch not set) take the int8 kernels: the RDNA2 class, or any card in a build without MMQ.
inline bool i8_expert_class_default(int state, const char* gcn, bool mmq_free = false) { return state == -1 && (mmq_free || gfx_arch_is_gfx103x_i8(gcn)); }
/// The order of the prompt-expert paths for one layer of one chunk: the fused kernels (a long chunk on a layer they cover) and the staged group entry (a short chunk, the fused kernels'
/// entry) come first, the int8 kernels take what is left, the FP16 path what even they do not cover. This holds for a value the user set too (STRATA_EXPERT_I8=1 asks for the int8 kernels
/// where nothing faster takes the layer: R9700, 2,048 tokens, fused 1,144.6 ms against int8 1,624.5); it is the order prefill.cpp's `i8_l` condition has.
inline bool i8_order_allows(bool fused_takes, bool staged_takes) { return !fused_takes && !staged_takes; }
inline bool i8_expert_takes(int state, const char* gcn, int64_t group_entries, bool supported); // (defined below)
/// The whole question for one layer of one chunk, as the pure rule (the engine asks the two halves where it has them: i8_order_allows in prefill.cpp, i8_expert_takes in iq_kernels.cu).
inline bool i8_layer_takes(int raw_state, bool mmq_free, const char* gcn, int64_t group_entries, bool supported, bool fused_takes, bool staged_takes) {
return i8_order_allows(fused_takes, staged_takes) && i8_expert_takes(i8_switch_effective(raw_state, mmq_free), gcn, group_entries, supported);
}
/// Do the expert groups of a layer take `native_expert_i8`? `state` = i8_switch_parse(getenv), `gcn` the device's gcnArchName, `group_entries` the entries
/// of one launch on average, `supported` = native_expert_i8_supported(layout) (formats, sizes, the device's shared memory).
inline bool i8_expert_takes(int state, const char* gcn, int64_t group_entries, bool supported) {
if (state == 0 || !supported || group_entries < kI8MinGroupEntries) return false;
return state == 1 || i8_expert_class_default(state, gcn);
}
// The few-rows route. A layer whose experts average fewer routed rows than a crossing runs on the grouped kernels (native_expert_grouped, no shared-memory
// staging: one launch pair per 16 experts like the int8 kernel's, the q8_1 image of the rows made by quantize_q8_1_rows); from the crossing up it runs on the
// int8 kernel. Measured on one MoE layer of Flash-Next's shape (average rows per expert where both take equal time), WITHOUT the 8-entry slices (N8): Tesla P100 (sm_60) 8.4, A4000 10.2 - 11.7,
// RX 6700 XT 10.2 - 10.8, R9700 11.7 (par/RESULTS-I8-RESEARCH.md); WITH them (STRATA_I8_N8, on by default in this range, see i8_n8_takes) P100 5.7 - 5.8, A4000 6.9 - 7.4, R9700 6.9 - 7.4 (par/RESULTS-I8-MMQOFF.md). The limits below are the crossings with N8; the int8 side never loses more than 5 %.
// Without the route the int8 kernel keeps the size floor above (256 entries per group of 16 experts = 16 rows per expert) and the layers under it stay on today's path.
inline constexpr int kI8FewRowsDefault = 7; ///< every card but the Tesla P100 (10 with STRATA_I8_N8=0)
inline constexpr int kI8FewRowsSm60 = 6; ///< compute capability 6.0 (the P100): its crossing is lower (8 with STRATA_I8_N8=0)
/// STRATA_I8_FEWROWS read as the limit: not set (or empty, or text that is no number) = the card class's own `class_default`, 0 = no route, N = a limit of N rows per expert.
inline int i8_fewrows_limit(const char* text, int class_default) {
if (text == nullptr || text[0] == '\0') return class_default;
if (text[0] < '0' || text[0] > '9') return class_default;
long v = 0;
for (const char* p = text; *p >= '0' && *p <= '9'; ++p) {
v = v * 10 + (*p - '0');
if (v > 100000) break;
}
return (int) v;
}
/// The class's default limit: the P100 (compute capability 6.0) 6, every other card 7.
inline int i8_fewrows_class_default(int cc_major, int cc_minor) { return cc_major == 6 && cc_minor == 0 ? kI8FewRowsSm60 : kI8FewRowsDefault; }
/// Does a layer with `rows` routed rows over `experts` experts (those with at least one row) take the grouped kernels? limit 0 = the route is off.
inline bool i8_fewrows_takes(int limit, int64_t rows, int64_t experts) { return limit > 0 && experts > 0 && rows < (int64_t) limit * experts; }
// The 8-entry slices of the tile-2..4 int8 kernel (N8: two weight rows and one entry of each 8-entry slice per thread; bit-identical output). Measured on the A4000, the P100 and
// the R9700 (par/RESULTS-I8-MMQOFF.md, I8 column of the expert-paths bench, Flash-Next's shape, IQ2_XXS / Q2_0 and IQ3_S / IQ4_NL): tile 2 (up to 39 entries per expert on average, about
// 1,950 tokens) 23 - 33 % faster at 100 - 300 tokens, 12 - 17 % at 1,000 and 6 - 13 % at 1,500 on all three; tile 3 (2,048 tokens) 3 - 6 % faster on the A4000 and the P100 but
// 1.6 - 2.9 % SLOWER on the R9700. So the default is tile 2 only; STRATA_I8_N8=1 asks for tiles 2 - 4, STRATA_I8_N8=0 for none.
/// STRATA_I8_N8 read as a state (1 / 0 / -1 not set), the tile code the call settled on (2, 3, 4 = rows of 16 entries per thread; 8 = the 128-entry kernel, which has no 8-entry form).
inline bool i8_n8_takes(int state, int tile) {
if (state == 0) return false;
return state == 1 ? tile >= 2 && tile <= 4 : tile == 2;
}
// Volta (compute capability 7.0: 96 KB of shared memory per multiprocessor, no int8 matrix cores, so every routed expert of a prompt runs on these kernels). The tile the
// other cards take from 96 entries a group on average (tile 8, 128 x 128, 54-62 KB) and tile 4 (51-59 KB) leave one block of 8 warps per multiprocessor there; tiles 2 and 3 of
// the IQ3 formats (43 / 48 KB) run two. Tesla V100-SXM2 32 GB, one layer of Flash-Next's shape, uniform routing, MMQ time / int8 time (above 1: ours faster), the call's
// own pick against tile 3 (phaseA-tests/tune0216, bench1-v100): IQ3_S / IQ4_NL 0.745 -> 0.949 at 8,192 tokens and 0.795 -> 0.820 at 26,000, IQ3_XXS / IQ4_NL 0.721 -> 0.955 and
// 0.795 -> 0.831; output bits equal at every tile (the tile only groups entries). The big-grid formats (IQ2_S's 8 KB grid table) read their grid from global memory there
// (I8Smem GG: the same words, the same bits), so their tile 3 fits two blocks too. So on Volta the call's pick is lowered to the largest tile that still gives two blocks per
// multiprocessor (tile 8 counts as 4 first); a tile set by STRATA_I8_TM is kept as given.
/// `tm` the pick (2, 3, 4 or 8), `bytes2/3/4` the dynamic shared memory of tiles 2-4 for the layer's formats, `smem_sm` the multiprocessor's shared memory, `reserved` the
/// driver's reservation per block (cudaDevAttrReservedSharedMemoryPerBlock).
inline int i8_tile_two_blocks(int tm, std::size_t bytes2, std::size_t bytes3, std::size_t bytes4, std::size_t smem_sm, std::size_t reserved) {
int t = tm >= 4 ? 4 : tm <= 2 ? 2 : 3;
auto fits = [&](int k) { const std::size_t b = (k == 2 ? bytes2 : k == 3 ? bytes3 : bytes4) + reserved; return 2 * b <= smem_sm; };
while (t > 2 && !fits(t)) --t;
return t;
}
/// Volta's tensor-core form of the kernels (tile code 5, src/kernels/cuda/i8h_volta.cuh: the same products on the FP16 tensor cores, bit-identical output) from this many
/// entries a launch's expert has on average. Tesla V100, one layer of Flash-Next's shape, uniform routing, MMQ time / time (phaseA-tests/tune0216 bench5), tile 3 -> tile 5:
/// at 40 entries (2,048 tokens) 1.38 -> 1.22 (slower), at 160 (8,192) 0.95 -> 0.96 (IQ3_S), 0.95 -> 0.94 (IQ3_XXS), 0.90 -> 0.94 (IQ2_S), at 508 (26,000) 0.82 -> 0.86,
/// 0.83 -> 0.84, 0.82 -> 0.89; output hashes equal at every size.
inline constexpr int64_t kI8hMinAvg = 160;
/// The Volta pick: tile 5 from kI8hMinAvg entries on average when the formats have it (`h_ok`), else the two-block tile of i8_tile_two_blocks.
inline int i8_tile_volta(int two_block_tile, int64_t avg, bool h_ok) { return h_ok && avg >= kI8hMinAvg ? 5 : two_block_tile; }
/// STRATA_I8_SM70 read as a state (1 / 0 / -1 not set): the Volta tile rule above and the global grid are on unless it is 0.
inline bool i8_volta_rule_on(int state) { return state != 0; }
// The Tesla P100 (compute capability 6.0) in a build without MMQ. There the build WITH MMQ takes the FP16 prompt path by default (prefill.cpp gp100_fp16_default: GP100 has no
// dp4a), so the unset-switch int8 default of a build without MMQ (i8_switch_effective) must not replace it where the int8 kernel loses to it. Measured on the P100 (OUT build,
// prompt read ms int8 / FP16, par/RESULTS-P100-GATE.md): 300 0.874, 600 0.865, 1,000 0.844, then 1,200 1.196, 1,500 1.142, 2,048 1.085, 8,192 1.081: the step sits at the chunk size from
// which every expert streams (stream_all_min, 1,024 tokens, prefill.cpp), so the limit is that floor and no constant of its own: the int8 default applies to chunks BELOW it
// (the staged per-layer path), the FP16 path from it up, as the build with MMQ does. A value the user set wins at every size (STRATA_EXPERT_I8=1 keeps the int8 kernels, =0 turns
// them off); every other card class has no such limit.
/// May the int8 default (switch NOT set, build without MMQ) take a chunk of `chunk_tokens` tokens on this device? `raw_state` = i8_switch_parse(getenv): a set value (0 or 1) is
/// not this rule's to decide (true); a build with MMQ, or a card that is not the P100 (`sm60`), has no limit (true); otherwise the chunk must be under `limit`.
inline bool i8_chunk_default_allows(int raw_state, bool mmq_free, bool sm60, int64_t chunk_tokens, int64_t limit) {
if (raw_state != -1 || !mmq_free || !sm60) return true;
return chunk_tokens < limit;
}
} // namespace strata::kernels
@@ -0,0 +1,197 @@
// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S,
// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's
// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding).
//
// The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh,
// ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it
// means in llama.cpp. Activations are q8_1 (32 values, fp16 scale and fp16 sum), the llama.cpp CUDA contract.
#pragma once
#include <cstddef>
#include <cstdint>
namespace strata::kernels {
/// ggml type ids handled here.
bool iq_supported(int ggml_type) noexcept;
/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30).
bool embed_type_supported(int ggml_type) noexcept;
/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block).
size_t iq_row_bytes(int ggml_type, int64_t n) noexcept;
/// q8_1 blocks for `n_rows` rows of `n_cols` floats (n_cols a multiple of 32): y is n_rows * n_cols/32 blocks.
void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);
/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column).
void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream);
/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32; fp16 times `*scale` when given (device:
/// an NVFP4 expert's s_down, read by the kernel itself so the source may be released right after it).
void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale = nullptr);
void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream);
/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped
/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256).
void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,
int64_t n_embd, float* out, void* stream);
/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path
/// uses: row 2r = gate row r, row 2r+1 = up row r. `tail` (device, NVFP4 only): the blob's {s_gate, s_up,
/// s_down, 0}; gate rows are scaled by s_gate and up rows by s_up (s_down goes on the down matrix: folded into up,
/// the up weights would sit near 1e-8, deep in FP16's subnormals).
void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst,
void* stream, const float* tail = nullptr);
/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks.
struct NativeExpertLayout {
int gu_type = -1, d_type = -1;
int64_t n_embd = 0, n_ff = 0;
size_t gu_row = 0, d_row = 0; // bytes per row
size_t up_off = 0, down_off = 0; // byte offsets inside the blob
size_t bytes = 0; // the whole blob
size_t tail_off = 0; // NVFP4: {s_gate, s_up, s_down, 0} at the blob's end; 0 = none
// APR (prism.hadamard): the down weights are Hadamard-folded, so native_expert_grouped rotates h before
// quantizing it (hadamard_rows). had_block 0 = none; d_signs is a DEVICE vector of n_ff signs or nullptr.
int had_block = 0;
bool gu_nib = false; // STRATA_EXPERT_NIBBLE: gate/up as 4-bit codes (strata/core/expert_nibble.hpp's
// slot); set only by native_expert_layout_nib
const float* d_signs = nullptr;
};
NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
/// STRATA_EXPERT_NIBBLE: a converted VRAM slot - gate/up as 4-bit codes, scales and d (expert_nibble.hpp's layout:
/// up_off = the up rows' codes, down_off = kGuBytes, bytes = the slot), the GGUF down rows after them. IQ2_S /
/// IQ3_XXS / IQ3_S at n_embd 2560, n_ff 640 only, and only in a build with the kernels (`native_expert_nib_supported`).
NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;
/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the
/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated).
bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;
/// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries.
size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff);
/// A770 port (STRATA_PF_XMX=2): up to kXmxGroupMax experts' products in one XMX launch, the weights decoded from the
/// quantized rows into local memory. Expert i: Y_i[cnt[i]][N] = X_i . W_i^T (X FP16, Y FP32, rows back to back).
/// gate/up: b != nullptr (a = gate, b = up rows of n_embd = K; the output's virtual rows interleave gate/up);
/// down: b == nullptr, a = the [N][K] rows. N a multiple of 128, K of 32 (and a whole number of rows per 256 block).
constexpr int kXmxGroupMax = 16;
void iq_xmx_grouped(int ty, const uint8_t* const* a, const uint8_t* const* b, const int32_t* cnt, int n,
const uint16_t* X, float* Y, int N, int K, void* stream);
/// Grouped experts in the native format: group g's blob at device address grp_ptr[g]; its entries
/// [grp_start[g], grp_start[g+1]) read token ent_tok[e]'s q8_1 activation (n_embd/32 blocks per token in x_q8_1)
/// and write row ent_dst[e] of `out` (n_embd floats). Counts are read on the device.
/// `grid_groups` (1 .. cap_groups; 0 = cap_groups) groups run side by side, a block row each striding over the rest:
/// a call that usually has few groups or none (the verify window's PCIe share) launches less for the ones it does
/// not have. The results do not depend on it.
void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,
const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,
int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,
int64_t grid_groups = 0);
/// OWN-I8 (research, off by default): the same call as `native_expert_grouped` on our own int8 dot-product kernels - a tile of
/// 64 weight rows x 32..64 entries per block, each weight sub-block decoded once per tile into int8 in shared memory, `dp4a`
/// products, SwiGLU and the q8_1 quantization of H in the gate/up epilogue (gate/up never go to memory). For cards with no
/// matrix cores the fused prompt kernels can use. `scratch` as for native_expert_grouped (native_expert_scratch_bytes).
/// Covered: gate/up IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S / IQ2_S with a down of IQ4_NL / Q2_0 (`native_expert_i8_supported`);
/// no NVFP4 tail, no APR Hadamard, no 4-bit slots. STRATA_EXPERT_I8=1 makes `native_expert_grouped` itself take it for a call of
/// 256 entries or more (the prompt chunk of a Qwen3.6 engine without MMQ); STRATA_I8_TM = 2 | 3 | 4 forces the tile.
bool native_expert_i8_supported(const NativeExpertLayout& L) noexcept;
/// OWN-I8, the prompt path's question (once per layer, src/prefill/prefill.cpp): do the expert groups of this layer take `native_expert_i8`
/// on this device, for groups of about `group_entries` entries (rows of one launch)? STRATA_EXPERT_I8=1 asks for it on any card, =0 never; unset:
/// the HIP cards gfx1030 / gfx1031 / gfx1032 take it, every other card keeps MMQ (include/strata/kernels/i8_expert_rule.hpp). The formats and the
/// device's shared memory still have to allow it (`native_expert_i8_supported`); groups under 256 entries keep the other path.
/// Shared prompt code, no device work: a Metal build answers false.
bool native_expert_i8_prompt(const NativeExpertLayout& L, int64_t group_entries) noexcept;
/// OWN-I8: true when the answer above is "yes" because of the card class or the build (STRATA_EXPERT_I8 not set), not because the variable names it; the engine's
/// start line differs. A Metal build answers false.
bool native_expert_i8_by_default() noexcept;
/// OWN-I8: called once, before main, by a build without llama.cpp's MMQ (prefill.cpp, STRATA_PF_OWN_ONLY): an unset STRATA_EXPERT_I8 then reads as 1 (i8_expert_rule.hpp,
/// i8_switch_effective); a build with MMQ never calls it. A Metal build ignores it.
void native_expert_i8_set_mmq_free() noexcept;
/// OWN-I8, the few-rows route (include/strata/kernels/i8_expert_rule.hpp): the average routed rows per expert under which a prompt layer that takes the int8 kernels
/// runs on the grouped kernels instead; 0 = no route (STRATA_I8_FEWROWS=0, or the int8 kernels are off). The class default: 6 on a Tesla P100, 7 elsewhere.
/// Shared prompt code, no device work for a build that has none: a Metal build answers 0.
int native_expert_i8_few_rows_limit() noexcept;
/// OWN-I8 (tests, logs; CUDA / HIP builds only, no Metal definition: nothing shared calls these three): the dynamic shared memory per block the current device
/// lets `native_expert_i8` use, in bytes (the device's opt-in attribute, 48 KB where it reports less; STRATA_I8_SMEM_LIMIT can lower it).
size_t native_expert_i8_smem_limit() noexcept;
/// What the last `native_expert_i8` call asked its two launches for: the tile code, the dynamic shared memory passed as each launch's third argument, and each
/// launch's own status (cudaPeekAtLastError right after it, 0 = accepted).
struct NativeExpertI8Launch {
int tile;
size_t gu_bytes, down_bytes;
int gu_err, down_err;
};
NativeExpertI8Launch native_expert_i8_last_launch() noexcept;
/// Does a launch of an empty kernel with this much dynamic shared memory run on the current device? 1 yes, 0 refused, -1 not available (a HIP build). A
/// diagnostic for native_i8_parity; the attribute call is tried and its refusal ignored, the launch decides; the context is left clean.
int native_expert_i8_probe_launch(size_t bytes) noexcept;
/// Bytes of scratch `native_expert_i8` needs (it is smaller than native_expert_scratch_bytes: H goes out as q8_1 blocks only): `cap_entries`
/// entries, at most `cap_groups` groups, `n_ff` features.
size_t native_expert_i8_scratch_bytes(int64_t cap_entries, int64_t cap_groups, int64_t n_ff);
/// The activation image `native_expert_i8` reads (its `x_q8_1` argument): `n_rows` x `n_cols` floats as blocks of 32 values {float d; int8 q[32]} (36 bytes), MMQ's numbers
/// (d_inv = 127 / amax, q = round(x * d_inv), d = 1 / d_inv, the scale in FP32). NOT the q8_1 block of the other kernels (half2 ds); `n_cols` a multiple of 32.
void native_expert_i8_quantize(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);
/// A launch record of at most kI8PutRecordMax bytes (a multiple of 4) written to `dst` (device) on `stream` by a one-block kernel that takes the bytes as its argument:
/// no host-to-device copy, so the write does not queue behind other copies in the copy engine (the prompt path's streamed experts). False: too many bytes, or the launch failed.
constexpr size_t kI8PutRecordMax = 512;
bool native_expert_i8_put_record(void* dst, const void* src, size_t bytes, void* stream);
void native_expert_i8(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, const void* x_q8_1,
void* scratch, float* out, void* stream);
/// true: `native_expert_grouped`'s launches before the group stride (STRATA_GROUPED_V1=1 at startup) - a block row
/// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results
/// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs.
void native_grouped_set_v1(bool v1);
/// The bench / parity only: the 4-bit gate/up kernel of every format (-1 = expert_nibble.hpp's gu_skeleton, the
/// default; 0 = the S skeleton; 1 = the P skeleton). Bitwise the same results; set before graph capture.
void native_expert_nib_set_variant(int v);
/// gu-proto (nib_gu_proto.cuh): variant v's registers, local bytes and resident 256-thread blocks per SM for gu_type;
/// false when v is not a gu-proto id (>= 10) or the type has none.
bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm);
/// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase
/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down, 3 gate/up only).
void native_expert_set_mode(int mode, int phase);
/// APR (prism.hadamard): y = H_block (signs * x) per block of `block` values of each of `rows` rows of `width`
/// (x == y allowed). `signs`: a device vector of `width` signs, or nullptr (identity). The same floats as the CPU's
/// hadamard_rotate. The f16 form rotates in place, computing in float.
void hadamard_rows(const float* x, float* y, int64_t rows, int64_t width, int block, const float* signs, void* stream);
void hadamard_rows_f16(uint16_t* x, int64_t rows, int64_t width, int block, const float* signs, void* stream);
/// A device copy (on the current device) of the host sign vector `host` of `width` signs, made on first use and
/// kept for the process. Call it at setup, not inside a CUDA graph capture. nullptr for a nullptr `host`.
const float* hadamard_device_signs(const float* host, int width);
/// EXPDEC (STRATA_EXPDEC, docs/EXPERTDEC.md): `native_expert_grouped` stages the group's q8_1 activations in shared
/// memory and computes several rows per lane, the same sums per (row, entry) as the default kernels (bitwise), for
/// gate/up IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S / IQ2_S at n_embd 2560 and down IQ4_NL / Q2_0 at n_ff 640; other layouts
/// keep the default kernels. Enabled by default on gfx12 (STRATA_EXPDEC=0 disables it) and opt-in elsewhere
/// (STRATA_EXPDEC=1). Set before graph capture; captured graphs keep the kernels they captured.
void native_expert_set_expdec(int on);
int native_expert_expdec();
/// Its knobs, read from the environment at startup (STRATA_EXPDEC_R 1 | 2, _DR 1 | 2 | 4, _MINB 2 | 4, _D20 0 | 1,
/// _RB, _DRB, _MINBLK): gate/up and down rows per lane, the gate/up kernel's __launch_bounds__ minimum blocks per SM
/// (2 = up to 128 registers, 4 = up to 64), EXPDEC for the IQ4_NL down too, gate/up and down rows per block (0 = auto
/// from the launch's groups), the auto rule's minimum blocks. In the setter a field <= 0 (< 0 for the two rows per
/// block and down_iq4_nl) keeps the current value.
/// `down` (STRATA_EXPDEC_DOWN, default 1 on gfx12 for Q2_0 down and 0 elsewhere; STRATA_EXPDEC_DOWN=0/1 overrides):
/// EXPDEC for the down too; `down_iq4_nl` (STRATA_EXPDEC_D20, default 0) remains opt-in everywhere.
struct NativeExpertExpdecParams {
int gu_rows_per_lane = 0, down_rows_per_lane = 0, gu_min_blocks_per_sm = 0, down_iq4_nl = -1, down = -1;
int gu_rows_per_block = -1, down_rows_per_block = -1, min_blocks = 0;
};
void native_expert_set_expdec_params(const NativeExpertExpdecParams& p);
NativeExpertExpdecParams native_expert_expdec_params();
/// Whether EXPDEC has kernels for this layout's gate/up and down (the bench's check).
bool native_expert_expdec_takes(const NativeExpertLayout& L, bool& gu, bool& down);
/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry;
/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give
/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured.
/// Volta prompt experts (STRATA_PF_WMMA): Y[rows of expert e] = X[rows] . W_e^T for a group of experts, W_e at
/// W + e * expert_bytes (n_out rows of K values of type ty, GGUF blocks), X FP16 (ldx), rows bounds[e]..bounds[e+1],
/// Y FP32 (ldy). FP16 tensor cores, FP32 sums. false: not launched (shape or type not covered). CUDA only.
bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx,
const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream);
void iq_set_old_kernels(bool old);
bool iq_old_kernels();
} // namespace strata::kernels
@@ -0,0 +1,64 @@
// strata/kernels/mrope.hpp - multimodal rotary positions (the vision path).
//
// qwen4exp rotates with interleaved M-RoPE (llama.cpp LLAMA_ROPE_TYPE_IMROPE, rope.dimension_sections 11/11/10/0):
// each of the 32 rotated pairs takes its position from one of three streams, time t, height h and width w. Text
// has t = h = w, which is why every rope kernel here takes one position per row. An image does not: its tokens
// share t and differ in h and w (mtmd: t = p, h = p + y, w = p + x), and the text after it continues at
// p + max(nx, ny), not at its cell index.
//
// The table: nullptr (the default) keeps every kernel exactly as before - the position a caller passes is the
// rotary position. Set, it is a DEVICE int32 [cells][3] (t, h, w) and the position a caller passes is read as a
// CELL index; pair i rotates by tab[cell * 3 + mrope_sector(i)]. Every caller in the engine passes cell indices
// (pos_base is 0 everywhere), so the table covers the prompt path, the verify window and the MTP drafter at once.
// The pointer must be set before any CUDA graph is captured (kernels take it as an argument); the contents may
// change between requests.
#pragma once
#include <cstdint>
#if defined(__HIPCC__) && defined(STRATA_HIP_GFX906) // PR #638: the gfx906 compat build only
#include <hip/hip_runtime.h>
#endif
#include "strata/kernels/rope_scaling.hpp"
namespace strata::kernels {
/// The table of the CURRENT device (a layer split sets one per device; null = the identity).
void mrope_table_set(const int32_t* device_table);
const int32_t* mrope_table();
/// #280, opt-in (STRATA_ROPE_TABLE=1): the rotation angles, 32 pairs of a 64-wide rotary slice, from the session's
/// float64 table (build_rope_table, [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT
/// device. With it the rope kernels rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under
/// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode
/// (fast-math) disagree with each other.
struct RopeTab {
const float* cos = nullptr; ///< null: no table, the kernels compute the angle as they always did
const float* sin = nullptr;
int max_pos = 0;
};
/// Registers the table the session just built with `scaling` (the latest one of the device wins).
void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling);
/// Forgets the table `cos_tab` (on every device) - before the memory that holds it is freed (session_release).
void rope_table_release(const float* cos_tab);
/// The registered table when STRATA_ROPE_TABLE=1 and it was built with `scaling`; otherwise none (the default: the
/// kernels compute the angle exactly as before).
RopeTab rope_table_for(const RopeScaling& scaling);
#if defined(__CUDACC__) || defined(__HIPCC__)
/// ggml rope_multi, is_imrope, sections {11, 11, 10, 0}: sector = pair % 32; sector % 3 == 1 -> h (sector < 33),
/// == 2 -> w (sector < 30), == 0 -> t (sector < 33). For pairs 0..31 all three bounds hold, so it is pair % 3.
__device__ __forceinline__ int mrope_pos(const int32_t* tab, int pos, int pair) {
return tab ? __ldg(tab + (size_t) pos * 3 + pair % 3) : pos;
}
/// cos and sin of rotary position p, pair `pair` (0..31) from the table (scaling and magnitude included); false
/// when there is no table or p lies past it - then the caller computes the angle as it always did
__device__ __forceinline__ bool rope_tab_cs(const RopeTab& t, int p, int pair, float& c, float& s) {
if (t.cos == nullptr || p < 0 || p >= t.max_pos) return false;
c = __ldg(t.cos + (size_t) p * 32 + pair);
s = __ldg(t.sin + (size_t) p * 32 + pair);
return true;
}
#endif
} // namespace strata::kernels
@@ -0,0 +1,22 @@
#pragma once
#include "strata/kernels/gdn.hpp"
namespace strata::kernels {
// Configure before creating/capturing a session. Existing captures retain their
// selected kernel, so changing the flag does not change an existing graph.
void native_gdn_set_enabled(bool enabled);
bool native_gdn_enabled();
// Pinned CUDA gated_delta_net recurrence for one token, S=128 and h_v % h_k=0.
// q/k are normalized F32 inputs; q MUST NOT be pre-scaled by 1/sqrt(S).
// Scaling is applied to the completed readout, as in the pinned fused operator.
// State retains Strata's layout: state[(i*h_v+h)*S+j]. The caller owns it and
// output; both must be disjoint from each other and from every read-only input.
// All spans must be aligned to four bytes. A nonnull ordered stream is required.
// No allocation, wait, or change to normalization/gate preprocessing occurs.
void native_gdn_step(float* state, const float* q, const float* k, const float* v,
const float* gate, const float* beta, float* output,
const GdnShapes& shapes, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,37 @@
#pragma once
#include <cstdint>
namespace strata::kernels {
// Optional pinned CUDA GDN preprocessing. The layer selects these functions with
// native_gdn_enabled(); direct callers explicitly select them by calling them.
// Require a nonnull ordered stream, finite inputs, and four-byte aligned spans.
// No function allocates or synchronizes. All pointers are caller-owned.
// Four-tap convolution, then FP32 fast-math SiLU. History is [channels,3], oldest
// first; weights are [channels,4]. Both outputs are required, mutually disjoint,
// and disjoint from input/weights/history. History must not alias other spans.
void native_gdn_conv_silu(float* history, const float* input, const float* weights,
float* raw_output, float* silu_output, int64_t channels,
int64_t d_conv, void* stream);
// In-place [rows,128]: scale(rms_norm(x,epsilon/128),1/sqrt(128)). This includes
// the L2 normalization scale, but NOT the recurrence's readout scale.
// Epsilon is finite/nonnegative; epsilon=0 additionally requires nonzero rows.
void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream);
// In-place sigmoid over per-head beta; one token.
void native_gdn_beta_gate(float* beta, int64_t heads, void* stream);
// One token: gate[h] = softplus(alpha[h]+dt[h])*ssm_a[h], using the pinned CUDA
// log(1+exp(x)) expression and threshold 20. Output is disjoint from inputs.
void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a,
float* gate, int64_t heads, void* stream);
// [heads,128]: rms_norm(output,epsilon)*gamma*sigmoid(z). Gamma contains only
// 128 floats and broadcasts across heads. Destination is disjoint from inputs.
void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
float* destination, int64_t heads, int64_t cols,
float epsilon, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,21 @@
#pragma once
namespace strata::kernels {
// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d CUDA weighted F32
// RMSNorm for contiguous [n_cols, n_rows] data and equally shaped F32 gamma.
// Every row has independent norm statistics. Output is (scale * input) * gamma.
// Uses 256 threads below n_cols=1024, otherwise 1024, with the pinned XOR tree.
// Compile the implementation with --use_fast_math; no FP64, allocation, or wait.
// All buffers are caller-owned, nonoverlapping, and at least four-byte aligned.
// Require positive dimensions and finite nonnegative epsilon. Inputs/gamma and
// intermediate sums must be finite; epsilon=0 additionally requires nonzero rows.
// Enqueues on the supplied CUDA stream. A null handle explicitly selects CUDA's
// default stream, preserving gr_read's existing API; this function never syncs.
void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output,
int n_cols, int n_rows, float epsilon, void* stream);
void native_gr_rms_norm_weighted_multi(const float* input, const float* gamma, float* output,
int n_cols, int n_rows, int n_tok, float epsilon, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,39 @@
#pragma once
namespace strata::kernels {
// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d contiguous F32
// single-token GR post-operations. Explicit stream, no allocation or wait; null
// selects the default stream. Positive dimensions with n*hc <= INT_MAX, finite
// values/intermediates, and four-byte alignment are required.
// Buffers must not overlap except the explicitly in-place arguments below.
// Implementation compiles separately with --use_fast_math.
// In-place pinned SCALE(1/hc), then SiLU, applied to the raw down projection.
void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream);
// xn and raw gate contain [n_embd,hc]. gate is overwritten with xn*sigmoid(gate).
// Layer path: pinned DSV4_HC_PRE_GATED ordered FMA accumulation, then scale.
// Head path (fused_layer=false): individually rounded products, ordered adds
// starting from stream zero, then SCALE. This retains the oracle's il=-1 graph.
void native_gr_pre_gated(const float* xn, float* gate, float* mixed,
int n_embd, int hc, bool fused_layer, void* stream);
void native_gr_pre_gated_multi(const float* xn, float* gate, float* mixed,
int n_embd, int hc, int n_tok, bool fused_layer, void* stream);
// inject[hc] -> SCALE(1/hc), sigmoid, SCALE(2), identity DSV4_HC_POST.
// residual/output contain [n_embd,hc], block_out has n_embd elements.
// output may equal residual exactly; all other overlaps are invalid.
void native_gr_post(const float* residual, const float* block_out, const float* inject,
float* output, int n_embd, int hc, void* stream);
/// native_gr_post for n_tok tokens in one launch, token t's operands at t times the given strides (floats): the same
/// expression per element. output may equal residual exactly.
void native_gr_post_multi(const float* residual, const float* block_out, const float* inject, float* output,
int n_embd, int hc, int n_tok, long long r_stride, long long b_stride, long long i_stride,
void* stream);
void native_gr_post_multi(const float* residual, const float* block_out, const float* inject,
float* output, int n_embd, int hc, int n_tok, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,37 @@
#pragma once
#include <cstdint>
namespace strata::kernels {
// Configure before constructing/capturing sessions. Existing captures keep their
// selected kernels; changing this flag does not rewrite an existing graph.
void native_moe_combine_set_enabled(bool enabled);
bool native_moe_combine_enabled();
// Pinned CUDA weighted-reduction contract for one token, k in [1, 15].
// The backend fuses k=2..15; k=1 is its ordinary multiply/contiguous/add path.
// parts: k contiguous F32 rows of n_embd; weights: k F32 values. The first
// product rounds to F32, following products accumulate with FMA in expert order,
// and optional shared is added once afterward. Shared is not router weighted.
// Requires a nonnull ordered stream and disjoint output. No allocation or sync.
void native_moe_combine(const float* parts, const float* weights, const float* shared,
float* output, int64_t n_embd, int64_t k, void* stream);
/// n_tok rows (parts [n,k,N], weights [n,k], shared/output [n,N]) in one launch, each as the single call.
/// 143-amdk: native_moe_combine_multi with moe_hit_add folded in: for the rows listed in dst[0, *count) (entry index = token * k + expert,
/// relative to `parts` and `hits`) the expert's part is parts + hits (the add moe_hit_add made in place), then the combine as before.
/// Only the k = 10 vec4 case; `native_moe_combine_hits_supported` says whether a call may use it.
bool native_moe_combine_hits_supported(const float* parts, const float* shared, const float* output, int64_t n_embd, int64_t k, int n_tok);
void native_moe_combine_multi_hits_added(const float* parts, const float* hits, const int32_t* dst, const int32_t* count,
const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k,
int n_tok, void* stream);
void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output,
int64_t n_embd, int64_t k, int n_tok, void* stream);
/// STRATA_VERIFY_RESIDENT: the same, reading every part as `0.0f + hit[i]` - bitwise what a zeroed part row plus
/// moe_hit_add (parts += hit) gave, without the zero fill and the add launch.
void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output,
int64_t n_embd, int64_t k, int n_tok, void* stream);
/// S26 STRATA_LFUSE: the same with `shared` unscaled and shared_gate[t] the shared expert's raw gate logit: the
/// row is scaled by sigmoid(shared_gate[t]) here, bitwise what shared_expert_multi's sigmoid + scale gave.
void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared,
const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok,
void* stream);
}
@@ -0,0 +1,31 @@
#pragma once
#include "strata/kernels/rope_scaling.hpp"
namespace strata::kernels {
void native_rope_set_enabled(bool enabled);
bool native_rope_enabled();
// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, equal text positions in all four
// IMRoPE sections. Each device position must be nonnegative. The position buffer remains live
// through graph replay. Supports head_dim 128/256 and exact x==out; partial overlap is rejected.
// Explicit stream required. No allocation or synchronization.
//
// The scaling (rope_scaling.hpp) rides in as the resolved process config: none reproduces the
// original contract exactly, linear/YaRN apply ggml's rope_yarn - the interpolation mix, the
// corr_dims ramp along the pairs, and the mscale magnitude correction folded into cos and sin.
// The struct's knobs are process constants, so kernel arguments baked at graph capture stay valid.
void native_rope_apply(const float* x, float* out, int rows, int head_dim,
int n_rot, const RopeScaling& scaling, const int* positions, void* stream);
/// (#783 PR-f, stuchapin909) native_qsa_rms_norm_weighted + native_rope_apply in one launch, bit-identical to the pair
/// (rope_parity check 6): x rows are `in_stride` apart (2 * head_dim reads a q row out of a q|gate row), out rows are
/// head_dim apart, x may equal out when in_stride == head_dim. head_dim 128 or 256 and n_rot 64 only.
void native_qsa_rms_norm_rope(const float* x, int in_stride, const float* gamma, float* out,
int rows, int head_dim, int n_rot, float epsilon,
const RopeScaling& scaling, const int* positions, void* stream);
/// Whether callers should take the fused kernel (and the in-place rope's 32-thread launch) for this geometry. On the
/// CUDA build it is on unless STRATA_NO_NORM_ROPE=1; on the HIP build it is off until the AMD parity check passes there
/// (rope_parity check 6) and only STRATA_NORM_ROPE=1 turns it on.
bool native_norm_rope_usable(int head_dim, int n_rot);
}
@@ -0,0 +1,27 @@
#pragma once
#include <cstdint>
namespace strata::kernels {
// Configure before session capture. Existing graphs retain their selected kernels.
// This experiment is off by default and does not modify the legacy router.
void native_router_set_enabled(bool enabled);
bool native_router_enabled();
// Pinned CUDA topk-moe contract for ONE token, 512 experts, top 10, softmax,
// no selection bias, lower normalization clamp 2^-14, and scale 1.
// Reads 512 finite F32 logits; writes 10 I32 IDs and 10 F32 weights. Equal
// computed probabilities select the lower expert index. All spans must be
// four-byte aligned and outputs disjoint from each other and the input.
// Requires a nonnull ordered CUDA stream. No allocation or synchronization.
void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream);
/// n_tok rows at once (logits [n,512], ids/weights [n,10]); each row exactly as the single call.
void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream);
/// The same contract for a model family's (experts, top-k): 512 / 10 (Flash-Next: the two calls above, unchanged) and
/// 256 / 8 (Qwen3.6-35B-A3B). logits [n_tok, n_expert], ids / weights [n_tok, k]. CUDA / HIP.
bool native_router_topk_supported(int n_expert, int k);
void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream);
/// STRATA_ROUTE_RESIDENT: swap non-resident tail-rank experts for resident ones within `margin` logits (see the .cu).
/// `stats` is nullptr or 4 device uint64 counters: tail entries seen, swaps, non-resident before, non-resident after.
void native_route_resident(const float* logits, int32_t* ids, float* weights, const int32_t* res_layer, int n_tok, float margin,
int rank_lo, int rank_hi, unsigned long long* stats, void* stream);
}
@@ -0,0 +1,28 @@
// include/strata/kernels/nvfp4_decode_sm120.hpp - Clean-room MIT Blackwell sm_120a hardware NVFP4 grouped decode/verify.
//
// MIT License
// Copyright (c) 2026 Niko1221 and the Strata contributors
#pragma once
#include "strata/kernels/iq_kernels.hpp"
#include <cstdint>
namespace strata::kernels {
/// True when compiled with sm_120a/sm_121a hardware FP4 decode support and running on a Blackwell sm_120/sm_121 GPU
/// (STRATA_NVFP4_DEC_SM120=0 disables at runtime).
bool nvfp4_decode_sm120_available() noexcept;
/// Test/benchmark override: -1 = follow STRATA_NVFP4_DEC_SM120 env (default), 0 = disable, 1 = enable.
void nvfp4_decode_sm120_set_override(int mode) noexcept;
/// Hardware Blackwell sm_120a grouped NVFP4 (type 40) MoE decode/verify (fused gate+up+SwiGLU+Q8_1 -> down).
/// Uses native PTX cvt.rn.f16x2.e2m1x2 + K-chunked split-half FP16 shared-memory activation caching across up to
/// 8 tokens per expert group, reading weights once per group. Returns false if unsupported shape/device.
bool nvfp4_decode_sm120_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr,
const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst,
const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries,
const void* x_q8_1, void* hq_scratch, float* out, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,105 @@
// include/strata/kernels/pdl.hpp - programmatic dependent launch (PDL) for the verify window's kernel chain.
//
// On sm_90+ a kernel launched with cudaLaunchAttributeProgrammaticStreamSerialization may start while the kernel
// before it is still running: everything before `pdl_wait()` overlaps that kernel (and its launch latency), everything
// after it sees the kernel's writes, exactly as after an ordinary launch. The kernels that opt in only LOAD constant
// weights before `pdl_wait()` and write nothing, so every value they compute is unchanged. `pdl_trigger()` lets the
// next kernel launch early (it still waits for this grid to finish before it reads anything). Their activations and
// outputs are not `__restrict__` on CUDA (STRATA_PDL_RESTRICT): with it the compiler may load them before the wait
// (the reason llama.cpp's PDL drops __restrict__ too); the weights keep it.
//
// Stream capture turns the attribute into a programmatic graph edge, which CUDA allows only between two kernel nodes.
// `launch_pdl` therefore uses it only while `pdl_scope()` is set (the verify window's recorder, on a device where
// `pdl_supported()`), only for a kernel whose code was built for sm_90+ (PTX of an older architecture, JIT-compiled,
// has no griddepcontrol.wait: such a kernel would race), and only when every node the capturing stream's next node
// depends on is a kernel - never after a memcpy, a memset, a host node or an event node. After a join of branches
// (several kernels) each edge is programmatic and the wait covers them all; STRATA_DF_PDL=2 allows one predecessor
// only. Everything else is an ordinary launch. On HIP all of this is an ordinary launch, the device functions are
// no-ops and the kernels keep their plain loops (kPdlPrefetch).
#pragma once
#include <cuda_runtime.h>
#include "strata/core/dispatch_stats.hpp"
#include <utility>
namespace strata::kernels {
/// Whether launches on this thread may carry the PDL attribute (set by the verify window's recorder).
bool& pdl_scope();
/// The current device runs PDL: a CUDA 12.3+ build, sm_90+ (STRATA_EMULATE_CC counts), code built for it, and
/// STRATA_DF_PDL is set (1, or 2 for single-predecessor edges only). Always false on HIP.
bool pdl_supported();
#if (defined(__CUDACC__) || defined(__HIPCC__))
// STRATA_PDL_RESTRICT never goes on a __global__ signature: the host pass and the stub must see the same signature on
// every architecture (MSVC rejects the template stubs otherwise, and so does g++ when the stub is generated from a
// device pass). A kernel takes plain pointers and declares `const T* STRATA_PDL_RESTRICT p = p_;` locals in its body.
// On CUDA the activation pointers lose __restrict__ so the compiler cannot load them before pdl_wait() - but only
// where PDL can run (sm_70 and newer here). On Pascal and older (__CUDA_ARCH__ < 700, no PDL) `__restrict__` is what
// lets the compiler use the read-only data path (LDG.CI): without it decode on sm_61 halves (#1469).
#if defined(__HIPCC__)
#define STRATA_PDL_RESTRICT __restrict__
#elif defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700)
#define STRATA_PDL_RESTRICT __restrict__
#else
#define STRATA_PDL_RESTRICT
#endif
#if defined(__HIPCC__)
inline constexpr bool kPdlPrefetch = false; // HIP: no PDL, the kernels keep their plain loops
#else
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700)
inline constexpr bool kPdlPrefetch = false; // Pascal and older: no PDL, the prefetch only costs registers (#1469)
#else
inline constexpr bool kPdlPrefetch = true; // CUDA: the weights a kernel can load before pdl_wait() are loaded there
#endif
/// `kernel` may be launched with the PDL attribute into `stream` now (see the header comment).
bool pdl_launch_ok(const void* kernel, cudaStream_t stream);
#endif
__device__ __forceinline__ void pdl_wait() {
#if !defined(__HIPCC__) && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)
asm volatile("griddepcontrol.wait;" ::: "memory");
#endif
}
__device__ __forceinline__ void pdl_trigger() {
#if !defined(__HIPCC__) && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)
asm volatile("griddepcontrol.launch_dependents;" :::);
#endif
}
/// `kernel<<<grid, block, smem, stream>>>(args...)`, with the PDL attribute when `pdl_launch_ok` says so. A launch
/// error stays the thread's last error for the caller's own check (cudaGetLastError) to report.
template <typename... KArgs, typename... Args>
inline void launch_pdl(void (*kernel)(KArgs...), dim3 grid, dim3 block, size_t smem, cudaStream_t stream,
Args&&... args) {
#if !defined(__HIPCC__)
// BW-MEASURE: inside the verify recorder with STRATA_DF_PDL on, the two notes below say whether a launch got the programmatic edge
if (pdl_scope() && pdl_launch_ok((const void*) kernel, stream)) {
strata::dispatch::note("pdl: launch with a programmatic edge");
cudaLaunchConfig_t cfg = {};
cfg.gridDim = grid;
cfg.blockDim = block;
cfg.dynamicSmemBytes = smem;
cfg.stream = stream;
cudaLaunchAttribute attr[1];
attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attr[0].val.programmaticStreamSerializationAllowed = 1;
cfg.attrs = attr;
cfg.numAttrs = 1;
(void) cudaLaunchKernelEx(&cfg, kernel, std::forward<Args>(args)...);
return;
}
if (pdl_scope()) strata::dispatch::note("pdl: ordinary launch inside a PDL window (kernel not sm_90 code, or a predecessor is not a kernel)");
#endif
kernel<<<grid, block, smem, stream>>>(std::forward<Args>(args)...);
}
#endif // __CUDACC__ || __HIPCC__
} // namespace strata::kernels
@@ -0,0 +1,50 @@
// include/strata/kernels/q8_1_finite.hpp - #606: the q8_1 activation block's scale and sum, kept finite.
//
// A q8_1 block stores its scale d = amax / 127 and the sum of its 32 raw activations as fp16. A sum past 65504 (one
// massive-activation dimension among 32 values is enough) rounds to inf, and d does past amax = 8.3M; the dot
// products then read inf * 0 = NaN, and a NaN in the residual ends as one token repeated (ggml-org/llama.cpp#23606
// is the same defect). Clamped to the largest finite half, such a block gives an approximate product instead of NaN,
// and the values are held to the int8 range they then exceed. Every block that was finite before is stored bit for
// bit as before: values in (65504, 65520) round to 65504 anyway, and a finite block's |x / d| is at most 127. A NaN
// stays NaN (the comparisons are false for it), so STRATA_DBG_NAN still sees one.
#pragma once
#include <cuda_fp16.h>
namespace strata::kernels {
constexpr float kHalfMax = 65504.0f;
__device__ __forceinline__ float q8_1_finite(const float v) {
return fabsf(v) > kHalfMax ? copysignf(kHalfMax, v) : v;
}
/// #3948: native_mmvq.cu (native_quantize_q8_1, the separate quantiser every consumer of a q8_1 image was written for)
/// is compiled with --use_fast_math, which makes `a / b` the fast full-range division (div.full.f32, up to 2 ulp off). The
/// fused producers (fused_gr.cu's hyper-connection read, verify_kernels.cu's GDN output norm: STRATA_QFUSE) are not, so
/// their IEEE division gave a different code at the rare element whose x / d lies next to a rounding boundary (found by
/// gr_parity: one code in about 10^6, off by one). A translation unit that defines STRATA_Q81_FASTMATH_DIV before including
/// this header divides the way the fast-math one does; every other one, and every HIP build, keeps `a / b` (so nothing
/// that compiled before this changes).
__device__ __forceinline__ float q81_div(const float a, const float b) {
#if defined(STRATA_Q81_FASTMATH_DIV) && defined(__CUDA_ARCH__) && !defined(__HIPCC__)
float r;
asm("div.full.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b));
return r;
#else
return a / b;
#endif
}
/// The block's quantized value of `xi` for the (finite) scale `d`; `amax` = 0 is an all-zero block.
__device__ __forceinline__ int8_t q8_1_quant(const float xi, const float d, const float amax) {
if (amax == 0.0f) return 0;
const float q = roundf(q81_div(xi, d));
return (int8_t) (q > 127.0f ? 127.0f : q < -127.0f ? -127.0f : q);
}
__device__ __forceinline__ half2 q8_1_ds(const float d, const float sum) {
return make_half2(__float2half(q8_1_finite(d)), __float2half(q8_1_finite(sum)));
}
} // namespace strata::kernels

Some files were not shown because too many files have changed in this diff Show More