Compare commits

...
Author SHA1 Message Date
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
grenadeandClaude Opus 5.5 0898d13718 docs: the symmetric-FSQ trap and the cover instruction
CI / Config consistency (push) Successful in 11s
CI / Classify changes (push) Successful in 16s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 15s
CI / Clippy (push) Successful in 2m51s
CI / Test (push) Successful in 6m23s
CI / CUDA type-check (push) Successful in 19m58s
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:57:49 +03:00
grenadeandClaude Opus 5.5 9740812517 fix(neuron): ACE-Step FSQ is symmetric; planned renders take the cover instruction; auto plans
CI / Config consistency (push) Successful in 10s
CI / Format (push) Canceled after 0s
CI / Web (lint + typecheck + i18n + build) (push) Canceled after 0s
CI / Clippy (push) Canceled after 0s
CI / Test (push) Canceled after 0s
CI / CUDA type-check (push) Canceled after 0s
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 / Classify changes (push) Canceled after 17s
Three fixes that take a planned render to parity with upstream's
vocal_en_30s_plan trace (latents rel L2 4.6e-6, waveform 1.6e-5, in f32
on the CPU), and turn the planner on by default (#384).

- ResidualFSQ: vector_quantize_pytorch builds its FSQ layers with
  preserve_symmetry=True, so level k of L decodes to 2k/(L-1) - 1. The
  vendored port used the asymmetric formula and skewed every planner
  hint by 18%. Encoding gets the library's soft clamp and hard-clamped
  bound too. The tests are now pinned to values recorded from the
  library, not re-derived from the port's own formula.
- The DiT instruction: upstream turns text2music into a cover when the
  planner supplies codes, and the text encoder sees "Generate audio
  semantic tokens…" instead of "Fill the audio semantic mask…".
- `planner: "auto"` (and no planner field) now runs the planner when
  the model has one, the vendor default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:57:31 +03:00
grenadeandClaude Opus 5.5 1065ffa12e feat(neuron): the ACE-Step planner matches upstream — constrained CoT, YAML re-dump, CFG codes
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 15s
CI / Clippy (push) Successful in 2m58s
CI / Test (push) Successful in 7m4s
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 17m0s
The planner now generates as upstream's generate_with_stop_condition
does (#384), and in f32 with greedy decoding reproduces upstream's trace
exactly: the 164-token CoT byte for byte and all 150 audio codes of the
vocal_en_30s_plan case.

- CoT phase: a port of MetadataConstrainedLogitsProcessor (fsm.rs) —
  the field grammar, prefix trees built from how the tokenizer splits
  each value after its field name, the caption's free-form ending, and
  the stop where </think> would begin. No CFG in this phase.
- Codes phase: a fresh prompt carrying the plan as upstream re-dumps it
  with yaml.dump (cot.rs, PyYAML's folding at column 80 and its quoting
  rules), ending </think>\n\n; CFG 2.0 against the unconditional
  "NO USER INPUT" prompt with empty reasoning, on a cloned model whose
  KV cache is its own; EOS forced at exactly five codes per second.
- The plan is read back as parse_lm_output does, so the caption the DiT
  sees is unfolded to one line.
- Prompts prefill in one forward, and token text is only ever decoded
  whole, so a multi-byte character split across tokens survives.

The reference parity test runs planned cases through the planner, and
acestep_planner_matches_reference pins the trace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:40:17 +03:00
grenadeandClaude Opus 5.5 f9613c0a11 feat(neuron): an ACE-Step planner can be its own repo
CI / Config consistency (push) Successful in 11s
CI / Classify changes (push) Successful in 16s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 13s
CI / Clippy (push) Successful in 2m45s
CI / Test (push) Successful in 6m22s
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 17m45s
The 0.6B planner, the one an 8 GB card can hold, ships as
ACE-Step/acestep-5Hz-lm-0.6B rather than inside the main snapshot.
`[harness.candle.audio] planner` now takes a repo id as well as a
snapshot subfolder, fetched through the same registry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:22:16 +03:00
grenadeandClaude Opus 5.5 fe5a1a826f docs: ACE-Step layouts, measured peaks, and the padded ConvTranspose1d trap
CI / Config consistency (push) Successful in 12s
CI / Classify changes (push) Successful in 18s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
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 13s
CI / Format (push) Canceled after 14s
CI / Clippy (push) Canceled after 11s
CI / Test (push) Canceled after 11s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:21:38 +03:00
grenadeandClaude Opus 5.5 de2378b8b3 perf(neuron): ACE-Step VAE upsamples through candle's matmul path; per-phase timings
CI / Config consistency (push) Successful in 10s
CI / Format (push) Canceled after 0s
CI / Web (lint + typecheck + i18n + build) (push) Canceled after 0s
CI / Clippy (push) Canceled after 0s
CI / Test (push) Canceled after 0s
CI / CUDA type-check (push) Canceled after 0s
CI / Build cortex SRPM (push) Canceled after 0s
CI / Build neuron SRPM (push) Canceled after 0s
CI / Classify changes (push) Canceled after 16s
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
candle's CUDA backend computes a transposed 1-D convolution by col2im
(a matmul) only when it is unpadded; the Oobleck decoder's upsampling
layers are padded, so they fell back to a direct kernel. The decoder
now runs them unpadded and trims the padding from the output, which is
the same result. Measured, q8 on an RTX 3060: a 30 s song's decode
22.8 s -> 4.3 s. bf16 on an RTX 4090: a 480 s song 27.3 s -> 9.1 s.

ACE-Step renders now report encode, denoise and decode time separately
(each phase ends with a device synchronize), instead of one number.

The layout drift check judges the mean across cases against upstream
bf16's mean: single-case drift swings with tiny numeric differences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:21:18 +03:00
grenadeandClaude Opus 5.5 a4fbe929ea feat(neuron): ACE-Step memory layouts — q8 ISQ, per-component placement, a VRAM budget
CI / Classify changes (push) Successful in 16s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Config consistency (push) Successful in 16s
CI / Format (push) Successful in 15s
CI / Clippy (push) Successful in 3m16s
CI / Test (push) Successful in 6m23s
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 9m30s
`[harness.candle.audio]` describes how this host lays out an ACE-Step
pipeline (#385):

- `quant = "q8_0"` quantizes the DiT's, the text encoder's and the
  planner's linear layers in situ; a quantized pipeline computes in f32,
  which is also the recipe for cards without fast half precision.
- `compute = "f32"` for unquantized f32 compute.
- `placement.{text_encoder,planner,dit,vae} = "gpu" | "cpu"`. Only the
  prompt's hidden states and the denoised latents cross devices.
- `planner` names one planner subfolder, or "none".
- `vram_budget_mb` decodes the VAE in smaller chunks;
  `enforce_vram_budget` holds the rest of the card's free memory so a
  large card rehearses a small one.
- `max_duration_secs` caps songs below the model's own limit.

The vendored modules now build their projections through a local
`Linear` that is dense or `QMatMul`, chosen by a load-time scope, so the
vendored code stays an import change away from upstream.

The 0.6B planner keeps the `model.` prefix the 1.7B one drops; the
loader now detects which, instead of failing the 0.6B silently.

`acestep_profile_gpu` measures peak VRAM and latency per song length
for a layout, and the reference parity test can measure any layout's
drift on a GPU, bounded by upstream's own bf16 drift for that case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:11:26 +03:00
grenadeandClaude Opus 5.5 1bd8991053 Merge branch 'fix/376-models-unhealthy-node': /v1/models agrees with routing about unhealthy neurons
build-prerelease / Resolve version stamps + change detection (push) Successful in 21s
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 / Lint (fmt + clippy) (push) Successful in 3m30s
build-prerelease / Build neuron-ada (push) Successful in 2m37s
build-prerelease / Test (push) Successful in 12m10s
build-prerelease / Build neuron-blackwell (push) Successful in 16m35s
build-prerelease / Build neuron-ampere (push) Successful in 22m57s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m20s
build-prerelease / Package helexa-neuron-ampere RPM (push) Successful in 3m59s
build-prerelease / Package helexa-neuron-blackwell RPM (push) Successful in 4m4s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 18:06:42 +03:00
99 changed files with 21611 additions and 1201 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 }}
+87 -8
View File
@@ -1301,14 +1301,37 @@ render.
upstream CPU f32 reference is ~1e-5 with it.
- **Seeding is host-side** (SplitMix64 + Box-Muller): candle's CPU
`set_seed` is unsupported, and a host RNG makes CPU and GPU agree.
- **The ACE planner checkpoint has no `model.` prefix**; it is renamed at
load. A planner that fails to load is non-fatal. It stays off unless
`planner: "on"` until #384 closes the parity gaps (code-phase CFG,
constrained decoding).
- **The 1.7B planner checkpoint has no `model.` prefix; the 0.6B one
does.** The loader strips it only where it is absent. A planner that
fails to load is non-fatal, so a wrong prefix shows up only as a
warning and `plan_ms: 0`.
- **The planner matches upstream exactly (#384)** — in f32 with greedy
decoding, the CoT byte for byte and every audio code of the trace — and
`auto` (the default) now runs it. That parity rests on three things a
port gets wrong easily: the CoT grammar (`fsm.rs`, a port of
`MetadataConstrainedLogitsProcessor`); the codes prompt, which carries
the plan *re-dumped by PyYAML* (`cot.rs`: folded at column 80, quoting
values that would read back as bools or numbers); and CFG 2.0 in the
codes phase only, against `NO USER INPUT` with empty reasoning.
Upstream's own bf16 already picks a different first code, so judge
parity in f32.
- **ACE-Step's FSQ is the symmetric variant.** `vector_quantize_pytorch`'s
`ResidualFSQ` builds its layers with `preserve_symmetry=True` (level k
of L → `2k/(L-1) − 1`). The vendored port had the asymmetric formula
and tests re-derived from that same formula, so they passed while every
planner hint was 18% off. Pin vendored maths to values recorded from
the reference library, never to the port's own arithmetic. With codes,
upstream also switches the DiT instruction to the cover one.
- **Levels follow each upstream.** ACE-Step peak-normalises to −1 dBFS;
HeartMuLa does not.
- **ACE timing is one number.** `text2music` is a single call, so
`generate_ms` covers encode + denoise + VAE.
- **ACE timing is split** into `encode_ms`, `generate_ms` (denoise) and
`decode_ms` (VAE). Each phase ends with a device synchronize, so queued
GPU work is charged to the phase that queued it.
- **candle only uses its fast transposed-conv path when unpadded.** The
Oobleck decoder runs its upsampling unpadded and trims the padding
from the output (identical result). Before that, the VAE decode was
~95% of a render: 22.8 s for a 30 s song on a 3060, 27 s for 480 s on
benjy. Watch for the same trap in any padded `ConvTranspose1d`.
- **HeartMuLa's first decode after load is slow** (~33 s, one-time
warm-up); every decode after that is ~2 s per 10 s of audio.
- **benjy's root drive is slow under pressure** (DRAM-less, 90% full;
@@ -1322,6 +1345,62 @@ render.
**Retired:** the PyTorch evaluation beta (`beta.music.helexa.ai`, #388).
Its ratings data is archived privately.
**Next:** #384 (planner parity), #385 (q8 + an 8 GB profile), and the
Pascal epic #380 (rig work waits until rigs are named; the fallback if
**Layouts (#385).** `[harness.candle.audio]` in neuron.toml sets, per
host: `quant = "q8_0"` (DiT, text encoder and planner linears, f32
compute), `compute = "f32"`, `placement.<component> = "gpu" | "cpu"`,
`planner = "<subfolder>" | "none"`, `max_duration_secs`, and
`vram_budget_mb` (smaller VAE chunks). `enforce_vram_budget` holds the
rest of the card's memory so a 24 GB card rehearses an 8 GB one.
Measured peaks (process, CUDA context included):
| Layout | Resident | 180 s song | 240 s | 480 s |
|---|---|---|---|---|
| bf16, no planner | 6.4 GB | 7.8 GB | 7.8 GB | 9.1 GB |
| q8 + 8 GiB budget, no planner | 4.6 GB | 6.0 GB | 6.2 GB | 10.0 GB |
| q8 + 8 GiB budget + 0.6B planner | 5.8 GB | 7.6 GB | 7.9 GB | 13.1 GB |
| dense f32 | 13.2 GB | — | — | — |
So an 8 GB card serves q8 with the 0.6B planner up to 240 s; beyond
that a term grows with the square of song length. q8's mean latent drift
from upstream's f32 reference (0.26 rel L2 over four cases) is smaller
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())
}
+8
View File
@@ -16,6 +16,11 @@ 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-mtp-probe"
path = "src/bin/mtp_probe.rs"
@@ -48,6 +53,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"]
+68
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,72 @@ 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-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 sources = [
// UD-IQ4_XS has no NVFP4 experts, so upstream's stub satisfies
// the reference from the grouped dispatch.
(
"strata_nvfp4_absent.o",
vendor.join("src/kernels/cuda/nvfp4_decode_sm120_absent.cpp"),
),
(
"strata_iq_kernels.o",
vendor.join("src/kernels/cuda/iq_kernels.cu"),
),
(
"strata_shim.o",
root.join("src/cuda/strata_adapter/strata_shim.cu"),
),
(
"strata_probe.o",
root.join("src/cuda/strata_adapter/strata_probe.cu"),
),
];
let mut objects = Vec::new();
for (name, source) in &sources {
let object = build_dir.join(name);
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());
objects.push(object);
}
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");
}
}
}
@@ -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]
);
}
+72
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
@@ -138,6 +142,73 @@ pub struct CandleHarnessConfig {
/// text-to-image pipeline.
#[serde(default)]
pub image: ImageConfig,
/// `[harness.candle.audio]` settings (#385) — how an ACE-Step
/// pipeline is laid out on this host.
#[serde(default)]
pub audio: AudioConfig,
}
/// `[harness.candle.audio]` settings (#385).
///
/// These describe the host, not the model, which is why they live here
/// and not in the catalogue: the same ACE-Step id serves bf16 on a 4090
/// and q8 with f32 compute on an 8 GB Pascal card.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AudioConfig {
/// In-situ weight quantization of the DiT, the text encoder and the
/// planner: `"q8_0"`, or unset for none. Quantized components compute
/// in f32. The VAE is never quantized.
#[serde(default)]
pub quant: Option<String>,
/// Compute dtype of the unquantized GPU components: `"bf16"`
/// (default) or `"f32"`. Cards without fast bf16 (Pascal) need f32.
#[serde(default)]
pub compute: Option<String>,
/// Where each component runs.
#[serde(default)]
pub placement: AudioPlacement,
/// Which planner LM to load: a snapshot subfolder (for example
/// `"acestep-5Hz-lm-1.7B"`), a repo id of its own (the 0.6B planner is
/// `"ACE-Step/acestep-5Hz-lm-0.6B"`), or `"none"`. Unset takes the
/// largest the snapshot has.
#[serde(default)]
pub planner: Option<String>,
/// Treat the device as having this much free memory for the pipeline,
/// in MiB. Under a budget the VAE decodes in smaller chunks.
#[serde(default)]
pub vram_budget_mb: Option<u64>,
/// Make the budget real by holding the rest of the device's free
/// memory while the pipeline is loaded, so a larger card fails exactly
/// where a card of the budget's size would. For rehearsing a small
/// card's profile on a large one; never for serving.
#[serde(default)]
pub enforce_vram_budget: bool,
/// Longest song this host accepts, in seconds, when it is less than
/// 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
/// default) or `"cpu"`. CPU components compute in f32.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AudioPlacement {
#[serde(default)]
pub text_encoder: Option<String>,
#[serde(default)]
pub planner: Option<String>,
#[serde(default)]
pub dit: Option<String>,
#[serde(default)]
pub vae: Option<String>,
}
/// `[harness.candle.image]` settings (#198).
@@ -534,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;
+85
View File
@@ -0,0 +1,85 @@
//! 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;
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,
);
}
@@ -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,77 @@
// 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;
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));
}
} // extern "C"
@@ -13,9 +13,10 @@
//! All encoder layers share the same architecture: pre-norm (RmsNorm) bidirectional
//! GQA attention followed by a gated SiLU MLP, matching the Qwen3 block design.
use super::linear::{Linear, linear_b, linear_no_bias};
use candle_core::{DType, Device, Module, Result, Tensor};
use candle_nn::{Activation, VarBuilder};
use candle_transformers::models::with_tracing::{Linear, RmsNorm, linear_b, linear_no_bias};
use candle_transformers::models::with_tracing::RmsNorm;
use candle_transformers::utils::repeat_kv;
use super::AceStepConfig;
@@ -0,0 +1,615 @@
//! The planner's chain of thought, as text (#384).
//!
//! The planner writes its plan as YAML between `<think>` tags. Upstream
//! reads it back with `parse_lm_output`, then writes it out again with
//! `yaml.dump` to build the prompt the audio codes are generated from. Those
//! bytes are model input, so the dump has to be reproduced exactly,
//! including where PyYAML folds a long caption and when it quotes a value.
//!
//! Reference: `acestep/llm_inference.py` (`parse_lm_output`,
//! `_format_metadata_as_cot`) and `acestep/constrained_logits_processor.py`
//! (`postprocess_caption`) at ACE-Step 1.5 `ca1e85fe`; PyYAML's
//! `emitter.py` for the scalar writers.
use std::collections::BTreeMap;
/// A plan field's value as upstream holds it: `int(...)` where the text is
/// a whole number, the text otherwise. The distinction decides how YAML
/// writes it.
#[derive(Debug, Clone, PartialEq)]
pub enum MetaValue {
Int(i64),
Str(String),
}
impl MetaValue {
pub fn as_text(&self) -> String {
match self {
Self::Int(i) => i.to_string(),
Self::Str(s) => s.clone(),
}
}
}
/// The plan's fields, by name.
pub type Metadata = BTreeMap<String, MetaValue>;
/// Fields the codes-phase prompt carries, in the order YAML sorts them.
const COT_FIELDS: [&str; 6] = [
"bpm",
"caption",
"duration",
"keyscale",
"language",
"timesignature",
];
/// Join a YAML-folded caption back into one line: every line trimmed,
/// blank lines dropped, joined with single spaces.
pub fn postprocess_caption(caption: &str) -> String {
caption
.split('\n')
.map(str::trim)
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
/// Python's `str.isdigit` for the ASCII digits upstream's values use.
fn is_digits(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
}
/// Read a plan out of the planner's output, as `parse_lm_output` does.
///
/// The CoT phase stops before `</think>`, so the reasoning section is the
/// text between the tags when both are present, else everything before the
/// first audio code. A field is a line that does not start with whitespace
/// and has a colon; indented lines continue the previous field.
pub fn parse_plan(output: &str) -> Metadata {
let reasoning = match (output.find("<think>"), output.find("</think>")) {
(Some(s), Some(e)) if e > s => output[s + "<think>".len()..e].trim().to_string(),
_ => output
.split("<|audio_code_")
.next()
.unwrap_or("")
.trim()
.to_string(),
};
let mut meta = Metadata::new();
let mut key: Option<String> = None;
let mut lines: Vec<&str> = Vec::new();
let save = |key: &mut Option<String>, lines: &mut Vec<&str>, meta: &mut Metadata| {
if let Some(k) = key.take()
&& !lines.is_empty()
{
let value = lines.join("\n");
let v = match k.as_str() {
"bpm" | "duration" => match value.trim().parse::<i64>() {
Ok(i) => MetaValue::Int(i),
Err(_) => MetaValue::Str(value.trim().to_string()),
},
"caption" => MetaValue::Str(postprocess_caption(&value)),
"genres" | "keyscale" | "language" | "timesignature" => {
MetaValue::Str(value.trim().to_string())
}
_ => {
lines.clear();
return;
}
};
meta.insert(k, v);
}
lines.clear();
};
for line in reasoning.split('\n') {
if line.trim().starts_with('<') {
continue;
}
let starts_blank = line.chars().next().is_some_and(char::is_whitespace);
if !line.is_empty() && !starts_blank && line.contains(':') {
save(&mut key, &mut lines, &mut meta);
let (k, v) = line.split_once(':').unwrap_or((line, ""));
key = Some(k.trim().to_lowercase());
if !v.trim().is_empty() {
lines.push(v);
}
} else if (line.starts_with(' ') || line.starts_with('\t')) && key.is_some() {
lines.push(line);
}
}
save(&mut key, &mut lines, &mut meta);
meta
}
/// The CoT block the codes phase is prompted with, as
/// `_format_metadata_as_cot` builds it: `<think>\n{yaml}\n</think>`.
pub fn format_plan(meta: &Metadata) -> String {
let mut yaml = String::new();
for key in COT_FIELDS {
let Some(value) = meta.get(key) else {
continue;
};
let value = match value {
MetaValue::Str(s) if key == "timesignature" && s.ends_with("/4") => {
MetaValue::Str(s.split('/').next().unwrap_or("").to_string())
}
v => v.clone(),
};
let value = match value {
MetaValue::Str(s) if is_digits(&s) => match s.parse::<i64>() {
Ok(i) => MetaValue::Int(i),
Err(_) => MetaValue::Str(s),
},
v => v,
};
yaml.push_str(&yaml_entry(key, &value));
}
format!("<think>\n{}\n</think>", yaml.trim())
}
// ── A PyYAML block-mapping entry ─────────────────────────────────────
/// PyYAML's default line width and mapping indent.
const BEST_WIDTH: usize = 80;
const INDENT: usize = 2;
/// One `key: value\n` line (or lines) of `yaml.dump(..., allow_unicode=True)`.
fn yaml_entry(key: &str, value: &MetaValue) -> String {
let mut w = Writer {
out: format!("{key}:"),
column: key.chars().count() + 1,
};
match value {
MetaValue::Int(i) => {
w.out.push(' ');
w.out.push_str(&i.to_string());
}
MetaValue::Str(s) => match scalar_style(s) {
Style::Plain => w.plain(s),
Style::SingleQuoted => w.single_quoted(s),
Style::DoubleQuoted => w.double_quoted(s),
},
}
w.out.push('\n');
w.out
}
#[derive(Debug, PartialEq)]
enum Style {
Plain,
SingleQuoted,
DoubleQuoted,
}
fn is_ws(c: Option<char>) -> bool {
matches!(
c,
None | Some('\0' | ' ' | '\t' | '\r' | '\n' | '\u{85}' | '\u{2028}' | '\u{2029}')
)
}
fn is_break(c: char) -> bool {
matches!(c, '\n' | '\u{85}' | '\u{2028}' | '\u{2029}')
}
/// `choose_scalar_style` for a block-mapping value: plain when PyYAML's
/// analysis allows a block plain scalar and the text would read back as a
/// string, else single-quoted when allowed, else double-quoted.
fn scalar_style(s: &str) -> Style {
if s.is_empty() {
// An empty value would read back as null.
return Style::SingleQuoted;
}
let chars: Vec<char> = s.chars().collect();
let n = chars.len();
let mut block_indicators = s.starts_with("---") || s.starts_with("...");
let mut line_breaks = false;
let mut special = false;
let (mut leading_space, mut leading_break, mut trailing_space, mut trailing_break) =
(false, false, false, false);
let (mut break_space, mut space_break) = (false, false);
let (mut previous_space, mut previous_break) = (false, false);
let mut preceded_by_ws = true;
for i in 0..n {
let ch = chars[i];
let followed_by_ws = is_ws(chars.get(i + 1).copied());
if i == 0 {
if "#,[]{}&*!|>'\"%@`".contains(ch) {
block_indicators = true;
}
if "?:".contains(ch) && followed_by_ws {
block_indicators = true;
}
if ch == '-' && followed_by_ws {
block_indicators = true;
}
} else {
if ch == ':' && followed_by_ws {
block_indicators = true;
}
if ch == '#' && preceded_by_ws {
block_indicators = true;
}
}
if is_break(ch) {
line_breaks = true;
}
if !(ch == '\n' || (' '..='~').contains(&ch)) {
let printable = ch == '\u{85}'
|| ('\u{A0}'..='\u{D7FF}').contains(&ch)
|| ('\u{E000}'..='\u{FFFD}').contains(&ch)
|| ('\u{10000}'..'\u{10FFFF}').contains(&ch);
// allow_unicode=True: printable non-ASCII is fine.
if !printable || ch == '\u{FEFF}' {
special = true;
}
}
if ch == ' ' {
leading_space |= i == 0;
trailing_space |= i == n - 1;
break_space |= previous_break;
previous_space = true;
previous_break = false;
} else if is_break(ch) {
leading_break |= i == 0;
trailing_break |= i == n - 1;
space_break |= previous_space;
previous_space = false;
previous_break = true;
} else {
previous_space = false;
previous_break = false;
}
preceded_by_ws = is_ws(Some(ch));
}
let mut allow_plain = true;
let mut allow_single = true;
if leading_space || leading_break || trailing_space || trailing_break {
allow_plain = false;
}
if break_space {
allow_plain = false;
allow_single = false;
}
if space_break || special {
allow_plain = false;
allow_single = false;
}
if line_breaks || block_indicators {
allow_plain = false;
}
if allow_plain && resolves_as_string(s) {
Style::Plain
} else if allow_single {
Style::SingleQuoted
} else {
Style::DoubleQuoted
}
}
/// Whether a plain scalar with this text would read back as a string under
/// PyYAML's YAML 1.1 implicit resolvers (bool, int, float, null, merge,
/// value, timestamp). Anything else needs quoting.
fn resolves_as_string(s: &str) -> bool {
const BOOLS: [&str; 18] = [
"yes", "Yes", "YES", "no", "No", "NO", "true", "True", "TRUE", "false", "False", "FALSE",
"on", "On", "ON", "off", "Off", "OFF",
];
const NULLS: [&str; 4] = ["~", "null", "Null", "NULL"];
if BOOLS.contains(&s) || NULLS.contains(&s) || s == "<<" || s == "=" {
return false;
}
!(is_yaml_int(s) || is_yaml_float(s) || is_yaml_timestamp(s))
}
fn strip_sign(s: &str) -> &str {
s.strip_prefix(['-', '+']).unwrap_or(s)
}
/// PyYAML's int resolver: binary, octal, decimal, hex and sexagesimal,
/// with `_` separators.
fn is_yaml_int(s: &str) -> bool {
let b = strip_sign(s);
let all = |t: &str, ok: fn(char) -> bool| !t.is_empty() && t.chars().all(|c| ok(c) || c == '_');
if let Some(t) = b.strip_prefix("0b") {
return all(t, |c| c == '0' || c == '1');
}
if let Some(t) = b.strip_prefix("0x") {
return all(t, |c| c.is_ascii_hexdigit());
}
if b == "0" {
return true;
}
if let Some(t) = b.strip_prefix('0') {
return all(t, |c| ('0'..='7').contains(&c));
}
if b.starts_with(|c: char| ('1'..='9').contains(&c)) {
if all(b, |c| c.is_ascii_digit()) {
return true;
}
// Sexagesimal: [1-9][0-9_]*(:[0-5]?[0-9])+
let mut parts = b.split(':');
let head = parts.next().unwrap_or("");
let rest: Vec<&str> = parts.collect();
return !rest.is_empty()
&& all(head, |c| c.is_ascii_digit())
&& rest.iter().all(|p| {
let p: Vec<char> = p.chars().collect();
match p.as_slice() {
[d] => d.is_ascii_digit(),
[a, d] => ('0'..='5').contains(a) && d.is_ascii_digit(),
_ => false,
}
});
}
false
}
/// PyYAML's float resolver, including `.inf`, `.nan` and sexagesimal.
fn is_yaml_float(s: &str) -> bool {
let b = strip_sign(s);
if matches!(b, ".inf" | ".Inf" | ".INF") {
return true;
}
if matches!(s, ".nan" | ".NaN" | ".NAN") {
return true;
}
// [-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? and \.[0-9][0-9_]*(?:[eE][-+][0-9]+)?
let (mantissa, exp) = match b.find(['e', 'E']) {
Some(i) => (&b[..i], Some(&b[i + 1..])),
None => (b, None),
};
if let Some(e) = exp {
let digits = e.strip_prefix(['-', '+']);
if !digits.is_some_and(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit())) {
return false;
}
}
let Some((int, frac)) = mantissa.split_once('.') else {
// Sexagesimal float: [0-9][0-9_]*(:[0-5]?[0-9])+\.[0-9_]*
return false;
};
let digits_ = |t: &str| t.chars().all(|c| c.is_ascii_digit() || c == '_');
if int.is_empty() {
frac.starts_with(|c: char| c.is_ascii_digit()) && digits_(frac)
} else {
int.starts_with(|c: char| c.is_ascii_digit()) && digits_(int) && digits_(frac)
}
}
/// PyYAML's timestamp resolver, enough to catch dates and date-times.
fn is_yaml_timestamp(s: &str) -> bool {
let c: Vec<char> = s.chars().collect();
c.len() >= 8
&& c[..4].iter().all(char::is_ascii_digit)
&& c[4] == '-'
&& c[5].is_ascii_digit()
&& c.iter().skip(5).take_while(|x| x.is_ascii_digit()).count() <= 2
&& s[5..].contains('-')
}
/// The emitter state a scalar writer needs: the text so far and the
/// current column.
struct Writer {
out: String,
column: usize,
}
impl Writer {
fn write(&mut self, s: &str) {
self.column += s.chars().count();
self.out.push_str(s);
}
/// `write_indent` mid-scalar: a line break and the mapping indent.
fn indent(&mut self) {
self.out.push('\n');
self.out.push_str(&" ".repeat(INDENT));
self.column = INDENT;
}
/// `write_plain` with `split=True`: a run of exactly one space past
/// the best width becomes a line break.
fn plain(&mut self, text: &str) {
self.write(" ");
let chars: Vec<char> = text.chars().collect();
let (mut spaces, mut start, mut end) = (false, 0usize, 0usize);
while end <= chars.len() {
let ch = chars.get(end).copied();
if spaces {
if ch != Some(' ') {
if start + 1 == end && self.column > BEST_WIDTH {
self.indent();
} else {
self.write(&chars[start..end].iter().collect::<String>());
}
start = end;
}
} else if ch.is_none() || ch == Some(' ') {
self.write(&chars[start..end].iter().collect::<String>());
start = end;
}
if let Some(c) = ch {
spaces = c == ' ';
}
end += 1;
}
}
/// `write_single_quoted` with `split=True` (no line breaks reach it:
/// captions are joined to one line first).
fn single_quoted(&mut self, text: &str) {
self.write(" '");
let chars: Vec<char> = text.chars().collect();
let n = chars.len();
let (mut spaces, mut start, mut end) = (false, 0usize, 0usize);
while end <= n {
let ch = chars.get(end).copied();
if spaces {
if ch != Some(' ') {
if start + 1 == end && self.column > BEST_WIDTH && start != 0 && end != n {
self.indent();
} else {
self.write(&chars[start..end].iter().collect::<String>());
}
start = end;
}
} else if (ch.is_none() || ch == Some(' ') || ch == Some('\'')) && start < end {
self.write(&chars[start..end].iter().collect::<String>());
start = end;
}
if ch == Some('\'') {
self.write("''");
start = end + 1;
}
if let Some(c) = ch {
spaces = c == ' ';
}
end += 1;
}
self.write("'");
}
/// Double quotes for text with control characters. PyYAML folds these
/// too; a plan never contains them, so this writes one line.
fn double_quoted(&mut self, text: &str) {
let mut s = String::from(" \"");
for c in text.chars() {
match c {
'"' => s.push_str("\\\""),
'\\' => s.push_str("\\\\"),
'\n' => s.push_str("\\n"),
'\t' => s.push_str("\\t"),
c if (c as u32) < 0x20 => s.push_str(&format!("\\x{:02X}", c as u32)),
c => s.push(c),
}
}
s.push('"');
self.write(&s);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture_planner() -> serde_json::Value {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("src/harness/testdata/acestep/vocal_en_30s_plan__cpu_f32.json");
let meta: serde_json::Value =
serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
meta["planner"].clone()
}
/// The codes-phase prompt upstream built from its own CoT output: the
/// plan read back, then dumped as YAML, folded at column 80.
#[test]
fn the_plan_round_trips_to_upstream_s_codes_prompt() {
let planner = fixture_planner();
let cot_out = planner[0]["output_text"].as_str().unwrap();
let codes_prompt = planner[1]["formatted_prompt"].as_str().unwrap();
let plan = parse_plan(cot_out);
assert_eq!(plan["bpm"], MetaValue::Int(130));
assert_eq!(plan["duration"], MetaValue::Int(30));
assert_eq!(plan["timesignature"], MetaValue::Str("4".into()));
let MetaValue::Str(caption) = &plan["caption"] else {
panic!("caption is text");
};
assert!(caption.starts_with("An energetic indie rock track"));
assert!(!caption.contains('\n'), "the caption is unfolded");
let cot = format_plan(&plan);
let start = codes_prompt.find("<think>").unwrap();
let want = &codes_prompt[start..codes_prompt.len() - "\n\n".len()];
assert_eq!(cot, want);
}
#[test]
fn values_that_would_read_back_as_something_else_are_quoted() {
assert_eq!(
yaml_entry("language", &MetaValue::Str("no".into())),
"language: 'no'\n"
);
assert_eq!(
yaml_entry("language", &MetaValue::Str("en".into())),
"language: en\n"
);
assert_eq!(
yaml_entry("keyscale", &MetaValue::Str("F# minor".into())),
"keyscale: F# minor\n"
);
assert_eq!(
yaml_entry("caption", &MetaValue::Str("Lo-fi: dusty drums".into())),
"caption: 'Lo-fi: dusty drums'\n"
);
assert_eq!(
yaml_entry("caption", &MetaValue::Str("'quoted' start".into())),
"caption: '''quoted'' start'\n"
);
assert_eq!(
yaml_entry("caption", &MetaValue::Str("1.5".into())),
"caption: '1.5'\n"
);
assert_eq!(yaml_entry("bpm", &MetaValue::Int(92)), "bpm: 92\n");
}
/// Recorded from PyYAML 6 (`yaml.dump({"caption": v}, allow_unicode=True,
/// sort_keys=True)`).
#[test]
fn scalars_match_pyyaml() {
let folded = "A track: ".to_string() + &"word ".repeat(30) + "end";
let cases: Vec<(String, &str)> = vec![
("no".into(), "caption: 'no'\n"),
("en".into(), "caption: en\n"),
("F# minor".into(), "caption: F# minor\n"),
(
"Lo-fi: dusty drums".into(),
"caption: 'Lo-fi: dusty drums'\n",
),
("'quoted' start".into(), "caption: '''quoted'' start'\n"),
("1.5".into(), "caption: '1.5'\n"),
(
folded,
"caption: 'A track: word word word word word word word word word word word word word\n word word word word word word word word word word word word word word word word\n word end'\n",
),
("yes".into(), "caption: 'yes'\n"),
("2024-01-02".into(), "caption: '2024-01-02'\n"),
("1:30".into(), "caption: '1:30'\n"),
("0x1F".into(), "caption: '0x1F'\n"),
("~".into(), "caption: '~'\n"),
("null".into(), "caption: 'null'\n"),
("- dash start".into(), "caption: '- dash start'\n"),
("tag #x".into(), "caption: 'tag #x'\n"),
("a#b".into(), "caption: a#b\n"),
("ends:".into(), "caption: 'ends:'\n"),
];
for (v, want) in cases {
assert_eq!(
yaml_entry("caption", &MetaValue::Str(v.clone())),
want,
"{v:?}"
);
}
}
#[test]
fn a_quoted_caption_folds_like_a_plain_one() {
let caption = "A track: ".to_string() + &"word ".repeat(30) + "end";
let entry = yaml_entry("caption", &MetaValue::Str(caption));
let lines: Vec<&str> = entry.trim_end().split('\n').collect();
assert!(lines[0].starts_with("caption: 'A track: word"));
assert!(lines.len() > 1);
assert!(lines[1..].iter().all(|l| l.starts_with(" ")));
assert!(lines[0].chars().count() > BEST_WIDTH);
}
#[test]
fn genres_and_unknown_fields_never_reach_the_prompt() {
let plan = parse_plan("<think>\nbpm: 90\ngenres: jazz\nmood: calm\n</think>");
assert!(plan.contains_key("genres"));
assert!(!plan.contains_key("mood"));
assert_eq!(format_plan(&plan), "<think>\nbpm: 90\n</think>");
}
}
@@ -14,11 +14,12 @@
//!
//! Reference: <https://huggingface.co/ACE-Step/ACE-Step-v1-3.5B>
use super::linear::{Linear, linear_b, linear_no_bias};
use candle_core::{D, DType, Device, Module, Result, Tensor};
use candle_nn::{
Activation, Conv1d, Conv1dConfig, ConvTranspose1d, ConvTranspose1dConfig, VarBuilder,
};
use candle_transformers::models::with_tracing::{Linear, RmsNorm, linear_b, linear_no_bias};
use candle_transformers::models::with_tracing::RmsNorm;
use candle_transformers::utils::repeat_kv;
use super::AceStepConfig;
@@ -0,0 +1,579 @@
//! Constrained decoding of the planner's chain of thought (#384).
//!
//! A port of upstream's `MetadataConstrainedLogitsProcessor` as the CoT
//! phase uses it: genres skipped, caption and language generated, no
//! user-provided fields, and generation stopped where `</think>` would
//! begin (`stop_at_reasoning`). It walks
//!
//! ```text
//! <think> \n bpm: <30..300> \n caption: <free text> \n duration: <10..600> \n
//! keyscale: <note[acc] major|minor> \n language: <code> \n timesignature: <2|3|4|6> \n
//! ```
//!
//! and ends in EOS. Each step it masks the logits to what the current state
//! allows; after sampling it advances on the token chosen. Field values are
//! matched as token-id sequences against prefix trees built from how the
//! tokenizer actually splits `"bpm: 120"` and the like, as upstream does.
//!
//! Reference: `acestep/constrained_logits_processor.py` at ACE-Step 1.5
//! `ca1e85fe` (`_process_single_sequence`, `update_state`, and the prefix
//! tree builders).
use std::collections::{BTreeSet, HashMap};
use candle_core::Result;
/// Upstream's `BPM_MIN..=BPM_MAX`.
const BPM: (u32, u32) = (30, 300);
/// Upstream's `DURATION_MIN..=DURATION_MAX`.
const DURATION: (u32, u32) = (10, 600);
const TIME_SIGNATURES: [&str; 4] = ["2", "3", "4", "6"];
const KEYSCALE_NOTES: [&str; 7] = ["A", "B", "C", "D", "E", "F", "G"];
const KEYSCALE_ACCIDENTALS: [&str; 5] = ["", "#", "b", "♯", "♭"];
const KEYSCALE_MODES: [&str; 2] = ["major", "minor"];
/// Upstream's `VALID_LANGUAGES`, `unknown` included.
pub const LANGUAGES: [&str; 51] = [
"ar", "az", "bg", "bn", "ca", "cs", "da", "de", "el", "en", "es", "fa", "fi", "fr", "he", "hi",
"hr", "ht", "hu", "id", "is", "it", "ja", "ko", "la", "lt", "ms", "ne", "nl", "no", "pa", "pl",
"pt", "ro", "ru", "sa", "sk", "sr", "sv", "sw", "ta", "te", "th", "tl", "tr", "uk", "ur", "vi",
"yue", "zh", "unknown",
];
/// Caption tokens before the caption is forced to end.
const MAX_CAPTION_TOKENS: usize = 512;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
ThinkTag,
NewlineAfterThink,
BpmName,
BpmValue,
CaptionName,
CaptionValue,
DurationName,
DurationValue,
KeyscaleName,
KeyscaleValue,
LanguageName,
LanguageValue,
TimesigName,
TimesigValue,
ThinkEndTag,
Completed,
}
impl State {
fn fixed(self) -> Option<&'static str> {
Some(match self {
Self::ThinkTag => "<think>",
Self::NewlineAfterThink => "\n",
Self::BpmName => "bpm:",
Self::CaptionName => "caption:",
Self::DurationName => "duration:",
Self::KeyscaleName => "keyscale:",
Self::LanguageName => "language:",
Self::TimesigName => "timesignature:",
Self::ThinkEndTag => "</think>",
_ => return None,
})
}
/// Field order with genres skipped.
fn next(self) -> Self {
match self {
Self::ThinkTag => Self::NewlineAfterThink,
Self::NewlineAfterThink => Self::BpmName,
Self::BpmName => Self::BpmValue,
Self::BpmValue => Self::CaptionName,
Self::CaptionName => Self::CaptionValue,
Self::CaptionValue => Self::DurationName,
Self::DurationName => Self::DurationValue,
Self::DurationValue => Self::KeyscaleName,
Self::KeyscaleName => Self::KeyscaleValue,
Self::KeyscaleValue => Self::LanguageName,
Self::LanguageName => Self::LanguageValue,
Self::LanguageValue => Self::TimesigName,
Self::TimesigName => Self::TimesigValue,
Self::TimesigValue => Self::ThinkEndTag,
Self::ThinkEndTag | Self::Completed => Self::Completed,
}
}
}
/// Token-id prefix → the tokens that may follow it.
type PrefixTree = HashMap<Vec<u32>, BTreeSet<u32>>;
/// The tokenizer, as the state machine needs it.
pub trait Vocab {
/// Encode without special tokens added (special tokens in the text
/// still encode to their ids).
fn encode(&self, text: &str) -> Result<Vec<u32>>;
/// One token's text, special tokens kept.
fn decode(&self, token: u32) -> Result<String>;
}
/// Build a prefix tree for `values` as they tokenize after `"{field}: "`,
/// keyed from where `"{field}:"` ends. A value whose tokens do not start
/// with the field's own tokens is skipped, as upstream does.
fn prefix_tree(
vocab: &dyn Vocab,
field: &str,
values: &[String],
newline: u32,
first_must_be_note: bool,
) -> Result<PrefixTree> {
let context = vocab.encode(&format!("{field}:"))?;
let mut tree = PrefixTree::new();
for value in values {
let full = vocab.encode(&format!("{field}: {value}"))?;
if full.len() < context.len() || full[..context.len()] != context[..] {
continue;
}
let ids = &full[context.len()..];
if ids.is_empty() {
continue;
}
if first_must_be_note {
let first = vocab.decode(ids[0])?;
let c = first
.trim_start()
.chars()
.next()
.map(|c| c.to_ascii_uppercase());
if !c.is_some_and(|c| "ABCDEFG".contains(c)) {
continue;
}
}
for i in 0..=ids.len() {
let entry = tree.entry(ids[..i].to_vec()).or_default();
entry.insert(if i < ids.len() { ids[i] } else { newline });
}
}
Ok(tree)
}
/// Keep only `allowed`; with nothing allowed, every logit is `-inf`.
fn whitelist(logits: &mut [f32], allowed: &[u32]) {
let keep: Vec<(usize, f32)> = allowed
.iter()
.filter_map(|&t| logits.get(t as usize).map(|&v| (t as usize, v)))
.collect();
logits.fill(f32::NEG_INFINITY);
for (i, v) in keep {
logits[i] = v;
}
}
/// `torch.argmax`: the first maximum.
fn argmax(logits: &[f32]) -> u32 {
let mut best = 0;
for (i, &v) in logits.iter().enumerate() {
if v > logits[best] {
best = i;
}
}
best as u32
}
/// The CoT phase's constraint, one per generation.
pub struct MetaFsm {
state: State,
position: usize,
acc_ids: Vec<u32>,
acc_value: String,
caption_after_newline: bool,
caption_tokens: usize,
caption_ending: bool,
pending_field: String,
newline: u32,
eos: u32,
backtick: Option<u32>,
audio_codes: (u32, u32),
bpm: PrefixTree,
duration: PrefixTree,
timesig: PrefixTree,
keyscale: PrefixTree,
language: PrefixTree,
}
impl MetaFsm {
/// `eos` is `<|im_end|>`; `audio_codes` the inclusive id range of the
/// `<|audio_code_N|>` tokens, which a caption may never contain.
pub fn new(vocab: &dyn Vocab, eos: u32, audio_codes: (u32, u32)) -> Result<Self> {
let last = |s: &str| -> Result<Option<u32>> { Ok(vocab.encode(s)?.last().copied()) };
let newline =
last("\n")?.ok_or_else(|| candle_core::Error::Msg("newline has no token".into()))?;
let range = |(lo, hi): (u32, u32)| (lo..=hi).map(|v| v.to_string()).collect::<Vec<_>>();
let mut keyscales = Vec::new();
for note in KEYSCALE_NOTES {
for acc in KEYSCALE_ACCIDENTALS {
for mode in KEYSCALE_MODES {
keyscales.push(format!("{note}{acc} {mode}"));
}
}
}
let strings = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
Ok(Self {
state: State::ThinkTag,
position: 0,
acc_ids: Vec::new(),
acc_value: String::new(),
caption_after_newline: false,
caption_tokens: 0,
caption_ending: false,
pending_field: String::new(),
newline,
eos,
backtick: last("`")?,
audio_codes,
bpm: prefix_tree(vocab, "bpm", &range(BPM), newline, false)?,
duration: prefix_tree(vocab, "duration", &range(DURATION), newline, false)?,
timesig: prefix_tree(
vocab,
"timesignature",
&strings(&TIME_SIGNATURES),
newline,
false,
)?,
keyscale: prefix_tree(vocab, "keyscale", &keyscales, newline, true)?,
language: prefix_tree(vocab, "language", &strings(&LANGUAGES), newline, false)?,
})
}
pub fn is_completed(&self) -> bool {
self.state == State::Completed
}
/// The longest prefix of what remains of a fixed string that is one
/// token; failing that, the first token of the remainder.
fn fixed_token(&self, vocab: &dyn Vocab, fixed: &str) -> Result<Option<u32>> {
let rest: Vec<char> = fixed.chars().skip(self.position).collect();
if rest.is_empty() {
return Ok(None);
}
for end in (1..=rest.len()).rev() {
let ids = vocab.encode(&rest[..end].iter().collect::<String>())?;
if ids.len() == 1 {
return Ok(Some(ids[0]));
}
}
Ok(vocab
.encode(&rest.iter().collect::<String>())?
.first()
.copied())
}
fn transition(&mut self) {
self.state = self.state.next();
self.position = 0;
self.acc_value.clear();
self.acc_ids.clear();
self.caption_after_newline = false;
self.caption_tokens = 0;
self.caption_ending = false;
self.pending_field.clear();
}
fn tree(&self) -> &PrefixTree {
match self.state {
State::BpmValue => &self.bpm,
State::DurationValue => &self.duration,
State::TimesigValue => &self.timesig,
State::KeyscaleValue => &self.keyscale,
_ => &self.language,
}
}
fn allows_newline(&self) -> bool {
self.tree()
.get(&self.acc_ids)
.is_some_and(|s| s.contains(&self.newline))
}
fn continuations(&self) -> Vec<u32> {
self.tree()
.get(&self.acc_ids)
.map(|s| s.iter().copied().collect())
.unwrap_or_default()
}
/// Mask `logits` to what the current state allows.
pub fn constrain(&mut self, vocab: &dyn Vocab, logits: &mut [f32]) -> Result<()> {
if self.state == State::Completed {
return Ok(());
}
if let Some(fixed) = self.state.fixed() {
if self.state == State::ThinkEndTag {
// stop_at_reasoning: end where `</think>` would begin.
whitelist(logits, &[self.eos]);
return Ok(());
}
match self.fixed_token(vocab, fixed)? {
Some(t) => whitelist(logits, &[t]),
None => {
self.transition();
if self.state.fixed().is_none() {
logits.fill(0.0);
return self.constrain(vocab, logits);
}
}
}
return Ok(());
}
match self.state {
State::BpmValue | State::DurationValue => {
let mut allowed = self.continuations();
if self.allows_newline() {
allowed.push(self.newline);
}
whitelist(logits, &allowed);
}
State::CaptionValue => {
if self.caption_after_newline {
self.caption_after_newline = false;
let top = vocab.decode(argmax(logits))?;
if top.chars().next().is_some_and(|c| c != ' ' && c != '\t') {
// The model is starting the next field's name: let
// it, and pick the field up from what it writes.
self.caption_ending = true;
self.pending_field.clear();
return Ok(());
}
}
if self.caption_ending {
return Ok(());
}
if let Some(b) = self.backtick
&& let Some(v) = logits.get_mut(b as usize)
{
*v = f32::NEG_INFINITY;
}
let (lo, hi) = self.audio_codes;
for v in logits.iter_mut().take(hi as usize + 1).skip(lo as usize) {
*v = f32::NEG_INFINITY;
}
if self.caption_tokens >= MAX_CAPTION_TOKENS {
whitelist(logits, &[self.newline]);
}
}
State::KeyscaleValue | State::TimesigValue => {
if self.allows_newline() {
whitelist(logits, &[self.newline]);
} else {
let allowed = self.continuations();
if allowed.is_empty() && self.state == State::KeyscaleValue {
whitelist(logits, &[self.newline]);
} else {
whitelist(logits, &allowed);
}
}
}
State::LanguageValue => {
if self.acc_ids.is_empty() {
// The single best first token among every language's.
let candidates = self.continuations();
match candidates.iter().copied().reduce(|best, t| {
let v = |t: u32| logits.get(t as usize).copied().unwrap_or(f32::MIN);
if v(t) > v(best) { t } else { best }
}) {
Some(t) => whitelist(logits, &[t]),
None => whitelist(logits, &[self.newline]),
}
} else if self.allows_newline() {
whitelist(logits, &[self.newline]);
} else {
let allowed = self.continuations();
if allowed.is_empty() {
whitelist(logits, &[self.newline]);
} else {
whitelist(logits, &allowed);
}
}
}
_ => {}
}
Ok(())
}
/// Advance on the token that was chosen.
pub fn update(&mut self, vocab: &dyn Vocab, token: u32) -> Result<()> {
if self.state == State::Completed {
return Ok(());
}
let text = vocab.decode(token)?;
if let Some(fixed) = self.state.fixed() {
self.position += text.chars().count();
if self.state == State::ThinkEndTag && token == self.eos {
self.state = State::Completed;
} else if self.position >= fixed.chars().count() {
self.transition();
}
return Ok(());
}
match self.state {
State::BpmValue
| State::DurationValue
| State::TimesigValue
| State::KeyscaleValue
| State::LanguageValue => {
if token == self.newline {
self.transition();
} else {
self.acc_ids.push(token);
self.acc_value.push_str(&text);
}
}
State::CaptionValue => {
self.caption_tokens += 1;
self.acc_value.push_str(&text);
self.caption_after_newline = text.contains('\n');
if self.caption_ending {
self.pending_field.push_str(&text);
if text.contains(':') {
let name = self
.pending_field
.trim()
.trim_end_matches(':')
.trim()
.to_lowercase();
let target = match name.as_str() {
"duration" => Some(State::DurationValue),
"keyscale" => Some(State::KeyscaleValue),
"language" => Some(State::LanguageValue),
"timesignature" => Some(State::TimesigValue),
_ => None,
};
match target {
Some(s) => {
self.transition();
self.state = s;
}
None => self.transition(),
}
}
}
}
_ => {}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A vocabulary that splits text into characters, except that a space
/// joins the character after it (as `" G"` is one token in the real
/// one), with `<think>`, `</think>` and `<|im_end|>` as specials.
/// Enough to drive every state; the real tokenizer is exercised by the
/// planner parity test.
struct Chars;
const SPECIALS: [&str; 3] = ["<think>", "</think>", "<|im_end|>"];
const BASE: u32 = 1000;
const SPACED: u32 = 3000;
impl Vocab for Chars {
fn encode(&self, text: &str) -> Result<Vec<u32>> {
if let Some(i) = SPECIALS.iter().position(|s| *s == text) {
return Ok(vec![BASE + i as u32]);
}
let chars: Vec<char> = text.chars().collect();
let mut ids = Vec::new();
let mut i = 0;
while i < chars.len() {
if chars[i] == ' '
&& i + 1 < chars.len()
&& (chars[i + 1] as u32) < 128
&& chars[i + 1] != ' '
{
ids.push(SPACED + chars[i + 1] as u32);
i += 2;
} else {
ids.push(chars[i] as u32);
i += 1;
}
}
Ok(ids)
}
fn decode(&self, token: u32) -> Result<String> {
Ok(match token {
t if (BASE..BASE + 3).contains(&t) => SPECIALS[(t - BASE) as usize].to_string(),
t if (SPACED..SPACED + 128).contains(&t) => {
format!(" {}", char::from_u32(t - SPACED).unwrap_or('?'))
}
t => char::from_u32(t).unwrap_or('?').to_string(),
})
}
}
/// Drive the machine with a model that always prefers the next
/// character of `wanted`; return what it generates.
fn run(wanted: &str) -> String {
let v = Chars;
let eos = BASE + 2;
let mut fsm = MetaFsm::new(&v, eos, (2000, 2010)).unwrap();
let want: Vec<u32> = {
let mut ids = vec![BASE];
ids.extend(v.encode(wanted).unwrap());
ids
};
let mut out = String::new();
for step in 0..400 {
let mut logits = vec![0f32; 4000];
if let Some(&t) = want.get(step) {
logits[t as usize] = 10.0;
}
fsm.constrain(&v, &mut logits).unwrap();
let t = argmax(&logits);
fsm.update(&v, t).unwrap();
if t == eos {
out.push_str("<EOS>");
break;
}
out.push_str(&v.decode(t).unwrap());
}
out
}
#[test]
fn a_well_formed_plan_passes_through_and_stops_before_the_close_tag() {
let plan = "\nbpm: 120\ncaption: A calm piano piece\n with soft strings\nduration: 30\nkeyscale: C major\nlanguage: en\ntimesignature: 4\n";
assert_eq!(run(plan), format!("<think>{plan}<EOS>"));
}
#[test]
fn out_of_range_and_off_vocabulary_values_are_steered() {
// bpm 999 is out of range; keyscale H is not a note; language xx
// is not a code. The model's preference is followed only where the
// grammar allows it.
let plan = "\nbpm: 999\ncaption: x\nduration: 30\nkeyscale: H major\nlanguage: xx\ntimesignature: 5\n";
let got = run(plan);
assert!(got.starts_with("<think>\nbpm: 99"), "{got}");
let bpm: u32 = got["<think>\nbpm: ".len()..]
.split('\n')
.next()
.unwrap()
.parse()
.unwrap();
assert!((BPM.0..=BPM.1).contains(&bpm), "{got}");
assert!(got.contains("\nkeyscale: A"), "{got}");
let lang = got
.split("language: ")
.nth(1)
.unwrap()
.split('\n')
.next()
.unwrap();
assert!(LANGUAGES.contains(&lang), "{got}");
let ts = got
.split("timesignature: ")
.nth(1)
.unwrap()
.split('\n')
.next()
.unwrap();
assert!(TIME_SIGNATURES.contains(&ts), "{got}");
assert!(got.ends_with("<EOS>"));
}
}
@@ -0,0 +1,162 @@
//! A linear layer that is either dense or quantized in situ (#385).
//!
//! The vendored modules build their projections through `linear_b` /
//! `linear_no_bias`, the same names `candle_transformers::with_tracing`
//! exports, so switching them over is an import change and the vendored
//! code stays diffable against upstream.
//!
//! Whether a layer is quantized is decided while it is built, by
//! [`with_quant`]. A scope rather than a parameter, because the setting
//! would otherwise have to be threaded through every constructor of the
//! DiT, the condition encoder, the text encoder and the planner. Loads
//! run on one thread (the device worker), so the scope cannot leak into
//! another model's load.
//!
//! A quantized layer runs through candle's `QMatMul`, which wants f32
//! activations: build the component with an f32 `VarBuilder`.
use candle_core::quantized::{GgmlDType, QMatMul};
use candle_core::{Module, Result, Tensor};
use candle_nn::VarBuilder;
use std::cell::Cell;
use std::sync::Arc;
thread_local! {
static QUANT: Cell<Option<GgmlDType>> = const { Cell::new(None) };
}
/// Build with `quant` applied to every linear layer `f` creates. A layer
/// whose input width does not divide the block size stays dense.
pub fn with_quant<R>(quant: Option<GgmlDType>, f: impl FnOnce() -> R) -> R {
let previous = QUANT.with(|q| q.replace(quant));
let out = f();
QUANT.with(|q| q.set(previous));
out
}
#[derive(Debug, Clone)]
pub enum Linear {
Dense(candle_nn::Linear),
Quantized {
weight: QMatMul,
bias: Option<Tensor>,
},
}
impl Linear {
/// A dense layer from existing weights (tied heads, identity
/// projections). Never quantized: the weight is shared or synthetic.
pub fn from_weights(weight: Tensor, bias: Option<Tensor>) -> Self {
Self::Dense(candle_nn::Linear::new(weight, bias))
}
fn build(weight: Tensor, bias: Option<Tensor>) -> Result<Self> {
let quant = QUANT.with(Cell::get);
let width = weight.dims().last().copied().unwrap_or(0);
match quant {
Some(dtype) if width > 0 && width.is_multiple_of(dtype.block_size()) => {
let qt = crate::harness::tp::isq::quantize_parallel(&weight, dtype)
.map_err(|e| candle_core::Error::Msg(format!("{e:#}")))?;
Ok(Self::Quantized {
weight: QMatMul::from_arc(Arc::new(qt))?,
bias,
})
}
_ => Ok(Self::Dense(candle_nn::Linear::new(weight, bias))),
}
}
pub fn is_quantized(&self) -> bool {
matches!(self, Self::Quantized { .. })
}
}
impl Module for Linear {
fn forward(&self, x: &Tensor) -> Result<Tensor> {
match self {
Self::Dense(l) => l.forward(x),
Self::Quantized { weight, bias } => {
// The quantized kernels read a contiguous (batch, rows, k)
// or (rows, k) input.
let y = match x.dims() {
[a, b, c, k] => weight
.forward(&x.contiguous()?.reshape((a * b, *c, *k))?)?
.reshape((*a, *b, *c, ()))?,
_ => weight.forward(&x.contiguous()?)?,
};
match bias {
Some(b) => y.broadcast_add(b),
None => Ok(y),
}
}
}
}
}
pub fn linear_b(d1: usize, d2: usize, bias: bool, vb: VarBuilder) -> Result<Linear> {
let weight = vb.get((d2, d1), "weight")?;
let bias = if bias {
Some(vb.get(d2, "bias")?)
} else {
None
};
Linear::build(weight, bias)
}
pub fn linear_no_bias(d1: usize, d2: usize, vb: VarBuilder) -> Result<Linear> {
linear_b(d1, d2, false, vb)
}
pub fn linear(d1: usize, d2: usize, vb: VarBuilder) -> Result<Linear> {
linear_b(d1, d2, true, vb)
}
#[cfg(test)]
mod tests {
use super::*;
use candle_core::{DType, Device};
use std::collections::HashMap;
fn vb_with(weight: Tensor) -> VarBuilder<'static> {
let mut map = HashMap::new();
map.insert("weight".to_string(), weight);
VarBuilder::from_tensors(map, DType::F32, &Device::Cpu)
}
#[test]
fn quantization_is_scoped_and_skips_widths_that_do_not_tile() -> Result<()> {
let w = Tensor::randn(0f32, 1.0, (64, 64), &Device::Cpu)?;
let dense = linear_no_bias(64, 64, vb_with(w.clone()))?;
assert!(!dense.is_quantized(), "no scope, no quantization");
let q = with_quant(Some(GgmlDType::Q8_0), || {
linear_no_bias(64, 64, vb_with(w.clone()))
})?;
assert!(q.is_quantized());
let narrow = Tensor::randn(0f32, 1.0, (64, 6), &Device::Cpu)?;
let kept = with_quant(Some(GgmlDType::Q8_0), || {
linear_no_bias(6, 64, vb_with(narrow))
})?;
assert!(!kept.is_quantized(), "6 does not tile a 32-block");
let after = linear_no_bias(64, 64, vb_with(w))?;
assert!(!after.is_quantized(), "the scope must end with the call");
Ok(())
}
#[test]
fn q8_output_tracks_the_dense_layer() -> Result<()> {
let w = Tensor::randn(0f32, 0.05, (128, 256), &Device::Cpu)?;
let x = Tensor::randn(0f32, 1.0, (3, 256), &Device::Cpu)?;
let dense = linear_no_bias(256, 128, vb_with(w.clone()))?.forward(&x)?;
let q = with_quant(Some(GgmlDType::Q8_0), || {
linear_no_bias(256, 128, vb_with(w))
})?
.forward(&x)?;
let err = (dense.clone() - q)?.abs()?.max_all()?.to_scalar::<f32>()?;
let scale = dense.abs()?.max_all()?.to_scalar::<f32>()?;
assert!(err / scale < 0.02, "q8_0 relative error {}", err / scale);
Ok(())
}
}
File diff suppressed because it is too large Load Diff
@@ -30,7 +30,10 @@
//! - [GitHub Repository](https://github.com/ACE-Step/ACE-Step-1.5)
pub mod condition;
pub mod cot;
pub mod dit;
pub mod fsm;
pub mod linear;
pub mod lm;
pub mod model;
pub mod pipeline;
@@ -18,6 +18,17 @@ use anyhow::Result;
use candle_core::{DType, Device, Tensor};
use candle_nn::VarBuilder;
/// The DiT's task instruction for a text-to-music render (upstream's
/// `TASK_INSTRUCTIONS["text2music"]`).
pub const TEXT2MUSIC_INSTRUCTION: &str =
"Fill the audio semantic mask based on the given conditions:";
/// The instruction once audio codes condition the render. Upstream turns a
/// text-to-music request into a cover when the planner supplies codes
/// (`_resolve_generate_music_task`), and so does a reference cover.
pub const COVER_INSTRUCTION: &str = "Generate audio semantic tokens based on the given conditions:";
/// Upstream's `TASK_INSTRUCTIONS["repaint"]`.
pub const REPAINT_INSTRUCTION: &str = "Repaint the mask area based on the given conditions:";
/// Metadata from LM CoT output, used to enrich the DiT text prompt.
///
/// When the LM generates chain-of-thought metadata (BPM, keyscale, etc.),
@@ -94,6 +105,21 @@ pub struct AudioOutput {
pub sample_rate: u32,
/// The denoised latents `(1, T, acoustic_dim)` the VAE decoded.
pub latents: Tensor,
/// Wall time per phase. Each phase ends with a device synchronize, so
/// queued GPU work is charged to the phase that queued it.
pub timing: PhaseTiming,
}
/// Wall time of one render's phases, in milliseconds.
#[derive(Debug, Clone, Copy, Default)]
pub struct PhaseTiming {
pub encode_ms: u64,
pub denoise_ms: u64,
pub decode_ms: u64,
}
fn elapsed_ms(since: std::time::Instant) -> u64 {
since.elapsed().as_millis() as u64
}
/// High-level pipeline: text prompt → stereo audio.
@@ -107,8 +133,16 @@ pub struct AceStepPipeline {
silence_latent: Tensor,
dit_config: AceStepConfig,
vae_config: VaeConfig,
/// The DiT's device and dtype. Conditioning, latents and the planner's
/// hints live here.
device: Device,
dtype: DType,
/// Where the text encoder and the VAE run, which may differ from the
/// DiT's (#385). Only their small outputs cross between devices: the
/// prompt's hidden states and the denoised latents.
text_device: Device,
vae_device: Device,
vae_dtype: DType,
}
struct LmState {
@@ -119,7 +153,8 @@ struct LmState {
impl AceStepPipeline {
/// Load all components.
///
/// - `dit_vb` / `vae_vb` / `text_vb`: VarBuilders for each model
/// - `dit_vb` / `vae_vb` / `text_vb`: VarBuilders for each model. Each
/// component runs on its builder's device and dtype.
/// - `text_config`: Qwen3 config (for the embedding model, NOT the LM)
/// - `tokenizer_path`: `tokenizer.json` for the text encoder
/// - `silence_latent`: `(1, T, acoustic_dim)` pre-loaded
@@ -138,6 +173,9 @@ impl AceStepPipeline {
) -> Result<Self> {
let device = dit_vb.device().clone();
let dtype = dit_vb.dtype();
let text_device = text_vb.device().clone();
let vae_device = vae_vb.device().clone();
let vae_dtype = vae_vb.dtype();
let text_encoder = qwen3::Model::new(text_config, text_vb)?;
let tokenizer = tokenizers::Tokenizer::from_file(tokenizer_path)
@@ -162,6 +200,9 @@ impl AceStepPipeline {
vae_config: vae_config.clone(),
device,
dtype,
text_device,
vae_device,
vae_dtype,
})
}
@@ -178,18 +219,27 @@ impl AceStepPipeline {
lyrics: &str,
params: &GenerationParams,
) -> Result<AudioOutput> {
let t = std::time::Instant::now();
let instruction = if params.lm_hints_25hz.is_some() {
COVER_INSTRUCTION
} else {
TEXT2MUSIC_INSTRUCTION
};
let (text_hs, text_mask, lyric_hs, lyric_mask) = self.encode_text(
instruction,
prompt,
lyrics,
params.duration_secs,
params.lm_metadata.as_ref(),
params.language.as_deref(),
)?;
self.device.synchronize()?;
let encode_ms = elapsed_ms(t);
let latent_frames = self.latent_frames(params.duration_secs);
let timbre_frames = 750.min(self.silence_latent.dim(1)?);
self.generate_inner(
let mut out = self.generate_inner(
&text_hs,
&text_mask,
&lyric_hs,
@@ -198,7 +248,9 @@ impl AceStepPipeline {
&self.silence_latent.narrow(1, 0, timbre_frames)?,
params,
latent_frames,
)
)?;
out.timing.encode_ms = encode_ms;
Ok(out)
}
/// Generate a cover conditioned on reference audio `(1, 2, T)` at 48kHz.
@@ -221,6 +273,7 @@ impl AceStepPipeline {
params: &GenerationParams,
) -> Result<AudioOutput> {
let (text_hs, text_mask, lyric_hs, lyric_mask) = self.encode_text(
COVER_INSTRUCTION,
prompt,
lyrics,
params.duration_secs,
@@ -232,7 +285,11 @@ impl AceStepPipeline {
.vae_encoder
.as_ref()
.ok_or_else(|| anyhow::anyhow!("VAE encoder not loaded (pass load_encoder=true)"))?;
let ref_latent = vae.encode_mean(reference_audio)?.transpose(1, 2)?;
let ref_latent = vae
.encode_mean(reference_audio)?
.transpose(1, 2)?
.to_device(&self.device)?
.to_dtype(self.dtype)?;
let latent_frames = self.latent_frames(params.duration_secs);
let ref_len = ref_latent.dim(1)?;
@@ -246,7 +303,11 @@ impl AceStepPipeline {
// Timbre: use separate timbre audio if provided, otherwise reference audio
let refer_audio_packed = if let Some(timbre) = timbre_audio {
let timbre_latent = vae.encode_mean(timbre)?.transpose(1, 2)?;
let timbre_latent = vae
.encode_mean(timbre)?
.transpose(1, 2)?
.to_device(&self.device)?
.to_dtype(self.dtype)?;
let timbre_len = timbre_latent.dim(1)?;
let timbre_frames = 750.min(timbre_len);
timbre_latent.narrow(1, 0, timbre_frames)?
@@ -289,6 +350,7 @@ impl AceStepPipeline {
params: &GenerationParams,
) -> Result<AudioOutput> {
let (text_hs, text_mask, lyric_hs, lyric_mask) = self.encode_text(
REPAINT_INSTRUCTION,
prompt,
lyrics,
params.duration_secs,
@@ -300,7 +362,11 @@ impl AceStepPipeline {
.vae_encoder
.as_ref()
.ok_or_else(|| anyhow::anyhow!("VAE encoder not loaded (pass load_encoder=true)"))?;
let src_latent = vae.encode_mean(source_audio)?.transpose(1, 2)?; // (1, T_lat, D)
let src_latent = vae
.encode_mean(source_audio)?
.transpose(1, 2)?
.to_device(&self.device)?
.to_dtype(self.dtype)?; // (1, T_lat, D)
let latent_frames = self.latent_frames(params.duration_secs);
let hop = self.vae_config.hop_length() as f64;
@@ -394,6 +460,9 @@ impl AceStepPipeline {
lm_vb: VarBuilder,
lm_tokenizer_path: &std::path::Path,
) -> Result<()> {
// The planner runs on its builder's device; only its integer codes
// reach the DiT.
let lm_device = lm_vb.device().clone();
let lm_model = qwen3::ModelForCausalLM::new(lm_config, lm_vb)?;
let lm_tokenizer = tokenizers::Tokenizer::from_file(lm_tokenizer_path)
.map_err(|e| anyhow::anyhow!("LM tokenizer: {e}"))?;
@@ -403,7 +472,7 @@ impl AceStepPipeline {
.map_err(|e| candle_core::Error::Msg(format!("encode {s:?}: {e}")))?;
Ok(enc.get_ids().to_vec())
})?;
let pipeline = LmPipeline::new(lm_model, token_ids, self.device.clone());
let pipeline = LmPipeline::new(lm_model, token_ids, lm_device);
self.lm = Some(LmState {
pipeline,
tokenizer: lm_tokenizer,
@@ -427,15 +496,9 @@ impl AceStepPipeline {
.as_mut()
.ok_or_else(|| anyhow::anyhow!("LM not loaded — call load_lm() first"))?;
let prompt_text = LmPipeline::format_prompt(prompt, lyrics);
let prompt_enc = lm
.tokenizer
.encode(prompt_text.as_str(), false)
.map_err(|e| anyhow::anyhow!("LM encode: {e}"))?;
let decode_fn = |t: u32| -> candle_core::Result<String> {
let decode_fn = |ids: &[u32]| -> candle_core::Result<String> {
lm.tokenizer
.decode(&[t], false)
.decode(ids, false)
.map_err(|e| candle_core::Error::Msg(format!("{e}")))
};
let encode_fn = |s: &str| -> candle_core::Result<Vec<u32>> {
@@ -447,7 +510,8 @@ impl AceStepPipeline {
};
let output = lm.pipeline.generate(
prompt_enc.get_ids(),
prompt,
lyrics,
duration_secs,
lm_config,
&decode_fn,
@@ -479,6 +543,7 @@ impl AceStepPipeline {
/// lyrics under their language. `language` defaults to `"unknown"`,
/// upstream's own default when the caller names none.
pub fn format_prompts(
instruction: &str,
prompt: &str,
lyrics: &str,
duration_secs: f64,
@@ -496,7 +561,7 @@ impl AceStepPipeline {
.and_then(|m| m.keyscale.as_deref())
.unwrap_or("N/A");
let caption_text = format!(
"# Instruction\nFill the audio semantic mask based on the given conditions:\n\n\
"# Instruction\n{instruction}\n\n\
# Caption\n{caption}\n\n# Metas\n\
- bpm: {bpm}\n- timesignature: {timesig}\n- keyscale: {keyscale}\n- duration: {} seconds\n\
<|endoftext|>\n",
@@ -534,28 +599,44 @@ impl AceStepPipeline {
fn encode_text(
&mut self,
instruction: &str,
prompt: &str,
lyrics: &str,
duration_secs: f64,
metadata: Option<&LmMetadata>,
language: Option<&str>,
) -> Result<(Tensor, Tensor, Tensor, Tensor)> {
let (caption_text, lyric_text) =
Self::format_prompts(prompt, lyrics, duration_secs, metadata, language);
let (caption_text, lyric_text) = Self::format_prompts(
instruction,
prompt,
lyrics,
duration_secs,
metadata,
language,
);
let encoding = self
.tokenizer
.encode(caption_text.as_str(), true)
.map_err(|e| anyhow::anyhow!("tokenization: {e}"))?;
let prompt_tokens = Tensor::new(encoding.get_ids(), &self.device)?.unsqueeze(0)?;
let text_hidden_states = self.text_encoder.forward(&prompt_tokens, 0)?;
let prompt_tokens = Tensor::new(encoding.get_ids(), &self.text_device)?.unsqueeze(0)?;
let text_hidden_states = self
.text_encoder
.forward(&prompt_tokens, 0)?
.to_device(&self.device)?
.to_dtype(self.dtype)?;
self.text_encoder.clear_kv_cache();
let lyric_encoding = self
.tokenizer
.encode(lyric_text.as_str(), true)
.map_err(|e| anyhow::anyhow!("lyric tokenization: {e}"))?;
let lyric_tokens = Tensor::new(lyric_encoding.get_ids(), &self.device)?.unsqueeze(0)?;
let lyric_hidden_states = self.text_encoder.embed_tokens(&lyric_tokens)?;
let lyric_tokens =
Tensor::new(lyric_encoding.get_ids(), &self.text_device)?.unsqueeze(0)?;
let lyric_hidden_states = self
.text_encoder
.embed_tokens(&lyric_tokens)?
.to_device(&self.device)?
.to_dtype(self.dtype)?;
let text_mask = Tensor::new(encoding.get_attention_mask(), &self.device)?
.unsqueeze(0)?
@@ -638,6 +719,7 @@ impl AceStepPipeline {
.num_steps
.unwrap_or(if params.is_turbo { 8 } else { 50 });
let t = std::time::Instant::now();
let xt = self.model.generate_latents(
&condition,
None,
@@ -657,17 +739,32 @@ impl AceStepPipeline {
self.dtype,
)?;
self.device.synchronize()?;
let denoise_ms = elapsed_ms(t);
let t = std::time::Instant::now();
let latents = xt
.transpose(1, 2)?
.to_device(&self.vae_device)?
.to_dtype(self.vae_dtype)?;
let audio = self.vae_decoder.tiled_decode(
&xt.transpose(1, 2)?,
&latents,
params.vae_chunk_frames,
params.vae_chunk_overlap,
)?;
let audio = audio.squeeze(0)?;
self.vae_device.synchronize()?;
let decode_ms = elapsed_ms(t);
Ok(AudioOutput {
audio,
sample_rate: self.vae_config.sampling_rate as u32,
latents: xt,
timing: PhaseTiming {
encode_ms: 0,
denoise_ms,
decode_ms,
},
})
}
}
@@ -1,9 +1,7 @@
use super::linear::{Linear, linear_b, linear_no_bias};
use candle_core::{DType, Device, Module, Result, Tensor};
use candle_nn::{Activation, VarBuilder, kv_cache::ConcatKvCache};
use candle_transformers::{
models::with_tracing::{Linear, RmsNorm, linear_b, linear_no_bias},
utils::repeat_kv,
};
use candle_transformers::{models::with_tracing::RmsNorm, utils::repeat_kv};
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
@@ -12,9 +12,10 @@
//! - `AttentionPooler` / `AudioTokenizer`: structurally correct, minor
//! float precision differences propagate through FSQ rounding.
use super::linear::{Linear, linear, linear_no_bias};
use candle_core::{D, DType, Module, Result, Tensor};
use candle_nn::{Activation, VarBuilder};
use candle_transformers::models::with_tracing::{Linear, RmsNorm, linear, linear_no_bias};
use candle_transformers::models::with_tracing::RmsNorm;
use candle_transformers::utils::repeat_kv;
use std::sync::Arc;
@@ -255,23 +256,18 @@ impl AttentionPooler {
/// Residual Finite Scalar Quantization.
///
/// Matches `vector_quantize_pytorch.ResidualFSQ` with a single top-level
/// `project_in` (dim → codebook_dim) and `project_out` (codebook_dim → dim).
/// Each FSQ layer independently quantizes each codebook dimension to its
/// corresponding number of levels using `tanh` bounding and rounding.
/// Matches `vector_quantize_pytorch.ResidualFSQ` 1.27 as ACE-Step builds it
/// (one quantizer, the library defaults): a top-level `project_in`
/// (dim → codebook_dim) and `project_out` (codebook_dim → dim), a soft clamp
/// of the projected input to `±(1 + 1/(L-1))`, and an FSQ layer constructed
/// with `preserve_symmetry=True` and a hard-clamped bound. Symmetric FSQ puts
/// level `k` of `L` at `2k/(L-1) - 1`, spanning `[-1, 1]`; the asymmetric
/// formula (`(k - L/2) / (L/2)`) is not what the checkpoint was trained with.
#[derive(Debug, Clone)]
pub struct ResidualFSQ {
project_in: Linear,
project_out: Linear,
/// Precomputed: (levels - 1) * (1 + eps) / 2 for each codebook dim
half_l: Vec<f32>,
/// Precomputed: levels // 2
half_width: Vec<f32>,
/// Precomputed: 0.5 for even levels, 0.0 for odd
offset: Vec<f32>,
/// Precomputed: atanh(offset / half_l) shift
shift: Vec<f32>,
/// Precomputed basis for index calculation: [1, L0, L0*L1, ...]
/// Basis for the flat index: `[1, L0, L0*L1, ...]`.
basis: Vec<i64>,
/// Quantization levels per codebook dimension (e.g. [8, 8, 8, 5, 5, 5]).
levels: Vec<usize>,
@@ -290,22 +286,6 @@ impl ResidualFSQ {
let project_in = linear(dim, codebook_dim, vb.pp("project_in"))?;
let project_out = linear(codebook_dim, dim, vb.pp("project_out"))?;
let eps = 1e-3f32;
let half_l: Vec<f32> = levels
.iter()
.map(|&l| (l as f32 - 1.0) * (1.0 + eps) / 2.0)
.collect();
let half_width: Vec<f32> = levels.iter().map(|&l| (l / 2) as f32).collect();
let offset: Vec<f32> = levels
.iter()
.map(|&l| if l % 2 == 0 { 0.5 } else { 0.0 })
.collect();
let shift: Vec<f32> = half_l
.iter()
.zip(&offset)
.map(|(&hl, &o)| (o / hl).atanh())
.collect();
let mut basis = vec![1i64];
for i in 0..levels.len() - 1 {
basis.push(basis[i] * levels[i] as i64);
@@ -314,76 +294,54 @@ impl ResidualFSQ {
Ok(Self {
project_in,
project_out,
half_l,
half_width,
offset,
shift,
basis,
levels: levels.to_vec(),
model_dtype,
})
}
/// FSQ bound + round: `round(tanh(z + shift) * half_l - offset) / half_width`
fn fsq_quantize(&self, z: &Tensor) -> Result<Tensor> {
let dev = z.device();
let half_l = Tensor::new(&self.half_l[..], dev)?
.unsqueeze(0)?
.unsqueeze(0)?;
let offset = Tensor::new(&self.offset[..], dev)?
.unsqueeze(0)?
.unsqueeze(0)?;
let shift = Tensor::new(&self.shift[..], dev)?
.unsqueeze(0)?
.unsqueeze(0)?;
let half_width = Tensor::new(&self.half_width[..], dev)?
.unsqueeze(0)?
.unsqueeze(0)?;
/// A per-codebook-dimension constant as a `(1, 1, d)` f32 tensor.
fn per_dim(&self, dev: &candle_core::Device, f: impl Fn(f32) -> f32) -> Result<Tensor> {
let v: Vec<f32> = self.levels.iter().map(|&l| f(l as f32)).collect();
Tensor::new(&v[..], dev)?.unsqueeze(0)?.unsqueeze(0)
}
// bound: tanh(z + shift) * half_l - offset, then round, then / half_width
let bounded = z
.broadcast_add(&shift)?
.tanh()?
.broadcast_mul(&half_l)?
.broadcast_sub(&offset)?;
let rounded = bounded.round()?;
rounded.broadcast_div(&half_width)
/// Soft clamp, then the symmetric hard-clamped bound:
/// `2/(L-1) * floor((L-1) * (clamp(z, -1, 1) + 1) / 2 + 0.5) - 1`.
/// Returns `(codes, level_indices)`.
fn fsq_quantize(&self, z: &Tensor) -> Result<(Tensor, Tensor)> {
let dev = z.device();
let z = z.to_dtype(DType::F32)?;
let clamp = self.per_dim(dev, |l| 1.0 + 1.0 / (l - 1.0))?;
let z = z.broadcast_div(&clamp)?.tanh()?.broadcast_mul(&clamp)?;
let lm1 = self.per_dim(dev, |l| l - 1.0)?;
let levels = z
.clamp(-1f32, 1f32)?
.affine(0.5, 0.5)?
.broadcast_mul(&lm1)?
.affine(1.0, 0.5)?
.floor()?;
let codes = levels.broadcast_div(&lm1)?.affine(2.0, -1.0)?;
Ok((codes, levels))
}
/// Quantize continuous representations into discrete tokens.
/// Input: `(B, N, dim)`. Returns `(quantized_out, indices)` where
/// `quantized_out` has the same shape as input and `indices` is `(B, N, num_quantizers)`.
pub fn forward(&self, x: &Tensor) -> Result<(Tensor, Tensor)> {
// project_in: (B, N, dim) -> (B, N, codebook_dim)
let projected = x.apply(&self.project_in)?;
// FSQ quantize
let codes = self.fsq_quantize(&projected)?; // (B, N, codebook_dim)
// Compute indices from codes: scale_and_shift then dot with basis
let dev = x.device();
let half_width = Tensor::new(&self.half_width[..], dev)?
let (codes, levels) = self.fsq_quantize(&projected)?;
let basis: Vec<f32> = self.basis.iter().map(|&b| b as f32).collect();
let basis = Tensor::new(&basis[..], x.device())?
.unsqueeze(0)?
.unsqueeze(0)?;
let offset = Tensor::new(&self.offset[..], dev)?
.unsqueeze(0)?
.unsqueeze(0)?;
let basis = Tensor::new(&self.basis[..], dev)?
.unsqueeze(0)?
.unsqueeze(0)?;
// scale_and_shift: codes * half_width + offset
let shifted = codes.broadcast_mul(&half_width)?.broadcast_add(&offset)?;
let indices = shifted
.to_dtype(DType::F32)?
.broadcast_mul(&basis.to_dtype(DType::F32)?)?
let indices = levels
.broadcast_mul(&basis)?
.sum(2)?
.round()?
.to_dtype(DType::I64)?
.unsqueeze(2)?; // (B, N, 1)
// project_out: (B, N, codebook_dim) -> (B, N, dim)
let quantized_out = codes.apply(&self.project_out)?;
let quantized_out = codes.to_dtype(self.model_dtype)?.apply(&self.project_out)?;
Ok((quantized_out, indices))
}
@@ -393,42 +351,30 @@ impl ResidualFSQ {
codes.apply(&self.project_out)
}
/// Reconstruct from packed indices.
/// Input: `(B, N, 1)` → Output: `(B, N, dim)`.
///
/// Inverse of the forward path: decompose flat index into per-level values
/// via basis, then invert scale_and_shift, then `project_out`.
pub fn get_output_from_indices(&self, indices: &Tensor) -> Result<Tensor> {
/// The codes for packed indices: level `k = (index / basis) % L` of each
/// dimension, at `2k/(L-1) - 1`. Input `(B, N, 1)` → `(B, N, codebook_dim)`.
pub fn codes_from_indices(&self, indices: &Tensor) -> Result<Tensor> {
let dev = indices.device();
let indices = indices.squeeze(D::Minus1)?.to_dtype(DType::F32)?;
let codebook_dim = self.levels.len();
// Decompose: level_val[i] = floor(index / basis[i]) % levels[i]
// F32 has enough precision for indices up to 64000 (max codebook size).
let mut code_dims = Vec::with_capacity(codebook_dim);
for i in 0..codebook_dim {
let b = self.basis[i] as f32;
let l = self.levels[i] as f32;
let dim_val = indices.affine(1.0 / b as f64, 0.0)?.floor()?;
// modulo: dim_val - floor(dim_val / l) * l
let dim_val = (&dim_val
- dim_val
.affine(1.0 / l as f64, 0.0)?
.floor()?
.affine(l as f64, 0.0)?)?;
code_dims.push(dim_val);
// F32 holds every index exactly: the codebook has 64000 entries.
let mut levels = Vec::with_capacity(self.levels.len());
for (i, &l) in self.levels.iter().enumerate() {
let l = l as f64;
let v = indices.affine(1.0 / self.basis[i] as f64, 0.0)?.floor()?;
let v = (&v - v.affine(1.0 / l, 0.0)?.floor()?.affine(l, 0.0)?)?;
levels.push(v);
}
let shifted = Tensor::stack(&code_dims, D::Minus1)?;
let levels = Tensor::stack(&levels, D::Minus1)?;
let lm1 = self.per_dim(dev, |l| l - 1.0)?;
levels.broadcast_div(&lm1)?.affine(2.0, -1.0)
}
// Inverse scale_and_shift (Python convention):
// forward: shifted = codes * half_width + half_width → shifted ∈ [0, levels-1]
// inverse: codes = (shifted - half_width) / half_width
let hw = Tensor::new(&self.half_width[..], dev)?
.unsqueeze(0)?
.unsqueeze(0)?;
let codes = shifted.broadcast_sub(&hw)?.broadcast_div(&hw)?;
codes.to_dtype(self.model_dtype)?.apply(&self.project_out)
/// Reconstruct from packed indices.
/// Input: `(B, N, 1)` → Output: `(B, N, dim)`.
pub fn get_output_from_indices(&self, indices: &Tensor) -> Result<Tensor> {
self.codes_from_indices(indices)?
.to_dtype(self.model_dtype)?
.apply(&self.project_out)
}
}
@@ -437,104 +383,93 @@ mod tests {
use super::*;
use candle_core::Device;
/// Build a minimal ResidualFSQ with identity projections for testing.
/// A ResidualFSQ with identity projections, as the library builds one
/// when `dim` equals the codebook dimension.
fn test_fsq() -> Result<ResidualFSQ> {
let dev = &Device::Cpu;
let levels = vec![8, 8, 8, 5, 5, 5];
let codebook_dim = levels.len();
// Identity-like project_in/project_out (codebook_dim x codebook_dim)
let eye = Tensor::eye(codebook_dim, DType::F32, dev)?;
let zeros = Tensor::zeros(codebook_dim, DType::F32, dev)?;
let eps = 1e-3f32;
let half_l: Vec<f32> = levels
.iter()
.map(|&l| (l as f32 - 1.0) * (1.0 + eps) / 2.0)
.collect();
let half_width: Vec<f32> = levels.iter().map(|&l| (l / 2) as f32).collect();
let offset: Vec<f32> = levels
.iter()
.map(|&l| if l % 2 == 0 { 0.5 } else { 0.0 })
.collect();
let shift: Vec<f32> = half_l
.iter()
.zip(&offset)
.map(|(&hl, &o)| (o / hl).atanh())
.collect();
let mut basis = vec![1i64];
for i in 0..levels.len() - 1 {
basis.push(basis[i] * levels[i] as i64);
}
Ok(ResidualFSQ {
project_in: Linear::from_weights(eye.clone(), Some(zeros.clone())),
project_out: Linear::from_weights(eye, Some(zeros)),
half_l,
half_width,
offset,
shift,
basis,
levels,
model_dtype: DType::F32,
})
}
fn close(got: &[f32], want: &[f32]) {
for (i, (g, w)) in got.iter().zip(want).enumerate() {
assert!((g - w).abs() < 1e-5, "dim {i}: got {g}, want {w}");
}
}
/// Recorded from vector_quantize_pytorch 1.27.20:
/// `FSQ([8,8,8,5,5,5], preserve_symmetry=True).indices_to_codes(...)`.
#[test]
fn test_get_output_from_indices_roundtrip() -> Result<()> {
// Test that manually-packed Python-convention indices correctly
// reconstruct codes via get_output_from_indices.
fn indices_decode_to_symmetric_codes() -> Result<()> {
let fsq = test_fsq()?;
let dev = &Device::Cpu;
// levels = [8,8,8,5,5,5], half_width = [4,4,4,2,2,2]
// basis = [1, 8, 64, 512, 2560, 12800]
//
// Choose codes: [0.25, -0.5, 0.75, 0.5, -1.0, 0.0]
// Python scale_and_shift: shifted = codes * half_width + half_width
// = [0.25*4+4, -0.5*4+4, 0.75*4+4, 0.5*2+2, -1.0*2+2, 0.0*2+2]
// = [5, 2, 7, 3, 0, 2]
// index = 5*1 + 2*8 + 7*64 + 3*512 + 0*2560 + 2*12800
// = 5 + 16 + 448 + 1536 + 0 + 25600 = 27605
let expected_codes: Vec<f32> = vec![0.25, -0.5, 0.75, 0.5, -1.0, 0.0];
let index: i64 = 27605;
let indices = Tensor::new(&[[index]], dev)?.unsqueeze(2)?; // (1, 1, 1)
let reconstructed = fsq.get_output_from_indices(&indices)?;
let vals = reconstructed.squeeze(0)?.squeeze(0)?.to_vec1::<f32>()?;
for (i, (&got, &want)) in vals.iter().zip(expected_codes.iter()).enumerate() {
assert!((got - want).abs() < 1e-5, "dim {i}: got={got}, want={want}");
let cases: [(i64, [f32; 6]); 4] = [
(0, [-1.0; 6]),
(27605, [3.0 / 7.0, -3.0 / 7.0, 1.0, 0.5, -1.0, 0.0]),
(32036, [1.0 / 7.0, 1.0 / 7.0, 1.0 / 7.0, 0.0, 0.0, 0.0]),
(63999, [1.0; 6]),
];
for (index, want) in cases {
let indices = Tensor::new(&[[index]], &Device::Cpu)?.unsqueeze(2)?;
let got = fsq
.get_output_from_indices(&indices)?
.flatten_all()?
.to_vec1::<f32>()?;
close(&got, &want);
}
Ok(())
}
/// Recorded from vector_quantize_pytorch 1.27.20:
/// `ResidualFSQ(dim=6, levels=[8,8,8,5,5,5], num_quantizers=1)(x)`.
#[test]
fn test_get_output_from_indices_known_values() -> Result<()> {
fn forward_matches_the_library() -> Result<()> {
let fsq = test_fsq()?;
let dev = &Device::Cpu;
// Index 0 should decompose to level_vals = [0, 0, 0, 0, 0, 0]
// Python convention: codes = (level_vals - half_width) / half_width
// For levels [8,8,8,5,5,5]: half_width=[4,4,4,2,2,2]
// codes = [(0-4)/4, (0-4)/4, (0-4)/4, (0-2)/2, (0-2)/2, (0-2)/2]
// = [-1, -1, -1, -1, -1, -1]
let indices = Tensor::new(&[[0i64]], dev)?.unsqueeze(2)?; // (1, 1, 1)
let result = fsq.get_output_from_indices(&indices)?;
let vals = result.squeeze(0)?.squeeze(0)?.to_vec1::<f32>()?;
assert!((vals[0] - (-1.0)).abs() < 1e-5, "val[0]={}", vals[0]);
assert!((vals[3] - (-1.0)).abs() < 1e-5, "val[3]={}", vals[3]);
// Index that corresponds to center: half_width values for each level
// level_vals = [4, 4, 4, 2, 2, 2]
// packed index = 4*1 + 4*8 + 4*64 + 2*512 + 2*2560 + 2*12800
// = 4 + 32 + 256 + 1024 + 5120 + 25600 = 32036
// codes = [0, 0, 0, 0, 0, 0]
let indices = Tensor::new(&[[32036i64]], dev)?.unsqueeze(2)?;
let result = fsq.get_output_from_indices(&indices)?;
let vals = result.squeeze(0)?.squeeze(0)?.to_vec1::<f32>()?;
for (i, &v) in vals.iter().enumerate() {
assert!(v.abs() < 1e-5, "center val[{i}]={v}, expected 0");
}
let x = Tensor::new(
&[[
[0.3f32, -0.9, 2.0, 0.1, -0.05, 0.6],
[-3.0, 0.0, 0.49, -0.6, 0.9, -0.2],
]],
&Device::Cpu,
)?;
let (q, idx) = fsq.forward(&x)?;
let q = q.flatten_all()?.to_vec1::<f32>()?;
close(
&q,
&[
3.0 / 7.0,
-5.0 / 7.0,
1.0,
0.0,
0.0,
0.5,
-1.0,
1.0 / 7.0,
3.0 / 7.0,
-0.5,
1.0,
0.0,
],
);
assert_eq!(idx.flatten_all()?.to_vec1::<i64>()?, vec![45005, 36704]);
// And the indices decode back to the same codes.
let back = fsq
.get_output_from_indices(&idx)?
.flatten_all()?
.to_vec1::<f32>()?;
close(&back, &q);
Ok(())
}
}
+53 -3
View File
@@ -171,7 +171,10 @@ impl Module for OobleckEncoderBlock {
#[derive(Debug, Clone)]
pub struct OobleckDecoderBlock {
snake1: Snake1d,
/// Built unpadded; the padding is trimmed from its output instead. See
/// [`upsample`].
conv_t1: ConvTranspose1d,
trim: usize,
res_unit1: OobleckResidualUnit,
res_unit2: OobleckResidualUnit,
res_unit3: OobleckResidualUnit,
@@ -182,7 +185,7 @@ impl OobleckDecoderBlock {
let snake1 = Snake1d::new(input_dim, vb.pp("snake1"))?;
let cfg = ConvTranspose1dConfig {
stride,
padding: stride.div_ceil(2),
padding: 0,
..Default::default()
};
let conv_t1 = encodec::conv_transpose1d_weight_norm(
@@ -199,6 +202,7 @@ impl OobleckDecoderBlock {
Ok(Self {
snake1,
conv_t1,
trim: stride.div_ceil(2),
res_unit1,
res_unit2,
res_unit3,
@@ -208,14 +212,25 @@ impl OobleckDecoderBlock {
impl Module for OobleckDecoderBlock {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
xs.apply(&self.snake1)?
.apply(&self.conv_t1)?
upsample(&xs.apply(&self.snake1)?, &self.conv_t1, self.trim)?
.apply(&self.res_unit1)?
.apply(&self.res_unit2)?
.apply(&self.res_unit3)
}
}
/// A transposed convolution with `padding = trim`, computed as the
/// unpadded convolution with `trim` samples cut from each end, which is
/// the same result. candle's CUDA backend only takes its matmul (col2im)
/// path for unpadded transposed convolutions; with padding it falls back
/// to a direct kernel that made the VAE decode some 30x slower than the
/// denoise on an RTX 3060.
fn upsample(xs: &Tensor, conv: &ConvTranspose1d, trim: usize) -> Result<Tensor> {
let ys = xs.apply(conv)?;
let len = ys.dim(2)?;
ys.narrow(2, trim, len - 2 * trim)
}
// ---------------------------------------------------------------------------
// OobleckEncoder
// ---------------------------------------------------------------------------
@@ -718,4 +733,39 @@ mod tests {
);
Ok(())
}
#[test]
fn unpadded_then_trimmed_matches_the_padded_transposed_conv() -> Result<()> {
let dev = Device::Cpu;
for stride in [2usize, 4, 5, 8, 10] {
let k = 2 * stride;
let pad = stride.div_ceil(2);
let x = Tensor::randn(0f32, 1.0, (1, 6, 9), &dev)?;
let w = Tensor::randn(0f32, 1.0, (6, 4, k), &dev)?;
let b = Tensor::randn(0f32, 1.0, 4, &dev)?;
let padded = ConvTranspose1d::new(
w.clone(),
Some(b.clone()),
ConvTranspose1dConfig {
stride,
padding: pad,
..Default::default()
},
);
let unpadded = ConvTranspose1d::new(
w,
Some(b),
ConvTranspose1dConfig {
stride,
..Default::default()
},
);
let want = x.apply(&padded)?;
let got = upsample(&x, &unpadded, pad)?;
assert_eq!(want.dims(), got.dims(), "stride {stride}");
let diff = (want - got)?.abs()?.max_all()?.to_scalar::<f32>()?;
assert!(diff < 1e-4, "stride {stride}: max diff {diff}");
}
Ok(())
}
}
@@ -0,0 +1,324 @@
//! 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)
}
/// 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());
}
#[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;
+313 -11
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,32 @@ 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>;
}
/// 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 +129,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 +272,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 +425,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 +467,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 +518,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 +546,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 +615,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,
})
}
}
@@ -534,6 +685,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 +711,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 +732,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 +758,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 +820,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 +906,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 +1097,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(),
)
};
@@ -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
@@ -37,11 +37,17 @@
pub mod config;
pub mod decoder;
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 +93,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,
@@ -849,6 +855,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,
@@ -0,0 +1,684 @@
//! Routed experts on Strata's grouped kernels, from a GGUF's own blocks.
//!
//! Neuron keeps routing. For each layer this module groups the routed
//! tokens by expert, makes each active expert's `[gate | up | down]`
//! blob addressable on the device, and runs them all in one
//! `native_expert_grouped` launch.
//!
//! An expert comes from the VRAM tier when it is held. Decode-sized
//! forwards admit what they miss. A prompt chunk must not (see
//! [`ExpertTier::peek`]), so its misses are copied into a reusable arena
//! for the duration of that layer.
use std::ffi::c_void;
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result, ensure};
use candle_core::cuda_backend::cudarc::driver::result::mem_pool;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr, DeviceSlice, sys};
use candle_core::{CudaDevice, CudaStorage, DType, Device, Storage, Tensor};
use memmap2::{Advice, Mmap};
use rayon::prelude::*;
use super::gguf_index::{GgufIndex, GgufTensor, read_expert_profile};
use crate::cuda::strata as ffi;
use crate::harness::arch::qwen3_5::expert_tier::ExpertTier;
use crate::harness::arch::qwen3_5::moe::{
ExternalExpertSource, ExternalExperts, TIER_ADMIT_MAX_ROWS,
};
const Q8_1_BLOCK_BYTES: usize = 36;
const Q8_1_BLOCK_VALUES: usize = 32;
/// Pinned host memory expert blobs are staged through. Pinned because
/// an unpinned source makes the driver stage it again, at a fraction of
/// the link's speed.
const STAGING_BYTES: usize = 2 << 30;
/// Pinned host memory. Freed on the device worker with the model.
struct PinnedBuffer {
ptr: *mut u8,
len: usize,
}
// SAFETY: the buffer is plain host memory, and every access is made
// while holding the workspace lock.
unsafe impl Send for PinnedBuffer {}
impl PinnedBuffer {
fn new(len: usize) -> candle_core::Result<Self> {
// SAFETY: returns null or an allocation of `len` bytes.
let ptr = unsafe { ffi::neuron_strata_pinned_alloc(len) }.cast::<u8>();
if ptr.is_null() {
candle_core::bail!("cannot pin {len} bytes of staging memory");
}
Ok(Self { ptr, len })
}
}
impl Drop for PinnedBuffer {
fn drop(&mut self) {
// SAFETY: allocated by `neuron_strata_pinned_alloc`, freed once.
unsafe { ffi::neuron_strata_pinned_free(self.ptr.cast()) };
}
}
/// An expert's blob held in VRAM.
pub struct ExpertSlot {
blob: CudaSlice<u8>,
}
/// A CUDA memory pool for the tier's experts alone.
///
/// Thousands of long-lived expert blobs allocated from the default pool
/// sit among the forward pass's transient tensors and pin the blocks
/// they share, so the pool cannot hand those blocks back: measured on
/// one 5090, 29 GB reserved against a 21 GB peak of live data. With
/// their own pool the experts only ever share blocks with each other,
/// and the default pool's trims return the transients' memory.
struct TierPool(sys::CUmemoryPool);
// SAFETY: a pool handle may be used from any thread of its context, and
// the source is only used from its device worker.
unsafe impl Send for TierPool {}
// SAFETY: as above; allocation from a pool is thread-safe in the driver.
unsafe impl Sync for TierPool {}
impl TierPool {
fn new(ordinal: usize) -> candle_core::Result<Self> {
// SAFETY: an all-zero props struct is valid; the fields that
// matter are set below, and zero handle types means none.
let mut props: sys::CUmemPoolProps = unsafe { std::mem::zeroed() };
props.allocType = sys::CUmemAllocationType::CU_MEM_ALLOCATION_TYPE_PINNED;
props.location.type_ = sys::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE;
props.location.id = ordinal as i32;
// SAFETY: `props` describes this device.
let pool = unsafe { mem_pool::create(&props) }.map_err(candle_err)?;
// Keep what eviction frees: the next admission reuses it.
let mut keep = u64::MAX;
// SAFETY: the release threshold is a cuuint64_t.
unsafe {
mem_pool::set_attribute(
pool,
sys::CUmemPool_attribute::CU_MEMPOOL_ATTR_RELEASE_THRESHOLD,
(&raw mut keep).cast(),
)
}
.map_err(candle_err)?;
Ok(Self(pool))
}
fn alloc(&self, device: &CudaDevice, bytes: usize) -> candle_core::Result<CudaSlice<u8>> {
let stream = device.cuda_stream();
let mut ptr: sys::CUdeviceptr = 0;
// SAFETY: the pool and stream belong to this device's context.
unsafe { sys::cuMemAllocFromPoolAsync(&mut ptr, bytes, self.0, stream.cu_stream()) }
.result()
.map_err(candle_err)?;
// SAFETY: `ptr` is a fresh allocation of `bytes` bytes. Its drop
// frees it stream-ordered, which returns it to this pool.
Ok(unsafe { stream.upgrade_device_ptr(ptr, bytes) })
}
}
impl Drop for TierPool {
fn drop(&mut self) {
// SAFETY: created by `new`; the driver defers the destruction
// until every allocation from it has been freed.
let _ = unsafe { mem_pool::destroy(self.0) };
}
}
fn device_address<T: candle_core::cuda_backend::cudarc::driver::DeviceRepr + 'static>(
slice: &CudaSlice<T>,
) -> u64 {
slice.device_ptr(slice.stream()).0
}
/// Per-layer timing, from `NEURON_EXPERT_TIMING`.
fn timing_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("NEURON_EXPERT_TIMING").is_some())
}
fn candle_err(e: impl std::fmt::Display) -> candle_core::Error {
candle_core::Error::msg(e.to_string())
}
/// Where one projection of a layer's experts lies.
#[derive(Clone, Copy)]
struct Role {
shard: usize,
offset: usize,
bytes: usize,
}
struct Layer {
gu_type: i32,
d_type: i32,
gate: Role,
up: Role,
down: Role,
blob_bytes: usize,
}
/// One expert blob to copy to the device.
#[derive(Clone, Copy)]
struct Upload {
expert: usize,
address: u64,
in_arena: bool,
}
/// Device buffers reused from layer to layer.
///
/// Reuse is safe because each layer synchronizes the stream before
/// returning, so no queued kernel still reads them.
#[derive(Default)]
struct Workspace {
q8: Option<CudaSlice<u8>>,
scratch: Option<CudaSlice<u8>>,
grp_ptr: Option<CudaSlice<u64>>,
grp_start: Option<CudaSlice<i32>>,
n_groups: Option<CudaSlice<i32>>,
ent_dst: Option<CudaSlice<i32>>,
ent_tok: Option<CudaSlice<i32>>,
arena: Option<CudaSlice<u8>>,
staging: Option<PinnedBuffer>,
}
fn ensure_capacity<T: candle_core::cuda_backend::cudarc::driver::DeviceRepr + 'static>(
device: &CudaDevice,
slot: &mut Option<CudaSlice<T>>,
len: usize,
) -> candle_core::Result<()> {
if slot.as_ref().is_none_or(|s| s.len() < len) {
*slot = None;
// SAFETY: every user writes the range it later reads.
*slot = Some(unsafe { device.alloc::<T>(len.max(1))? });
}
Ok(())
}
fn upload<T: candle_core::cuda_backend::cudarc::driver::DeviceRepr + 'static>(
device: &CudaDevice,
slot: &mut Option<CudaSlice<T>>,
data: &[T],
) -> candle_core::Result<u64> {
ensure_capacity(device, slot, data.len())?;
let buffer = slot.as_mut().expect("capacity was just ensured");
device.memcpy_htod(data, &mut buffer.slice_mut(..data.len()))?;
Ok(device_address(buffer))
}
/// The model's GGUF experts, shared by its MoE blocks.
pub struct GgufExpertSource {
device: CudaDevice,
n_embd: usize,
n_ff: usize,
maps: Vec<Mmap>,
layers: Vec<Layer>,
tier: Option<Arc<ExpertTier<ExpertSlot>>>,
workspace: Mutex<Workspace>,
/// Declared after `tier`, so the experts are freed first.
tier_pool: TierPool,
}
fn role(
index: &GgufIndex,
layer: usize,
name: &str,
want_dims: [u64; 3],
) -> Result<(GgufTensor, usize)> {
let key = format!("blk.{layer}.ffn_{name}_exps.weight");
let tensor = index
.tensors
.get(&key)
.with_context(|| format!("GGUF has no {key}"))?;
ensure!(
tensor.dims == want_dims,
"{key} is {:?}, expected {want_dims:?}",
tensor.dims
);
// SAFETY: a pure function of its integer arguments.
let row = unsafe { ffi::neuron_strata_row_bytes(tensor.ggml_type as i32, want_dims[0] as i64) };
ensure!(row > 0, "{key}: unsupported type {}", tensor.ggml_type);
Ok((tensor.clone(), row * want_dims[1] as usize))
}
impl GgufExpertSource {
/// Indexes the GGUF whose first shard is `first` and maps its shards.
pub fn open(
first: &Path,
device: &Device,
layers: usize,
experts: usize,
n_embd: usize,
n_ff: usize,
tier_budget_mb: Option<u64>,
) -> 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::Random).context("advise expert map")?;
maps.push(map);
}
let (e, h, f) = (experts as u64, n_embd as u64, n_ff as u64);
let mut parsed = Vec::with_capacity(layers);
for layer in 0..layers {
let (gate, gate_bytes) = role(&index, layer, "gate", [h, f, e])?;
let (up, up_bytes) = role(&index, layer, "up", [h, f, e])?;
let (down, down_bytes) = role(&index, layer, "down", [f, h, e])?;
ensure!(
gate.ggml_type == up.ggml_type,
"layer {layer}: gate and up differ in type"
);
let (gu_type, d_type) = (gate.ggml_type as i32, down.ggml_type as i32);
// SAFETY: pure functions of their integer arguments.
let (supported, blob_bytes) = unsafe {
(
ffi::neuron_strata_expert_supported(
gu_type,
d_type,
n_embd as i64,
n_ff as i64,
),
ffi::neuron_strata_expert_bytes(gu_type, d_type, n_embd as i64, n_ff as i64),
)
};
ensure!(
supported != 0,
"layer {layer}: no kernels for types {gu_type}/{d_type}"
);
ensure!(
blob_bytes == gate_bytes + up_bytes + down_bytes,
"layer {layer}: blob is {blob_bytes} bytes, roles sum to {}",
gate_bytes + up_bytes + down_bytes
);
for (tensor, bytes) in [(&gate, gate_bytes), (&up, up_bytes), (&down, down_bytes)] {
let end = tensor.offset + (bytes * experts) as u64;
ensure!(
end <= maps[tensor.shard].len() as u64,
"layer {layer}: expert tensor runs past the end of its shard"
);
}
let as_role = |t: &GgufTensor, bytes| Role {
shard: t.shard,
offset: t.offset as usize,
bytes,
};
parsed.push(Layer {
gu_type,
d_type,
gate: as_role(&gate, gate_bytes),
up: as_role(&up, up_bytes),
down: as_role(&down, down_bytes),
blob_bytes,
});
}
let tier = tier_budget_mb.map(|mb| ExpertTier::new(mb << 20));
let tier_pool = TierPool::new(device.cuda_stream().context().ordinal())?;
let profile = std::env::var_os("NEURON_EXPERT_PROFILE")
.map(|path| read_expert_profile(Path::new(&path), layers, experts))
.transpose()?;
tracing::info!(
shards = maps.len(),
layers,
tier_budget_mb,
"native expert kernels enabled, reading experts from GGUF"
);
let source = Self {
device,
n_embd,
n_ff,
maps,
layers: parsed,
tier,
workspace: Mutex::new(Workspace::default()),
tier_pool,
};
if let Some(ranked) = profile {
let started = std::time::Instant::now();
let filled = source.warm_tier(&ranked)?;
tracing::info!(
filled,
elapsed_ms = started.elapsed().as_millis() as u64,
"VRAM expert tier filled from profile"
);
}
Ok(source)
}
fn copy_blob(&self, layer: &Layer, expert: usize, dst: &mut [u8]) {
let (gate, rest) = dst.split_at_mut(layer.gate.bytes);
let (up, down) = rest.split_at_mut(layer.up.bytes);
for (out, role) in [(gate, layer.gate), (up, layer.up), (down, layer.down)] {
let start = role.offset + expert * role.bytes;
out.copy_from_slice(&self.maps[role.shard][start..start + role.bytes]);
}
}
/// Queues blob copies on the stream.
///
/// The last batch's staging memory stays in use until the caller
/// synchronizes. Neighbouring arena blobs are copied as one; slots
/// are separate allocations even when their addresses adjoin, and a
/// copy may not span two allocations.
fn stage_blobs(
&self,
staging: &mut Option<PinnedBuffer>,
layer: &Layer,
items: &[Upload],
) -> candle_core::Result<()> {
if items.is_empty() {
return Ok(());
}
if staging.is_none() {
*staging = Some(PinnedBuffer::new(STAGING_BYTES)?);
}
let pinned = staging.as_ref().expect("allocated above");
let stream = self.device.cuda_stream();
let per_batch = pinned.len / layer.blob_bytes;
for (b, batch) in items.chunks(per_batch).enumerate() {
if b > 0 {
stream.synchronize().map_err(candle_err)?;
}
// SAFETY: the stream has passed any earlier use of this
// range, and the lock gives this call the only reference.
let host = unsafe {
std::slice::from_raw_parts_mut(pinned.ptr, batch.len() * layer.blob_bytes)
};
host.par_chunks_mut(layer.blob_bytes)
.zip(batch.par_iter())
.for_each(|(dst, item)| self.copy_blob(layer, item.expert, dst));
let mut i = 0;
while i < batch.len() {
let mut run = 1;
while batch[i].in_arena
&& i + run < batch.len()
&& batch[i + run].in_arena
&& batch[i + run].address == batch[i].address + (run * layer.blob_bytes) as u64
{
run += 1;
}
// SAFETY: both ranges are live for `run` blobs, and the
// staging range is not rewritten before a synchronize.
let status = unsafe {
ffi::neuron_strata_copy_to_device(
batch[i].address as *mut c_void,
host.as_ptr().add(i * layer.blob_bytes).cast(),
run * layer.blob_bytes,
stream.cu_stream() as *mut c_void,
)
};
if status != 0 {
candle_core::bail!("expert upload failed with CUDA status {status}");
}
i += run;
}
}
Ok(())
}
/// Fills the tier with the profile's hottest experts, so the first
/// requests do not pay for its warm-up.
fn warm_tier(&self, ranked: &[(u16, u16)]) -> candle_core::Result<usize> {
let Some(tier) = &self.tier else {
return Ok(0);
};
let mut workspace = self.workspace.lock().map_err(candle_err)?;
let capacity = tier.capacity_bytes();
let mut used = 0_u64;
let mut by_layer: Vec<Vec<Upload>> = vec![Vec::new(); self.layers.len()];
let mut filled = 0;
for &(l, e) in ranked {
let (l, e) = (l as usize, e as usize);
let bytes = self.layers[l].blob_bytes as u64;
if used + bytes > capacity {
break;
}
used += bytes;
let pending = &mut by_layer[l];
tier.get_or_load(l as u32, e as u32, bytes, || -> candle_core::Result<_> {
// Filled by `stage_blobs` before first use.
let blob = self.tier_pool.alloc(&self.device, bytes as usize)?;
pending.push(Upload {
expert: e,
address: device_address(&blob),
in_arena: false,
});
Ok(ExpertSlot { blob })
})?;
filled += 1;
}
for (l, pending) in by_layer.iter().enumerate() {
self.stage_blobs(&mut workspace.staging, &self.layers[l], pending)?;
self.device
.cuda_stream()
.synchronize()
.map_err(candle_err)?;
}
Ok(filled)
}
fn forward_layer(
&self,
layer_index: usize,
xs: &Tensor,
tokens_for: &[Vec<u32>],
weights_for: &[Vec<f32>],
k: usize,
) -> candle_core::Result<Tensor> {
let started = std::time::Instant::now();
let layer = &self.layers[layer_index];
let (rows, hidden) = xs.dims2()?;
if hidden != self.n_embd {
candle_core::bail!(
"activations are {hidden} wide, experts take {}",
self.n_embd
);
}
let entries = rows * k;
let active: Vec<usize> = (0..tokens_for.len())
.filter(|&e| !tokens_for[e].is_empty())
.collect();
let admit = rows <= TIER_ADMIT_MAX_ROWS;
let mut workspace = self.workspace.lock().map_err(candle_err)?;
let ws = &mut *workspace;
// Resolve every active expert to a device address.
let mut held = Vec::with_capacity(active.len());
let mut addresses = vec![0_u64; active.len()];
let mut misses = Vec::new();
let mut uploads: Vec<Upload> = Vec::new();
for (g, &e) in active.iter().enumerate() {
let slot = match &self.tier {
Some(tier) if admit => Some(tier.get_or_load(
layer_index as u32,
e as u32,
layer.blob_bytes as u64,
|| -> candle_core::Result<_> {
// Filled by `stage_blobs` before the launch.
let blob = self.tier_pool.alloc(&self.device, layer.blob_bytes)?;
uploads.push(Upload {
expert: e,
address: device_address(&blob),
in_arena: false,
});
Ok(ExpertSlot { blob })
},
)?),
Some(tier) => tier.peek(layer_index as u32, e as u32),
None => None,
};
match slot {
Some(slot) => {
addresses[g] = device_address(&slot.blob);
held.push(slot);
}
None => misses.push((g, e)),
}
}
let resolved = started.elapsed();
if !misses.is_empty() {
ensure_capacity(&self.device, &mut ws.arena, misses.len() * layer.blob_bytes)?;
let arena_address = device_address(ws.arena.as_ref().expect("allocated above"));
for (i, &(g, e)) in misses.iter().enumerate() {
let address = arena_address + (i * layer.blob_bytes) as u64;
addresses[g] = address;
uploads.push(Upload {
expert: e,
address,
in_arena: true,
});
}
}
self.stage_blobs(&mut ws.staging, layer, &uploads)?;
let streamed = started.elapsed();
// Each token writes its k outputs side by side, so the mix below
// is one multiply and one sum rather than a scatter.
let mut grp_start = Vec::with_capacity(active.len() + 1);
let mut ent_dst = Vec::with_capacity(entries);
let mut ent_tok = Vec::with_capacity(entries);
let mut weights = vec![0_f32; entries];
let mut rank = vec![0_usize; rows];
for &e in &active {
grp_start.push(ent_dst.len() as i32);
for (&token, &weight) in tokens_for[e].iter().zip(&weights_for[e]) {
let token = token as usize;
let dst = token * k + rank[token];
rank[token] += 1;
ent_dst.push(dst as i32);
ent_tok.push(token as i32);
weights[dst] = weight;
}
}
grp_start.push(ent_dst.len() as i32);
if ent_dst.len() != entries || rank.iter().any(|&r| r != k) {
candle_core::bail!("routing did not give every token {k} experts");
}
let grp_ptr = upload(&self.device, &mut ws.grp_ptr, &addresses)?;
let grp_start_ptr = upload(&self.device, &mut ws.grp_start, &grp_start)?;
let n_groups = upload(&self.device, &mut ws.n_groups, &[active.len() as i32])?;
let ent_dst_ptr = upload(&self.device, &mut ws.ent_dst, &ent_dst)?;
let ent_tok_ptr = upload(&self.device, &mut ws.ent_tok, &ent_tok)?;
ensure_capacity(
&self.device,
&mut ws.q8,
rows * (hidden / Q8_1_BLOCK_VALUES) * Q8_1_BLOCK_BYTES,
)?;
// SAFETY: a pure function of its integer arguments.
let scratch_bytes =
unsafe { ffi::neuron_strata_expert_scratch_bytes(entries as i64, self.n_ff as i64) };
ensure_capacity(&self.device, &mut ws.scratch, scratch_bytes)?;
let prepared = started.elapsed();
let x = xs.to_dtype(DType::F32)?.contiguous()?;
let (storage, x_layout) = x.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
candle_core::bail!("native experts need activations on the GPU");
};
let x_slice = storage.as_cuda_slice::<f32>()?;
let x_ptr = x_slice
.slice(x_layout.start_offset()..)
.device_ptr(x_slice.stream())
.0 as *const f32;
// SAFETY: the kernel writes `entries * hidden` values.
let out = unsafe { self.device.alloc::<f32>(entries * hidden)? };
let stream = self.device.cuda_stream().cu_stream() as *mut c_void;
// SAFETY: every pointer is a live device allocation sized above
// and owned for the call. `held` keeps tier slots alive until
// the synchronize below, including any evicted while resolving.
unsafe {
let q8 = device_address(ws.q8.as_ref().expect("allocated")) as *mut c_void;
ffi::neuron_strata_quantize_q8_1(x_ptr, rows as i64, hidden as i64, q8, stream);
ffi::neuron_strata_expert_grouped(
layer.gu_type,
layer.d_type,
self.n_embd as i64,
self.n_ff as i64,
grp_ptr as *const u64,
grp_start_ptr as *const i32,
n_groups as *const i32,
ent_dst_ptr as *const i32,
ent_tok_ptr as *const i32,
active.len() as i64,
entries as i64,
q8 as *const c_void,
device_address(ws.scratch.as_ref().expect("allocated")) as *mut c_void,
device_address(&out) as *mut f32,
stream,
);
}
self.device
.cuda_stream()
.synchronize()
.map_err(candle_err)?;
drop(held);
if timing_enabled() {
let finished = started.elapsed();
tracing::info!(
layer = layer_index,
rows,
active = active.len(),
misses = misses.len(),
resolve_us = resolved.as_micros() as u64,
arena_us = (streamed - resolved).as_micros() as u64,
arrays_us = (prepared - streamed).as_micros() as u64,
kernel_us = (finished - prepared).as_micros() as u64,
"native experts"
);
}
let out = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
(rows, k, hidden),
));
let weights = Tensor::from_vec(weights, (rows, k, 1), xs.device())?;
out.broadcast_mul(&weights)?.sum(1)
}
}
struct NativeBlock {
source: Arc<GgufExpertSource>,
layer: usize,
}
impl ExternalExperts for NativeBlock {
fn forward(
&self,
xs: &Tensor,
tokens_for: &[Vec<u32>],
weights_for: &[Vec<f32>],
k: usize,
) -> candle_core::Result<Tensor> {
self.source
.forward_layer(self.layer, xs, tokens_for, weights_for, k)
}
}
/// Hands each MoE block its view of one [`GgufExpertSource`].
pub struct NativeExpertFactory(pub Arc<GgufExpertSource>);
impl ExternalExpertSource for NativeExpertFactory {
fn block(&self, layer: usize) -> Result<Box<dyn ExternalExperts>> {
ensure!(
layer < self.0.layers.len(),
"no GGUF experts for layer {layer}"
);
Ok(Box::new(NativeBlock {
source: self.0.clone(),
layer,
}))
}
}
+611 -51
View File
@@ -10,6 +10,7 @@
//! the worker's audio slab, one `Job::GenerateAudio` runs a whole song, and
//! the reply is CPU-side samples. WAV encoding happens on the async side.
use super::arch::acestep::linear::with_quant;
use super::arch::acestep::pipeline::{AceStepPipeline, GenerationParams, LmMetadata};
use super::arch::acestep::{AceStepConfig, VaeConfig, lm::LmConfig, qwen3, sampling};
use anyhow::{Context, Result};
@@ -77,12 +78,109 @@ pub fn is_acestep_layout(filenames: &[&str]) -> bool {
&& filenames.contains(&format!("{VAE_DIR}/diffusion_pytorch_model.safetensors").as_str())
}
/// A resolved snapshot: the root directory every component sits under, and
/// which planner (if any) it has.
/// A resolved snapshot: the root directory every component sits under,
/// which planner (if any) it has, and how this host lays it out.
#[derive(Debug, Clone)]
pub struct AceStepFiles {
pub root: PathBuf,
pub planner: Option<String>,
pub layout: AceStepLayout,
}
/// Where a pipeline component runs (#385).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Place {
/// The model's device.
#[default]
Gpu,
/// The host CPU, in f32.
Cpu,
}
impl Place {
fn parse(component: &str, value: Option<&str>) -> Result<Self> {
match value.map(str::to_ascii_lowercase).as_deref() {
None | Some("gpu") | Some("cuda") => Ok(Self::Gpu),
Some("cpu") => Ok(Self::Cpu),
Some(other) => anyhow::bail!(
"audio placement for {component} is '{other}'; expected \"gpu\" or \"cpu\" \
(a component on another card of the host is not supported yet)"
),
}
}
}
/// How an ACE-Step pipeline is laid out on this host (#385): weight
/// quantization, compute precision, where each component runs, and the
/// memory budget it must fit.
#[derive(Debug, Clone, Default)]
pub struct AceStepLayout {
/// Quantizes the DiT's, the text encoder's and the planner's linear
/// layers. Quantized pipelines compute in f32.
pub quant: Option<candle_core::quantized::GgmlDType>,
/// f32 compute on the GPU even without quantization.
pub f32_compute: bool,
pub text_encoder: Place,
pub planner: Place,
pub dit: Place,
pub vae: Place,
pub vram_budget_mb: Option<u64>,
pub enforce_vram_budget: bool,
}
impl AceStepLayout {
pub fn from_config(cfg: &crate::config::AudioConfig) -> Result<Self> {
let quant = match cfg.quant.as_deref().map(str::to_ascii_lowercase).as_deref() {
None | Some("") | Some("none") => None,
Some("q8_0") | Some("q8") => Some(candle_core::quantized::GgmlDType::Q8_0),
Some(other) => {
anyhow::bail!("unsupported audio quant '{other}'; ACE-Step serves q8_0 or none")
}
};
let f32_compute = match cfg
.compute
.as_deref()
.map(str::to_ascii_lowercase)
.as_deref()
{
None | Some("bf16") => false,
Some("f32") => true,
Some(other) => {
anyhow::bail!("unsupported audio compute '{other}'; expected bf16 or f32")
}
};
if cfg.enforce_vram_budget && cfg.vram_budget_mb.is_none() {
anyhow::bail!("enforce_vram_budget needs vram_budget_mb");
}
let p = &cfg.placement;
Ok(Self {
quant,
f32_compute,
text_encoder: Place::parse("text_encoder", p.text_encoder.as_deref())?,
planner: Place::parse("planner", p.planner.as_deref())?,
dit: Place::parse("dit", p.dit.as_deref())?,
vae: Place::parse("vae", p.vae.as_deref())?,
vram_budget_mb: cfg.vram_budget_mb,
enforce_vram_budget: cfg.enforce_vram_budget,
})
}
/// The device and dtype a component placed at `place` runs with.
fn component(&self, place: Place, gpu: &Device) -> (Device, DType) {
match place {
Place::Cpu => (Device::Cpu, DType::F32),
Place::Gpu if gpu.is_cpu() || self.quant.is_some() || self.f32_compute => {
(gpu.clone(), DType::F32)
}
Place::Gpu => (gpu.clone(), DType::BF16),
}
}
/// VAE decode chunk, in latent frames. A budget halves the default
/// chunk, which roughly halves the decoder's transient memory.
fn vae_chunk_frames(&self) -> Option<usize> {
self.vram_budget_mb.map(|_| 64)
}
}
/// One generation's parameters, already validated against the model's limits.
@@ -123,6 +221,10 @@ impl AudioGenResult {
pub struct AceStepEngine {
pipeline: AceStepPipeline,
has_planner: bool,
vae_chunk_frames: Option<usize>,
/// Device memory held so the pipeline sees only its budget
/// (`enforce_vram_budget`). Dropped with the engine.
_ballast: Option<candle_core::Tensor>,
}
fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T> {
@@ -131,13 +233,18 @@ fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T> {
}
impl AceStepEngine {
/// Build every component on `device`: bf16 on a GPU, f32 on the CPU.
/// Build every component where `files.layout` places it: bf16 on a
/// GPU, f32 on the CPU or when quantized or asked for.
pub fn load(files: &AceStepFiles, device: &Device) -> Result<Self> {
let dtype = if device.is_cpu() {
DType::F32
} else {
DType::BF16
let layout = &files.layout;
let ballast = match (layout.enforce_vram_budget, layout.vram_budget_mb) {
(true, Some(budget)) => hold_all_but(device, budget)?,
_ => None,
};
let (dit_device, dtype) = layout.component(layout.dit, device);
let (text_device, text_dtype) = layout.component(layout.text_encoder, device);
let (vae_device, vae_dtype) = layout.component(layout.vae, device);
let (planner_device, planner_dtype) = layout.component(layout.planner, device);
let root = &files.root;
let dit = root.join(DIT_DIR);
let te = root.join(TEXT_ENCODER_DIR);
@@ -150,19 +257,27 @@ impl AceStepEngine {
// SAFETY: the snapshot is a read-only cache the daemon owns; the
// files are not modified while mapped.
let dit_vb = unsafe {
VarBuilder::from_mmaped_safetensors(&[dit.join("model.safetensors")], dtype, device)?
VarBuilder::from_mmaped_safetensors(
&[dit.join("model.safetensors")],
dtype,
&dit_device,
)?
};
let vae_vb = unsafe {
VarBuilder::from_mmaped_safetensors(
&[vae.join("diffusion_pytorch_model.safetensors")],
dtype,
device,
vae_dtype,
&vae_device,
)?
};
// The embedding model's tensors carry a `model.` prefix the bare
// qwen3 encoder does not expect.
let text_vb = unsafe {
VarBuilder::from_mmaped_safetensors(&[te.join("model.safetensors")], dtype, device)?
VarBuilder::from_mmaped_safetensors(
&[te.join("model.safetensors")],
text_dtype,
&text_device,
)?
}
.rename_f(|n| n.strip_prefix("model.").unwrap_or(n).to_string());
@@ -170,25 +285,36 @@ impl AceStepEngine {
&dit.join("silence_latent.pt"),
dit_config.audio_acoustic_hidden_dim,
dtype,
device,
)?;
let mut pipeline = AceStepPipeline::new(
&dit_config,
&vae_config,
&text_config,
dit_vb,
vae_vb,
text_vb,
&te.join("tokenizer.json"),
silence_latent,
false,
&dit_device,
)?;
// The VAE builds outside the scope: its decoder is convolutions, and
// the quantization scope only touches linear layers anyway.
let mut pipeline = with_quant(layout.quant, || {
AceStepPipeline::new(
&dit_config,
&vae_config,
&text_config,
dit_vb,
vae_vb,
text_vb,
&te.join("tokenizer.json"),
silence_latent,
false,
)
})?;
// The planner is optional and runs only when asked for, so a planner
// that will not load leaves a working engine without one rather
// than failing the model.
let has_planner = match &files.planner {
Some(dir) => match Self::load_planner(&mut pipeline, &root.join(dir), dtype, device) {
Some(dir) => match with_quant(layout.quant, || {
Self::load_planner(
&mut pipeline,
&root.join(dir),
planner_dtype,
&planner_device,
)
}) {
Ok(()) => true,
Err(e) => {
tracing::warn!(planner = %dir, error = %format!("{e:#}"), "song planner failed to load; serving without it");
@@ -197,9 +323,20 @@ impl AceStepEngine {
},
None => false,
};
tracing::info!(
quant = ?layout.quant,
dit = ?(dit_device.location(), dtype),
text_encoder = ?(text_device.location(), text_dtype),
vae = ?(vae_device.location(), vae_dtype),
planner = ?has_planner.then(|| (planner_device.location(), planner_dtype)),
budget_mb = ?layout.vram_budget_mb,
"ACE-Step pipeline laid out"
);
Ok(Self {
pipeline,
has_planner,
vae_chunk_frames: layout.vae_chunk_frames(),
_ballast: ballast,
})
}
@@ -207,9 +344,8 @@ impl AceStepEngine {
self.has_planner
}
/// Load the planner LM into the pipeline. Its checkpoint stores the
/// decoder's tensors without the `model.` prefix the causal-LM wrapper
/// asks for, and ties the output head to the embeddings.
/// Load the planner LM into the pipeline. The output head is tied to
/// the embeddings.
fn load_planner(
pipeline: &mut AceStepPipeline,
dir: &Path,
@@ -219,8 +355,14 @@ impl AceStepEngine {
let lm_config: qwen3::Config = read_json(&dir.join("config.json"))?;
let lm_vb = unsafe {
VarBuilder::from_mmaped_safetensors(&[dir.join("model.safetensors")], dtype, device)?
}
.rename_f(|n| n.strip_prefix("model.").unwrap_or(n).to_string());
};
// The 1.7B checkpoint stores the decoder without the `model.`
// prefix; the 0.6B one keeps it. Strip it only where it is absent.
let lm_vb = if lm_vb.contains_tensor("model.embed_tokens.weight") {
lm_vb
} else {
lm_vb.rename_f(|n| n.strip_prefix("model.").unwrap_or(n).to_string())
};
pipeline.load_lm(&lm_config, lm_vb, &dir.join("tokenizer.json"))?;
Ok(())
}
@@ -240,17 +382,7 @@ impl AceStepEngine {
self.pipeline
.generate_lm_hints(&p.prompt, &p.lyrics, p.duration_secs, &cfg)?;
timing.plan_ms = t.elapsed().as_millis() as u64;
let metadata = LmMetadata {
bpm: meta.get("bpm").cloned(),
timesignature: meta.get("timesignature").cloned(),
keyscale: meta.get("keyscale").cloned(),
caption: meta.get("caption").cloned(),
language: meta
.get("language")
.or_else(|| meta.get("vocal_language"))
.cloned(),
};
(Some(hints), Some(metadata))
(Some(hints), Some(lm_metadata(&meta)))
} else {
(None, None)
};
@@ -268,12 +400,14 @@ impl AceStepEngine {
lm_metadata,
infer_method: sampling::InferMethod::Ode,
language: p.language.clone(),
vae_chunk_frames: self.vae_chunk_frames,
..Default::default()
};
let t = Instant::now();
let out = self.pipeline.text2music(&p.prompt, &p.lyrics, &params)?;
let audio = out.audio.to_dtype(DType::F32)?.to_device(&Device::Cpu)?;
timing.generate_ms = t.elapsed().as_millis() as u64;
timing.encode_ms = out.timing.encode_ms;
timing.generate_ms = out.timing.denoise_ms;
timing.decode_ms = out.timing.decode_ms;
let mut left = audio.get(0)?.to_vec1::<f32>()?;
let mut right = audio.get(1)?.to_vec1::<f32>()?;
@@ -290,6 +424,49 @@ impl AceStepEngine {
}
}
/// The plan's fields the DiT prompt carries.
fn lm_metadata(meta: &std::collections::BTreeMap<String, String>) -> LmMetadata {
LmMetadata {
bpm: meta.get("bpm").cloned(),
timesignature: meta.get("timesignature").cloned(),
keyscale: meta.get("keyscale").cloned(),
caption: meta.get("caption").cloned(),
language: meta
.get("language")
.or_else(|| meta.get("vocal_language"))
.cloned(),
}
}
/// Allocate all of `device`'s free memory except `budget_mb`, so what
/// loads next sees a card of the budget's size (#385). `None` on the CPU,
/// or when the device already has no more than the budget free.
#[cfg(feature = "cuda")]
fn hold_all_but(device: &Device, budget_mb: u64) -> Result<Option<candle_core::Tensor>> {
if device.is_cpu() {
return Ok(None);
}
// The device worker bound this device's context to the calling thread.
let (free, _) = candle_core::cuda::cudarc::driver::result::mem_get_info()
.map_err(|e| anyhow::anyhow!("mem_get_info: {e:?}"))?;
let hold = (free as u64).saturating_sub(budget_mb * 1024 * 1024);
if hold == 0 {
return Ok(None);
}
tracing::warn!(
held_mb = hold / (1024 * 1024),
budget_mb,
"holding device memory so the audio pipeline sees only its budget"
);
let t = candle_core::Tensor::zeros(hold as usize, DType::U8, device)?;
Ok(Some(t))
}
#[cfg(not(feature = "cuda"))]
fn hold_all_but(_device: &Device, _budget_mb: u64) -> Result<Option<candle_core::Tensor>> {
Ok(None)
}
// ── HeartMuLa (#393) ─────────────────────────────────────────────────
/// What HeartMuLa oss-3B serves: songs of 10 s to 4 min, as the evaluation
@@ -566,6 +743,55 @@ pub fn encode_flac_pcm16(left: &[f32], right: &[f32], sample_rate: u32) -> anyho
mod tests {
use super::*;
fn layout(toml: &str) -> Result<AceStepLayout> {
let cfg: crate::config::AudioConfig = toml::from_str(toml).unwrap();
AceStepLayout::from_config(&cfg)
}
#[test]
fn the_default_layout_is_bf16_on_the_gpu() {
let l = layout("").unwrap();
assert_eq!(l.quant, None);
// A CPU stands in for the GPU here; what matters is the dtype rule.
let gpu = Device::Cpu;
assert_eq!(
l.component(Place::Gpu, &gpu).1,
DType::F32,
"CPU is always f32"
);
assert_eq!(l.vae_chunk_frames(), None);
}
#[test]
fn the_pascal_recipe_parses_to_q8_with_f32_compute_and_a_budget() {
let l = layout(
r#"
quant = "q8_0"
vram_budget_mb = 8192
enforce_vram_budget = true
[placement]
text_encoder = "cpu"
"#,
)
.unwrap();
assert_eq!(l.quant, Some(candle_core::quantized::GgmlDType::Q8_0));
assert_eq!(l.text_encoder, Place::Cpu);
assert_eq!(l.dit, Place::Gpu);
assert_eq!(l.vae_chunk_frames(), Some(64));
}
#[test]
fn layout_errors_name_the_problem() {
let e = format!("{:#}", layout(r#"quant = "q4_k""#).unwrap_err());
assert!(e.contains("q4_k"), "{e}");
let e = format!("{:#}", layout(r#"compute = "f16""#).unwrap_err());
assert!(e.contains("f16"), "{e}");
let e = format!("{:#}", layout("[placement]\ndit = \"cuda:1\"").unwrap_err());
assert!(e.contains("dit") && e.contains("cuda:1"), "{e}");
let e = format!("{:#}", layout("enforce_vram_budget = true").unwrap_err());
assert!(e.contains("vram_budget_mb"), "{e}");
}
#[test]
fn heartmula_is_recognised_by_its_config() {
assert!(is_heartmula_config(
@@ -653,6 +879,7 @@ mod hardware {
let files = AceStepFiles {
root: root.into(),
planner: None,
layout: AceStepLayout::default(),
};
let t = Instant::now();
let mut engine = AceStepEngine::load(&files, &Device::Cpu).expect("load");
@@ -732,14 +959,32 @@ mod hardware {
};
let cases = std::env::var("ACESTEP_CASES")
.unwrap_or_else(|_| "instr_10s_noplan,vocal_es_20s_noplan".into());
// ACESTEP_LAYOUT (a `[harness.candle.audio]` body) and
// ACESTEP_DEVICE=cuda measure another layout's drift from the
// reference (#385). Only the default layout on the CPU is held to
// parity; any other is reported, and held to a drift bound.
let layout_toml = std::env::var("ACESTEP_LAYOUT").unwrap_or_default();
let cfg: crate::config::AudioConfig = toml::from_str(&layout_toml).unwrap();
let device = match std::env::var("ACESTEP_DEVICE").as_deref() {
Ok("cuda") => Device::new_cuda(0).unwrap(),
_ => Device::Cpu,
};
let parity = layout_toml.trim().is_empty() && device.is_cpu();
// (case, this layout's drift, upstream bf16's drift)
let mut drifts: Vec<(String, f32, f32)> = Vec::new();
// A planned case (`*_plan`) runs the planner greedily first, as the
// trace did; its plan and codes then condition the DiT (#384).
let planned = cases.split(',').any(|c| c.ends_with("_plan"));
let mut engine = AceStepEngine::load(
&AceStepFiles {
root: root.into(),
planner: None,
planner: planned.then(|| PLANNER_DIRS[0].to_string()),
layout: AceStepLayout::from_config(&cfg).unwrap(),
},
&Device::Cpu,
&device,
)
.expect("load");
assert_eq!(engine.has_planner(), planned, "planner load");
let dir =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/harness/testdata/acestep");
for case in cases.split(',') {
@@ -771,8 +1016,56 @@ mod hardware {
let language = c["language"].as_str().unwrap();
let duration = c["duration"].as_f64().unwrap();
let (text, lyric) =
AceStepPipeline::format_prompts(caption, lyrics, duration, None, Some(language));
let (hints, metadata) = if c["planner"].as_bool() == Some(true) {
let cfg = crate::harness::arch::acestep::lm::LmConfig {
temperature: 0.0,
..Default::default()
};
// ACESTEP_PLAN_FROM_TRACE takes the trace's own codes and
// plan instead of running the planner, to test what follows
// the planner on its own (and in seconds rather than
// minutes).
let (hints, meta) = if std::env::var("ACESTEP_PLAN_FROM_TRACE").is_ok() {
let codes = file
.load("planner_audio_codes", &Device::Cpu)
.unwrap()
.to_vec1::<i64>()
.unwrap();
let cot = meta["planner"][0]["output_text"].as_str().unwrap();
(
engine.pipeline.audio_codes_to_latents(&codes).unwrap(),
crate::harness::arch::acestep::lm::LmPipeline::parse_metadata(cot),
)
} else {
engine
.pipeline
.generate_lm_hints(caption, lyrics, duration, &cfg)
.unwrap()
};
let want_hints = file
.load("gen_precomputed_lm_hints_25Hz", &Device::Cpu)
.unwrap();
eprintln!(
"{case}: lm hints rel L2 {:.2e}",
rel_l2(&hints.to_device(&Device::Cpu).unwrap(), &want_hints)
);
(Some(hints), Some(lm_metadata(&meta)))
} else {
(None, None)
};
let instruction = if hints.is_some() {
crate::harness::arch::acestep::pipeline::COVER_INSTRUCTION
} else {
crate::harness::arch::acestep::pipeline::TEXT2MUSIC_INSTRUCTION
};
let (text, lyric) = AceStepPipeline::format_prompts(
instruction,
caption,
lyrics,
duration,
metadata.as_ref(),
Some(language),
);
let (text_ids, lyric_ids) = engine.pipeline.prompt_token_ids(&text, &lyric).unwrap();
let ids = |k: &str| -> Vec<u32> {
want[k]
@@ -796,6 +1089,8 @@ mod hardware {
infer_method: sampling::InferMethod::Ode,
initial_noise: Some(want["noise"].clone()),
language: Some(language.to_string()),
lm_hints_25hz: hints,
lm_metadata: metadata,
..Default::default()
};
let t = Instant::now();
@@ -803,17 +1098,57 @@ mod hardware {
.pipeline
.text2music(caption, lyrics, &params)
.unwrap();
let latents = rel_l2(&out.latents, &want["target_latents"]);
let cpu = |t: &candle_core::Tensor| t.to_device(&Device::Cpu).unwrap();
let latents = rel_l2(&cpu(&out.latents), &want["target_latents"]);
let wave_ref = &want["vae_waveform"];
let n = wave_ref.dim(2).unwrap();
let wave = out.audio.narrow(1, 0, n).unwrap().unsqueeze(0).unwrap();
let wave = cpu(&out.audio)
.narrow(1, 0, n)
.unwrap()
.unsqueeze(0)
.unwrap();
let waveform = rel_l2(&wave, wave_ref);
eprintln!(
"{case}: latents rel L2 {latents:.2e}, waveform rel L2 {waveform:.2e} ({:.1}s)",
"{case} [{layout_toml:?} on {:?}]: latents rel L2 {latents:.2e}, waveform rel L2 {waveform:.2e} ({:.1}s)",
device.location(),
t.elapsed().as_secs_f32()
);
assert!(latents < 1e-3, "{case}: latents rel L2 {latents}");
assert!(waveform < 1e-2, "{case}: waveform rel L2 {waveform}");
if parity {
assert!(latents < 1e-3, "{case}: latents rel L2 {latents}");
assert!(waveform < 1e-2, "{case}: waveform rel L2 {waveform}");
} else {
// The yardstick is upstream's own: how far its bf16 GPU run
// of the same case lands from its f32 CPU run. (Its f16 run
// of a vocal case is NaN.)
let envelope_file = unsafe {
candle_core::safetensors::MmapedSafetensors::new(
dir.join(format!("{case}__cuda_bf16.safetensors")),
)
}
.unwrap();
let upstream_bf16 = envelope_file.load("target_latents", &Device::Cpu).unwrap();
let envelope = rel_l2(&upstream_bf16, &want["target_latents"]);
eprintln!("{case}: upstream bf16 drifts {envelope:.2e}");
drifts.push((case.to_string(), latents, envelope));
}
}
// Turbo denoising is chaotic: per-case drift swings with tiny
// numeric differences, so a layout is judged on its mean across
// cases against upstream bf16's mean, and every case must be
// finite.
if !drifts.is_empty() {
let n = drifts.len() as f32;
let mean = drifts.iter().map(|d| d.1).sum::<f32>() / n;
let envelope = drifts.iter().map(|d| d.2).sum::<f32>() / n;
eprintln!("mean latents rel L2 {mean:.2e}; upstream bf16 mean {envelope:.2e}");
assert!(
drifts.iter().all(|d| d.1.is_finite()),
"non-finite drift: {drifts:?}"
);
assert!(
mean <= envelope,
"mean drift {mean} beyond upstream bf16's {envelope}: {drifts:?}"
);
}
}
@@ -878,6 +1213,86 @@ mod hardware {
assert_eq!(out.left, again.left, "same seed must render identically");
}
/// Planner parity with upstream (#384): greedy decoding in f32 over the
/// `vocal_en_30s_plan` case must reproduce upstream's CoT text exactly,
/// and its audio codes (CFG 2.0, 150 of them). Ignored: needs
/// ACESTEP_SNAPSHOT; ACESTEP_DEVICE=cuda runs it on the GPU.
#[test]
#[ignore = "needs ACESTEP_SNAPSHOT"]
fn acestep_planner_matches_reference() {
use crate::harness::arch::acestep::lm::{LmConfig, LmPipeline, TokenIds};
let Ok(root) = std::env::var("ACESTEP_SNAPSHOT") else {
return;
};
let device = match std::env::var("ACESTEP_DEVICE").as_deref() {
Ok("cuda") => Device::new_cuda(0).unwrap(),
_ => Device::Cpu,
};
let dir = PathBuf::from(root).join(PLANNER_DIRS[0]);
let cfg: qwen3::Config = read_json(&dir.join("config.json")).unwrap();
let vb = unsafe {
VarBuilder::from_mmaped_safetensors(
&[dir.join("model.safetensors")],
DType::F32,
&device,
)
.unwrap()
}
.rename_f(|n| n.strip_prefix("model.").unwrap_or(n).to_string());
let model = qwen3::ModelForCausalLM::new(&cfg, vb).unwrap();
let tok = tokenizers::Tokenizer::from_file(dir.join("tokenizer.json")).unwrap();
let encode = |s: &str| -> candle_core::Result<Vec<u32>> {
Ok(tok.encode(s, false).unwrap().get_ids().to_vec())
};
let decode =
|ids: &[u32]| -> candle_core::Result<String> { Ok(tok.decode(ids, false).unwrap()) };
let ids = TokenIds::discover(encode).unwrap();
let mut lm = LmPipeline::new(model, ids, device);
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("src/harness/testdata/acestep/vocal_en_30s_plan__cpu_f32.json");
let f: serde_json::Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
let case = &f["case"];
let config = LmConfig {
temperature: 0.0,
..Default::default()
};
let t = Instant::now();
let out = lm
.generate(
case["caption"].as_str().unwrap(),
case["lyrics"].as_str().unwrap(),
case["duration"].as_f64().unwrap(),
&config,
&decode,
&encode,
)
.unwrap();
eprintln!("planner ran in {:.1}s", t.elapsed().as_secs_f32());
let want_cot = f["planner"][0]["output_text"].as_str().unwrap();
// raw_text is the CoT, a newline, then the re-dumped plan and codes.
let got_cot = &out.raw_text[..want_cot.len().min(out.raw_text.len())];
assert_eq!(got_cot, want_cot, "CoT text");
let want_codes = crate::harness::arch::acestep::lm::parse_audio_codes_from_text(
f["planner"][1]["output_text"].as_str().unwrap(),
);
let same = out
.audio_codes
.iter()
.zip(&want_codes)
.take_while(|(a, b)| a == b)
.count();
eprintln!(
"codes: {} generated, {} expected, first {same} identical",
out.audio_codes.len(),
want_codes.len()
);
assert_eq!(out.audio_codes.len(), want_codes.len(), "code count");
assert_eq!(out.audio_codes, want_codes, "audio codes");
}
/// The planner LM loads from the real snapshot (its tensors carry no
/// `model.` prefix). Ignored: needs ACESTEP_SNAPSHOT.
#[test]
@@ -899,4 +1314,149 @@ mod hardware {
.rename_f(|n| n.strip_prefix("model.").unwrap_or(n).to_string());
qwen3::ModelForCausalLM::new(&cfg, vb).expect("planner loads");
}
/// Peak device memory and latency per song length, for a layout
/// (#385). Run on a CUDA host:
///
/// ACESTEP_SNAPSHOT=… ACESTEP_LAYOUT='quant = "q8_0"' \
/// ACESTEP_PLANNER=acestep-5Hz-lm-1.7B ACESTEP_DURATIONS=30,180 \
/// cargo test -p neuron --features cuda --lib -- --ignored \
/// acestep_profile_gpu --nocapture
///
/// `ACESTEP_PLANNER` is a snapshot subfolder or an absolute path; set,
/// the planner runs. Peak memory is this process's, as nvidia-smi
/// reports it, CUDA context included, so it is what a card of that
/// size would have to hold. The pool is trimmed between songs, as the
/// device worker does after every job.
#[cfg(feature = "cuda")]
#[test]
#[ignore = "needs ACESTEP_SNAPSHOT and a CUDA device"]
fn acestep_profile_gpu() {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
let Ok(root) = std::env::var("ACESTEP_SNAPSHOT") else {
eprintln!("ACESTEP_SNAPSHOT not set; skipping");
return;
};
// The engine reports a planner that fails to load as a warning and
// carries on without it; show it.
let _ = tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(tracing_subscriber::EnvFilter::new("neuron=info"))
.try_init();
let cfg: crate::config::AudioConfig =
toml::from_str(&std::env::var("ACESTEP_LAYOUT").unwrap_or_default()).unwrap();
let planner = std::env::var("ACESTEP_PLANNER").ok();
let durations: Vec<f64> = std::env::var("ACESTEP_DURATIONS")
.unwrap_or_else(|_| "30,120,240,480".into())
.split(',')
.map(|d| d.trim().parse().unwrap())
.collect();
let pid = std::process::id();
let peak = Arc::new(AtomicU64::new(0));
let stop = Arc::new(AtomicBool::new(false));
let sampler = {
let (peak, stop) = (peak.clone(), stop.clone());
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let out = std::process::Command::new("nvidia-smi")
.args([
"--query-compute-apps=pid,used_memory",
"--format=csv,noheader,nounits",
])
.output()
.unwrap();
for line in String::from_utf8_lossy(&out.stdout).lines() {
let mut f = line.split(',').map(str::trim);
if f.next() == Some(pid.to_string().as_str())
&& let Some(mb) = f.next().and_then(|m| m.parse::<u64>().ok())
{
peak.fetch_max(mb, Ordering::Relaxed);
}
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
})
};
let trim = || {
use candle_core::cuda::cudarc::driver::result::{ctx, device, mem_pool};
unsafe {
ctx::synchronize().unwrap();
let pool = device::get_default_mem_pool(device::get(0).unwrap()).unwrap();
mem_pool::trim_to(pool, 0).unwrap();
}
};
let device = Device::new_cuda(0).unwrap();
let files = AceStepFiles {
root: root.into(),
planner: planner.clone(),
layout: AceStepLayout::from_config(&cfg).unwrap(),
};
let t = Instant::now();
let mut engine = AceStepEngine::load(&files, &device).expect("load");
assert_eq!(
engine.has_planner(),
planner.is_some(),
"the planner asked for did not load"
);
trim();
std::thread::sleep(std::time::Duration::from_millis(300));
eprintln!(
"PROFILE load layout={:?} planner={:?} secs={:.1} resident_mb={}",
std::env::var("ACESTEP_LAYOUT").unwrap_or_default(),
planner,
t.elapsed().as_secs_f32(),
peak.swap(0, Ordering::Relaxed)
);
for d in durations {
let params = AudioGenParams {
prompt: "Upbeat synth-pop with bright female vocals, punchy drums, 120 BPM".into(),
lyrics: "[verse]\nCity lights are calling out my name\nEvery street a spark, every night a flame\n\
[chorus]\nWe run, we run, until the morning comes\nHearts like drums, we run\n"
.into(),
duration_secs: d,
seed: 7,
steps: None,
guidance_scale: None,
planner: planner.is_some(),
temperature: None,
language: Some("en".into()),
top_k: None,
};
let t = Instant::now();
let res = engine.generate(&params);
let secs = t.elapsed().as_secs_f32();
std::thread::sleep(std::time::Duration::from_millis(300));
let mb = peak.swap(0, Ordering::Relaxed);
match res {
Ok(out) => {
let rms = (out.left.iter().map(|s| s * s).sum::<f32>()
/ out.left.len().max(1) as f32)
.sqrt();
eprintln!(
"PROFILE song secs={d} wall={secs:.1} plan_ms={} encode_ms={} denoise_ms={} decode_ms={} peak_mb={mb} rms={rms:.4}",
out.timing.plan_ms,
out.timing.encode_ms,
out.timing.generate_ms,
out.timing.decode_ms
);
if let Ok(dir) = std::env::var("ACESTEP_OUT") {
std::fs::write(
format!("{dir}/song_{d}.flac"),
encode_flac_pcm16(&out.left, &out.right, out.sample_rate).unwrap(),
)
.unwrap();
}
}
Err(e) => {
eprintln!("PROFILE song secs={d} wall={secs:.1} peak_mb={mb} error={e:#}")
}
}
trim();
}
stop.store(true, Ordering::Relaxed);
sampler.join().unwrap();
}
}
+288 -54
View File
@@ -116,6 +116,8 @@ pub struct CandleHarness {
/// Image-pipeline settings (#198): text-encoder residency and the
/// resolution ceiling.
image_cfg: crate::config::ImageConfig,
/// `[harness.candle.audio]` (#385).
audio_cfg: crate::config::AudioConfig,
}
/// Devices/capabilities snapshot of a model entering auto-recovery
@@ -661,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-
@@ -1168,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(())
@@ -2522,6 +2595,7 @@ impl CandleHarness {
reasoning_budget_cfg: config.reasoning_budget.clone(),
admission_cfg: config.admission.clone(),
image_cfg: config.image.clone(),
audio_cfg: config.audio.clone(),
});
// Background auto-recovery task (#17). Holds a `Weak` so it can't
// keep the harness alive. Spawned only when a tokio runtime is
@@ -2993,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")?;
@@ -3822,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()
@@ -3952,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
@@ -4012,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,
});
}
}
@@ -4406,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),
);
@@ -4415,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"
);
@@ -4473,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")]
@@ -4667,47 +4767,93 @@ 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());
let handle = worker
.load_audio(files, spec.model_id.clone())
.await
.map_err(|e| anyhow::anyhow!("worker load_audio: {e:#}"))?;
// A host may accept shorter songs than the model allows (#385), for
// a card whose memory runs out first.
let mut limits = limits;
if let super::audio::AudioFiles::AceStep(_) = &files
&& let Some(max) = self.audio_cfg.max_duration_secs
{
anyhow::ensure!(
max >= limits.min_duration,
"[harness.candle.audio] max_duration_secs {max} is below the model's minimum {}",
limits.min_duration
);
limits.max_duration = limits.max_duration.min(max);
limits.default_duration = limits.default_duration.min(limits.max_duration);
}
// 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(())
}
@@ -4741,8 +4887,38 @@ impl CandleHarness {
.context("snapshot path shorter than its repo path")?
.to_path_buf();
}
// `[harness.candle.audio] planner` names one planner, or none;
// unset tries them largest first.
let named = self.audio_cfg.planner.as_deref();
let candidates: Vec<&str> = match named {
Some(n) if n.eq_ignore_ascii_case("none") => Vec::new(),
Some(n) => vec![n],
None => super::audio::PLANNER_DIRS.to_vec(),
};
let mut planner = None;
for dir in super::audio::PLANNER_DIRS {
// A name with a slash is a repo of its own (the 0.6B planner ships
// as `ACE-Step/acestep-5Hz-lm-0.6B`, not in the main snapshot),
// fetched through the same registry; the engine joins an absolute
// path onto the root unchanged.
if let Some(id) = named.filter(|n| n.contains('/')) {
let planner_repo = api.model(id.to_string());
let mut dir = None;
for file in ["config.json", "model.safetensors", "tokenizer.json"] {
let path = planner_repo
.get(file)
.await
.with_context(|| format!("fetch {file} from planner repo {id}"))?;
dir = path.parent().map(|p| p.to_path_buf());
}
let dir = dir.context("planner repo resolved to no directory")?;
planner = Some(dir.to_string_lossy().into_owned());
}
let candidates = if planner.is_some() {
Vec::new()
} else {
candidates
};
for dir in candidates {
let mut ok = true;
for file in super::audio::planner_files(dir) {
if let Err(e) = repo.get(&file).await {
@@ -4756,7 +4932,19 @@ impl CandleHarness {
break;
}
}
Ok(super::audio::AceStepFiles { root, planner })
if let (Some(n), None) = (named, &planner)
&& !n.eq_ignore_ascii_case("none")
{
anyhow::bail!(
"{display_id} has no planner '{n}' (named by [harness.candle.audio] planner)"
);
}
let layout = super::audio::AceStepLayout::from_config(&self.audio_cfg)?;
Ok(super::audio::AceStepFiles {
root,
planner,
layout,
})
}
/// Resolve a HeartMuLa LM repo (#393) and the two sibling repos it
@@ -5271,16 +5459,17 @@ impl CandleHarness {
request
.validate_limits(&audio.limits)
.map_err(|detail| InferenceError::InvalidAudioParams { detail })?;
// The planner runs only when asked for until its port is proven
// against the reference (#384); `auto` means off until then.
// `auto` (or nothing) follows the vendor default: plan the song
// when the model has a planner. The port matches upstream's trace
// (#384).
let planner = match request.planner.as_deref() {
Some("on") if !audio.has_planner => {
return Err(InferenceError::InvalidAudioParams {
detail: "this model has no song planner; use planner=off or auto".into(),
});
}
Some("on") => true,
_ => false,
Some("off") => false,
_ => audio.has_planner,
};
// A random seed small enough to type back in, so any render can be
// reproduced from what the job reports.
@@ -5307,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();
@@ -8604,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.
+12
View File
@@ -0,0 +1,12 @@
# 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`.
@@ -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,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,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,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,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,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,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
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,268 @@
// src/kernels/cuda/i8h_volta.cuh - the Volta form of the int8 expert kernels (TUNE-0216): the same products as i8_kernel, on the tensor cores.
// Included by i8_expert.cuh (inside iq_kernels.cu's anonymous namespace) after the tile kernels; it uses their decode (i8_load / i8_pack / i8_convert), their
// activation image and their tile tables. CUDA only; the device code is Volta's (__CUDA_ARCH__ 700): every other architecture compiles a trap.
//
// Why. On a Tesla V100 (no int8 matrix cores) the dp4a tile kernels read prompts of 8,192+ tokens at 0.75-0.95 of MMQ's speed per layer, and with every expert
// resident (#6053's 6x V100) a 26K prompt's expert products took 1.30 times MMQ's time. Volta's FP16 tensor cores do 512 FMA a clock per SM against dp4a's 256.
//
// Exact, by construction. The weights' int8 codes (the decoded sub-blocks i8_convert writes) and the activations' int8 codes become FP16 values (integers of
// -128..127: exact), mma.m8n8k4 multiplies them exactly and adds them in FP32; every partial sum is an integer below 2^24 (32 products of at most 127 x 127), so it is
// exact in any order. A fresh accumulator collects each 32-value sub-block (each 16-value half for the two-scale formats), and the epilogue then does what the dp4a
// kernels do with their integer sums, in the same order: t = s1 m1 + s0 m0 (or s m, or s), acc = fmaf(t, base * d_x, acc), sub-block after sub-block. The products
// t are integers below 2^24 as well (the dp4a kernels' own bound), so t is the same number whether made in int or float: the output is bit-identical to i8_kernel's.
//
// Shape. A block of 256 threads (8 warps) owns 64 weight rows (gate/up: 32 gate + the same 32 up features, as i8_kernel) x 64 entries of one expert, K in stages of
// 128 values (4 sub-blocks). Warp w: rows 16 (w % 4) .. +16, entries 32 (w / 4) .. +32. Per k-step of 4 values each of the warp's four quad pairs computes one 8 x 8
// tile; two mma per k-step cover the warp's 16 x 32. FP16 operands in shared memory (one buffer, the next stage's raw bytes held in registers meanwhile): 44 KB, two
// blocks per SM.
//
// The m8n8k4 fragments (PTX ISA, mma.m8n8k4 .row.col, f16 inputs, f32 accumulators; checked on the V100 by phaseA-tests/tune0216/probe_m884.cu): quad pair
// q = (lane % 16) / 4 holds lanes 4q..4q+3 and 4q+16..4q+19, local index t = lane % 4 + 4 (lane / 16); thread t supplies row t of A (k 0..3) and column t of B
// (k 0..3); accumulator element i of thread (g = lane % 4, h = lane / 16) is row (g & 1) + (i & 2) + 4 h, column (i & 4) + (g & 2) + (i & 1).
#pragma once
constexpr int I8H_BM = 64; // entries of a tile
constexpr int I8H_LDH = 136; // halves per shared row: 128 + 8 (bank spread)
constexpr int I8H_RS = 16; // words per row of the scale records: 4 sub-blocks x {m0, m1, base, 0}
// formats of the Volta form: the decodes with no per-32 minimum (the minimum formats Q4_K / Q5_K / Q5_1 keep the dp4a kernels)
__host__ __device__ constexpr bool i8h_type(int t) { return !i8_min_type(t) && (i8_gu_type(t) || i8_d_type(t)); }
template <int T>
struct I8HSmem {
static constexpr int GW = i8_gg_type(T) ? 0 : (i8_grid_words(T) + 3) / 4 * 4; // a big grid is read from global memory (as I8Smem's GG)
static constexpr int SG = i8_sign_type(T) ? 512 : 0;
static constexpr int SZ_W = 64 * I8H_LDH / 2, SZ_A = I8H_BM * I8H_LDH / 2; // words
static constexpr int SZ_R = 64 * I8H_RS, SZ_D = I8H_BM * 4;
static constexpr int o_sg = GW, o_w = o_sg + SG, o_a = o_w + SZ_W, o_r = o_a + SZ_A, o_d = o_r + SZ_R, o_src = o_d + SZ_D,
total = (o_src + I8H_BM + 3) / 4 * 4;
static constexpr size_t bytes = (size_t) total * 4;
};
// four int8 (bytes of w) as four FP16 values, exactly: x + 128 is the mantissa of 1024 + x + 128, minus 1152
__device__ __forceinline__ uint2 i8h_cvt4(uint32_t w) {
const uint32_t c = w ^ 0x80808080u;
const uint32_t lo = __byte_perm(c, 0x64646464u, 0x5140), hi = __byte_perm(c, 0x64646464u, 0x7362);
const __half2 m = __floats2half2_rn(1152.0f, 1152.0f);
const __half2 l = __hsub2(*(const __half2*) &lo, m), h = __hsub2(*(const __half2*) &hi, m);
return make_uint2(*(const uint32_t*) &l, *(const uint32_t*) &h);
}
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 700
__device__ __forceinline__ void i8h_mma(float (&d)[8], uint2 a, uint2 b) {
asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, {%0,%1,%2,%3,%4,%5,%6,%7};\n"
: "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]), "+f"(d[4]), "+f"(d[5]), "+f"(d[6]), "+f"(d[7])
: "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y));
}
#endif
template <int T, bool GU>
__global__ void __launch_bounds__(I8_NT, 2)
i8h_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups,
const int32_t* __restrict__ tile_off, const int32_t* __restrict__ ent_idx, const block_q8_1* __restrict__ A,
block_q8_1* __restrict__ hq, float* __restrict__ out, NativeExpertLayout L) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 700
using SM = I8HSmem<T>;
extern __shared__ uint4 i8_dyn[];
uint32_t* const smem = (uint32_t*) i8_dyn;
uint32_t* const s_grid = smem;
uint32_t* const s_sg = smem + SM::o_sg;
__half* const s_w = (__half*) (smem + SM::o_w);
__half* const s_a = (__half*) (smem + SM::o_a);
uint32_t* const s_r = smem + SM::o_r;
float* const s_ad = (float*) (smem + SM::o_d);
int* const s_src = (int*) (smem + SM::o_src);
const uint32_t* const grid_rd = i8_gg_type(T) ? i8_grid_src<T>() : s_grid;
const int ng = *n_groups;
const int ti = blockIdx.x;
if (ti >= tile_off[ng]) return;
int lo = 0, hi = ng - 1;
while (lo < hi) {
const int mid = (lo + hi + 1) >> 1;
if (tile_off[mid] <= ti) lo = mid; else hi = mid - 1;
}
const int g = lo;
const int e_lo = grp_start[g] + (ti - tile_off[g]) * I8H_BM;
const int e_hi = min(grp_start[g + 1], e_lo + I8H_BM);
const int nv = e_hi - e_lo;
I8P blob = i8_uniform(I8_GPTR(grp_ptr[g]));
const int tid = threadIdx.x;
const int K = GU ? (int) L.n_embd : (int) L.n_ff;
const int ns = K / I8_KS;
const size_t wrb = GU ? L.gu_row : L.d_row;
if constexpr (i8_grid_words(T) > 4 && !i8_gg_type(T)) {
const uint32_t* src = i8_grid_src<T>();
for (int i = tid; i < i8_grid_words(T); i += I8_NT) s_grid[i] = src[i];
}
if constexpr (i8_sign_type(T)) { // as i8_kernel's table
const uint32_t b = (uint32_t) tid;
uint32_t sb = b;
if constexpr (T != 21 && T != 22) sb = (b & 127u) | (((uint32_t) __popc(b & 127u) & 1u) << 7);
uint32_t mlo = 0, mhi = 0;
#pragma unroll
for (int k = 0; k < 4; ++k) {
mlo |= ((sb >> k) & 1u) ? (0xFFu << (8 * k)) : 0u;
mhi |= ((sb >> (4 + k)) & 1u) ? (0xFFu << (8 * k)) : 0u;
}
*(uint2*) (s_sg + 2 * b) = make_uint2(mlo, mhi);
}
uint32_t kv[4] = {0, 0, 0, 0};
if constexpr (T == 20 || T == 23) {
const uint32_t* t = (const uint32_t*) kvalues_iq4nl;
#pragma unroll
for (int i = 0; i < 4; ++i) kv[i] = t[i];
}
if (tid < I8H_BM) s_src[tid] = (e_lo + tid < e_hi) ? (GU ? ent_idx[e_lo + tid] : e_lo + tid) : -1;
__syncthreads();
// decode thread: row wr of the tile, sub-block wp of the stage (as i8_kernel); activation thread: q8_1 block (tid & 3) of entry (tid >> 2)
const int wr = tid >> 2, wp = tid & 3;
uint32_t row_off;
if constexpr (GU) row_off = (uint32_t) ((wr >= 32 ? L.up_off : (size_t) 0) + (size_t) (blockIdx.y * 32 + (wr & 31)) * wrb);
else row_off = (uint32_t) (L.down_off + (size_t) (blockIdx.y * 64 + wr) * wrb);
const I8Off woff = i8_offs<T>(row_off, wp);
I8P const abase = I8_GPTR(A);
uint32_t a_vo;
{
const int src = s_src[tid >> 2];
a_vo = (uint32_t) ((size_t) (src >= 0 ? src : 0) * (size_t) ((K / 32) * 36) + (size_t) (tid & 3) * 36);
}
auto store_w = [&](int st, const uint32_t (&r)[I8NR<T>]) {
uint32_t q[8], w[I8NW<T>];
int m0, m1;
float base, minv = 0.0f;
const int ibs = (st * 4 + wp) & 7;
i8_pack<T>(r, ibs, w);
i8_convert<T>(w, grid_rd, (const uint2*) s_sg, kv, q, m0, m1, base, ibs, &minv);
uint2* dst = (uint2*) (s_w + wr * I8H_LDH + wp * 32);
#pragma unroll
for (int k = 0; k < 8; ++k) dst[k] = i8h_cvt4(q[k]);
*(uint4*) (s_r + wr * I8H_RS + wp * 4) = make_uint4((uint32_t) m0, (uint32_t) m1, __float_as_uint(base), 0u);
};
auto store_a = [&](const uint32_t (&ar)[9]) {
uint2* d = (uint2*) (s_a + (tid >> 2) * I8H_LDH + (tid & 3) * 32);
#pragma unroll
for (int k = 0; k < 8; ++k) d[k] = i8h_cvt4(ar[1 + k]);
s_ad[tid] = __uint_as_float(ar[0]);
};
const int lane = tid & 31, warp = tid >> 5;
const int qp = (lane & 15) >> 2, tl = (lane & 3) + 4 * (lane >> 4);
const int gg = lane & 3, hh = lane >> 4;
const int r0 = 16 * (warp & 3) + 8 * (qp & 1); // the quad pair's 8 rows
const int c0 = 32 * (warp >> 2) + 8 * (qp >> 1); // its 8 entries of the first 16-entry half (the second: + 16)
const __half* const a_row = s_w + (r0 + tl) * I8H_LDH; // A: row tl of the quad pair's rows
const __half* const b_col0 = s_a + (c0 + tl) * I8H_LDH; // B: column tl (an entry) of the first half
const __half* const b_col1 = b_col0 + 16 * I8H_LDH; // ... of the second half
float acc[2][8];
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) acc[j][i] = 0.0f;
uint32_t wraw[I8NR<T>], ar[9];
i8_load<T>(blob, woff, 0, wraw);
{
I8P p = abase + a_vo;
#pragma unroll
for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
}
store_w(0, wraw);
store_a(ar);
__syncthreads();
for (int st = 0; st < ns; ++st) {
if (st + 1 < ns) { // the next stage's raw bytes into registers while this one computes
i8_load<T>(blob, woff, st + 1, wraw);
I8P p = abase + (size_t) (st + 1) * 144 + a_vo;
#pragma unroll
for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
}
#pragma unroll 1
for (int blk = 0; blk < 4; ++blk) {
float p0[2][8], p1[2][8]; // the sub-block's sums: values 0-15 (p0) and 16-31 (p1), or all 32 in p0 for the one-scale formats
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) { p0[j][i] = 0.0f; p1[j][i] = 0.0f; }
#pragma unroll
for (int kk = 0; kk < 8; ++kk) {
const int k = 32 * blk + 4 * kk;
const uint2 a = *(const uint2*) (a_row + k);
const uint2 b0 = *(const uint2*) (b_col0 + k), b1 = *(const uint2*) (b_col1 + k);
if (i8_two_scales(T) && kk >= 4) { i8h_mma(p1[0], a, b0); i8h_mma(p1[1], a, b1); }
else { i8h_mma(p0[0], a, b0); i8h_mma(p0[1], a, b1); }
}
// epilogue of the sub-block: the dp4a kernels' arithmetic on the same integers, in the same order
float axv[2][4]; // the activation scales of the thread's eight entries for this sub-block
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int cc = 0; cc < 4; ++cc) axv[j][cc] = s_ad[(c0 + 16 * j + ((cc & 2) << 1) + (gg & 2) + (cc & 1)) * 4 + blk];
#pragma unroll
for (int rr = 0; rr < 2; ++rr) { // the thread's two rows: (g & 1) + 2 rr + 4 h
const int row = r0 + (gg & 1) + 2 * rr + 4 * hh;
const uint4 rc = *(const uint4*) (s_r + row * I8H_RS + blk * 4);
const float base = __uint_as_float(rc.z);
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int cc = 0; cc < 4; ++cc) { // the thread's four entries: (cc & 2) * 2 + (g & 2) + (cc & 1)
const int i = (cc & 1) | (rr << 1) | ((cc & 2) << 1); // element index: col bit 0 = i & 1, row bit 1 = i & 2, col bit 2 = i & 4
const float ax = axv[j][cc];
float t;
if constexpr (i8_two_scales(T)) t = p1[j][i] * (float) (int) rc.y + p0[j][i] * (float) (int) rc.x;
else if constexpr (i8_unit_scale(T)) t = p0[j][i];
else t = p0[j][i] * (float) (int) rc.x;
acc[j][i] = fmaf(t, base * ax, acc[j][i]);
}
}
}
if (st + 1 < ns) {
__syncthreads();
store_w(st + 1, wraw);
store_a(ar);
}
__syncthreads();
}
// epilogues
if constexpr (GU) {
// the 64 rows x 64 entries of sums through shared memory (the weight and activation buffers are free now): F[row][entry]
float* const F = (float*) s_w; // 64 x 65 floats (16.6 KB) inside the two buffers (34.8 KB)
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int row = r0 + (gg & 1) + (i & 2) + 4 * hh, col = c0 + 16 * j + (i & 4) + (gg & 2) + (i & 1);
F[row * 65 + col] = acc[j][i];
}
__syncthreads();
const int nb = (int) (L.n_ff / 32);
for (int e8 = 0; e8 < 8; ++e8) { // warp w: entries 8 w .. 8 w + 7; lane: feature (gate row lane, up row 32 + lane)
const int el = 8 * warp + e8;
if (el >= nv) break; // uniform per warp
const float gv = F[lane * 65 + el], uv = F[(32 + lane) * 65 + el];
const float h = (gv / (1.0f + __expf(-gv))) * uv;
float amax = fabsf(h);
#pragma unroll
for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
const float d_inv = 127.0f / amax;
block_q8_1* hb = hq + (size_t) (e_lo + el) * nb + blockIdx.y;
hb->qs[lane] = i8_code(h, d_inv, amax);
if (lane == 0) i8_put_scale(hb, amax, d_inv);
}
} else {
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int row = r0 + (gg & 1) + (i & 2) + 4 * hh, col = c0 + 16 * j + (i & 4) + (gg & 2) + (i & 1);
if (col < nv) out[(size_t) ent_idx[e_lo + col] * L.n_embd + (size_t) blockIdx.y * 64 + row] = acc[j][i];
}
}
#else
(void) grp_ptr; (void) grp_start; (void) n_groups; (void) tile_off; (void) ent_idx; (void) A; (void) hq; (void) out; (void) L;
__trap();
#endif
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,19 @@
// src/kernels/cuda/nvfp4_decode_sm120_absent.cpp - Fallback stub when sm_120a/sm_121a is not in CUDA_ARCHITECTURES.
//
// MIT License
// Copyright (c) 2026 Niko1221 and the Strata contributors
#include "strata/kernels/nvfp4_decode_sm120.hpp"
namespace strata::kernels {
void nvfp4_decode_sm120_set_override(int) noexcept {}
bool nvfp4_decode_sm120_available() noexcept { return false; }
bool nvfp4_decode_sm120_grouped(const NativeExpertLayout&, const unsigned long long*, const int32_t*,
const int32_t*, const int32_t*, const int32_t*, int64_t, int64_t,
const void*, void*, float*, void*) {
return false;
}
} // namespace strata::kernels
@@ -0,0 +1,71 @@
// S26: several warp sums at once (P per-lane values -> P sums), bitwise equal to P separate xor-butterfly warp sums
// (`for (o = 16; o > 0; o >>= 1) v += shfl_xor(v, o)`). At offset 16 a lane keeps half of its P values and adds the
// partner's copy of that half, at 8 half again, ... until one value is left, then plain xor steps for the remaining
// offsets. Every level adds the same pair of values as the butterfly does (fp add commutes, so x + y == y + x
// bitwise), only each lane carries fewer of them: P - 1 + (5 - log2 P) cross-lane moves instead of 5 P. Value j's sum
// ends in the lanes whose bits 4, 3, .. (MSB first) spell j: tsum_lane<P>(j) is one of them. On AMD the moves are
// DPP row_xmask / permlanex16 instead of ds_bpermute.
#pragma once
#include <cuda_runtime.h> // (before the first use of __forceinline__ / __float_as_int: a gfx906 build gets them from its shim)
namespace strata::kernels::s26ts {
#if defined(__HIP_PLATFORM_AMD__) && !defined(STRATA_HIP_GFX906) // (permlanex16 / DPP row_xmask: gfx10+ only)
__device__ __forceinline__ float xmov16(float v) {
return __int_as_float(__builtin_amdgcn_permlanex16(__float_as_int(v), __float_as_int(v), 0x76543210u, 0xfedcba98u,
false, false));
}
template <int O>
__device__ __forceinline__ float xmov(float v) {
if constexpr (O == 16) return xmov16(v);
else return __int_as_float(__builtin_amdgcn_update_dpp(0, __float_as_int(v), 0x160 + O, 0xf, 0xf, false));
}
#else
template <int O>
__device__ __forceinline__ float xmov(float v) { return __shfl_xor_sync(0xffffffffu, v, O); }
#endif
__host__ __device__ constexpr int pow2_ceil(int t) { return t <= 1 ? 1 : t <= 2 ? 2 : t <= 4 ? 4 : t <= 8 ? 8 : t <= 16 ? 16 : 32; }
__host__ __device__ constexpr int log2c(int p) { return p <= 1 ? 0 : p == 2 ? 1 : p == 4 ? 2 : p == 8 ? 3 : p == 16 ? 4 : 5; }
template <int O>
__device__ __forceinline__ float tplain(float x) {
if constexpr (O >= 1) { x += xmov<O>(x); return tplain<O / 2>(x); }
else return x;
}
// v[0..CNT) (CNT a power of two <= 32): this lane's values; returns the sum of value tsum_token<CNT>(lane)
template <int CNT, int O = 16>
__device__ __forceinline__ float tsum(float* v, int lane) {
if constexpr (CNT > 1) {
constexpr int H = CNT / 2;
const bool hi = (lane & O) != 0;
#pragma unroll
for (int j = 0; j < H; ++j) {
const float send = hi ? v[j] : v[j + H];
const float keep = hi ? v[j + H] : v[j];
v[j] = keep + xmov<O>(send);
}
return tsum<H, O / 2>(v, lane);
} else {
return tplain<O>(v[0]);
}
}
template <int P>
__device__ __forceinline__ int tsum_token(int lane) {
constexpr int L = log2c(P);
int k = 0;
#pragma unroll
for (int b = 0; b < L; ++b) k = (k << 1) | ((lane >> (4 - b)) & 1);
return k;
}
template <int P>
__device__ __forceinline__ int tsum_lane(int k) {
constexpr int L = log2c(P);
int lane = 0;
#pragma unroll
for (int b = 0; b < L; ++b) lane |= ((k >> (L - 1 - b)) & 1) << (4 - b);
return lane;
}
} // namespace strata::kernels::s26ts
@@ -0,0 +1,137 @@
#pragma once
// int8 copy of the TQ codebook tq2t_lut_f16 (2048 2-D points): point i = (lo byte, hi byte) as int8,
// value ~= TQ_LUT_I8_SCALE * int8. One global scale (max |point| = 3.984375 -> 127); relative RMS error
// 0.0085 of the codebook std, far below the trellis quantization error.
// Generated from ggml-common.h (the tq2t codebook).
#include <cstdint>
#define TQ_LUT_I8_SCALE (3.984375f/127.0f)
alignas(16) static const __device__ uint16_t tq_lut_i8[2048] = {
0xecd6, 0x27f2, 0x76d3, 0xed2e, 0xf815, 0x2e1f, 0x25eb, 0x1bdb, 0xed27, 0x30e3, 0xe41a, 0x2dd5, 0x1ec7, 0x0df8, 0xfef8, 0x0b4f,
0x16bb, 0x16cf, 0xe9eb, 0x2415, 0xd155, 0xd8f5, 0x41f8, 0x361e, 0x41f3, 0xcf1c, 0xf72d, 0xedee, 0x13f6, 0x0906, 0x1208, 0x13e7,
0x1dd9, 0x2a07, 0x263a, 0xea05, 0x160e, 0xf2f2, 0xd3cc, 0xd0da, 0x430d, 0x35f6, 0x1623, 0xd5f3, 0x0b36, 0xe158, 0xfa04, 0x06ef,
0xe0f5, 0xfc27, 0x3b14, 0xf91e, 0xf3fb, 0x0701, 0xebe2, 0xff0a, 0x0fbc, 0x2406, 0x2303, 0x0304, 0xd502, 0x320f, 0x27ec, 0x13da,
0xd206, 0xd80e, 0x13ca, 0x11eb, 0x0408, 0x0d0f, 0x3a04, 0xcb19, 0xdd20, 0xd9e3, 0x24ff, 0xed12, 0x0803, 0xf20d, 0xede2, 0x15eb,
0x1615, 0xf51c, 0x95fd, 0xe80a, 0xf208, 0xfa11, 0xfcee, 0xdd19, 0x0b18, 0x0747, 0xfb12, 0xfcfb, 0xf4fe, 0x2a20, 0xf5fa, 0xe0f8,
0x3a29, 0x13dd, 0xf2ed, 0xd103, 0x01cb, 0xe322, 0x031e, 0xfa6f, 0x07f5, 0xd312, 0x0b03, 0x11ed, 0xf318, 0xd537, 0xd60c, 0x1019,
0x0414, 0x1010, 0xdf00, 0x0c01, 0xef03, 0x12ef, 0x2520, 0x0fac, 0x38f8, 0x23c0, 0x1bd3, 0x00fb, 0xf3e9, 0xf711, 0xff19, 0xe8da,
0x21d8, 0x0a04, 0xd2dd, 0xd1e1, 0xebf7, 0xd3f5, 0xd20a, 0x3d1f, 0x1f18, 0x02f3, 0x1b40, 0x0c2a, 0xf405, 0xe2d7, 0x26fb, 0xf918,
0x2af6, 0x01fa, 0xcc11, 0xf0dc, 0xfb06, 0x05e1, 0x10db, 0x0310, 0x559c, 0x19d9, 0xd22d, 0x22fa, 0xc041, 0xfb1f, 0x10d6, 0xffeb,
0x2823, 0x680b, 0xdbe9, 0x0bea, 0xfce8, 0xe00c, 0x16f3, 0x0123, 0xf3fd, 0x2eee, 0xf40c, 0x070d, 0x1b15, 0xf5e4, 0xff38, 0x2227,
0xfa4b, 0xe7e6, 0x2ad1, 0x2010, 0xd9d4, 0x0de7, 0xcff0, 0xd4e7, 0x091e, 0xf0a4, 0x0f09, 0x00f7, 0x09ea, 0xeaf8, 0x0614, 0x30ff,
0x2f01, 0xd215, 0xf8f1, 0xf5e8, 0xb1ed, 0x0fd4, 0x360d, 0x22d0, 0x0e1b, 0x4709, 0x03d3, 0x261b, 0xff0e, 0xdbdb, 0xf600, 0x060a,
0xfb43, 0x08e5, 0xda2f, 0xdddd, 0x1b39, 0x1812, 0x272d, 0xccee, 0xf120, 0xe4ef, 0xe60e, 0x0af4, 0xc60a, 0xd8ec, 0x0ff5, 0xd8ef,
0x16c8, 0x2b37, 0x1fe3, 0xf0c4, 0x1545, 0x04fc, 0xf3dc, 0x020a, 0xe021, 0x06c2, 0xf21a, 0xd3eb, 0x221b, 0x0f12, 0x312e, 0x01f0,
0xccff, 0xf1f4, 0xdb13, 0xeb19, 0x0ad1, 0xf51e, 0x0416, 0x00fd, 0x1ff0, 0x0318, 0xe3e3, 0xfbd3, 0xe510, 0x040f, 0xe5d4, 0x092b,
0xe728, 0xecfd, 0xf2d0, 0xf6bb, 0x040c, 0x17ed, 0x34ed, 0x134d, 0xfee6, 0xfaf3, 0xf4b5, 0x2811, 0x0006, 0xe208, 0xefe6, 0x3511,
0xeeaf, 0x03d0, 0xed00, 0x0cf6, 0xfc11, 0x09dc, 0x052b, 0x0eb5, 0x40fc, 0x3525, 0xf4d6, 0x2f28, 0x0639, 0x05eb, 0x03f0, 0xf3f9,
0x0af1, 0x9be8, 0x24df, 0x0ccb, 0x49af, 0xc705, 0x06d0, 0x04f4, 0x0b23, 0x0507, 0x9b21, 0xe125, 0x0109, 0x520f, 0x0605, 0xfd03,
0xc2e1, 0xcdfb, 0xe3fb, 0xc828, 0x18d2, 0x0141, 0x16f1, 0xbae1, 0x01e5, 0x2ff3, 0xfed7, 0x2f58, 0x2c31, 0xfefc, 0xf613, 0x88eb,
0x28c9, 0xfafe, 0xcb03, 0xe1cf, 0x1ac5, 0x2ce0, 0x0bf6, 0xbe11, 0xf0ec, 0x1e07, 0x1bf2, 0xf413, 0x25f8, 0x3900, 0x02ee, 0x15f9,
0x3ad2, 0x17df, 0x04de, 0xecf8, 0x24b9, 0xf8f3, 0xf229, 0xf310, 0xcaf9, 0x07e7, 0xf01b, 0xcef8, 0x4aea, 0xe7f4, 0xf41c, 0x15d4,
0x03e7, 0xede4, 0xfd02, 0x12d4, 0xbffe, 0x230d, 0xe504, 0xf914, 0xc307, 0xfffe, 0x13fc, 0x0a28, 0xfd1d, 0xfa54, 0xe7f9, 0x1802,
0xef47, 0xf7e9, 0xe800, 0xd6f9, 0x04e5, 0x3409, 0xf300, 0xd806, 0xddef, 0x3b9f, 0xcc2d, 0x0715, 0xeb00, 0x0f35, 0x14fd, 0x2bf0,
0x0817, 0x5ec1, 0xf737, 0xeee9, 0xb30d, 0x46f5, 0x23e6, 0x1beb, 0xf031, 0xfb0b, 0x22ed, 0xfc00, 0x0519, 0xeb02, 0x3be1, 0x30ed,
0xb9f9, 0xda4f, 0x1c09, 0xd814, 0x12df, 0xd83c, 0xfc08, 0xee24, 0xec0d, 0x0cef, 0xde0d, 0x18f3, 0x24f9, 0xf104, 0x0b07, 0x1529,
0xc314, 0x2fc0, 0xfc19, 0x2ccd, 0xd090, 0x29fb, 0xf111, 0x1b4f, 0xbeed, 0x31ea, 0xd1e5, 0xf0d6, 0xcff4, 0xfeec, 0x1040, 0x6e2a,
0xfaf9, 0xfebd, 0xb9d7, 0x0ef2, 0x06e5, 0xf015, 0x0617, 0xf7d8, 0x2310, 0xe414, 0x121d, 0xff02, 0xf71d, 0x269c, 0x1bfa, 0xcc0e,
0x0a63, 0x1f1b, 0x0f1f, 0x27da, 0x411b, 0xc21a, 0xe9f0, 0xc8c4, 0xfff2, 0xf420, 0xf036, 0xdb0a, 0x13e5, 0xebf4, 0x3930, 0x04f0,
0xdbfe, 0x2ce4, 0xd6db, 0xe0e3, 0xe91a, 0xfd0f, 0xc8ea, 0xddd0, 0x0be8, 0x0ee4, 0xf822, 0x23ee, 0x3319, 0xed1a, 0x090a, 0x234c,
0xdecc, 0x00e7, 0xf2ea, 0xe011, 0x18f7, 0xb05a, 0x0324, 0x1bde, 0x190e, 0x0ef4, 0x21e9, 0xfbe1, 0x07fa, 0x2116, 0xf511, 0x2927,
0x3dea, 0xfb30, 0x1125, 0xfd09, 0x1a1e, 0x07e3, 0x1b0a, 0xe8f2, 0x0eda, 0x0cee, 0x1ad0, 0x0f1d, 0x14f2, 0xf4f7, 0x0f06, 0x1215,
0x02f1, 0xefe0, 0xe215, 0x12f2, 0x0212, 0x0cfe, 0x1be9, 0xedf4, 0x3fba, 0xef1e, 0x1eec, 0xf1fc, 0x21e4, 0x16f6, 0xb3e5, 0xd1f7,
0xbfe7, 0xdb10, 0x1bf8, 0x3202, 0xed1e, 0x1a13, 0xf225, 0x10e4, 0xfbe6, 0xfb15, 0xef11, 0x0c17, 0x021c, 0x1e0f, 0x10ff, 0x5df0,
0x1b04, 0xffdb, 0x0ec7, 0x09ef, 0xd5f7, 0xf6fd, 0xe5ed, 0xd5ff, 0x2633, 0x0800, 0x21fe, 0x00e9, 0xf416, 0xedf1, 0x0401, 0x01d6,
0xe520, 0x0cf1, 0xf60e, 0xfbef, 0xb5cc, 0x31f1, 0x31fc, 0x1ddf, 0x06a9, 0x0c0d, 0xf2f7, 0xf81a, 0x4604, 0xd6ed, 0x171e, 0xfdcb,
0xfb1c, 0x0dfc, 0xe5d1, 0xd50f, 0x26dd, 0x030b, 0xe82b, 0xfeea, 0xf9c5, 0xab0b, 0x0707, 0xf1e8, 0x1022, 0x0720, 0xdf1e, 0xd71d,
0x17e9, 0xe506, 0x0cfa, 0xfd14, 0xf2ef, 0xe1e6, 0x0e08, 0xabfc, 0xf11c, 0xdef7, 0xf5c4, 0xdb24, 0x23da, 0xfb17, 0xf50f, 0xdaf4,
0x381b, 0x0abf, 0xf312, 0x07eb, 0xd2ef, 0x5118, 0x00d9, 0x0210, 0xfffa, 0x2df7, 0xf6ed, 0xf30e, 0x0efa, 0x0ffe, 0xdc2c, 0xeae8,
0x0723, 0xfca7, 0xd4d7, 0x311d, 0xf3e6, 0x0a02, 0x01f9, 0xc24e, 0xf4f0, 0x1a26, 0xfa08, 0x0e21, 0x4aff, 0x22f0, 0x0532, 0xe8e9,
0xe624, 0xfd16, 0xe7c1, 0x2c09, 0xc3f5, 0x06ed, 0x091c, 0xf52a, 0x022d, 0x2b17, 0x1bf6, 0x1ffd, 0x00d2, 0x11e9, 0xb1dd, 0x1631,
0xff2e, 0xbfc7, 0x17eb, 0x3e0c, 0x2af8, 0x20db, 0x07d6, 0x0a3b, 0x1132, 0xef08, 0x000f, 0x10f3, 0x38b0, 0x13eb, 0x1ff7, 0xe706,
0x12c6, 0x0bc4, 0xdeed, 0x48d4, 0xfbf3, 0xe5fe, 0xeb21, 0x19ec, 0x38f4, 0xe512, 0x36bc, 0xe6f2, 0xfbea, 0xf702, 0x2fe7, 0x1bcd,
0x12f7, 0x232b, 0x23f6, 0xf0cd, 0x0230, 0xde31, 0xf20b, 0x2dc7, 0x06d9, 0x03f8, 0xeefe, 0xf407, 0xf50a, 0x17e6, 0xc7f2, 0x03d9,
0x4134, 0xe3eb, 0x0309, 0x1c47, 0xea1e, 0xd921, 0x2135, 0x14d1, 0x3214, 0x30df, 0xe80f, 0xed07, 0x0931, 0x0ae6, 0x29e5, 0xcdea,
0xa204, 0xd0d0, 0x04f2, 0xcd24, 0x2e0b, 0xf4f5, 0xf6f8, 0xf9fa, 0x16f8, 0x28d6, 0x1c17, 0xd701, 0x2bd9, 0xf4ee, 0xf60c, 0x0bf7,
0x1313, 0x17ef, 0x1fff, 0x24fc, 0x0302, 0xf8e3, 0xe102, 0xd725, 0xe229, 0xd0ec, 0x2b11, 0xb2f5, 0x0923, 0x01ea, 0x11d1, 0x3938,
0x21f7, 0xc9fd, 0x0119, 0xf0fe, 0xf646, 0xfa23, 0xe50b, 0xe206, 0x2f12, 0xf109, 0xe81f, 0x00f1, 0xec0f, 0x26d3, 0x1127, 0x0404,
0x0afe, 0x43e9, 0xdc03, 0xc9f5, 0x0b09, 0x1e0a, 0x070b, 0x1835, 0xed40, 0x0b2e, 0xe20b, 0x100b, 0xdee6, 0x08fb, 0x2200, 0x19d5,
0xe8b4, 0xd745, 0xee21, 0x0e13, 0x0201, 0x0d1d, 0xbe0a, 0x45cb, 0xffde, 0xc932, 0xe3fe, 0x4df2, 0x0ff8, 0xe4f7, 0x0825, 0x1be6,
0x14df, 0xb5c0, 0xefee, 0x0113, 0x46ef, 0x65fc, 0x231e, 0x20e6, 0xe6fb, 0xf42d, 0x2fd1, 0x1407, 0x4b0d, 0xe40e, 0xe2fc, 0xa1f7,
0x493b, 0xfd2d, 0x0015, 0x4add, 0x19f9, 0x1104, 0xf305, 0x8111, 0xfff0, 0x04dc, 0xca0a, 0x2706, 0xfd3d, 0xf12d, 0x11f5, 0x1111,
0x04d7, 0xf9e8, 0xf2d3, 0x1bee, 0xcf0c, 0x0c11, 0x2501, 0xd521, 0x0b05, 0x1c1c, 0x36e4, 0x23c6, 0x0f2a, 0xd6c6, 0x1520, 0x2009,
0xe409, 0xe6c6, 0xeb64, 0xb61c, 0x07f2, 0x05f5, 0xed0b, 0x2daa, 0x24f1, 0xf7eb, 0x2103, 0x03fd, 0xe6dd, 0xfbce, 0x33db, 0x3f25,
0xe1c4, 0x3fee, 0x4c1f, 0xe31f, 0x26ee, 0xfae4, 0x1419, 0x27fd, 0xd4d3, 0xd3fc, 0xec2b, 0xd514, 0x03f6, 0xcf33, 0x0d09, 0xf2e4,
0xc30e, 0x09fc, 0x10fa, 0x08e9, 0x3716, 0xf2f4, 0x1302, 0x000d, 0x2add, 0xf1f1, 0xecec, 0x0c1f, 0xd5b9, 0x16d9, 0x28e0, 0x0107,
0x52d8, 0xf0c9, 0x35f1, 0x0af2, 0x2508, 0xe4f2, 0xdfd9, 0x1435, 0x1fe9, 0x0e15, 0x16e1, 0x3f40, 0xea3a, 0xcf17, 0xf9f7, 0x051b,
0x4cf9, 0x1e21, 0x1718, 0x5128, 0xe20d, 0x1924, 0x20f5, 0x1b29, 0xef85, 0x0d03, 0xd4f9, 0x2cfa, 0x25d7, 0x090f, 0xf525, 0x4d07,
0x4201, 0xff03, 0xed14, 0x2007, 0xe3dd, 0xdfe0, 0x010f, 0x2ff6, 0x3601, 0xd2f2, 0xe426, 0x0329, 0xc2bc, 0x0ec2, 0xfd07, 0x29bc,
0x023b, 0x1c0f, 0xbd05, 0x1311, 0xfe21, 0xe9e1, 0x1503, 0x4b14, 0x0011, 0xe804, 0x1a0c, 0x1217, 0x38e9, 0xdac0, 0x15e6, 0xfef4,
0x0a00, 0xe3f8, 0xf1e1, 0x08e1, 0xf3bf, 0x08ff, 0x2db5, 0xf2ff, 0xd9e9, 0xf804, 0x040a, 0xc127, 0x098e, 0xd224, 0x180f, 0xfe15,
0xd61a, 0xf698, 0xc302, 0xebdb, 0x06e9, 0x12fe, 0x0804, 0xec32, 0x05e7, 0xbd18, 0xf71b, 0xf106, 0xc6af, 0xfcfc, 0x0321, 0xdd1c,
0x14f4, 0x3cf1, 0xc71c, 0x2787, 0x0125, 0xd00f, 0xb926, 0xaa39, 0x0a20, 0x28f6, 0x04bd, 0x11f9, 0xdba4, 0x3708, 0xfe00, 0xf123,
0xe9f5, 0x02e8, 0xfe11, 0x59fe, 0x1409, 0x21a7, 0xf102, 0xcc15, 0xd6fc, 0x1b2d, 0x23eb, 0x0528, 0xdd10, 0xef05, 0x290f, 0x435d,
0x20f9, 0xde05, 0xedfa, 0x2a45, 0x0120, 0xa8f0, 0x052e, 0xd6ea, 0xeb07, 0xd013, 0xb90d, 0xdd08, 0xb714, 0x1425, 0x95cf, 0xf810,
0x1dfe, 0x01ec, 0xd30d, 0x39ee, 0xaf04, 0x18f1, 0x1d05, 0x05f9, 0x1706, 0x040d, 0xe014, 0x08ee, 0x20ee, 0xe711, 0x041d, 0x127a,
0xfb0d, 0xecf0, 0xd1e9, 0x64e2, 0x090e, 0xa71e, 0x0610, 0x4512, 0x2be7, 0x0de9, 0x1016, 0x10ec, 0x0e0d, 0xf82a, 0x26e5, 0xfdd1,
0xfb02, 0x12e1, 0xcae5, 0x2b0c, 0x250b, 0x2aea, 0x260f, 0x412c, 0x140f, 0x051f, 0xfafb, 0x1a08, 0xf216, 0x0b13, 0xeccc, 0xcea2,
0xcccc, 0xeb16, 0xfa1a, 0x0a0d, 0xdaf1, 0xf5fc, 0xe8ca, 0x4fe3, 0xb347, 0xc661, 0x0a08, 0xf60f, 0xf7f6, 0x1d35, 0xffe8, 0xe90d,
0x08f9, 0x203b, 0xef19, 0x30d8, 0xdcb9, 0xe00e, 0x0d01, 0x010c, 0xe8f7, 0x19ee, 0xd704, 0x120f, 0xee1c, 0xff21, 0x00ee, 0xfcf9,
0xfc0f, 0xfbb7, 0x5d08, 0x09f1, 0xe62f, 0xeafc, 0x0e3a, 0x6ceb, 0xf5dd, 0x0b1d, 0x2cf4, 0x01ff, 0xfe1b, 0x26ce, 0xe6ef, 0x0aee,
0xea2f, 0x16a5, 0xa72a, 0x33f9, 0xd8f2, 0xe6aa, 0x2f17, 0xf5c8, 0xece7, 0x0c1b, 0xe9fb, 0x19e7, 0xfac9, 0xe59a, 0x1829, 0x1401,
0x22f4, 0xe0fe, 0x0fe9, 0xf408, 0xd6e0, 0x1102, 0x19ea, 0xead8, 0x19c0, 0xfd0d, 0x7714, 0x1357, 0x2e1a, 0xeef8, 0xfb35, 0x2205,
0x1dea, 0x2cfc, 0x09f5, 0xf43b, 0x1219, 0xddfc, 0xea11, 0xf8ed, 0x0feb, 0xe84e, 0x4719, 0xdff1, 0xfddd, 0xe818, 0x323a, 0xde28,
0x34ea, 0xf118, 0xdd0b, 0xe61a, 0xd507, 0xe925, 0x06d4, 0xd9d8, 0xe6f7, 0xe0dc, 0xea0e, 0xccf6, 0xfad9, 0x1f05, 0xe538, 0xc21f,
0xc4fd, 0x02fc, 0x9432, 0x51cc, 0xda1d, 0xd72c, 0x0f0e, 0x1916, 0xda03, 0x2628, 0x390b, 0xfb5f, 0x33e6, 0x31f8, 0x0336, 0xdcfa,
0xbd20, 0xe4da, 0x2213, 0x201e, 0x0117, 0xebd1, 0x0e46, 0xfdf0, 0xc813, 0x100c, 0x2902, 0x10e8, 0x1006, 0x16e4, 0xf5ea, 0x0df0,
0x1dee, 0x0911, 0xf41a, 0x1ebd, 0x001e, 0xd1fe, 0x0b40, 0x08fd, 0x22d4, 0x1d1e, 0x12e3, 0xe81c, 0x3c08, 0x000a, 0xff1d, 0x2424,
0xef27, 0x1417, 0xe417, 0xfaec, 0xe21c, 0x571f, 0x060e, 0xdcf8, 0x15e8, 0xe617, 0x58e3, 0x07f4, 0xe1e9, 0x270c, 0xdaf6, 0xfe31,
0xe902, 0x0522, 0x080a, 0xf6d0, 0x1cf4, 0x0ed7, 0x0e24, 0xed18, 0x693e, 0xc70f, 0x2517, 0xf83e, 0xe2ee, 0xf916, 0xf4d9, 0xf813,
0x4827, 0xeff2, 0xd21a, 0xf909, 0x031a, 0xf434, 0x33cb, 0x17fb, 0xe7ff, 0xd020, 0xff17, 0xd531, 0x5c2c, 0xca07, 0xdefa, 0xeaf2,
0x2d06, 0x1a11, 0x2914, 0xcf01, 0xe9cf, 0xe1f0, 0x0be1, 0xafd4, 0xfdf4, 0xefb9, 0xf7ae, 0xf113, 0x1be4, 0x1008, 0x1900, 0x1af6,
0x34e1, 0xdcf2, 0x4949, 0x08cd, 0x172d, 0x0047, 0x22fc, 0xe036, 0x2715, 0x3543, 0xf920, 0xfadc, 0x2c03, 0xe2c9, 0xe213, 0xfbdf,
0xf9ef, 0x35fb, 0x1ddc, 0x04e3, 0x0ef7, 0x13ce, 0xfeee, 0xe51d, 0x071b, 0x0da0, 0x0e0b, 0x034e, 0xfbf5, 0xcee6, 0xfcff, 0x03fa,
0x3fc4, 0x14ef, 0x07de, 0xf30a, 0x09f7, 0xf00e, 0xf733, 0x060c, 0x0813, 0xea14, 0x5b14, 0xfaf1, 0x140d, 0xffb0, 0xd9cb, 0xeedd,
0xef3b, 0x122b, 0xfdfe, 0xd901, 0xef13, 0xb9e9, 0xf71f, 0x1797, 0x5407, 0x131b, 0x1de5, 0xf61a, 0x2b2b, 0xeff5, 0x0102, 0xd80b,
0xf70a, 0xf4cc, 0xfd17, 0xfef6, 0x090c, 0x150a, 0x04ec, 0x0ce5, 0x2512, 0x130c, 0xd8f8, 0x04ee, 0x0ddc, 0x0612, 0xe601, 0x0603,
0x29f1, 0xcf4a, 0xf4e2, 0x22e1, 0xe2f4, 0x2001, 0x02c2, 0xf80b, 0x11fc, 0x05f3, 0xfa28, 0xf518, 0x38d8, 0x0c08, 0x3008, 0x3bcb,
0xff05, 0xf906, 0x0600, 0x24b1, 0xec09, 0x1113, 0x001b, 0x02b7, 0xfec7, 0x0eef, 0x09b9, 0x161a, 0x17cc, 0xbef4, 0xe7e3, 0x1904,
0xe3e7, 0x29f4, 0x1c0c, 0x1b20, 0x1af0, 0x15fb, 0xedf6, 0x0cd4, 0xfc04, 0x14b5, 0xe714, 0xe049, 0x0ceb, 0xb49e, 0xe5e5, 0x00f8,
0xc6dc, 0xdc00, 0xeeeb, 0xff08, 0x0658, 0x0af9, 0xee15, 0xe52b, 0xff23, 0x09d3, 0x16c4, 0x160c, 0xe834, 0xbed0, 0x06dc, 0x29e2,
0xdbeb, 0xc3f0, 0xfa0b, 0x08f7, 0xe4e9, 0x0ffc, 0x20fb, 0x2efe, 0x06f6, 0xeafe, 0x1a1a, 0x2d6a, 0x3305, 0x030f, 0x0307, 0xf1e5,
0x07f0, 0xe22e, 0xcf28, 0xd8cf, 0xcad8, 0x0de2, 0x4015, 0x0e10, 0x1e30, 0xf902, 0xbd2e, 0xf9bf, 0x1808, 0xee0d, 0xfee2, 0xd428,
0xeefc, 0xe1bf, 0xf9e1, 0x2bed, 0x03e1, 0x14ed, 0x1af4, 0xb706, 0x3c18, 0x0e05, 0x9612, 0xfbf7, 0x3cf6, 0xfa00, 0x0ce3, 0xe70b,
0x00ce, 0xd5f0, 0xf303, 0xae16, 0x0f02, 0xccf2, 0x2342, 0x09e8, 0xebea, 0xefea, 0xc5e6, 0xf0f6, 0xf24e, 0x2600, 0x1a02, 0xc337,
0x19fb, 0xe009, 0x063f, 0x002b, 0xf000, 0x071d, 0x0d31, 0xe02c, 0xda28, 0xf40d, 0xee0f, 0x24f3, 0xe8f0, 0xfd0b, 0x04cd, 0x04e9,
0x29fd, 0xf8fe, 0x54f7, 0xf622, 0x0bfc, 0xe0f3, 0x1fe1, 0x2818, 0x0b0e, 0x18dd, 0xf323, 0x1322, 0xfd05, 0xe9d4, 0x0efe, 0x029e,
0xf7db, 0x1239, 0xf4f3, 0x1d00, 0xfdf2, 0xfe26, 0xd517, 0xe400, 0x101b, 0xe0ef, 0xb8b2, 0x1611, 0xf925, 0x0e00, 0xe946, 0x0625,
0x0811, 0x0d12, 0x2df1, 0xf9f5, 0xf6e6, 0x07c6, 0xec10, 0xc42d, 0x0fde, 0xfde0, 0x2c24, 0x1819, 0x42dd, 0x3321, 0xfcda, 0x06fc,
0xc7ee, 0xfce4, 0x0919, 0xdefe, 0x2c3f, 0xc717, 0xfdc2, 0xeff0, 0x0ff1, 0xf314, 0x15dc, 0xeb0b, 0xd9de, 0x09e3, 0x0028, 0x0502,
0xdef4, 0x0719, 0x1303, 0x22dd, 0xe9e5, 0x14e3, 0xecc6, 0xfa0f, 0x0df5, 0x181c, 0x19e2, 0x03c7, 0x10f7, 0xd23e, 0x3f10, 0xf608,
0xca42, 0xfb2a, 0x13e9, 0x0cf3, 0x1bd7, 0x173a, 0xecdf, 0xf10f, 0xdafc, 0x12f4, 0x13f0, 0xf9fc, 0xe5f9, 0xeaee, 0xc5cc, 0x26f5,
0xb8f1, 0x0412, 0xe478, 0x0106, 0xf8de, 0x1ed6, 0xf240, 0x3a4d, 0x151d, 0x5a52, 0x1a30, 0xf6f2, 0xdd15, 0x0e27, 0xf0f8, 0x0d06,
0x1814, 0x13f9, 0xf616, 0xdffc, 0xff0c, 0x163f, 0xb22e, 0x1100, 0x1b00, 0xda07, 0xeed9, 0x5fd5, 0xd8e6, 0xa9e5, 0xf4df, 0xdbe5,
0xe2b8, 0x563b, 0xcb20, 0x3923, 0x50ff, 0xcfc7, 0x17db, 0xe0ec, 0x17f9, 0x641c, 0xfdf6, 0x0a0b, 0x1405, 0xa7c9, 0x11e6, 0xec24,
0xf724, 0x2208, 0x0fe6, 0x00f5, 0x40d4, 0x3f04, 0x1f2b, 0x102e, 0x09df, 0xee2a, 0x1120, 0xe916, 0xf1d9, 0xfc1b, 0x06f2, 0x1604,
0x2b00, 0x1f0c, 0xe310, 0xf9ea, 0x1bb6, 0x4b30, 0x08d9, 0xee09, 0x0b25, 0xfed4, 0xffe4, 0xfb09, 0xf705, 0xe200, 0xf730, 0x4421,
0x1609, 0xecf2, 0x13d7, 0x4bc0, 0xe342, 0x3234, 0xf21e, 0x1e03, 0xfd12, 0x1b06, 0xea28, 0x0a15, 0xe104, 0x10d9, 0xdf02, 0x142e,
0xe2f6, 0x12fb, 0xef17, 0xf9d6, 0xe6eb, 0x0d2d, 0x2efa, 0x0d19, 0x271d, 0xcffe, 0x1ed3, 0x0c0b, 0x0728, 0x03ea, 0x0eed, 0x1cf0,
0xd2c0, 0xedc0, 0x072e, 0x09f3, 0x0808, 0xb3fe, 0x280a, 0x180d, 0x03ff, 0x1df6, 0x10e2, 0xf7fb, 0xfefa, 0x23cb, 0xdeea, 0x1ecf,
0xc4d5, 0x14f7, 0x07b2, 0x0508, 0x46e4, 0xcfd5, 0xdd12, 0xe007, 0x2f04, 0xf800, 0x1906, 0xe5cd, 0x26e2, 0x35d0, 0xdc05, 0x210e,
0xcde2, 0x05fd, 0x01f7, 0xe922, 0xdf17, 0x2d14, 0xdb0d, 0xf727, 0x40e4, 0x0c15, 0xddd6, 0xd817, 0x9652, 0x10cb, 0x08ec, 0x19e5,
0x45fb, 0x3023, 0x18f5, 0xe6e8, 0x0000, 0x22f2, 0xd809, 0xf6f6, 0x020d, 0xd1fb, 0x2deb, 0xf6e0, 0xe304, 0xd3af, 0xa312, 0xeed3,
0x0bde, 0x3cfb, 0xb838, 0xdbe0, 0x02e3, 0xe4fc, 0xf6f4, 0x0e17, 0x15ff, 0x0bec, 0xe0d3, 0xf718, 0x3a0f, 0x120b, 0x0c04, 0xdb16,
0x29ff, 0x20de, 0x2024, 0xa3da, 0x2221, 0xf2fa, 0x180b, 0xe2e0, 0xce05, 0x1a18, 0x0008, 0x02de, 0x1965, 0xe73e, 0x15f5, 0xfd23,
0xfa2d, 0xe6d7, 0x320c, 0x32f4, 0x0709, 0x0bdb, 0x24e8, 0x14e1, 0xcc39, 0xf7cc, 0x0ad6, 0xce09, 0x2edc, 0xc801, 0x23e4, 0xe609,
0x20eb, 0xe5f4, 0x34fe, 0xe9bb, 0xeed0, 0xe9de, 0xfc25, 0xf80d, 0x06fe, 0xf912, 0x1ef4, 0xed05, 0xfc21, 0x2a1b, 0x28e7, 0xeb12,
0xea09, 0x1e15, 0x1bfd, 0x1726, 0x1109, 0x05f7, 0xf514, 0x1ce2, 0xcddd, 0xf6d3, 0x0034, 0xf91b, 0x1de7, 0xf427, 0x1001, 0x35c5,
0xe913, 0x0cff, 0xc0db, 0xdde3, 0x130a, 0x11f0, 0x33d5, 0xe119, 0x1c23, 0x3604, 0xc3eb, 0x1efb, 0x0215, 0x52ec, 0x27f0, 0x131f,
0xe6e0, 0xfa39, 0xda1a, 0xebfa, 0x1004, 0x06ca, 0x16d7, 0x1415, 0x10ee, 0x0806, 0x13ff, 0xf7f9, 0x050b, 0xccba, 0x0fce, 0x1cfc,
0xfa0d, 0x02f5, 0x19af, 0xf606, 0xddc6, 0x0104, 0xf501, 0xa4b7, 0xdbee, 0x1306, 0x06f8, 0x1c02, 0xc723, 0x1e12, 0x1821, 0x2e0e,
0x2218, 0x28ee, 0xc9d2, 0xd201, 0x26e9, 0xe8fd, 0x1513, 0xe1fa, 0x05ff, 0x01dc, 0xfbfd, 0x070f, 0x4207, 0x28c3, 0x19fe, 0x2330,
0x0ac9, 0x0ddf, 0xeb1c, 0x2013, 0x2158, 0x0fe0, 0x0b10, 0x220b, 0x13c0, 0xd31d, 0x02fe, 0x16ed, 0xe402, 0x1e27, 0x38fd, 0x27f9,
0xee02, 0x3ae6, 0xe433, 0xc0f9, 0xdd41, 0xff13, 0x1d19, 0x2d4d, 0xee57, 0xd405, 0xf9e6, 0xec36, 0x05fa, 0xf430, 0x1fcc, 0xfe29,
0xe3f2, 0x78fa, 0x0dd1, 0x120d, 0x0326, 0x0306, 0xd8fb, 0xd5e4, 0x2905, 0xd8fe, 0xc8e1, 0x1ec2, 0xddf6, 0x2604, 0xdeb0, 0x1df2,
0xf614, 0x1c11, 0x0735, 0xd50a, 0xdc39, 0x0bd9, 0xc6f9, 0xd811, 0x1601, 0xf6ef, 0x0a17, 0x1aca, 0xb122, 0xfcd7, 0x0afa, 0xdf1b,
0xf4ec, 0xefe3, 0xfceb, 0x342a, 0xf0fa, 0x0cce, 0x1607, 0xf603, 0x1ae0, 0xdaf9, 0xf807, 0x00e1, 0x37de, 0xfe1f, 0xf9d1, 0x3cdb,
0xba00, 0xef0b, 0xe13b, 0x1df9, 0x00f3, 0xdb34, 0xe7ed, 0xd863, 0x3d00, 0x16fd, 0xe907, 0x1014, 0xde24, 0xf1de, 0x17ff, 0x20f2,
};
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023-2026 The ggml authors
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.
@@ -0,0 +1 @@
3cf03257f219afbe7334045ff7c6a06ac68c627d Sun Sep 20 16:08:11 2026 +0800
@@ -0,0 +1,319 @@
// third_party/ggml/ggml-common-tq.h - the trellis (APR) expert formats of Agention's llama.cpp fork
// (agentionai/llama.cpp 073bc9e68, ggml/src/ggml-common.h; MIT, the same license as the rest of third_party/ggml).
// The block structs and the 2048-point "Hyb" codebook, unchanged, for Strata's device kernels and its CPU trellis
// kernels (src/kernels/cpu/tq_*.cpp). ggml-cpu takes them from the fork itself (-DSTRATA_GGML_DIR).
//
// TQ2_T / TQK6 / TQK7: 128 weights per block, {fp16 d; qs}. qs is 32 trellis steps of K bits (K = 8 / 6 / 7;
// TQ2_T byte-aligned, TQK bit-packed LSB-first, circular, step t's 16-bit window at bit (31 - t)*K; TQ2_T's state
// s_t = qs[(t + 31) % 32] << 8 | qs[t]). Step t gives weights 4t..4t+3: x = (s & 0x7fff) * 0x9e3779b1, points
// lut[x >> 21] and lut[(x >> 10) & 2047] (fp16 pairs), times d.
#pragma once
#include <stdint.h>
#define QK_TQ2_T 128
#define QK_TQK 128
#define TQ_STATE_BITS 15
#define TQ_STATE_MASK ((1u << TQ_STATE_BITS) - 1u)
typedef struct {
uint16_t d; // fp16 scale
uint8_t qs[QK_TQ2_T/4]; // one trellis byte per 4 weights
} block_tq2_t;
static_assert(sizeof(block_tq2_t) == 34, "wrong tq2_t block size/padding");
typedef struct {
uint16_t d;
uint8_t qs[4*6]; // 32 steps x 6 bits
} block_tqk6;
static_assert(sizeof(block_tqk6) == 26, "wrong tqk6 block size/padding");
typedef struct {
uint16_t d;
uint8_t qs[4*7]; // 32 steps x 7 bits
} block_tqk7;
static_assert(sizeof(block_tqk7) == 30, "wrong tqk7 block size/padding");
// Gyro-L pair trellis (agentionai llama.cpp release/gyro-l): 64 steps of K bits, 2 weights per step
// (the TQ2_T codebook's first pair). Defined in the fork's ggml-common.h; repeated here so Strata's
// device and CPU kernels compile without GGML_COMMON_IMPL.
#define QK_TQP 128
typedef struct {
uint16_t d;
uint8_t qs[8*5]; // 64 steps x 5 bits
} block_tqp5;
static_assert(sizeof(block_tqp5) == 42, "wrong tqp5 block size/padding");
typedef struct {
uint16_t d;
uint8_t qs[8*6]; // 64 steps x 6 bits
} block_tqp6;
static_assert(sizeof(block_tqp6) == 50, "wrong tqp6 block size/padding");
typedef struct {
uint16_t d;
uint8_t qs[8*7]; // 64 steps x 7 bits
} block_tqp7;
static_assert(sizeof(block_tqp7) == 58, "wrong tqp7 block size/padding");
// device memory in a CUDA / HIP translation unit, ordinary host data everywhere else
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_TQ_LUT_SPACE __device__
#else
#define STRATA_TQ_LUT_SPACE
#endif
// point i = (tq_lut_f16[2i], tq_lut_f16[2i+1]) as fp16 bit patterns; 16-byte aligned so a point reads as one u32
alignas(16) static const STRATA_TQ_LUT_SPACE uint16_t tq_lut_f16[4096] = {
0xbd4d, 0xb8f7, 0xb6ce, 0x3cd5, 0xbd9e, 0x4368, 0x3dce, 0xb8a6, 0x395e, 0xb430, 0x3bc1, 0x3dbc, 0xb92b, 0x3c9c, 0xbca2, 0x3aaa,
0x3cdb, 0xb8e1, 0xbb33, 0x3dfb, 0x3a8d, 0xbb18, 0xbd64, 0x3da0, 0xbf1a, 0x3b83, 0xb389, 0x3659, 0xb40f, 0xabd7, 0x40ee, 0x35a2,
0xc057, 0x3972, 0xbe17, 0x3996, 0xb926, 0xb9b5, 0x393b, 0x3c75, 0x4151, 0xbdef, 0xb5a3, 0xbd09, 0xb408, 0x4012, 0x3b7f, 0x3ece,
0xb688, 0x4011, 0x3b17, 0xbe30, 0x3d9b, 0xb4bf, 0xb870, 0xb8c8, 0xb537, 0x38b2, 0x31be, 0x34b0, 0x3389, 0x3871, 0xba33, 0x38b8,
0xbce0, 0x3b3d, 0x3367, 0x3d3d, 0x3f50, 0x3cbe, 0x30b0, 0xb991, 0x3733, 0x3986, 0xb70e, 0xb6d9, 0xbe8c, 0xbd98, 0xbcca, 0xbe04,
0x36a9, 0x403c, 0xb527, 0x3eae, 0x3c6a, 0x3982, 0xb655, 0xbd5b, 0x3ebb, 0x3596, 0x417e, 0xbbbd, 0x2fe0, 0xb1d3, 0xb858, 0x31c0,
0xb54e, 0xbc10, 0x3cf0, 0xaf8b, 0x38e6, 0x3f5f, 0x3b87, 0xb2f6, 0xb114, 0xb675, 0x29bf, 0x3298, 0xbb7b, 0xb955, 0x34e9, 0xa984,
0xc04a, 0x378f, 0x31a0, 0x3c8c, 0x2dea, 0x3c68, 0x2fe1, 0x2d29, 0x2c33, 0xbd72, 0x379d, 0x3e3e, 0xb918, 0x3cf2, 0xbcbe, 0x38bf,
0x3284, 0xbdd5, 0x3707, 0xbd01, 0xbec1, 0x38c1, 0xb960, 0x3838, 0x3413, 0x3010, 0x376d, 0x3672, 0x302f, 0x3f42, 0x3a61, 0xbe9a,
0x3c06, 0xbc71, 0xbb57, 0xbcf2, 0xa9dc, 0x3c85, 0x3873, 0xb8b2, 0x2d1e, 0x340d, 0x3661, 0xb73f, 0xbb91, 0xb8b7, 0xb956, 0x3943,
0x3958, 0x3985, 0x3b26, 0xb556, 0xae17, 0xc2b9, 0x34e9, 0xb9ea, 0x33d5, 0xb6f4, 0x3826, 0xb1af, 0xb8a4, 0xaf98, 0x3a2d, 0xbc69,
0x3a25, 0x358e, 0x406d, 0x32fd, 0x38a4, 0xb11a, 0xb170, 0xb02e, 0xaa0a, 0xb5cb, 0x3c04, 0x3d45, 0xb258, 0xb55b, 0xb412, 0xbbf5,
0x3d33, 0x3f4b, 0xbc6e, 0x38a9, 0xb8c0, 0xb715, 0x2ec6, 0xbdd9, 0xbeb3, 0x2980, 0x3c54, 0xbb3c, 0x3ba0, 0x2d68, 0x42f9, 0xb209,
0xb557, 0x3337, 0x3870, 0xbda7, 0x2d57, 0x35bd, 0xb8cd, 0x385e, 0x39fe, 0xb68e, 0x3eda, 0xbd74, 0x3643, 0xbd54, 0x3a32, 0x37d4,
0x38f8, 0x2f7f, 0x37f3, 0x380f, 0x1b1e, 0xbc23, 0x25c7, 0x35c8, 0x2e3e, 0xb82a, 0xb85f, 0x3897, 0x3c0c, 0x3cb3, 0xc13e, 0x377b,
0xb3a4, 0x3f09, 0xc006, 0x3c73, 0xbda5, 0x3ad1, 0xb0c6, 0xa3cf, 0xb9d5, 0xb680, 0x384b, 0xb493, 0x3a3c, 0xa985, 0xbcb5, 0xba24,
0xbd0c, 0x3c21, 0x2f68, 0x34dc, 0xbc5d, 0xbdb7, 0xbbbf, 0xbddb, 0xb4c4, 0xb95a, 0xb59b, 0xbdaa, 0x34cf, 0xbdce, 0x3bad, 0x3f9d,
0x3a05, 0x3bd5, 0xb69c, 0x2c64, 0x4003, 0x3adb, 0x3d4c, 0x35e8, 0x308d, 0xb5cc, 0xbd2d, 0xbb86, 0xb124, 0x3cd3, 0x3a0a, 0xb2ab,
0xb507, 0x3d4b, 0xb190, 0x284c, 0x384c, 0xbe83, 0xbc94, 0xb806, 0x31e4, 0xb146, 0xbbe0, 0x3178, 0xbc9d, 0x3819, 0x3824, 0x2e8f,
0xc246, 0x4150, 0xbcf3, 0x3a43, 0x3da9, 0xbdd5, 0xb229, 0x3c47, 0x400e, 0xc001, 0x3bb2, 0xb0c3, 0xbd46, 0x3822, 0xb92d, 0xa4a9,
0x3c72, 0x3cfa, 0x3550, 0x4284, 0xb9e5, 0xbc97, 0xb996, 0x357a, 0xba03, 0xaf70, 0x35e7, 0xbc07, 0xb663, 0x397b, 0x3c59, 0x2942,
0xadf7, 0xb689, 0xb875, 0x3db8, 0x35ea, 0xb63c, 0x3674, 0x3349, 0x3926, 0x3ae0, 0xbb20, 0xb56e, 0x3f05, 0xa9ae, 0x3ce5, 0x3c38,
0x40b8, 0xb1ef, 0xba73, 0xba2b, 0xbdd7, 0x3d3f, 0x3822, 0x3c09, 0xbd87, 0xbce4, 0xba38, 0x36be, 0xb808, 0xbe23, 0xba33, 0xbd77,
0x3b90, 0x3466, 0xc1c5, 0xb805, 0x34c0, 0x375b, 0xb4be, 0xa2db, 0xb96c, 0x3495, 0xb38a, 0xb99a, 0x390a, 0x31d5, 0xa910, 0x3e16,
0x2878, 0x3dd6, 0x3964, 0xbdc0, 0xb783, 0xb3ef, 0xba12, 0xb571, 0xb8ce, 0xc0f2, 0xbd8f, 0x3771, 0x3656, 0x3eba, 0xbe0e, 0x3c39,
0x3ac5, 0x371b, 0x3469, 0x4071, 0xbd99, 0x2e19, 0x3ab2, 0x3cb8, 0x36d9, 0xa92c, 0xbcb4, 0xbc9b, 0xa0fa, 0xb4e2, 0x34ed, 0x31fd,
0x4033, 0xb0a0, 0xbac8, 0x342e, 0x3df5, 0xbccd, 0xbc5a, 0xbc5f, 0x3f32, 0x3ada, 0x3878, 0x39ec, 0x3db1, 0x3ce5, 0xb891, 0xbe93,
0x3c11, 0xb75e, 0xb82c, 0xbb27, 0x36d6, 0xba67, 0xb602, 0x352c, 0x3507, 0xbf3a, 0xb8e9, 0xbcf5, 0xb55e, 0x3773, 0xb832, 0xbd0a,
0xbf01, 0x3989, 0x3edf, 0x3d73, 0xbb3d, 0x3bc8, 0xbf82, 0xb7e0, 0x4053, 0x393f, 0xb07d, 0x2f91, 0xbc8b, 0xb6af, 0x3538, 0x2a46,
0x3c2f, 0xbbfd, 0xbfc9, 0x324e, 0x3a8f, 0xb702, 0xb939, 0xbda9, 0x3ac3, 0x3c3f, 0x3875, 0x3798, 0x3dc4, 0x3e1b, 0xb820, 0x255e,
0xa7e2, 0xbe92, 0xb63f, 0xb7c7, 0x38bd, 0xbcb4, 0x3a2f, 0xb958, 0xbdf2, 0x34fc, 0x3ba1, 0xb5a8, 0x3975, 0x3047, 0xaecc, 0x21da,
0xb7f7, 0x3bc4, 0x39f8, 0x2eb6, 0xbb3f, 0xbb3a, 0xbd9b, 0xb13d, 0x37fa, 0xbab2, 0x3794, 0x3074, 0xbd7e, 0xbad3, 0x3d65, 0x346b,
0x3cfd, 0xba61, 0xadd5, 0xb8fe, 0xbe09, 0xb6ec, 0xc05b, 0xb544, 0x360c, 0x2fdb, 0xb8ba, 0x39e5, 0xb8a8, 0x3e96, 0x40cf, 0x38cf,
0xba8b, 0xac5a, 0xb691, 0xb284, 0xc0b9, 0xb5d5, 0x3864, 0x3d00, 0x3220, 0xa382, 0x3422, 0xbb8f, 0xba85, 0xb85e, 0x3854, 0x3eb3,
0xc110, 0xb885, 0xbdf8, 0x2e60, 0x1cb3, 0xb8ba, 0xb4d3, 0x3636, 0x382a, 0xaf93, 0xbc81, 0x346a, 0x3d66, 0x3148, 0xc0b3, 0x36fe,
0xaf70, 0x4001, 0x3caf, 0x3eac, 0xbd48, 0xb614, 0x3d04, 0x3de8, 0x3f2b, 0x31d0, 0xb955, 0x30ce, 0xb81b, 0x2d33, 0xb328, 0xb657,
0xb7c2, 0x3527, 0xb9f6, 0xc255, 0xbc1a, 0x3c90, 0xbe9c, 0x35f3, 0xc11d, 0x409a, 0x30db, 0xbf2f, 0xbe02, 0x3285, 0xb607, 0x2f14,
0x3c56, 0x35c2, 0x3288, 0x30ac, 0x3c1c, 0xc25c, 0x3ca4, 0xbbd6, 0x3465, 0x29c8, 0x37a3, 0x4129, 0x3151, 0x3225, 0x2ef2, 0xad41,
0xbbcb, 0xbfc1, 0xb0c0, 0xbe71, 0xb17d, 0xbb59, 0x3cfe, 0xbefb, 0xbdb8, 0x39f0, 0x4014, 0x28a7, 0xb771, 0x396a, 0xbbdc, 0xc063,
0xbabe, 0x2898, 0xb683, 0x3de9, 0xbd1f, 0xaa78, 0x4187, 0x3ded, 0x3e18, 0x3d7b, 0xaf3c, 0xab0c, 0x38a7, 0xb524, 0xb964, 0xc38f,
0xbeda, 0x3d02, 0xaa74, 0xb25d, 0x2d90, 0xbe9a, 0xbe23, 0xbbb0, 0xbf6a, 0x3a8c, 0xbbfa, 0x3d87, 0xb53c, 0x3571, 0x385c, 0xc027,
0xb903, 0xb801, 0x3368, 0x3b7b, 0xb70c, 0x3ab8, 0x38b5, 0xb625, 0xb436, 0x3cb1, 0x8d2a, 0x3f2c, 0xb88e, 0x2c53, 0xb2c8, 0x393b,
0xbdbf, 0x3f40, 0xbc1b, 0x39d9, 0xbc3a, 0x306d, 0xb3ba, 0xb8fc, 0xc07b, 0x3c75, 0xb655, 0xb421, 0x3d34, 0xb720, 0x37f1, 0xb6a0,
0xb338, 0xbec7, 0xba58, 0x334e, 0x3aab, 0xb810, 0xb3d7, 0xbe3d, 0xb984, 0x40a2, 0xb5cd, 0xba54, 0x3afa, 0xb63e, 0xbd80, 0x394d,
0xba54, 0x2dda, 0xbaec, 0xb8e4, 0x2b2a, 0xad38, 0xbd82, 0x3886, 0xac6b, 0xc015, 0x368b, 0x3c72, 0x2fb3, 0xbaa7, 0x38fb, 0xb2cb,
0x335d, 0xbfb5, 0xaba9, 0xa535, 0xafb8, 0x38b7, 0x3d00, 0x3524, 0x3b42, 0xaeac, 0x4144, 0xb1a6, 0xb352, 0xba3a, 0x2c72, 0x39f3,
0x4079, 0xb82c, 0xb9e5, 0xb45f, 0x9d20, 0xb9f5, 0xb2ee, 0xbd36, 0xbad5, 0x2f11, 0x3450, 0x3e80, 0x213f, 0xb684, 0x3200, 0xbd07,
0xb839, 0xbc5e, 0xc217, 0x3f5d, 0x3d9a, 0xbe94, 0x3947, 0x3381, 0x9081, 0xb943, 0x3eac, 0x3795, 0xad61, 0x3915, 0xb810, 0x3d5d,
0x39cb, 0x33f2, 0xbfe8, 0x41ed, 0x3ee7, 0xb4a2, 0xb9e5, 0xb88a, 0x36b3, 0xc0da, 0xb57f, 0x406c, 0xba70, 0x3c5c, 0xb936, 0x3ae4,
0x3e2c, 0xb7ff, 0x35b6, 0xb08e, 0xb8d1, 0x3c3a, 0x227e, 0xafed, 0x3a3d, 0x310a, 0x2d00, 0xb926, 0xbbe1, 0x3f76, 0xb8aa, 0x3e15,
0xb31c, 0xc074, 0x40ee, 0xbcb6, 0x3449, 0x3b03, 0x38f5, 0xbd01, 0xbc2d, 0x386a, 0x3f94, 0xbcfc, 0x33a2, 0xb049, 0x3c77, 0xb86e,
0x366c, 0xb91c, 0xb832, 0x35c6, 0x36ab, 0xbc4c, 0xb6b9, 0x3a04, 0xb2c9, 0x3c84, 0x3006, 0xb762, 0x330e, 0x3580, 0x3d32, 0x3926,
0x38f9, 0xbfb2, 0xc00a, 0x3de6, 0x3a35, 0xafad, 0xbe69, 0x3d88, 0xc30f, 0xbe12, 0xb13d, 0x3d26, 0x382a, 0xb7a5, 0x40fa, 0x3ac3,
0xb8a9, 0xc028, 0xb979, 0x3e19, 0xbac1, 0xbdd7, 0xbd42, 0xb802, 0xb631, 0xbe1a, 0xb8fb, 0xac7a, 0x3ff8, 0x3819, 0x3d3f, 0x42e8,
0xb312, 0xb1dc, 0xc036, 0xaa42, 0xbd28, 0xc078, 0xb6f5, 0x36dd, 0xbad4, 0x31fd, 0x3933, 0xb7e9, 0x39b4, 0x31d4, 0xbd13, 0xb4ae,
0x37d3, 0x3c5d, 0x3925, 0xbafd, 0x3b52, 0x3875, 0x2a38, 0xa581, 0x3b51, 0xb450, 0xc248, 0x3ccc, 0xb1aa, 0x3ad2, 0x36eb, 0xbe90,
0x423c, 0x34e3, 0x3ac2, 0x3bc1, 0x3be5, 0x3749, 0xbcd1, 0x3cee, 0x3ac7, 0x4017, 0x3a67, 0xbfc4, 0xb7eb, 0xb9a8, 0xbf94, 0xbf08,
0xb711, 0xa983, 0x3c0f, 0xb609, 0x3ebd, 0xb7f7, 0x34f4, 0xbca7, 0xbac3, 0x38b1, 0xb5d0, 0xb93f, 0x3e04, 0x3f1d, 0xb7fd, 0x305c,
0xaae3, 0xbcaa, 0xbb0f, 0x3d8c, 0xbca4, 0xbd3f, 0xbb3b, 0xbc08, 0x3a90, 0xb9de, 0x377f, 0xad25, 0xb988, 0xbefe, 0xbdf7, 0xbc6c,
0xba23, 0x35c3, 0xbb14, 0x370a, 0x3c45, 0xb3a9, 0xb889, 0x3c72, 0x3a36, 0x3e71, 0x3a90, 0xb8e0, 0x34cb, 0x34a6, 0x40be, 0x3c6c,
0xbe95, 0xbc3f, 0xba4d, 0x2284, 0xb96e, 0xb73e, 0x384d, 0xbc04, 0xb452, 0x3a03, 0x41a8, 0xc100, 0x3c75, 0x2ed2, 0xbc47, 0x3ab6,
0x3746, 0x3a63, 0xb62f, 0x3735, 0xb9dd, 0x3c2f, 0xbba8, 0xb08f, 0xb270, 0x3289, 0x3972, 0x3c1e, 0x3844, 0xb5ae, 0x3cee, 0x3d30,
0xb98f, 0x3fa2, 0x3e16, 0xb150, 0x3c9c, 0x382c, 0x3483, 0xae2e, 0x3b71, 0x3a84, 0xbb53, 0x32f4, 0x3540, 0x3ab2, 0xb6e0, 0xba06,
0xbcc9, 0x3701, 0xb89a, 0x361a, 0xbe12, 0x3a74, 0x3b56, 0x37ae, 0xb6ec, 0x38ee, 0xb47a, 0xb60a, 0x3247, 0x374a, 0x394d, 0x3883,
0xb76f, 0x2c41, 0xbc07, 0xb862, 0x395e, 0xbba5, 0xb71f, 0x3865, 0x3897, 0x2cbc, 0xac7a, 0x35c9, 0xb9df, 0x3ac5, 0xb63b, 0xb8b9,
0xc064, 0x3ff6, 0x3ba3, 0xb829, 0xb904, 0x3b7e, 0xafdb, 0xb78e, 0xbaec, 0x3c22, 0xb53d, 0x39a5, 0xbab6, 0xc0d4, 0xb47e, 0xbddb,
0xba66, 0xc01c, 0x37ec, 0xbcb0, 0xb409, 0x3ac3, 0x2b2b, 0x3e47, 0x3b8a, 0xb8e0, 0x38cd, 0x3a77, 0x3cb0, 0xb724, 0xbaef, 0x381f,
0xba7a, 0xb0f9, 0x3940, 0xb138, 0x3855, 0xb840, 0x39af, 0x35f4, 0x3b0f, 0x2c19, 0x3760, 0x3b83, 0xa813, 0x3801, 0xb801, 0x41d6,
0x3026, 0x3ab3, 0xbca3, 0xa9f5, 0xbf1e, 0x370e, 0xb82b, 0x3467, 0xb4c3, 0xbd57, 0xad4c, 0xb4e9, 0xb8c4, 0xbad6, 0xa8f7, 0xbd66,
0x3e70, 0x3cd2, 0x236c, 0x3421, 0xaa8a, 0x3c22, 0xb9c2, 0x9661, 0x3988, 0xb622, 0xb797, 0xb8aa, 0x254c, 0x305c, 0xbd53, 0x271b,
0x3c11, 0xbaa9, 0xb75b, 0x3601, 0x36d1, 0xb4e9, 0xb856, 0xb15d, 0xbe96, 0xc0b2, 0xb7c5, 0x3e32, 0xb069, 0x3e22, 0xbc18, 0x3b41,
0xc16e, 0x31ca, 0x365a, 0x35f9, 0xb491, 0xb700, 0x3a6a, 0xb41b, 0x2f26, 0x406a, 0xb8a6, 0xbd54, 0x3b9b, 0x39e3, 0xbeae, 0xad0f,
0x3b1b, 0xb166, 0xafd4, 0x3655, 0xbde7, 0xbaa7, 0x37c1, 0xbd6c, 0xbc6d, 0x3cbf, 0x3584, 0x2dbd, 0x3d69, 0xb9f9, 0xb992, 0xac53,
0xbf6b, 0xb2a2, 0x35b5, 0xc157, 0x331a, 0x328e, 0xba14, 0xb7b3, 0x3c44, 0x3809, 0x3c08, 0x3361, 0x3b93, 0xbc1c, 0x3b53, 0xbd21,
0xb9d1, 0x39b2, 0x326b, 0xbad9, 0xb1c8, 0x35e6, 0x38ff, 0xaeff, 0xb831, 0xb734, 0xba96, 0xbbe1, 0x33f8, 0x36fb, 0xb049, 0xc15a,
0x3b22, 0xb7a3, 0xb462, 0xbc3d, 0xbf97, 0xb57c, 0x3c86, 0xbcaa, 0xbcb9, 0x3c6e, 0x39ca, 0xb0f5, 0x379f, 0xb5bf, 0xb629, 0xbcb6,
0x3aab, 0x3f0f, 0xc01a, 0x34fc, 0x3869, 0xb6be, 0xb953, 0x32f4, 0xb85f, 0xbdb7, 0x39f4, 0x411a, 0xbce8, 0x203c, 0x3824, 0x2a59,
0xb26f, 0xa60c, 0xb47f, 0x3d96, 0xb8d0, 0xb53f, 0x3706, 0xb69f, 0xb1c9, 0x36cf, 0xad03, 0x37c1, 0x3d80, 0xbc90, 0xba26, 0xb98e,
0x3c5b, 0x334b, 0xc196, 0xb051, 0xbd24, 0xbd79, 0x3b38, 0x3e2f, 0xba82, 0xb64d, 0x2a56, 0x34ed, 0xb36f, 0x2a01, 0x40e9, 0xbfbc,
0xb7ce, 0xb600, 0x3cce, 0x3a9c, 0x33c6, 0xb23c, 0x3c33, 0x36c8, 0xa776, 0x409e, 0xb822, 0x3c35, 0x3e43, 0x30ef, 0xb9b2, 0xb9f7,
0x3c79, 0xba81, 0x3973, 0xaedb, 0xbfe1, 0xba33, 0x348e, 0x3d8a, 0xb5ac, 0xbfa1, 0xb8d9, 0x31b7, 0x3aee, 0x3481, 0x3d3b, 0xb56e,
0x3d98, 0x2c65, 0x39e0, 0x3d74, 0xb51a, 0x3ae2, 0xae6c, 0x3bb9, 0xbdc8, 0x1d86, 0xb9d9, 0x3840, 0xbc60, 0xc0f1, 0x3e26, 0x396d,
0x3dc5, 0xa478, 0xbf35, 0xc01b, 0xb938, 0x39c8, 0x35d1, 0x3fd0, 0xb3bc, 0x3d41, 0xbca8, 0x3bf9, 0xbd36, 0x32f5, 0x3f59, 0x34c8,
0x3e38, 0x3854, 0x338e, 0xb82e, 0x37b2, 0xa3ce, 0xb683, 0x37fd, 0xc104, 0x3f02, 0xb92f, 0x38b3, 0xb454, 0x3bcd, 0x31f4, 0xba42,
0xbf4d, 0x3878, 0xbf7f, 0x3559, 0xb8e0, 0xbc53, 0xbd77, 0x407e, 0xb69e, 0xb0c6, 0xacce, 0xbabd, 0x3c1b, 0xb92f, 0xb8fa, 0x3a5f,
0xb628, 0x3f13, 0x3893, 0xbacd, 0xc047, 0x3ec8, 0xb70b, 0xba7f, 0xb997, 0xb140, 0x2c0c, 0xb466, 0xba3f, 0x3dde, 0xbe75, 0x3ae1,
0xb466, 0x3879, 0x3d68, 0x3c55, 0xb4d9, 0x3c6e, 0xbe71, 0xb803, 0x3e15, 0x2a52, 0x3e1b, 0xbc37, 0x3585, 0xb747, 0xbf22, 0x3db4,
0xbcdb, 0x31a6, 0xb415, 0x2e23, 0xab25, 0xb884, 0x329e, 0xb5ef, 0x3525, 0xb59c, 0xba76, 0x39c2, 0xb6f5, 0xbf1e, 0xbcdf, 0x2dad,
0x3e8c, 0x4019, 0xb92c, 0xbb4a, 0x3494, 0x2ddb, 0x406e, 0x3afd, 0x3b91, 0xb97a, 0x3c1f, 0xbce1, 0x3eae, 0x3c34, 0xbddd, 0x38ec,
0x390f, 0x3e4f, 0xbc20, 0x3e04, 0x378c, 0xba0b, 0x330d, 0xb8aa, 0x3e34, 0x348e, 0xbaa5, 0x352f, 0xbac3, 0x3d2b, 0xb982, 0xbe71,
0x305c, 0xc1e1, 0xbe05, 0xbe12, 0xb70b, 0x2fc1, 0x3c8b, 0xbe71, 0x35ad, 0x3dcc, 0xb581, 0xb612, 0xb42c, 0xb50c, 0xb1c9, 0xb36c,
0xb443, 0x3977, 0xbd4c, 0x3d11, 0x39b8, 0x3b17, 0x269a, 0xbd27, 0xbce0, 0x3d6c, 0xb86d, 0xb611, 0x35e7, 0xb50c, 0xb453, 0x359c,
0x38c6, 0x38bf, 0xb82a, 0x39a6, 0xa8c2, 0x3bb1, 0xb020, 0x3c8b, 0x2c82, 0x2dfa, 0xbb37, 0xb43e, 0x2b23, 0xbbbd, 0x3c97, 0xbd25,
0x3d21, 0xbb81, 0xb8e5, 0xbe12, 0x3845, 0x3d6a, 0xb571, 0xc0ec, 0x3c69, 0x34ba, 0xb96f, 0x2818, 0xbdde, 0x382d, 0x3f0c, 0x3f33,
0xb44b, 0x3c30, 0xaebd, 0xbef5, 0x3a3b, 0x2683, 0xaaf0, 0xb7f8, 0x405e, 0xb4f5, 0x3c5b, 0xb197, 0x359f, 0xbada, 0x3227, 0xbb77,
0x3877, 0x3dec, 0x34a2, 0xb7c6, 0x3bde, 0xba0e, 0xb758, 0x20cc, 0x3760, 0xb8e8, 0xbdaf, 0x3cb8, 0x3cf3, 0x385d, 0x306f, 0x3078,
0xac7a, 0x34d1, 0xb9b8, 0x402f, 0x2d2e, 0xbc80, 0xb55d, 0xbeef, 0x348e, 0x356a, 0x3511, 0x3b68, 0x35a4, 0x32ea, 0x3e99, 0x3a13,
0x4002, 0xb8c9, 0x3dc1, 0x355a, 0x3556, 0xbb78, 0x3560, 0x37ee, 0xba6e, 0xbc4a, 0xb14d, 0x33eb, 0x22a9, 0x3c4a, 0xbd5b, 0x3a27,
0xc0ca, 0xba1d, 0x4053, 0xbd31, 0x3c1a, 0xb87b, 0x38de, 0x36e3, 0x2663, 0x2b95, 0x3b4f, 0x3685, 0x353c, 0xc020, 0xbe97, 0x4050,
0xbc48, 0xa53a, 0x3e4e, 0xbeea, 0xac24, 0xbb52, 0xb743, 0x40d2, 0xb389, 0x3762, 0xb493, 0xbb02, 0x3cb4, 0x342f, 0xba83, 0x3ace,
0xbc28, 0x3923, 0xc004, 0xc0af, 0xb898, 0xb842, 0x38d0, 0x2760, 0xb83e, 0x405e, 0xaffb, 0x4254, 0x3b69, 0x3c6f, 0xba70, 0x3bed,
0xb0de, 0xba70, 0x3d9c, 0xb635, 0xbde3, 0x3de8, 0x3321, 0x38e5, 0x369f, 0x40ae, 0x36e3, 0xbaf2, 0xaf7b, 0xbb9b, 0xb484, 0xc1f3,
0x3f5a, 0x4097, 0x3da5, 0xaead, 0x3934, 0x1e3a, 0xbc67, 0x409f, 0xb2ed, 0x3a55, 0x3009, 0x385a, 0x3166, 0xb6ac, 0x3832, 0xc3f8,
0xb800, 0xa95f, 0xbc8a, 0x2f61, 0x353c, 0xbeba, 0x3284, 0x3ce3, 0x3fad, 0xade8, 0x3da0, 0xb7c1, 0xb56e, 0x382d, 0x385f, 0x3855,
0xbd34, 0x2ff5, 0xba07, 0xb290, 0xbda4, 0xb6f4, 0xb89b, 0x3ad2, 0x3613, 0xbe27, 0x3838, 0x35fc, 0x28e1, 0x3c96, 0x3c1e, 0xbd62,
0x315a, 0x356b, 0x3b05, 0x3b16, 0xbaf3, 0x3ed5, 0xbf42, 0x3c65, 0x3d3f, 0x378a, 0xbf4e, 0xbd43, 0x3c0d, 0x3964, 0x34c3, 0x3c00,
0x345a, 0xbafe, 0xbf4f, 0xba8b, 0x4240, 0xb95b, 0x3b21, 0xc0a2, 0xb6ed, 0x331d, 0xb57a, 0x3111, 0x3594, 0xb8ca, 0xc16a, 0x3d96,
0xb7a9, 0x3c86, 0xb949, 0xb498, 0x2d89, 0x3c1e, 0xad06, 0x2eeb, 0xbc5b, 0xba8a, 0xbe54, 0xb0b9, 0xbc9a, 0x3e71, 0x3ca7, 0x3ff4,
0xbf8b, 0xbbbc, 0xb894, 0x3fef, 0x3bda, 0x40c9, 0x3bc7, 0xbb66, 0xb87e, 0x3cbb, 0xbb1e, 0xb1f7, 0x3a3d, 0x38f6, 0xad22, 0x3cd9,
0xbdb4, 0xbd81, 0xb005, 0xbd96, 0x3d6e, 0xb91c, 0x38f2, 0xbd5e, 0xb513, 0x2e27, 0x3e5b, 0xbe1c, 0x34b3, 0x366e, 0xbb24, 0xb6cd,
0x36f7, 0xbfb4, 0xb00c, 0x34a3, 0xb1bf, 0x37df, 0xb9d6, 0x33d3, 0x396f, 0x3edf, 0xb5d1, 0xb6f7, 0x2aa1, 0x38b2, 0x36b1, 0x223d,
0xbc6a, 0x3d3e, 0xb777, 0xb7b5, 0xb8ed, 0xb91c, 0x3be6, 0x35f5, 0xc077, 0xbd74, 0xbcdc, 0x3966, 0xbc12, 0x3d0b, 0x3312, 0x28cb,
0xbd0d, 0x4128, 0xbef1, 0xb80e, 0xb758, 0x3eb4, 0xb6d3, 0x352f, 0x343d, 0x3ca3, 0xb733, 0xbaef, 0xbce4, 0xbc1d, 0x3eac, 0x38fa,
0xb9d1, 0x3bce, 0x3953, 0x36ec, 0xbbb4, 0x3985, 0x4005, 0x3fe2, 0x3f4e, 0xb991, 0x39d5, 0xbe2c, 0xb44e, 0xb37f, 0x3acf, 0x30aa,
0xb358, 0x40c3, 0x3c1f, 0x3b9b, 0x39ec, 0x39a7, 0x3d01, 0x4111, 0x367d, 0xbb76, 0x3c75, 0x3a48, 0xb547, 0x3c01, 0x3d2f, 0x3ae0,
0xc3b1, 0xb837, 0x2e1d, 0x36c1, 0xb2d3, 0xbd8e, 0xb23a, 0x3d80, 0xbd29, 0x3c9b, 0x37a8, 0x348c, 0x3c9e, 0xb5aa, 0x3311, 0x40d3,
0x256d, 0x4028, 0x2e47, 0xa66e, 0x390a, 0xb8de, 0x3306, 0x3c03, 0xbc58, 0xbb3f, 0xbc05, 0xbc21, 0x376c, 0x28e2, 0xb536, 0x3dda,
0x2427, 0x3ebb, 0xb70a, 0xbdbf, 0x3cc4, 0xbb10, 0x3d33, 0x2d29, 0xc044, 0xbfd0, 0xbfd3, 0x3726, 0x32d9, 0xad34, 0xc040, 0x3d32,
0x3f66, 0x2b12, 0x377a, 0x3ae9, 0x3088, 0xc02d, 0x384f, 0x38e2, 0x3c2b, 0xacfb, 0xbbda, 0xb9de, 0x2d0a, 0x3945, 0x38f1, 0x40ba,
0x3858, 0x1b91, 0x2f58, 0xba15, 0x3642, 0x3a7f, 0x39d4, 0x387a, 0xb9af, 0x3efc, 0xc007, 0xbcc6, 0xba9b, 0x3938, 0xb635, 0xaa27,
0xa2e3, 0x3509, 0xb38b, 0xbb66, 0xbbc3, 0xb775, 0xbbc7, 0x33f5, 0xc014, 0xb6ba, 0xa91a, 0x340b, 0xc0ad, 0x3dad, 0xa94d, 0xb70e,
0xb9b4, 0xbcf0, 0x2f73, 0xb38a, 0x34f1, 0x304e, 0x3cdf, 0xbfe6, 0xc329, 0x34c3, 0x3c80, 0xbdc0, 0x37bd, 0x39ed, 0x393d, 0xaaa3,
0x3a94, 0xbd49, 0xc288, 0xb4d2, 0x2c3e, 0xbfb6, 0xbca0, 0xb93d, 0xb9d6, 0x3200, 0xac36, 0x3875, 0x3072, 0x33f7, 0x3e47, 0xb8f7,
0xba54, 0x3116, 0x3a12, 0xc037, 0x3ad7, 0xb48c, 0x323b, 0xb798, 0xc11c, 0xbf50, 0xaf13, 0xaf0b, 0x3c1c, 0x2efc, 0x3b04, 0xbc68,
0xb611, 0x38fa, 0xb74f, 0x3f8c, 0x3b22, 0xbf1a, 0xc394, 0x3cef, 0x3ca6, 0x2614, 0x37c3, 0xbe03, 0x3cd0, 0xc072, 0x3f2e, 0xc15f,
0x3c11, 0x34da, 0xb4e7, 0x3cf5, 0xc030, 0x3030, 0xb32a, 0x3837, 0xc1c0, 0xbca2, 0x33dd, 0x3ef1, 0x982a, 0xac37, 0x3c5e, 0xb7b3,
0xb5b6, 0xb9cd, 0xb9e9, 0x2c0c, 0x3832, 0xab2a, 0xacea, 0x419a, 0x3458, 0x3922, 0xc18e, 0x3c1f, 0x2ae8, 0xb762, 0x393d, 0xbe8c,
0xb009, 0xbd47, 0x3d9b, 0x3abd, 0xb95a, 0x3c56, 0x3cfe, 0x3107, 0x37d9, 0xbc56, 0x312d, 0xb846, 0x3752, 0x3d2e, 0x41d2, 0x4030,
0xb2d1, 0x3bf0, 0x30c5, 0xbc39, 0xb1ee, 0xb8aa, 0x405a, 0x3d48, 0x3c11, 0x2a02, 0xb800, 0xc184, 0x3dd2, 0x308d, 0xb975, 0xbd48,
0x32b5, 0xb942, 0x38c6, 0xbe0e, 0x3688, 0xc06f, 0x33b3, 0xbc61, 0x3910, 0xc094, 0x3cb1, 0x38f8, 0xbe18, 0xc2b8, 0x37d6, 0xb3de,
0xab85, 0x3b2e, 0xb8f6, 0x299c, 0x3676, 0xbdb1, 0xb87d, 0x3f26, 0x3068, 0xc117, 0xb7ae, 0x3a16, 0x30ea, 0x3b44, 0xb347, 0x30a9,
0x31a2, 0x39c3, 0x36bf, 0x3021, 0x38f6, 0xbc13, 0xb882, 0x338d, 0xb892, 0x3bf4, 0x385d, 0xba38, 0x3b4e, 0x305d, 0x43aa, 0x387b,
0x36a4, 0xb0c4, 0xb800, 0xb925, 0xb9d7, 0xbdef, 0xbba6, 0x4244, 0x36da, 0x3452, 0x3b75, 0xc191, 0x381f, 0x318b, 0x38a3, 0x405a,
0xba2a, 0x3d74, 0xb9b5, 0x3666, 0x3990, 0x3802, 0xb8ed, 0x37cc, 0x3697, 0x36e9, 0x3d43, 0xb3ef, 0xbaa8, 0x3cbf, 0xbdf3, 0xadc4,
0x2c73, 0xb0b6, 0xbbd5, 0x386a, 0xbaaf, 0xbece, 0x35f2, 0x3d58, 0x358e, 0x3ca3, 0xb987, 0x3d37, 0x3770, 0x3cba, 0x3d8a, 0x400f,
0x37a5, 0x3910, 0x3bce, 0x3148, 0xb10b, 0xb1f2, 0x343f, 0x3a6d, 0x399b, 0xb733, 0x38b6, 0x3550, 0xbe87, 0xb90a, 0xc1ea, 0xbe4b,
0xbe96, 0xbe8f, 0x3999, 0xb92a, 0x3a77, 0xb1c8, 0x366c, 0x3508, 0xb7aa, 0xbcc4, 0xb03d, 0xb591, 0xbecf, 0xb9fc, 0xbb2f, 0x40f5,
0x4073, 0xc0db, 0x421c, 0xbf44, 0x339f, 0x34cd, 0x37bd, 0xb4dc, 0xb531, 0xb44c, 0x3e9d, 0x3b38, 0xba12, 0xa9ff, 0x3655, 0xb9ce,
0xb32e, 0x3441, 0x3f6f, 0x3c08, 0x3a43, 0xb860, 0xbcf7, 0x3dfe, 0xc07a, 0xbc86, 0x3745, 0xbbf6, 0x2987, 0x36a6, 0x35e0, 0x267f,
0xb4b8, 0xb9f1, 0xb865, 0x3a39, 0x2f53, 0xbd26, 0x37b5, 0x388c, 0x3b0e, 0xb889, 0x3c18, 0xa422, 0xb894, 0x1666, 0xb37f, 0xaf72,
0x3772, 0xb081, 0xc090, 0xb0ea, 0x33ad, 0x41d0, 0xb75b, 0x345f, 0x3de3, 0xba82, 0xafd1, 0xb979, 0x3f52, 0x36ec, 0xb928, 0x42c7,
0xbc71, 0xb54e, 0x3b45, 0x356d, 0xb63d, 0x3d77, 0xa722, 0x2873, 0x3ab5, 0xac22, 0xbe38, 0x3ccb, 0xb82f, 0xba9d, 0xb88a, 0x34f9,
0x3dde, 0xb997, 0xc1b1, 0x399d, 0x3d55, 0xc19a, 0xb380, 0x3e72, 0xb701, 0xbd0a, 0xc16c, 0xba7f, 0x39a8, 0x3df0, 0xbf04, 0xb595,
0xba46, 0xb904, 0x3ab7, 0x35c9, 0xb181, 0xb9da, 0xba29, 0x3a40, 0xbee1, 0xb257, 0xc262, 0xbabb, 0x3d35, 0x39fa, 0x2661, 0x3922,
0xb5da, 0x3c35, 0xac1e, 0xbc02, 0xb9c2, 0x375b, 0x343c, 0xb5e8, 0xbc03, 0xbd4a, 0x2c70, 0x3840, 0xb98c, 0x3a48, 0xbd06, 0xb987,
0xc008, 0x3a3f, 0x3676, 0xadf0, 0x391e, 0x437f, 0x4179, 0x38df, 0x3a92, 0x3dd2, 0xb42f, 0xb870, 0x3e99, 0xb0b3, 0x3136, 0x3c3b,
0xb98b, 0x3b57, 0xaf33, 0x3d80, 0xb578, 0x3475, 0x3f58, 0xb620, 0x3a60, 0x386c, 0xaf9c, 0xbc68, 0x3826, 0xb99a, 0xb8c8, 0xb414,
0xb952, 0x374b, 0x40e7, 0xba0c, 0x3a49, 0x4072, 0xb76d, 0xbc2a, 0xbc67, 0xaebb, 0x3a0b, 0xba0d, 0x3f56, 0x3e43, 0x3d02, 0xbc43,
0xb9a2, 0x3e82, 0x3a1f, 0xb796, 0x355d, 0xbc5c, 0x3a70, 0xba8a, 0x333c, 0xbd61, 0x3caf, 0xb9c7, 0xbd93, 0x31f0, 0xbd05, 0xbce5,
0xb4b9, 0xba81, 0xbc7d, 0xbbf2, 0x3740, 0xb976, 0xb53f, 0xbe7b, 0xbced, 0xb266, 0x30be, 0x3bda, 0x3f03, 0xbab0, 0x3bdf, 0xbfc7,
0xadc6, 0xbf88, 0xb00b, 0x2c42, 0x3e4d, 0xc2c9, 0xbe94, 0x4114, 0x3b5a, 0xbcba, 0x3d7c, 0xbd31, 0x3726, 0x37ac, 0x397e, 0x3a3a,
0x2f06, 0xbcd0, 0x3d0c, 0x3cb9, 0x35a6, 0x3f37, 0x41f6, 0xb161, 0xba84, 0x3e57, 0xb423, 0x3e1e, 0x3eb8, 0x2e08, 0xb1c0, 0xbc7f,
0x3bef, 0xc03a, 0xbcc4, 0xbb16, 0x38a5, 0x3c4a, 0x3b7f, 0x3bf8, 0x39c9, 0x2964, 0xbddc, 0xb944, 0x406a, 0x3717, 0xb80f, 0xaef2,
0x38c2, 0xbf14, 0x3633, 0x37eb, 0x2c27, 0x3d19, 0xba23, 0x37d2, 0x31dd, 0x3823, 0xbb12, 0x39a3, 0xb985, 0xb57c, 0xb7fa, 0x36a5,
0xb882, 0x3b5b, 0x3856, 0x34c0, 0x3a69, 0xb60d, 0xc03c, 0x3b6e, 0x3b95, 0x219c, 0xac3a, 0xbdd6, 0x4008, 0x356f, 0xae4c, 0x33cb,
0xbd84, 0x3c41, 0x3ba0, 0x3b3c, 0xbb56, 0x387e, 0x3b22, 0xba14, 0x33cb, 0x3f8d, 0x3508, 0x18e0, 0x3b2d, 0xa89e, 0x3c83, 0x3c7f,
0x3cd9, 0xb82a, 0x39b5, 0x3912, 0x39d4, 0xbb1c, 0xb8ed, 0xb1de, 0x3b0b, 0xbb92, 0x3be0, 0x4178, 0x3716, 0x31e8, 0xb3ff, 0xbc80,
0xba07, 0x393e, 0x39a9, 0xba87, 0xbb2d, 0x4185, 0xb616, 0x32fd, 0xb9d6, 0xbbe7, 0x3645, 0x3cee, 0xb4c6, 0xbcba, 0x3e24, 0xac74,
0x2b37, 0xb9ba, 0x3c42, 0x3142, 0x3505, 0x33e9, 0xbe07, 0xb53e, 0xb609, 0x3b1d, 0xbd2b, 0x36e4, 0x3c8a, 0x36fb, 0x39e9, 0xb8c3,
0x3fba, 0x4295, 0x3766, 0xbf1a, 0x39e3, 0x3ca3, 0x3fc7, 0xb434, 0xb899, 0xbb95, 0x398e, 0xb2e3, 0xbcd6, 0xb5c8, 0x38c5, 0xb442,
0x3cf2, 0x407d, 0xb6e2, 0xb847, 0x3a6a, 0xbdcd, 0x34b0, 0xb342, 0x3a83, 0x2d94, 0x3e96, 0xb644, 0xbead, 0x3e5d, 0xb0bb, 0x39cd,
0xa92f, 0xba58, 0x3c0b, 0xbdf9, 0x39ad, 0xa459, 0x3e21, 0xbd5c, 0x3d83, 0x41c8, 0x3299, 0xbeb7, 0xb260, 0xbc3a, 0xb6c7, 0xb98c,
0x321a, 0x3d96, 0x3834, 0x3a6f, 0x3920, 0x3d35, 0x28a0, 0xbe28, 0xbe36, 0xb9db, 0xb7d3, 0xbbba, 0xbbd1, 0x357f, 0xbd91, 0xc114,
0xb5fd, 0xae9b, 0xc078, 0xb85b, 0xc123, 0xb4c3, 0x38b3, 0xb796, 0xbb1b, 0x3ab8, 0x33b3, 0x37e5, 0x1a62, 0x3a31, 0xb4f1, 0x3a67,
0xbbce, 0x3e7b, 0xb73c, 0xbc7c, 0x408e, 0x4098, 0xbe64, 0x342b, 0x3da6, 0x39c7, 0x4077, 0x1dea, 0xaf4e, 0x3c46, 0x3ebd, 0xbbe8,
0x3936, 0x3cd8, 0x402f, 0x3e99, 0x3c05, 0xb2d2, 0xbc89, 0xb1eb, 0x2dfa, 0x3d84, 0xbed9, 0xbb80, 0x38a5, 0xbb72, 0xbc2c, 0xb173,
0xb84d, 0xb35d, 0xb0ff, 0x3e9f, 0xbc79, 0x3b57, 0xbb5b, 0x307d, 0xb498, 0x3703, 0xbe4a, 0x38be, 0xb878, 0xab2e, 0x3b46, 0xbacc,
0x3ab4, 0x32d8, 0xc20b, 0x365b, 0x35ac, 0x36ed, 0x40e5, 0x2d1b, 0xb594, 0xb0f7, 0xba7a, 0xbe4c, 0xa99c, 0xb070, 0xb21f, 0x2dca,
0xbf8a, 0x3fd8, 0xb83e, 0x391b, 0xbc35, 0x330f, 0x34e7, 0xb698, 0xb482, 0x34c1, 0x36cd, 0xb818, 0x3e69, 0xb449, 0x3646, 0x31ab,
0x38c2, 0x341e, 0x3925, 0xb987, 0x38e5, 0x41b9, 0xb79d, 0xb1ac, 0x36c6, 0x38f9, 0xc103, 0xa977, 0xbead, 0xbce0, 0xbc63, 0xb897,
0x3f5d, 0xb842, 0x3d63, 0x3875, 0xab3a, 0xad0b, 0x25c0, 0xbcd6, 0x38d6, 0xb851, 0xb9a9, 0xc077, 0x3be3, 0xb4a1, 0xc293, 0x39c4,
0x32dc, 0x414b, 0x3ada, 0x38cc, 0xbad6, 0x3b60, 0x3a85, 0xb52e, 0x3d6c, 0x3d6d, 0xb5a4, 0xb855, 0x2ccf, 0x27f6, 0x35b1, 0xbcf6,
0x34df, 0xb4a0, 0xbe85, 0xb62a, 0x39d4, 0xad0d, 0xb542, 0xab88, 0x35dd, 0x345a, 0x353b, 0x3951, 0xb8f8, 0x2f10, 0xbaae, 0x363f,
0x3878, 0x3ca2, 0x35df, 0x38da, 0xb443, 0xbcfd, 0xb87e, 0x2fdb, 0xbc75, 0x36ab, 0x389a, 0x3243, 0x29dc, 0xba70, 0x2ee6, 0x3250,
0xb748, 0x3d29, 0x40a9, 0xbe21, 0xbba6, 0xb60d, 0xbbbc, 0x3c40, 0xb5dd, 0xbb7b, 0x2631, 0x3bf3, 0xbfbb, 0x2ad5, 0x35b7, 0xb417,
0xafde, 0x3831, 0xb651, 0x3145, 0x3cfa, 0xb23f, 0x39ff, 0xb56f, 0xbd12, 0x3f03, 0x33d8, 0x3623, 0x3401, 0x3e04, 0xbe9f, 0x3f6b,
0x30db, 0xa9d7, 0x31d9, 0xb34d, 0x9f5e, 0x3252, 0xc0f6, 0x3c75, 0x348d, 0xb8ec, 0x38d0, 0x3841, 0x3abf, 0x20a8, 0xc090, 0x2b97,
0xbf35, 0xac01, 0xb854, 0x3722, 0xc074, 0x344d, 0x3a91, 0x3972, 0xbe82, 0x39b9, 0xb62c, 0xc02a, 0xbb3a, 0xba61, 0x2fcb, 0x3a29,
0xba51, 0xbb4e, 0xb604, 0x3d17, 0x363e, 0x3b16, 0x3c14, 0x3ab9, 0xb80d, 0x3a9c, 0xb0df, 0x3936, 0xb50c, 0xb8ca, 0xbd85, 0x35f3,
0x2ffc, 0xb02b, 0xc0b9, 0x38fe, 0x390d, 0xba48, 0x408f, 0xbc03, 0xb937, 0x3646, 0xc22b, 0xc0c1, 0xbab4, 0xbad0, 0xb3f6, 0x99a8,
0xbc8c, 0xbf40, 0x2074, 0xbc80, 0xb927, 0xb89b, 0x33be, 0xa9e5, 0x417f, 0x3229, 0xb346, 0x353c, 0x395d, 0xb883, 0x3d69, 0xbadd,
0x3c6c, 0xa743, 0xbd97, 0x3466, 0xbf85, 0x3977, 0x3618, 0x3976, 0x3e77, 0xb9f8, 0xbe06, 0xc024, 0xbc84, 0x325a, 0xbb6c, 0x3d18,
0xb930, 0xbca2, 0xb806, 0xbfb2, 0x3578, 0xb253, 0xb48c, 0x33f1, 0xb9ac, 0xbb21, 0xb012, 0x374a, 0xb0cc, 0x3c0b, 0xaca9, 0x3dc8,
0xb4d9, 0x322c, 0xab2c, 0xb993, 0x3aa6, 0x3a91, 0x42a1, 0x3da6, 0x3151, 0x3e59, 0x3751, 0x2d8e, 0x3365, 0x2d9a, 0xbaaa, 0xb77f,
0xb7f0, 0x32ee, 0x3dd2, 0xbb78, 0x3d0e, 0xbe1c, 0xbe19, 0xbd05, 0xbcfe, 0xbebd, 0xbba1, 0x36b0, 0x3962, 0x4006, 0x380e, 0x370d,
0x3e08, 0x3b9c, 0x2bfe, 0xb2a8, 0x3dd4, 0xc038, 0xc00f, 0xb32c, 0x33b5, 0x39f3, 0x3691, 0xb893, 0xbb79, 0xac1f, 0x3d09, 0xbd82,
0xafcd, 0xb867, 0xc01c, 0xbbb5, 0xbbca, 0xb323, 0xb8d8, 0x3d5d, 0xbbda, 0x2db4, 0xb8ca, 0x38f9, 0xb615, 0x3a87, 0x321c, 0xc099,
0x3a26, 0x3f8c, 0x30a7, 0x36f1, 0x386f, 0xc2a5, 0xb485, 0xb157, 0xb4d2, 0x3f94, 0x2056, 0xb1bb, 0xbb33, 0x35db, 0x35b5, 0xba51,
0xbe3f, 0x845e, 0xb7cd, 0xbd67, 0x2dae, 0xb670, 0x399d, 0xc11f, 0x2c99, 0x378e, 0xb735, 0xbe92, 0x4021, 0x3c61, 0xba18, 0x34c2,
0xb993, 0xb927, 0xb98a, 0xb82a, 0xba9d, 0xbf68, 0xb507, 0xb7f9, 0x40e7, 0xb718, 0x1e42, 0x3cd3, 0x2b48, 0x3a82, 0x3ef1, 0xbf98,
0xb0ad, 0x3a56, 0x34a6, 0xbc12, 0x3fe4, 0x31d6, 0x3d63, 0xa315, 0x22f5, 0xb81a, 0x3b45, 0x32d7, 0x3e26, 0x3689, 0x3d81, 0xbc0c,
0x3d04, 0xbcd3, 0x36b2, 0xb5c8, 0x37bb, 0xb86b, 0xb658, 0x3c81, 0xb81b, 0xba20, 0x356a, 0xadad, 0xbe5d, 0x3048, 0xb9d4, 0x301d,
0xadb0, 0x3d2d, 0xaa8b, 0xb415, 0xb4b2, 0x413f, 0x3c3c, 0xb516, 0xaff4, 0x3572, 0xb682, 0xbbf6, 0xbbce, 0x3bd3, 0x3a19, 0x3d0a,
0x3729, 0x3592, 0xbc5f, 0x3a21, 0x3c5b, 0xb667, 0x3c4b, 0x38c7, 0x3180, 0xaecd, 0xbd82, 0xb9d9, 0xac5a, 0x36d1, 0xc22c, 0x2c34,
0xbcae, 0xb450, 0x3f37, 0x388f, 0xb698, 0xb5fd, 0x23d2, 0x3b4a, 0xb721, 0xae67, 0x3cbc, 0xab02, 0x39d8, 0xbd73, 0x98eb, 0xbaf1,
0x3ad1, 0x381e, 0xb864, 0xbc12, 0xc0e9, 0xc084, 0x3831, 0x3971, 0x3ca9, 0xb2fa, 0xa167, 0x3708, 0x405f, 0xb9ca, 0x3ca1, 0x31ad,
0x383f, 0x339d, 0x389a, 0x364f, 0xb77d, 0x3db4, 0xb56a, 0xb2bc, 0xba8f, 0xb4dd, 0xbf46, 0x32b6, 0x381e, 0xb90a, 0x3db5, 0xbf8a,
0xbc4e, 0x37b4, 0xbc0e, 0xad30, 0x3c84, 0x3d83, 0x3a52, 0x3a04, 0xbc64, 0x4027, 0x3c18, 0x3e6d, 0xbcce, 0xaf48, 0xb052, 0x325c,
0xb876, 0xbf1d, 0xbafa, 0xaf28, 0x3a5b, 0x3498, 0xaab7, 0xbc54, 0x3fdb, 0x3d7e, 0x39e0, 0xbf20, 0xbfc8, 0xaddc, 0xb815, 0xb83b,
0xb793, 0x3798, 0x3915, 0xb6c5, 0xbc75, 0x395b, 0x358f, 0xb960, 0xbc4a, 0xbced, 0xbb4c, 0x34c2, 0x3cfd, 0x2022, 0x2cce, 0x30cf,
0xb632, 0xbc4d, 0x3a35, 0x3308, 0x2f07, 0x38d2, 0xbc58, 0x3c45, 0xbae1, 0xb9ad, 0xbb37, 0x3910, 0xbf4b, 0xb91e, 0x374d, 0xb27e,
0xb59a, 0x367b, 0x3af6, 0x39fb, 0xbb7c, 0x3a2a, 0xbf2d, 0x2d37, 0xb489, 0x3803, 0x3fc6, 0xbdc6, 0x381d, 0x3fe4, 0x33f7, 0xb508,
0x4023, 0xbeb9, 0x3d4c, 0xb0c6, 0xb9aa, 0x38c5, 0xb65d, 0x360a, 0xbd31, 0x3ad7, 0x3f3e, 0x39bf, 0xbc24, 0xb920, 0x3774, 0xb7a3,
0xafd2, 0xbcb9, 0xb627, 0x387a, 0xb7cc, 0x38cb, 0xaf26, 0xb37e, 0xb2c5, 0xbad1, 0xb881, 0xb982, 0xbe79, 0xbf5f, 0xb58c, 0x3cb6,
0xb76a, 0xc084, 0x3888, 0x305f, 0x4386, 0xbb1c, 0x318f, 0x2990, 0xbc45, 0xb415, 0xbd45, 0x3b9a, 0x400b, 0xb6c7, 0x40d8, 0x3f49,
0x3b3e, 0x3953, 0x4121, 0x41a5, 0x3e15, 0x3a86, 0xb745, 0xb50c, 0x394d, 0xbc62, 0x3ce8, 0x36fd, 0xb3fe, 0xb7d3, 0x320d, 0x3663,
0x38fd, 0x39e8, 0xb2dd, 0x38c0, 0x3992, 0xb516, 0xb019, 0xbc1f, 0x35e3, 0xa8c6, 0x3fda, 0x3975, 0x3dba, 0xc0dd, 0x166a, 0x3863,
0xa3cd, 0x3ab2, 0x332f, 0xbcb9, 0xbce3, 0xb88e, 0xbd5e, 0x41f6, 0xba72, 0xbd0a, 0xbac9, 0xc170, 0xbc26, 0xb615, 0xbab0, 0xbca7,
0xc082, 0xbb6c, 0x3f5b, 0x415e, 0x3be8, 0xbe9b, 0x3c55, 0x3f32, 0xa521, 0x410a, 0xbf27, 0xbe1e, 0xbca8, 0x39df, 0xb924, 0xbbf5,
0xb2aa, 0x39c7, 0x3af7, 0x424b, 0xb4c6, 0xaed0, 0x358e, 0x3532, 0x3116, 0x3924, 0xbee5, 0xc199, 0xba6e, 0x3849, 0x3c77, 0xb920,
0x3c82, 0xb481, 0x33de, 0x3c4e, 0xba98, 0x3775, 0xb594, 0x96a7, 0xbd85, 0x4000, 0x2fd0, 0x3fd8, 0x3d71, 0x3bb7, 0x3dc5, 0x3808,
0xbc1c, 0x34a8, 0x3d3d, 0xb86c, 0x3bf1, 0x3841, 0x399c, 0xb9d3, 0xbcee, 0xb752, 0x3ab9, 0xb00a, 0xb744, 0x3198, 0x2fcd, 0x398f,
0x9a32, 0x3d75, 0x360a, 0x3bbc, 0x37e9, 0xbb59, 0xb969, 0xb330, 0xc0a5, 0x3ae6, 0x3e0c, 0x40b0, 0xbcda, 0x343c, 0x34bc, 0xb86c,
0x3cb0, 0x35be, 0xbd82, 0xac1b, 0xbb08, 0xa5a7, 0x34bf, 0xb0f5, 0x3087, 0xb485, 0xa123, 0xbb9c, 0x3df9, 0xb45d, 0x3c17, 0x404c,
0x347a, 0x39a3, 0xb6e8, 0xb913, 0xbd20, 0x38ce, 0xc006, 0x40b0, 0x402a, 0xbb4d, 0x3e7d, 0x3e49, 0x3b8b, 0xb6c8, 0x2d82, 0x3b90,
0x388d, 0xae29, 0x327b, 0x3ad7, 0x3d10, 0xb984, 0x3933, 0x34cc, 0x3002, 0xbbda, 0xbcf3, 0x3819, 0x2c89, 0xbc31, 0x3dbd, 0x38e8,
0xb4e4, 0xbb87, 0xb172, 0x3886, 0x39b9, 0xb829, 0xbd54, 0xb345, 0xb951, 0xba7f, 0x3d9f, 0x36c1, 0xb259, 0x3dd3, 0x3a49, 0x36a4,
0x3b65, 0x3cf2, 0xacae, 0xbe2c, 0xbdae, 0x3ba3, 0x356a, 0x3603, 0x3d0e, 0x3370, 0xb96b, 0x2d88, 0xb8d3, 0x36e3, 0xb804, 0x3b24,
0xc000, 0xbdd0, 0xc006, 0xb8c7, 0x3dc9, 0x3367, 0xb663, 0x344b, 0x3406, 0x341f, 0xac64, 0xc0cf, 0x34c6, 0x3d02, 0x3676, 0x39f8,
0xa4b0, 0x2e04, 0xb4ee, 0x3b5f, 0xbb6d, 0x37d4, 0xb0cc, 0xb491, 0xb1aa, 0xacc8, 0xbea5, 0x3c6c, 0xb99e, 0xbc46, 0xbe17, 0x3b6c,
0xbd5d, 0xbf93, 0xb462, 0x38fa, 0xc0e4, 0x331f, 0x3419, 0x3164, 0xbb25, 0x4066, 0xbd61, 0xbe28, 0x3891, 0xbc66, 0x32be, 0xbc0c,
0x3055, 0x3dee, 0x20f7, 0xb3ab, 0x31ff, 0x3a50, 0xbe6a, 0xbad6, 0xbb8f, 0x3cb5, 0xbe0a, 0x3e97, 0x3110, 0xbc8b, 0x36cb, 0x3c1b,
0xbb83, 0xbe5f, 0xaecd, 0x310b, 0xb4b8, 0x2985, 0x3c4a, 0xb9d9, 0x39c5, 0xbc1d, 0x390b, 0x3d9e, 0x3675, 0xbca4, 0x3ce1, 0xb49c,
0xbb08, 0x3fff, 0x3927, 0x35e3, 0xbd50, 0xbc60, 0x39b6, 0xbd13, 0x4123, 0xc2a2, 0xbeab, 0x37d9, 0xb8ed, 0x3425, 0xbace, 0x3a36,
0xb0c7, 0x4057, 0x3c69, 0x3e0c, 0xb5b0, 0x3a03, 0xba05, 0xbaa0, 0x19c4, 0x9c4c, 0xb72f, 0x3c37, 0x3467, 0xbd02, 0xb522, 0xb537,
0x3673, 0x2c4d, 0xb17b, 0xbdef, 0xb95a, 0x3daa, 0xbbe8, 0xb4e3, 0x3034, 0xbb3a, 0xc116, 0xbd9c, 0x3891, 0xc1d5, 0xbd9f, 0xb874,
0xbc4b, 0x357f, 0xb09a, 0x3f79, 0x3f0c, 0xc07e, 0xbbfe, 0xbca2, 0xbb50, 0x2af5, 0xb02f, 0xbaf7, 0xb629, 0xb509, 0x39c8, 0x36fc,
0xa825, 0x395c, 0xb901, 0x3553, 0xbd9d, 0xbbeb, 0x39f2, 0xb451, 0x37bc, 0x3f3c, 0x35a3, 0x3866, 0x3046, 0x35fb, 0x3999, 0xbcb3,
0xa417, 0x3d1d, 0xbc37, 0x3bec, 0x3c7c, 0x3bfa, 0xbcb8, 0xc1d5, 0x3c1a, 0x3c40, 0xb23c, 0xb73b, 0x3546, 0x3a09, 0xbbf5, 0xbb7f,
0x30e8, 0xbe3f, 0x39fe, 0x3a8b, 0x341a, 0x9b02, 0xbc35, 0x2b91, 0x4256, 0x3a51, 0x3fd1, 0xba43, 0xb55c, 0x393a, 0x3c6f, 0xae6a,
0x3da8, 0xb266, 0xbd17, 0xba78, 0x35cf, 0x3e3a, 0xb5dd, 0x3e4d, 0x345d, 0x32ff, 0xbca2, 0x35a2, 0xb9f1, 0x3c82, 0xbbc5, 0x38f1,
0x3f36, 0xbe7b, 0xbe77, 0xb44a, 0xbd3b, 0x3501, 0x344c, 0xbe42, 0xbc81, 0x3dc3, 0x2613, 0xbf15, 0xbb1c, 0x3c71, 0x345f, 0xba6a,
0xb944, 0x3c03, 0xb5ea, 0xbae1, 0xab67, 0x3e77, 0xc04f, 0xb9db, 0xbe0c, 0xb86e, 0xbc4f, 0xb9cd, 0x3ca8, 0xb07a, 0x36be, 0xb41f,
0xac27, 0x3256, 0x3870, 0xb327, 0xb5f6, 0x3b9d, 0x30ba, 0xb8de, 0x3c1b, 0xb06a, 0x3ae1, 0x3d54, 0xba28, 0x3d08, 0x38a3, 0xb938,
0x3472, 0xb96b, 0x3945, 0x3b80, 0xadbe, 0x3ab1, 0x3ccf, 0x39b5, 0x34a8, 0x3836, 0xb49e, 0x308c, 0x3916, 0xb5ba, 0xbb8a, 0x3b1b,
0xbc56, 0xbe6f, 0xbd9e, 0xb4d5, 0x3e83, 0xa343, 0x3adc, 0xb2fc, 0xba2f, 0x3b55, 0x3cec, 0xb624, 0x261f, 0x37d7, 0xbf76, 0x3eb1,
0x38b1, 0xb9c8, 0xa60d, 0x361c, 0xbca6, 0xc00c, 0xbb55, 0xbc6b, 0x34c5, 0x38ba, 0xb802, 0x383c, 0xbd59, 0x3e68, 0x3a2e, 0xbbad,
0x3c74, 0x3b24, 0x3010, 0x3ebf, 0xb953, 0xbfa8, 0xb16b, 0x3b7c, 0x3952, 0x2c82, 0xb8ef, 0x412c, 0xb7ec, 0x3cdb, 0x3bc9, 0x38e0,
0xbbfb, 0xbaa3, 0x3f28, 0xb1df, 0x3a77, 0xbccf, 0xb1a5, 0xb933, 0x3018, 0x37cb, 0xbec0, 0x31bc, 0xbd2e, 0x3997, 0x3930, 0x3906,
0xb86f, 0x37fd, 0x323d, 0x33e5, 0xa60a, 0x38d7, 0xb30a, 0xb451, 0x3597, 0x3123, 0xc063, 0xbe8a, 0xbe42, 0x37af, 0xaff0, 0x3b21,
0x365f, 0xb277, 0xb5b8, 0x2ad2, 0xc11d, 0x3a45, 0x31fd, 0xb500, 0xbf3f, 0xbc72, 0x3038, 0x24a3, 0x2890, 0xb595, 0xc08f, 0xc1c7,
0xb86e, 0xbcaa, 0x3189, 0x38a6, 0xb408, 0x325d, 0x2ca7, 0x3b05, 0x3c55, 0xbf35, 0x387c, 0x3b7e, 0x3c20, 0x3a0b, 0x3741, 0x3db8,
0x3a12, 0x3c4d, 0xb87c, 0x3d11, 0xbdc9, 0xbed7, 0x2444, 0xbdbb, 0xb9c6, 0x3cc9, 0xae72, 0xba10, 0x38b7, 0x3953, 0xb1e6, 0xbbe2,
0xa918, 0x30b1, 0xbc8f, 0x283d, 0xaeb3, 0xb160, 0x3794, 0x3336, 0x3327, 0x401d, 0xbf99, 0x3d15, 0xad02, 0x3a32, 0x3df6, 0x3c57,
0xbef4, 0x34ed, 0xbc1f, 0x368c, 0x3aed, 0xb95b, 0x38dd, 0x3bf3, 0x4185, 0x3c2f, 0xbbfc, 0x37b5, 0x37f3, 0x355e, 0x3559, 0x3c46,
0xc003, 0x38bc, 0x3b53, 0xbda0, 0xac8d, 0x2acb, 0xb8ac, 0x396c, 0x2be0, 0xbb1f, 0x3ce8, 0x3b90, 0xae9f, 0x3ef8, 0xb33e, 0x3cf4,
0x2c97, 0xb898, 0xbaa5, 0x3f56, 0x3e58, 0xbb16, 0xb33c, 0xc004, 0x400e, 0xbc68, 0x38bd, 0xa939, 0x3a55, 0x3b35, 0x40d6, 0x3db5,
0x4176, 0xb869, 0x30ba, 0xbd7f, 0xba99, 0xb379, 0x3ecf, 0xb915, 0xb19f, 0x30f2, 0x3e11, 0xb632, 0xbe94, 0x3be5, 0x3d28, 0xac5d,
0xb6e7, 0xbb64, 0xb282, 0x4380, 0xbde1, 0x36b5, 0x36c2, 0x3867, 0x3cca, 0x2e1c, 0x31cc, 0x2e2f, 0xb0d4, 0xbcff, 0xbb1c, 0xbd67,
0x309a, 0x3d2c, 0xab7d, 0xbd03, 0xbbe1, 0xbefc, 0xbfbe, 0x3b98, 0xb53c, 0xbc72, 0x2f15, 0x3cca, 0xc106, 0xbc36, 0xb702, 0x3b57,
0x391a, 0xb4da, 0x3861, 0x3afe, 0x3ea8, 0x335b, 0x34e4, 0xbd62, 0x3f1f, 0xbc86, 0xbcf4, 0x35bc, 0xb34a, 0xbf53, 0x3834, 0xbd10,
0x273d, 0x39a1, 0xb839, 0xb4e4, 0x39b8, 0x34da, 0xbed6, 0x3a76, 0x3c50, 0xc0fa, 0xbd35, 0xb061, 0xb1b6, 0x34f0, 0x3ab1, 0xbc18,
0xb91d, 0xb62c, 0xbb36, 0xb829, 0xb940, 0xafab, 0x3d46, 0x3e81, 0xb20b, 0xb822, 0xbe39, 0x35fd, 0x32f1, 0x3966, 0x2e17, 0xb543,
0xbbed, 0x3a89, 0xb2a3, 0xbcc5, 0x3369, 0xb42b, 0xbbd4, 0x1f58, 0xbc48, 0x3ef4, 0x3bbe, 0xac2b, 0xbdf5, 0xb2e4, 0xbcae, 0x3f94,
0xa11a, 0xc068, 0x35bb, 0xb82e, 0x3f77, 0xbbb9, 0xb386, 0x3b46, 0xb675, 0x22f3, 0x3e8b, 0xbcb2, 0xb8ba, 0xba29, 0x4235, 0xbd08,
0x1038, 0x3f9f, 0xade8, 0x399f, 0x3363, 0xb9da, 0x3909, 0x37c8, 0x3c82, 0xbc4c, 0xbc3a, 0xb788, 0xa897, 0x39da, 0xb6d2, 0x3bee,
};
@@ -0,0 +1,6 @@
// ggml-common.h - the old name of Strata's quant format header, kept as a forwarder so every `#include "ggml-common.h"` keeps working.
//
// The header is include/strata/quant/strata-quant-common.h, generated by tools/gen_quant_header.py from Strata's own type and codebook tables
// (tools/strata_quants.py, tools/strata_quant_tables.py). New code includes that file. The Metal runtime reads the header's TEXT (it cannot
// follow an #include), and the Mac package ships it as metal/strata-quant-common.h plus a full-text copy under this old name.
#include "../../include/strata/quant/strata-quant-common.h"
+44
View File
@@ -167,3 +167,47 @@ name = "candle"
# Resolution ceiling per side; oversized requests are rejected before
# admission. Dimensions must be multiples of 16.
#max_dim = 2048
# Music generation layout (#385). Applies to ACE-Step pipelines. These
# describe this host's card, not the model, so the same model id can
# serve bf16 on a 24 GB card and q8 on an 8 GB one. All fields optional.
#[harness.candle.audio]
# In-situ q8_0 quantization of the DiT, text encoder and planner linear
# layers; quantized pipelines compute in f32. About 4.6 GB resident
# against 6.4 GB for bf16, with no planner loaded.
#quant = "q8_0"
# "f32" computes unquantized GPU components in f32 (cards without fast
# bf16). Dense f32 needs about 13 GB resident; on small cards use quant.
#compute = "bf16"
# Which planner LM to load: a snapshot subfolder, a repo id of its own
# ("ACE-Step/acestep-5Hz-lm-0.6B" for an 8 GB card), or "none".
#planner = "acestep-5Hz-lm-1.7B"
# Shorter songs than the model allows, for a card that runs out first.
#max_duration_secs = 240
# Treat the device as having this much memory for the pipeline (MiB);
# under a budget the VAE decodes in smaller chunks.
#vram_budget_mb = 8192
# Hold the rest of the card's free memory so a large card behaves like
# one of the budget's size. For rehearsing a small card; never in serving.
#enforce_vram_budget = false
# A copy of each music model on several cards, for a rig of identical
# cards: "per-device" (every card) or a list of device indices. Each copy
# renders one song at a time; cortex sees one model whose capacity is the
# number of copies. A model's own `replicas` in [[default_models]] wins.
#replicas = "per-device"
# Where each component runs: "gpu" (default) or "cpu".
#[harness.candle.audio.placement]
#text_encoder = "gpu"
#planner = "gpu"
#dit = "gpu"
#vae = "gpu"
# When this host is powered, for hosts that leave the mesh on a schedule
# (solar). /health announces the next dark window; cortex stops sending
# new work at its drain time and treats the absence as planned.
#[availability]
# UTC windows; one may wrap past midnight ("22:00-06:00").
#online = ["06:30-18:45"]
# Stop taking new work this long before each dark window (seconds). Make
# it longer than this host's longest job.
#drain_secs = 900