Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 13:02:42 +02:00
52 changed files with 8425 additions and 126 deletions
+10
View File
@@ -21,6 +21,16 @@ name = "neuron-strata-expert-probe"
path = "src/bin/strata_expert_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-engine-layer-probe"
path = "src/bin/engine_layer_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-engine-step-probe"
path = "src/bin/engine_step_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-mtp-probe"
path = "src/bin/mtp_probe.rs"
+62 -27
View File
@@ -83,50 +83,85 @@ fn build_strata_kernels(build_dir: &std::path::Path) {
println!("cargo:rerun-if-changed=vendor/strata");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_shim.cu");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_probe.cu");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/engine_shim.cu");
println!("cargo:rerun-if-env-changed=CUDA_COMPUTE_CAP");
let cap = std::env::var("CUDA_COMPUTE_CAP").expect("strata-kernels needs CUDA_COMPUTE_CAP");
let root = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let vendor = root.join("vendor/strata/engine");
let sources = [
let mut sources = vec![
// UD-IQ4_XS has no NVFP4 experts, so upstream's stub satisfies
// the reference from the grouped dispatch.
(
"strata_nvfp4_absent.o",
"strata_nvfp4_absent.o".to_string(),
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",
"strata_shim.o".to_string(),
root.join("src/cuda/strata_adapter/strata_shim.cu"),
),
(
"strata_probe.o",
"strata_probe.o".to_string(),
root.join("src/cuda/strata_adapter/strata_probe.cu"),
),
(
"engine_shim.o".to_string(),
root.join("src/cuda/strata_adapter/engine_shim.cu"),
),
];
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);
// The experts, then the decode kernels the native engine (#427)
// drives: linear attention, hyper-connections, router, MoE combine,
// activation quantisation and the BF16 projections.
for kernel in [
"iq_kernels",
"native_gdn",
"native_gdn_preprocess",
"fused_gdn",
"native_gr_norm",
"native_gr_postops",
"gr",
"native_router",
"native_rope",
"native_moe",
"quantize_act",
"bf16_gemv",
"native_bf16",
] {
sources.push((
format!("strata_{kernel}.o"),
vendor.join(format!("src/kernels/cuda/{kernel}.cu")),
));
}
// Independent translation units: compile them side by side.
let objects: Vec<std::path::PathBuf> = std::thread::scope(|scope| {
let jobs: Vec<_> = sources
.iter()
.map(|(name, source)| {
let object = build_dir.join(name);
let (cap, vendor) = (&cap, &vendor);
scope.spawn(move || {
let status = Command::new("nvcc")
.args(["-O3", "-DNDEBUG", "-std=c++20"])
.arg(format!(
"--generate-code=arch=compute_{cap},code=[compute_{cap},sm_{cap}]"
))
.args(["-DSTRATA_Q6K_EXPERTS=1", "-DSTRATA_VERIFY_MAX_T=8"])
.arg(format!("-I{}", vendor.join("third_party/ggml").display()))
.arg(format!("-I{}", vendor.join("include").display()))
.args(["--compiler-options", "-fPIC", "-c"])
.arg(source)
.arg("-o")
.arg(&object)
.status()
.expect("run nvcc");
assert!(status.success(), "nvcc failed on {}", source.display());
object
})
})
.collect();
jobs.into_iter()
.map(|j| j.join().expect("nvcc thread"))
.collect()
});
let library = build_dir.join("libneuronstrata.a");
let _ = std::fs::remove_file(&library);
let status = Command::new("ar")
+420
View File
@@ -0,0 +1,420 @@
//! Checks a native engine layer (#427) against candle's own, on the real
//! checkpoint and GGUF.
//!
//! ```sh
//! neuron-engine-layer-probe GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [LAYER] [STEPS] [gdn|attn|moe]
//! ```
//!
//! `gdn` (default) runs the mixer half of linear-attention layer `LAYER`
//! (default 0); `moe` runs the MoE half of any layer, and needs
//! `NEURON_EXPERT_DEVICE_ROUTING=1` (it pins every expert in host memory);
//! `attn` runs the mixer half of full-attention layer `LAYER` (3, 7, ...),
//! the context growing by one each step.
//! Either runs for `STEPS` decode tokens (default 8), carrying state, through both paths
//! from the same input: each step's residual is a real token embedding
//! repeated over the streams. Candle runs in BF16 (as served; its conv
//! kernel takes nothing wider) with the same GGUF Q8_0
//! projections the engine reads, so what differs is the engine's own
//! arithmetic and its BF16 hyper-connection and gate weights. Prints, per
//! step, the relative error of the layer's contribution (`out - in`).
use std::path::Path;
use anyhow::{Context, Result, bail};
use candle_core::cuda_backend::cudarc::driver::DevicePtr;
use candle_core::{DType, Device, IndexOp, Storage, Tensor};
use candle_nn::var_builder::ShardedSafeTensors;
use neuron::harness::arch::qwen3_5::proj::LinearSource;
use neuron::harness::arch::qwen4_exp::config::Config;
use neuron::harness::arch::qwen4_exp::engine::gdn;
use neuron::harness::arch::qwen4_exp::engine::weights::Gguf;
use neuron::harness::arch::qwen4_exp::gguf_dense::{GgufDenseSource, Heads};
use neuron::harness::arch::qwen4_exp::hyper::HyperConnection;
use neuron::harness::arch::qwen4_exp::linear_attn;
fn address(t: &Tensor) -> Result<u64> {
let (storage, layout) = t.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
bail!("expected a CUDA tensor");
};
let slice = storage.as_cuda_slice::<f32>()?;
Ok(slice.device_ptr(slice.stream()).0 + (layout.start_offset() * 4) as u64)
}
fn rel(a: &[f32], b: &[f32]) -> f64 {
let (mut num, mut den) = (0f64, 0f64);
for (x, y) in a.iter().zip(b) {
num += f64::from(x - y).powi(2);
den += f64::from(*y).powi(2);
}
(num / den.max(1e-30)).sqrt()
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
bail!(
"usage: {} GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [LAYER] [STEPS]",
args[0]
);
}
let (gguf_path, hf) = (Path::new(&args[1]), Path::new(&args[2]));
let layer: usize = args.get(3).map_or(Ok(0), |v| v.parse())?;
let steps: usize = args.get(4).map_or(Ok(8), |v| v.parse())?;
let mode = args.get(5).map_or("gdn", String::as_str);
let device = Device::new_cuda(0)?;
let cuda = device.as_cuda_device()?.clone();
let cfg = Config::from_config_json(
&std::fs::read_to_string(hf.join("config.json")).context("read config.json")?,
)?;
let text = &cfg.text_config;
let shapes = gdn::shapes(text)?;
// ---- candle, in f32, with the GGUF's Q8_0 projections.
let mut paths: Vec<_> = std::fs::read_dir(hf)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|x| x == "safetensors"))
.collect();
paths.sort();
// SAFETY: the checkpoint is not modified while mapped.
let vb = unsafe { ShardedSafeTensors::var_builder(&paths, DType::BF16, &device)? };
let dense = GgufDenseSource::open(
gguf_path,
&device,
Heads {
key_heads: text.linear_num_key_heads,
value_heads: text.linear_num_value_heads,
head_dim: text.linear_value_head_dim,
},
text.linear_num_key_heads * text.linear_key_head_dim,
)?;
let source: Option<&dyn LinearSource> = Some(&dense);
let lvb = vb.pp(format!("model.language_model.layers.{layer}"));
if mode == "attn" {
let embed = vb
.pp("model.language_model.embed_tokens")
.get((text.vocab_size, text.hidden_size), "weight")?;
return run_attn(gguf_path, &device, text, &lvb, source, &embed, layer, steps);
}
if mode == "moe" {
let embed = vb
.pp("model.language_model.embed_tokens")
.get((text.vocab_size, text.hidden_size), "weight")?;
return run_moe(gguf_path, &device, text, &lvb, dense, &embed, layer, steps);
}
let hc = HyperConnection::load(
&lvb.pp("attn_hyper_connection"),
text.hidden_size,
text.hc_count,
text.hc_lowrank,
text.rms_norm_eps,
true,
source,
)?;
let mut net = linear_attn::load(text, &lvb.pp("linear_attn"), source)?;
let embed = vb
.pp("model.language_model.embed_tokens")
.get((text.vocab_size, text.hidden_size), "weight")?;
// ---- the engine.
gdn::configure();
let gguf = Gguf::open(gguf_path, &cuda)?;
let weights = gdn::GdnWeights::load(&gguf, layer, &shapes)?;
let mut state = gdn::GdnState::zeroed(&cuda, &shapes)?;
let mut scratch = gdn::GdnScratch::new(&cuda, &shapes)?;
let out = cuda.alloc_zeros::<f32>(shapes.hc * shapes.n_embd)?;
let stream = cuda.cuda_stream().cu_stream() as *mut std::ffi::c_void;
// A deliberate fault, to show the probe can see one: the engine's
// state is reset every step while candle's carries on.
let fault = std::env::var_os("PROBE_FAULT_RESET_STATE").is_some();
let mut worst = 0f64;
for step in 0..steps {
if fault {
state = gdn::GdnState::zeroed(&cuda, &shapes)?;
}
let token = (1000 + 7919 * step) % text.vocab_size;
let h = embed
.i(token)?
.reshape((1, 1, text.hidden_size))?
.repeat((1, 1, text.hc_count))?;
let h = h.contiguous()?;
let split = hc.split(&h)?;
let inject = split
.inject
.as_ref()
.context("a decoder hyper-connection injects")?;
let mixed = net.forward(&split.input)?;
let want = hc.combine(&split.residual, &mixed, inject)?;
let h32 = h.to_dtype(DType::F32)?.contiguous()?;
gdn::forward(
&weights,
&mut state,
&mut scratch,
&shapes,
address(&h32)?,
out.device_ptr(out.stream()).0,
stream,
)?;
cuda.cuda_stream().synchronize()?;
let input: Vec<f32> = h32.flatten_all()?.to_vec1()?;
let want: Vec<f32> = want.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
let got = cuda.clone_dtoh(&out)?;
let delta = |r: &[f32]| -> Vec<f32> { r.iter().zip(&input).map(|(a, b)| a - b).collect() };
let err = rel(&delta(&got), &delta(&want));
worst = worst.max(err);
println!(
"layer {layer} step {step} token {token}: contribution rel err {err:.3e}, |out-in| {:.3e}",
delta(&want)
.iter()
.map(|v| f64::from(*v).powi(2))
.sum::<f64>()
.sqrt()
);
}
println!("layer {layer}: worst {worst:.3e} over {steps} steps");
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_moe(
gguf_path: &Path,
device: &Device,
text: &neuron::harness::arch::qwen4_exp::config::TextConfig,
lvb: &candle_nn::var_builder::ShardedVarBuilder,
dense: GgufDenseSource,
embed: &Tensor,
layer: usize,
steps: usize,
) -> Result<()> {
use neuron::harness::arch::qwen4_exp::engine::moe;
use neuron::harness::arch::qwen4_exp::native_experts::{GgufExpertSource, NativeExpertFactory};
use std::sync::Arc;
if std::env::var("NEURON_EXPERT_DEVICE_ROUTING").as_deref() != Ok("1") {
bail!("the moe probe needs NEURON_EXPERT_DEVICE_ROUTING=1");
}
let cuda = device.as_cuda_device()?.clone();
let shapes = gdn::shapes(text)?;
let mshapes = moe::shapes(text)?;
// No tier: every expert is read from the pinned host store by both
// paths alike, and neither admits anything.
let experts = Arc::new(GgufExpertSource::open(
gguf_path,
device,
text.num_hidden_layers,
text.num_experts,
text.hidden_size,
text.moe_intermediate_size,
None,
)?);
let dense: Arc<dyn LinearSource> = Arc::new(dense);
let opts = neuron::harness::arch::qwen4_exp::LoadOptions {
quant: None,
safetensors_paths: &[],
isq_cache: None,
experts_onto: &Device::Cpu,
experts_vb: None,
expert_tier: None,
external_experts: Some(Arc::new(NativeExpertFactory(experts.clone()))),
dense: Some(dense.clone()),
};
let hc = HyperConnection::load(
&lvb.pp("mlp_hyper_connection"),
text.hidden_size,
text.hc_count,
text.hc_lowrank,
text.rms_norm_eps,
true,
Some(dense.as_ref()),
)?;
let block = neuron::harness::arch::qwen4_exp::moe::load(text, &lvb.pp("mlp"), &opts)?;
let router_w = lvb
.pp("mlp")
.pp("gate")
.get((text.num_experts, text.hidden_size), "weight")?;
gdn::configure();
let gguf = Gguf::open(gguf_path, &cuda)?;
let weights = moe::MoeWeights::load(&gguf, layer, &shapes, &mshapes)?;
let mut scratch = moe::MoeScratch::new(&cuda, &shapes, &mshapes)?;
let out = cuda.alloc_zeros::<f32>(shapes.hc * shapes.n_embd)?;
let stream = cuda.cuda_stream().cu_stream() as *mut std::ffi::c_void;
let fault = std::env::var_os("PROBE_FAULT_SKIP_SHARED").is_some();
let mut worst = 0f64;
for step in 0..steps {
let token = (1000 + 7919 * step) % text.vocab_size;
let h = embed
.i(token)?
.reshape((1, 1, text.hidden_size))?
.repeat((1, 1, text.hc_count))?
.contiguous()?;
let split = hc.split(&h)?;
let inject = split
.inject
.as_ref()
.context("a decoder hyper-connection injects")?;
let mixed = candle_core::Module::forward(&block, &split.input)?;
let want = hc.combine(&split.residual, &mixed, inject)?;
let h32 = h.to_dtype(DType::F32)?.contiguous()?;
moe::forward(
&weights,
&experts,
layer,
&mut scratch,
&shapes,
&mshapes,
address(&h32)?,
out.device_ptr(out.stream()).0,
stream,
)?;
cuda.cuda_stream().synchronize()?;
let input: Vec<f32> = h32.flatten_all()?.to_vec1()?;
let want: Vec<f32> = want.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
let got = cuda.clone_dtoh(&out)?;
let delta = |r: &[f32]| -> Vec<f32> { r.iter().zip(&input).map(|(a, b)| a - b).collect() };
let (mut d_got, d_want) = (delta(&got), delta(&want));
if fault {
// A deliberate fault: drop a tenth of the contribution.
d_got.iter_mut().for_each(|v| *v *= 0.9);
}
let err = rel(&d_got, &d_want);
worst = worst.max(err);
// Which experts each path chose: the engine's from its own
// router, candle's recomputed from the same input and weight in
// candle's arithmetic (BF16 input, f32 softmax, descending sort).
let (mut ids, logits) = scratch.routed(&cuda)?;
ids.sort_unstable();
let probs = candle_nn::ops::softmax_last_dim(
&split
.input
.reshape(((), text.hidden_size))?
.matmul(&router_w.t()?)?
.to_dtype(DType::F32)?,
)?;
let order: Vec<u32> = probs.arg_sort_last_dim(false)?.flatten_all()?.to_vec1()?;
let mut cids: Vec<i32> = order[..mshapes.k].iter().map(|&e| e as i32).collect();
cids.sort_unstable();
if ids != cids {
let mut sorted = logits.clone();
sorted.sort_by(|a, b| b.total_cmp(a));
println!(
" routing differs: engine {ids:?} candle {cids:?}; engine logits at ranks 10/11: {:.5} / {:.5}",
sorted[mshapes.k - 1],
sorted[mshapes.k]
);
}
println!(
"layer {layer} moe step {step} token {token}: contribution rel err {err:.3e}, |out-in| {:.3e}",
d_want
.iter()
.map(|v| f64::from(*v).powi(2))
.sum::<f64>()
.sqrt()
);
}
println!("layer {layer} moe: worst {worst:.3e} over {steps} steps");
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_attn(
gguf_path: &Path,
device: &Device,
text: &neuron::harness::arch::qwen4_exp::config::TextConfig,
lvb: &candle_nn::var_builder::ShardedVarBuilder,
source: Option<&dyn LinearSource>,
embed: &Tensor,
layer: usize,
steps: usize,
) -> Result<()> {
use neuron::harness::arch::qwen4_exp::engine::attn;
use neuron::harness::arch::qwen4_exp::full_attn::Attention;
use std::sync::Arc;
let cuda = device.as_cuda_device()?.clone();
let shapes = gdn::shapes(text)?;
let ashapes = attn::shapes(text, steps.max(16))?;
let rotary = Arc::new(neuron::harness::arch::qwen4_exp::model::rotary_for(
text,
DType::BF16,
device,
)?);
let hc = HyperConnection::load(
&lvb.pp("attn_hyper_connection"),
text.hidden_size,
text.hc_count,
text.hc_lowrank,
text.rms_norm_eps,
true,
source,
)?;
let mut candle_attn = Attention::load(text, rotary.clone(), &lvb.pp("self_attn"), source)?;
gdn::configure();
let gguf = Gguf::open(gguf_path, &cuda)?;
let weights = attn::AttnWeights::load(&gguf, layer, &shapes, &ashapes)?;
let mut cache = attn::AttnCache::new(&cuda, &ashapes)?;
let mut scratch = attn::AttnScratch::new(&cuda, &shapes, &ashapes)?;
let mut positions = cuda.alloc_zeros::<i32>(32)?;
let out = cuda.alloc_zeros::<f32>(shapes.hc * shapes.n_embd)?;
let stream = cuda.cuda_stream().cu_stream() as *mut std::ffi::c_void;
let mut worst = 0f64;
for step in 0..steps {
let token = (1000 + 7919 * step) % text.vocab_size;
let h = embed
.i(token)?
.reshape((1, 1, text.hidden_size))?
.repeat((1, 1, text.hc_count))?
.contiguous()?;
let split = hc.split(&h)?;
let inject = split
.inject
.as_ref()
.context("a decoder hyper-connection injects")?;
let (cos, sin) = rotary.plain_cos_sin(step, 1)?;
let mixed = candle_attn.forward(&split.input, None, &cos, &sin, step)?;
let want = hc.combine(&split.residual, &mixed, inject)?;
// A deliberate fault: positions one ahead of candle's.
let shift = i32::from(std::env::var_os("PROBE_FAULT_POSITION").is_some());
cuda.memcpy_htod(&[step as i32 + shift; 32], &mut positions)?;
let h32 = h.to_dtype(DType::F32)?.contiguous()?;
attn::forward(
&weights,
&mut cache,
&mut scratch,
&shapes,
&ashapes,
positions.device_ptr(positions.stream()).0,
address(&h32)?,
out.device_ptr(out.stream()).0,
stream,
)?;
cuda.cuda_stream().synchronize()?;
let input: Vec<f32> = h32.flatten_all()?.to_vec1()?;
let want: Vec<f32> = want.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
let got = cuda.clone_dtoh(&out)?;
let delta = |r: &[f32]| -> Vec<f32> { r.iter().zip(&input).map(|(a, b)| a - b).collect() };
let err = rel(&delta(&got), &delta(&want));
worst = worst.max(err);
println!(
"layer {layer} attn step {step} token {token}: contribution rel err {err:.3e}, |out-in| {:.3e}",
delta(&want)
.iter()
.map(|v| f64::from(*v).powi(2))
.sum::<f64>()
.sqrt()
);
}
println!("layer {layer} attn: worst {worst:.3e} over {steps} steps");
Ok(())
}
+326
View File
@@ -0,0 +1,326 @@
//! Checks the native decode step (#427) end to end against candle's
//! model, on the real checkpoint and GGUF.
//!
//! ```sh
//! NEURON_EXPERT_DEVICE_ROUTING=1 neuron-engine-step-probe GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [STEPS]
//! ```
//!
//! Decodes a fixed token sequence from position 0 through both, one token
//! at a time, and compares each step's next-token distribution: KL from
//! candle's to the engine's, and whether the top token agrees. Both share
//! one expert source (and its VRAM tier, if NEURON_EXPERT_CACHE_MB is set) and the
//! GGUF's Q8_0 dense projections; candle runs in BF16 as served. The
//! engine takes PLE's contribution from candle's own PLE block, run on the
//! engine's residual, and candle's state is restored around that so its
//! own forward sees each token once.
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use candle_core::cuda_backend::cudarc::driver::DevicePtr;
use candle_core::{CudaStorage, DType, Device, Storage, Tensor};
use candle_nn::var_builder::ShardedSafeTensors;
use neuron::harness::arch::qwen3_5::proj::LinearSource;
use neuron::harness::arch::qwen4_exp::config::Config;
use neuron::harness::arch::qwen4_exp::engine::decoder::NativeDecoder;
use neuron::harness::arch::qwen4_exp::engine::weights::Gguf;
use neuron::harness::arch::qwen4_exp::gguf_dense::{GgufDenseSource, Heads};
use neuron::harness::arch::qwen4_exp::model::Qwen4ExpForCausalLM;
use neuron::harness::arch::qwen4_exp::native_experts::{GgufExpertSource, NativeExpertFactory};
fn softmax(x: &[f32]) -> Vec<f64> {
let m = x.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let e: Vec<f64> = x.iter().map(|&v| f64::from(v - m).exp()).collect();
let z: f64 = e.iter().sum();
e.into_iter().map(|v| v / z).collect()
}
fn argmax(x: &[f32]) -> usize {
x.iter()
.enumerate()
.max_by(|a, b| a.1.total_cmp(b.1))
.map_or(0, |(i, _)| i)
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
bail!(
"usage: {} GGUF_FIRST_SHARD HF_SNAPSHOT_DIR [STEPS]",
args[0]
);
}
if std::env::var("NEURON_EXPERT_DEVICE_ROUTING").as_deref() != Ok("1") {
bail!("needs NEURON_EXPERT_DEVICE_ROUTING=1");
}
let (gguf_path, hf) = (Path::new(&args[1]), Path::new(&args[2]));
let steps: usize = args.get(3).map_or(Ok(16), |v| v.parse())?;
let device = Device::new_cuda(0)?;
let cuda = device.as_cuda_device()?.clone();
let cfg = Config::from_config_json(
&std::fs::read_to_string(hf.join("config.json")).context("read config.json")?,
)?;
let text = &cfg.text_config;
let experts = Arc::new(GgufExpertSource::open(
gguf_path,
&device,
text.num_hidden_layers,
text.num_experts,
text.hidden_size,
text.moe_intermediate_size,
// NEURON_EXPERT_CACHE_MB, as served: a VRAM tier (filled from
// NEURON_EXPERT_PROFILE) changes where experts are read, not what
// they compute.
neuron::harness::arch::qwen3_5::expert_tier::configured_budget_mb(),
)?);
let dense: Arc<dyn LinearSource> = Arc::new(GgufDenseSource::open(
gguf_path,
&device,
Heads {
key_heads: text.linear_num_key_heads,
value_heads: text.linear_num_value_heads,
head_dim: text.linear_value_head_dim,
},
text.linear_num_key_heads * text.linear_key_head_dim,
)?);
let mut paths: Vec<_> = std::fs::read_dir(hf)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|x| x == "safetensors"))
.collect();
paths.sort();
// SAFETY: the checkpoint is not modified while mapped.
let vb = unsafe { ShardedSafeTensors::var_builder(&paths, DType::BF16, &device)? };
let mut model = Qwen4ExpForCausalLM::load(
&cfg,
DType::BF16,
&device,
&vb,
&neuron::harness::arch::qwen4_exp::LoadOptions {
quant: None,
safetensors_paths: &paths,
isq_cache: None,
experts_onto: &Device::Cpu,
experts_vb: None,
expert_tier: None,
external_experts: Some(Arc::new(NativeExpertFactory(experts.clone()))),
dense: Some(dense),
},
)?;
let gguf = Gguf::open(gguf_path, &cuda)?;
let mut engine = NativeDecoder::load(&gguf, text, experts.clone(), steps.max(16))?;
let wide = text.hidden_size * text.hc_count;
// PROBE_TOKENS: a comma-separated id file (a real prompt); else a
// fixed synthetic sequence. PROBE_DUMP_DIR: each step's logits as
// e<pos>.f32 (engine) and c<pos>.f32 (candle), for comparing both
// against another engine on the same prefix.
let tokens: Vec<u32> = match std::env::var_os("PROBE_TOKENS") {
Some(path) => std::fs::read_to_string(path)?
.trim()
.split(',')
.take(steps)
.map(|t| t.trim().parse())
.collect::<Result<_, _>>()?,
None => (0..steps)
.map(|i| (1000 + 7919 * i) as u32 % 150_000)
.collect(),
};
let dump = std::env::var_os("PROBE_DUMP_DIR").map(std::path::PathBuf::from);
let write = |name: String, values: &[f32]| -> Result<()> {
if let Some(dir) = &dump {
let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
std::fs::write(dir.join(name), bytes)?;
}
Ok(())
};
if let Some(n) = std::env::var("PROBE_TIMING")
.ok()
.and_then(|v| v.parse::<usize>().ok())
{
return time_steps(
&mut engine,
&mut model,
&cuda,
&tokens,
n.min(tokens.len()),
wide,
);
}
let (mut kl_sum, mut agree, mut worst, mut kl_head_sum) = (0f64, 0usize, 0f64, 0f64);
let lm_head = vb
.pp("lm_head")
.get((text.vocab_size, text.hidden_size), "weight")?;
for (pos, &token) in tokens.iter().enumerate() {
let ids = Tensor::new(&[[token]], &device)?;
let snapshot = model.snapshot_kv_cache()?;
engine.set_step(token, pos)?;
engine.segment_head()?;
// SAFETY: written in full by the copy below.
let mut copy = unsafe { cuda.alloc::<f32>(wide)? };
cuda.memcpy_dtod(engine.residual(), &mut copy)?;
let residual = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(copy, cuda.clone())),
(1, 1, wide),
));
if let Some(ple) = model.ple_contribution(&ids, &residual)? {
let ple = ple.to_dtype(DType::F32)?.contiguous()?;
let (storage, layout) = ple.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
bail!("PLE ran off the GPU");
};
let slice = storage.as_cuda_slice::<f32>()?;
engine.add_to_residual(
slice.device_ptr(slice.stream()).0 + (layout.start_offset() * 4) as u64,
)?;
}
engine.segment_tail()?;
let got = engine.logits()?;
// The engine's final hidden state through candle's own BF16 head:
// separates the Q6_K head from everything before it.
// SAFETY: written in full by the copy below.
let mut mixed = unsafe { cuda.alloc::<f32>(text.hidden_size)? };
cuda.memcpy_dtod(engine.mixed(), &mut mixed)?;
let mixed = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(mixed, cuda.clone())),
(1, text.hidden_size),
));
let via_head: Vec<f32> = mixed
.to_dtype(DType::BF16)?
.matmul(&lm_head.t()?)?
.to_dtype(DType::F32)?
.flatten_all()?
.to_vec1()?;
model.restore_kv_cache(&snapshot)?;
let want: Vec<f32> = model
.forward(&ids, pos)?
.to_dtype(DType::F32)?
.flatten_all()?
.to_vec1()?;
let kl_of = |p: &[f64], q: &[f64]| -> f64 {
p.iter()
.zip(q)
.filter(|(a, _)| **a > 0.0)
.map(|(a, b)| a * (a / b.max(1e-30)).ln())
.sum()
};
write(format!("e{pos}.f32"), &got)?;
write(format!("c{pos}.f32"), &want)?;
let p = softmax(&want);
let kl = kl_of(&p, &softmax(&got));
let kl_head = kl_of(&p, &softmax(&via_head));
kl_head_sum += kl_head;
let same = argmax(&want) == argmax(&got);
kl_sum += kl;
agree += usize::from(same);
worst = worst.max(kl);
println!(
"pos {pos} token {token}: KL {kl:.4e} (BF16 head {kl_head:.4e}) top1 candle {} engine {} {}",
argmax(&want),
argmax(&got),
if same { "same" } else { "DIFFERENT" }
);
}
println!(
"{steps} steps: mean KL {:.4e} (through candle's BF16 head {:.4e}), worst {worst:.4e}, top-1 agree {agree}/{steps}",
kl_sum / steps as f64,
kl_head_sum / steps as f64
);
Ok(())
}
/// Engine-only decode timing: the same tokens eagerly, then with each
/// segment replayed from its graph. Per step: write the inputs, adapt the
/// tier, segment one, PLE (eager, on the host-gathered n-grams), segment
/// two, read the logits.
fn time_steps(
engine: &mut NativeDecoder,
model: &mut Qwen4ExpForCausalLM,
cuda: &candle_core::CudaDevice,
tokens: &[u32],
n: usize,
wide: usize,
) -> Result<()> {
let device = Device::Cuda(cuda.clone());
let mut eager_logits: Vec<Vec<f32>> = Vec::new();
for graphs in [false, true] {
engine.reset()?;
model.clear_kv_cache()?;
let mut times = Vec::with_capacity(n);
let mut first = Vec::new();
let (mut worst_kl, mut agree) = (0f64, 0usize);
for (pos, &token) in tokens.iter().take(n).enumerate() {
let started = std::time::Instant::now();
let ids = Tensor::new(&[[token]], &device)?;
engine.set_step(token, pos)?;
engine.adapt()?;
if graphs {
engine.run_head()?;
} else {
engine.segment_head()?;
}
// SAFETY: written in full by the copy below.
let mut copy = unsafe { cuda.alloc::<f32>(wide)? };
cuda.memcpy_dtod(engine.residual(), &mut copy)?;
let residual = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(copy, cuda.clone())),
(1, 1, wide),
));
if let Some(ple) = model.ple_contribution(&ids, &residual)? {
let ple = ple.to_dtype(DType::F32)?.contiguous()?;
let (storage, layout) = ple.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
bail!("PLE ran off the GPU");
};
let slice = storage.as_cuda_slice::<f32>()?;
engine.add_to_residual(
slice.device_ptr(slice.stream()).0 + (layout.start_offset() * 4) as u64,
)?;
}
if graphs {
engine.run_tail()?;
} else {
engine.segment_tail()?;
}
let logits = engine.logits()?;
times.push(started.elapsed().as_secs_f64() * 1e3);
if graphs {
let (p, q) = (softmax(&eager_logits[pos]), softmax(&logits));
let kl: f64 = p
.iter()
.zip(&q)
.filter(|(a, _)| **a > 0.0)
.map(|(a, b)| a * (a / b.max(1e-30)).ln())
.sum();
worst_kl = worst_kl.max(kl);
agree += usize::from(argmax(&eager_logits[pos]) == argmax(&logits));
} else {
eager_logits.push(logits.clone());
}
if pos == 0 {
first = logits;
}
}
let steady: Vec<f64> = times.iter().skip(3).copied().collect();
let mean = steady.iter().sum::<f64>() / steady.len().max(1) as f64;
println!(
"{}: {n} tokens, steady {mean:.2} ms/token ({:.1} tok/s); first-step top-1 {}",
if graphs { "graphs" } else { "eager " },
1e3 / mean,
argmax(&first)
);
if graphs {
println!(
"graphs vs eager over {n} steps: worst KL {worst_kl:.3e}, top-1 agree {agree}/{n}"
);
}
}
Ok(())
}
+177
View File
@@ -74,6 +74,17 @@ unsafe extern "C" {
bytes: u64,
stream: *mut c_void,
) -> i32;
/// `cudaGetLastError`: the error of the most recent failing call,
/// cleared by reading.
pub fn neuron_strata_last_error() -> i32;
/// Queues a kernel copying `n` 32-bit words (`dst` may be the device
/// address of mapped pinned host memory).
pub fn neuron_strata_copy_words(
dst: *mut u32,
src: *const u32,
n: i32,
stream: *mut c_void,
) -> i32;
/// Queues a device-to-host copy into pinned memory.
pub fn neuron_strata_copy_to_host(
pinned_dst: *mut c_void,
@@ -136,4 +147,170 @@ unsafe extern "C" {
out: *mut f32,
stream: *mut c_void,
);
// ---- the native decode engine's kernels (#427): see engine_shim.cu.
// Each returns 0, a CUDA error code, or -1 with a message from
// `neuron_engine_last_error`.
pub fn neuron_engine_last_error() -> *const c_char;
pub fn neuron_engine_configure();
pub fn neuron_gr_workspace_bytes(n_embd: i64, hc: i64, hc_lr: i64) -> usize;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gr_read(
residual: *const f32,
w_norm: *const f32,
w_down: *const u16,
w_up: *const u16,
w_inject: *const u16,
eps: f32,
n_embd: i64,
hc: i64,
hc_lr: i64,
workspace: *mut c_void,
mixed: *mut f32,
inject: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gr_write(
residual: *const f32,
block_out: *const f32,
inject: *const f32,
n_embd: i64,
hc: i64,
hc_lr: i64,
residual_out: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_conv_l2(
history: *mut f32,
qkv: *const f32,
conv_w: *const f32,
h: *mut f32,
channels: i32,
qk_heads: i32,
eps: f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_ab(
x: *const f32,
w_alpha: *const u16,
w_beta: *const u16,
dt: *const f32,
ssm_a: *const f32,
gate: *mut f32,
beta: *mut f32,
n_embd: i32,
h_v: i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_step_norm(
state: *mut f32,
q: *const f32,
k: *const f32,
v: *const f32,
gate: *const f32,
beta: *const f32,
z: *const f32,
gamma: *const f32,
eps: f32,
y: *mut f32,
h_k: i32,
h_v: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_bf16_gemv(
x: *const f32,
w: *const u16,
y: *mut f32,
n_in: i64,
n_out: i64,
stream: *mut c_void,
) -> i32;
pub fn neuron_router_top10(
logits: *const f32,
ids: *mut i32,
weights: *mut f32,
stream: *mut c_void,
) -> i32;
pub fn neuron_moe_combine(
parts: *const f32,
weights: *const f32,
shared: *const f32,
output: *mut f32,
n_embd: i64,
k: i64,
stream: *mut c_void,
) -> i32;
pub fn neuron_swiglu(
gate: *const f32,
up: *const f32,
out: *mut f32,
n: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_scale_by_sigmoid(
x: *mut f32,
gate: *const f32,
n: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_append_rows(
src_a: *const f32,
src_b: *const f32,
dst_a: *mut f32,
dst_b: *mut f32,
pos: *const i32,
width: i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_decode_attn(
q: *const f32,
kc: *const f32,
vc: *const f32,
pos: *const i32,
heads: i32,
kv_heads: i32,
head_dim: i32,
scale: f32,
gate: *const f32,
gate_stride: i32,
out: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_norm_rope(
x: *const f32,
in_stride: i32,
gamma: *const f32,
out: *mut f32,
rows: i32,
head_dim: i32,
n_rot: i32,
eps: f32,
positions: *const i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_embed_rows(
ggml_type: i32,
table: *const c_void,
row_bytes: usize,
tokens: *const i32,
n_tok: i64,
n_embd: i64,
out: *mut f32,
stream: *mut c_void,
) -> i32;
pub fn neuron_repeat_row(
src: *const f32,
dst: *mut f32,
n: i32,
times: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_add_inplace(x: *mut f32, y: *const f32, n: i32, stream: *mut c_void) -> i32;
}
@@ -0,0 +1,307 @@
// C ABI over the vendored Strata decode kernels the native qwen4_exp
// engine drives (#427): linear attention, the hyper-connection, the
// router, the MoE combine and the BF16 projections.
//
// Several of these throw on invalid geometry. An exception must not
// unwind into Rust, so every entry point catches and returns a status:
// 0 on success, otherwise a CUDA error code or -1 for a thrown error,
// whose message `neuron_engine_last_error` returns.
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <exception>
#include <stdexcept>
#include <string>
#include <cuda_runtime.h>
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/fused_gdn.hpp"
#include "strata/kernels/gr.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/native_gdn.hpp"
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/native_router.hpp"
#include "strata/kernels/pdl.hpp"
namespace k = strata::kernels;
// Programmatic dependent launch is defined upstream in verify_kernels.cu,
// with the verify-window machinery the engine does not use. With
// `pdl_scope()` off, `launch_pdl` takes its ordinary launch, which is all
// the decode kernels need; PDL comes in with the verify windows (#313).
namespace strata::kernels {
bool& pdl_scope() {
static thread_local bool on = false;
return on;
}
bool pdl_supported() { return false; }
bool pdl_launch_ok(const void*, cudaStream_t) { return false; }
} // namespace strata::kernels
namespace {
thread_local std::string g_last_error;
template <typename F>
int guarded(F&& f) {
try {
f();
} catch (const std::exception& e) {
g_last_error = e.what();
return -1;
} catch (...) {
g_last_error = "unknown exception";
return -1;
}
const cudaError_t status = cudaGetLastError();
if (status != cudaSuccess) {
g_last_error = cudaGetErrorString(status);
return (int) status;
}
return 0;
}
// The shared expert's elementwise steps, which upstream fuses into code
// the engine does not vendor: SiLU(gate) * up, and scaling the expert's
// output by the sigmoid of its one-scalar gate.
__global__ void swiglu_kernel(const float* gate, const float* up, float* out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
const float g = gate[i];
out[i] = g / (1.0f + expf(-g)) * up[i];
}
}
__global__ void scale_by_sigmoid_kernel(float* x, const float* gate, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] *= 1.0f / (1.0f + expf(-gate[0]));
}
// ---- dense decode attention over a cache allocated once (#427).
//
// The cache is `[position][kv_head][head_dim]` f32. The current position
// lives in device memory (`pos[0]`), so nothing here takes a per-token
// argument and the step can be captured.
// Writes one token's rows (`width` floats each, `src_b` optional) into
// `dst_a[pos * width]` and `dst_b[pos * width]`.
__global__ void append_rows_kernel(const float* src_a, const float* src_b, float* dst_a, float* dst_b,
const int* pos, int width) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= width) return;
const size_t at = (size_t) pos[0] * width + i;
dst_a[at] = src_a[i];
if (src_b != nullptr) dst_b[at] = src_b[i];
}
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
// One block of 8 warps per query head, D = 256 (8 values per lane). Each
// warp takes positions w, w + 8, ... up to pos[0], keeping an online
// softmax; the warps' partial results are merged at the end. The output
// is multiplied by sigmoid(gate) (Qwen's per-head output gate), the gate
// row of head h at `gate[h * gate_stride]`.
template <int D>
__global__ void __launch_bounds__(256) decode_attn_kernel(const float* q, const float* kc, const float* vc,
const int* pos, int kv_heads, int group, float scale,
const float* gate, int gate_stride, float* out) {
constexpr int PER = D / 32;
constexpr int WARPS = 8;
const int h = blockIdx.x, kvh = h / group;
const int warp = threadIdx.x / 32, lane = threadIdx.x % 32;
const int n = pos[0] + 1;
float qv[PER], acc[PER];
#pragma unroll
for (int i = 0; i < PER; ++i) {
qv[i] = q[(size_t) h * D + lane * PER + i];
acc[i] = 0.0f;
}
float m = -INFINITY, l = 0.0f;
for (int p = warp; p < n; p += WARPS) {
const float* kr = kc + ((size_t) p * kv_heads + kvh) * D + lane * PER;
float dot = 0.0f;
#pragma unroll
for (int i = 0; i < PER; ++i) dot += qv[i] * kr[i];
const float sc = warp_sum(dot) * scale;
const float m_new = fmaxf(m, sc);
const float corr = expf(m - m_new), e = expf(sc - m_new);
l = l * corr + e;
const float* vr = vc + ((size_t) p * kv_heads + kvh) * D + lane * PER;
#pragma unroll
for (int i = 0; i < PER; ++i) acc[i] = acc[i] * corr + e * vr[i];
m = m_new;
}
__shared__ float s_m[WARPS], s_l[WARPS];
__shared__ float s_acc[WARPS][D];
if (lane == 0) {
s_m[warp] = m;
s_l[warp] = l;
}
#pragma unroll
for (int i = 0; i < PER; ++i) s_acc[warp][lane * PER + i] = acc[i];
__syncthreads();
float mx = -INFINITY;
#pragma unroll
for (int w = 0; w < WARPS; ++w) mx = fmaxf(mx, s_m[w]);
float total = 0.0f;
#pragma unroll
for (int w = 0; w < WARPS; ++w) total += s_m[w] == -INFINITY ? 0.0f : s_l[w] * expf(s_m[w] - mx);
for (int d = threadIdx.x; d < D; d += blockDim.x) {
float v = 0.0f;
#pragma unroll
for (int w = 0; w < WARPS; ++w)
if (s_m[w] != -INFINITY) v += s_acc[w][d] * expf(s_m[w] - mx);
const float g = gate[(size_t) h * gate_stride + d];
out[(size_t) h * D + d] = v / total * (1.0f / (1.0f + expf(-g)));
}
}
// `dst` = `times` copies of the `n`-float row `src` (the embedding into
// every residual stream).
__global__ void repeat_row_kernel(const float* src, float* dst, int n, int times) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n * times) dst[i] = src[i % n];
}
__global__ void add_inplace_kernel(float* x, const float* y, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] += y[i];
}
k::GrShapes gr_shapes(int64_t n_embd, int64_t hc, int64_t hc_lr) {
k::GrShapes s;
s.n_embd = n_embd;
s.hc = hc;
s.hc_lr = hc_lr;
return s;
}
} // namespace
extern "C" {
const char* neuron_engine_last_error() { return g_last_error.c_str(); }
/// Selects the pinned single-token FP32 contract for the hyper-connection
/// and GDN kernels, as Strata's decode does. Call before any capture.
void neuron_engine_configure() {
k::gr_set_native_mmvf(true);
k::native_gdn_set_enabled(true);
k::native_router_set_enabled(true);
k::native_moe_combine_set_enabled(true);
}
size_t neuron_gr_workspace_bytes(int64_t n_embd, int64_t hc, int64_t hc_lr) {
return k::gr_workspace_bytes(gr_shapes(n_embd, hc, hc_lr));
}
int neuron_gr_read(const float* residual, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, int64_t n_embd, int64_t hc, int64_t hc_lr, void* workspace,
float* mixed, float* inject, void* stream) {
return guarded([&] {
const k::GrShapes s = gr_shapes(n_embd, hc, hc_lr);
k::GrWorkspace ws;
k::gr_workspace_init(s, workspace, ws);
k::gr_read(residual, w_norm, w_down, w_up, w_inject, eps, s, ws, mixed, inject, stream);
});
}
int neuron_gr_write(const float* residual, const float* block_out, const float* inject, int64_t n_embd, int64_t hc,
int64_t hc_lr, float* residual_out, void* stream) {
return guarded([&] {
k::gr_write(residual, block_out, inject, gr_shapes(n_embd, hc, hc_lr), residual_out, stream);
});
}
int neuron_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
float eps, void* stream) {
return guarded([&] { k::fused_gdn_conv_l2(history, qkv, conv_w, h, channels, qk_heads, eps, stream); });
}
int neuron_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt,
const float* ssm_a, float* gate, float* beta, int n_embd, int h_v, void* stream) {
return guarded([&] { k::fused_gdn_ab(x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, stream); });
}
int neuron_gdn_step_norm(float* state, const float* q, const float* k_, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
void* stream) {
return guarded(
[&] { k::fused_gdn_step_norm(state, q, k_, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream); });
}
int neuron_bf16_gemv(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream) {
return guarded([&] { k::bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); });
}
int neuron_router_top10(const float* logits, int32_t* ids, float* weights, void* stream) {
return guarded([&] { k::native_router_top10(logits, ids, weights, stream); });
}
int neuron_moe_combine(const float* parts, const float* weights, const float* shared, float* output, int64_t n_embd,
int64_t k_, void* stream) {
return guarded([&] { k::native_moe_combine(parts, weights, shared, output, n_embd, k_, stream); });
}
int neuron_append_rows(const float* src_a, const float* src_b, float* dst_a, float* dst_b, const int* pos, int width,
void* stream) {
return guarded([&] {
append_rows_kernel<<<(width + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(src_a, src_b, dst_a,
dst_b, pos, width);
});
}
int neuron_decode_attn(const float* q, const float* kc, const float* vc, const int* pos, int heads, int kv_heads,
int head_dim, float scale, const float* gate, int gate_stride, float* out, void* stream) {
return guarded([&] {
if (head_dim != 256 || heads % kv_heads != 0) throw std::invalid_argument("decode attention: head_dim 256 only");
decode_attn_kernel<256><<<heads, 256, 0, static_cast<cudaStream_t>(stream)>>>(
q, kc, vc, pos, kv_heads, heads / kv_heads, scale, gate, gate_stride, out);
});
}
int neuron_norm_rope(const float* x, int in_stride, const float* gamma, float* out, int rows, int head_dim, int n_rot,
float eps, const int* positions, void* stream) {
return guarded([&] {
const k::RopeScaling scaling{};
k::native_qsa_rms_norm_rope(x, in_stride, gamma, out, rows, head_dim, n_rot, eps, scaling, positions, stream);
});
}
int neuron_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,
int64_t n_embd, float* out, void* stream) {
return guarded([&] { k::iq_embed_rows(ggml_type, table, row_bytes, tokens, n_tok, n_embd, out, stream); });
}
int neuron_repeat_row(const float* src, float* dst, int n, int times, void* stream) {
return guarded([&] {
repeat_row_kernel<<<(n * times + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(src, dst, n, times);
});
}
int neuron_add_inplace(float* x, const float* y, int n, void* stream) {
return guarded([&] {
add_inplace_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(x, y, n);
});
}
int neuron_swiglu(const float* gate, const float* up, float* out, int n, void* stream) {
return guarded([&] {
swiglu_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(gate, up, out, n);
});
}
int neuron_scale_by_sigmoid(float* x, const float* gate, int n, void* stream) {
return guarded([&] {
scale_by_sigmoid_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(x, gate, n);
});
}
} // extern "C"
@@ -108,6 +108,13 @@ __global__ void gather_blobs_kernel(const unsigned long long* src, const int32_t
for (unsigned long long t = tail + threadIdx.x; t < hi; t += blockDim.x) to[t] = from[t];
}
// Copies `n` 32-bit words, e.g. into mapped pinned host memory: a kernel
// rather than a memcpy so the copy captures like any other launch.
__global__ void copy_words_kernel(uint32_t* dst, const uint32_t* src, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) dst[i] = src[i];
}
} // namespace
extern "C" {
@@ -207,6 +214,13 @@ int neuron_strata_gather_blobs(const unsigned long long* src, const int32_t* n_m
return cudaGetLastError();
}
int neuron_strata_last_error() { return cudaGetLastError(); }
int neuron_strata_copy_words(uint32_t* dst, const uint32_t* src, int n, void* stream) {
copy_words_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(dst, src, n);
return cudaGetLastError();
}
int neuron_strata_copy_to_host(void* pinned_dst, const void* src, size_t bytes, void* stream) {
return cudaMemcpyAsync(pinned_dst, src, bytes, cudaMemcpyDeviceToHost, static_cast<cudaStream_t>(stream));
}
@@ -211,6 +211,16 @@ impl DecoderLayer {
through(mlp_hc, &h, |x| Ok(mlp.forward(x)?))
}
/// This layer's PLE contribution for residual `h` and gathered
/// n-gram embedding `e`, or `None` when it carries no PLE block. The
/// native engine (#427) adds it to its own residual.
pub fn ple_contribution(&mut self, h: &Tensor, e: &Tensor) -> Result<Option<Tensor>> {
match &mut self.ple {
Some(block) => Ok(Some(block.forward(h, e)?)),
None => Ok(None),
}
}
pub fn clear_kv_cache(&mut self) -> Result<()> {
match &mut self.mixer {
Mixer::Full(attn) => attn.clear_kv_cache(),
@@ -0,0 +1,390 @@
//! A full-attention layer's mixer half, native, for contexts within the
//! QSA budget.
//!
//! One decode token: the attention hyper-connection's read; the Q8_0
//! q (query and output gate interleaved per head), k and v projections;
//! RMS norm and rotary on q and k with the position read from device
//! memory; the K/V append into a cache allocated once; dense decode
//! attention over every cached position, with the per-head sigmoid
//! output gate; the Q8_0 output projection; the hyper-connection's write.
//!
//! Dense is exact while the context fits QSA's budget (2,048 tokens),
//! where the selection keeps every position. The indexer's raw key is
//! still projected and cached each step, so selection can take over
//! beyond the budget without rebuilding that cache.
use std::ffi::c_void;
use anyhow::{Result, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use super::gdn::{GdnShapes, check};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
const Q8_1_BLOCK_VALUES: usize = 32;
const Q8_1_BLOCK_BYTES: usize = 36;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
#[derive(Debug, Clone, Copy)]
pub struct AttnShapes {
pub heads: usize,
pub kv_heads: usize,
pub head_dim: usize,
pub n_rot: usize,
pub index_dim: usize,
/// Positions the cache holds.
pub max_len: usize,
}
impl AttnShapes {
fn q_width(&self) -> usize {
self.heads * self.head_dim
}
fn kv_width(&self) -> usize {
self.kv_heads * self.head_dim
}
}
pub struct AttnWeights {
hc_norm: DeviceTensor,
hc_down: DeviceTensor,
hc_up: DeviceTensor,
hc_inject: DeviceTensor,
q: DeviceTensor,
k: DeviceTensor,
v: DeviceTensor,
o: DeviceTensor,
q_norm: DeviceTensor,
k_norm: DeviceTensor,
index_k: DeviceTensor,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl AttnWeights {
pub fn load(gguf: &Gguf, layer: usize, s: &GdnShapes, a: &AttnShapes) -> Result<Self> {
let name = |t: &str| format!("blk.{layer}.{t}");
let projection = |t: &str, n_in: usize, n_out: usize| -> Result<DeviceTensor> {
let w = gguf.upload_raw(&name(t), row_bytes)?;
ensure!(
w.dims == [n_in as u64, n_out as u64],
"{} is {:?}, expected [{n_in}, {n_out}]",
name(t),
w.dims
);
// SAFETY: a pure function of its argument.
ensure!(
unsafe { ffi::neuron_strata_mmvq_supported(w.ggml_type as i32) } != 0,
"{}: no mmvq for type {}",
name(t),
w.ggml_type
);
Ok(w)
};
let wide = s.hc * s.n_embd;
let w = Self {
hc_norm: gguf.upload_f32(&name("hc_attn_norm.weight"))?,
hc_down: gguf.upload_bf16(&name("hc_attn_down.weight"))?,
hc_up: gguf.upload_bf16(&name("hc_attn_up.weight"))?,
hc_inject: gguf.upload_bf16(&name("hc_attn_inject.weight"))?,
q: projection("attn_q.weight", s.n_embd, 2 * a.q_width())?,
k: projection("attn_k.weight", s.n_embd, a.kv_width())?,
v: projection("attn_v.weight", s.n_embd, a.kv_width())?,
o: projection("attn_output.weight", a.q_width(), s.n_embd)?,
q_norm: gguf.upload_f32(&name("attn_q_norm.weight"))?,
k_norm: gguf.upload_f32(&name("attn_k_norm.weight"))?,
index_k: gguf.upload_bf16(&name("indexer.k_proj.weight"))?,
};
for (t, want) in [
(&w.hc_norm, wide),
(&w.hc_down, s.hc_lr * wide),
(&w.hc_up, wide * s.hc_lr),
(&w.hc_inject, s.hc * wide),
(&w.q_norm, a.head_dim),
(&w.k_norm, a.head_dim),
(&w.index_k, a.index_dim * s.n_embd),
] {
ensure!(
t.values() == want,
"layer {layer}: a tensor has {} values, expected {want}",
t.values()
);
}
Ok(w)
}
}
/// A sequence's caches for one full-attention layer.
pub struct AttnCache {
k: CudaSlice<f32>,
v: CudaSlice<f32>,
/// The indexer's raw (unnormalised, unrotated) keys.
index_keys: CudaSlice<f32>,
}
impl AttnCache {
/// Zeroes the caches in place: a captured step keeps its addresses.
pub fn clear(&mut self, device: &CudaDevice) -> Result<()> {
let stream = device.cuda_stream();
stream.memset_zeros(&mut self.k)?;
stream.memset_zeros(&mut self.v)?;
stream.memset_zeros(&mut self.index_keys)?;
Ok(())
}
pub fn new(device: &CudaDevice, a: &AttnShapes) -> Result<Self> {
Ok(Self {
k: device.alloc_zeros::<f32>(a.max_len * a.kv_width())?,
v: device.alloc_zeros::<f32>(a.max_len * a.kv_width())?,
index_keys: device.alloc_zeros::<f32>(a.max_len * a.index_dim)?,
})
}
}
pub struct AttnScratch {
gr: CudaSlice<u8>,
mixed: CudaSlice<f32>,
inject: CudaSlice<f32>,
x_q8: CudaSlice<u8>,
q_raw: CudaSlice<f32>,
q: CudaSlice<f32>,
k_raw: CudaSlice<f32>,
k: CudaSlice<f32>,
v: CudaSlice<f32>,
index_key: CudaSlice<f32>,
ctx: CudaSlice<f32>,
ctx_q8: CudaSlice<u8>,
out: CudaSlice<f32>,
}
impl AttnScratch {
pub fn new(device: &CudaDevice, s: &GdnShapes, a: &AttnShapes) -> Result<Self> {
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
let q8 = |n: usize| n / Q8_1_BLOCK_VALUES * Q8_1_BLOCK_BYTES;
Ok(Self {
gr: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
inject: device.alloc_zeros::<f32>(s.hc)?,
x_q8: device.alloc_zeros::<u8>(q8(s.n_embd))?,
q_raw: device.alloc_zeros::<f32>(2 * a.q_width())?,
q: device.alloc_zeros::<f32>(a.q_width())?,
k_raw: device.alloc_zeros::<f32>(a.kv_width())?,
k: device.alloc_zeros::<f32>(a.kv_width())?,
v: device.alloc_zeros::<f32>(a.kv_width())?,
index_key: device.alloc_zeros::<f32>(a.index_dim)?,
ctx: device.alloc_zeros::<f32>(a.q_width())?,
ctx_q8: device.alloc_zeros::<u8>(q8(a.q_width()))?,
out: device.alloc_zeros::<f32>(s.n_embd)?,
})
}
}
fn mmvq(w: &DeviceTensor, x_q8: u64, y: u64, stream: *mut c_void) {
// SAFETY: `w` is `dims[1]` rows of `dims[0]`, `x_q8` holds `dims[0]`
// values in q8_1 and `y` has room for `dims[1]` floats.
unsafe {
ffi::neuron_strata_mmvq(
w.ggml_type as i32,
w.address() as *const c_void,
x_q8 as *const c_void,
y as *mut f32,
w.dims[0] as i32,
w.dims[1] as i32,
1,
stream,
)
}
}
fn quantize(x: u64, n: usize, q8: u64, stream: *mut c_void) {
// SAFETY: `x` holds `n` floats and `q8` room for their q8_1 blocks.
unsafe {
ffi::neuron_strata_quantize_q8_1(x as *const f32, 1, n as i64, q8 as *mut c_void, stream)
}
}
/// The mixer half of one full-attention layer, for one token at the
/// position in `positions[0]` (a device array of at least `heads` equal
/// entries: the rotary reads one per row).
#[allow(clippy::too_many_arguments)]
pub fn forward(
w: &AttnWeights,
cache: &mut AttnCache,
sc: &mut AttnScratch,
s: &GdnShapes,
a: &AttnShapes,
positions: u64,
residual: u64,
residual_out: u64,
stream: *mut c_void,
) -> Result<()> {
let (n_embd, hc, hc_lr) = (s.n_embd as i64, s.hc as i64, s.hc_lr as i64);
let pos = positions as *const i32;
// SAFETY (all calls below): every pointer is a live device buffer of
// the size its kernel reads or writes, as allocated in `AttnScratch`,
// `AttnCache` and `AttnWeights`; `positions` holds at least `heads`
// entries; every launch is on `stream`.
unsafe {
check(
ffi::neuron_gr_read(
residual as *const f32,
w.hc_norm.address() as *const f32,
w.hc_down.address() as *const u16,
w.hc_up.address() as *const u16,
w.hc_inject.address() as *const u16,
s.eps,
n_embd,
hc,
hc_lr,
address(&sc.gr) as *mut c_void,
address(&sc.mixed) as *mut f32,
address(&sc.inject) as *mut f32,
stream,
),
"attn gr_read",
)?;
}
quantize(address(&sc.mixed), s.n_embd, address(&sc.x_q8), stream);
mmvq(&w.q, address(&sc.x_q8), address(&sc.q_raw), stream);
mmvq(&w.k, address(&sc.x_q8), address(&sc.k_raw), stream);
mmvq(&w.v, address(&sc.x_q8), address(&sc.v), stream);
// SAFETY: as above.
unsafe {
// q rows are [query | gate] per head: read the query half.
check(
ffi::neuron_norm_rope(
address(&sc.q_raw) as *const f32,
(2 * a.head_dim) as i32,
w.q_norm.address() as *const f32,
address(&sc.q) as *mut f32,
a.heads as i32,
a.head_dim as i32,
a.n_rot as i32,
s.eps,
pos,
stream,
),
"q norm + rope",
)?;
check(
ffi::neuron_norm_rope(
address(&sc.k_raw) as *const f32,
a.head_dim as i32,
w.k_norm.address() as *const f32,
address(&sc.k) as *mut f32,
a.kv_heads as i32,
a.head_dim as i32,
a.n_rot as i32,
s.eps,
pos,
stream,
),
"k norm + rope",
)?;
check(
ffi::neuron_bf16_gemv(
address(&sc.mixed) as *const f32,
w.index_k.address() as *const u16,
address(&sc.index_key) as *mut f32,
n_embd,
a.index_dim as i64,
stream,
),
"indexer key",
)?;
check(
ffi::neuron_append_rows(
address(&sc.k) as *const f32,
address(&sc.v) as *const f32,
address(&cache.k) as *mut f32,
address(&cache.v) as *mut f32,
pos,
a.kv_width() as i32,
stream,
),
"kv append",
)?;
check(
ffi::neuron_append_rows(
address(&sc.index_key) as *const f32,
std::ptr::null(),
address(&cache.index_keys) as *mut f32,
std::ptr::null_mut(),
pos,
a.index_dim as i32,
stream,
),
"indexer key append",
)?;
check(
ffi::neuron_decode_attn(
address(&sc.q) as *const f32,
address(&cache.k) as *const f32,
address(&cache.v) as *const f32,
pos,
a.heads as i32,
a.kv_heads as i32,
a.head_dim as i32,
1.0 / (a.head_dim as f32).sqrt(),
(address(&sc.q_raw) + (a.head_dim * 4) as u64) as *const f32,
(2 * a.head_dim) as i32,
address(&sc.ctx) as *mut f32,
stream,
),
"decode attention",
)?;
}
quantize(address(&sc.ctx), a.q_width(), address(&sc.ctx_q8), stream);
mmvq(&w.o, address(&sc.ctx_q8), address(&sc.out), stream);
// SAFETY: as above.
unsafe {
check(
ffi::neuron_gr_write(
residual as *const f32,
address(&sc.out) as *const f32,
address(&sc.inject) as *const f32,
n_embd,
hc,
hc_lr,
residual_out as *mut f32,
stream,
),
"attn gr_write",
)?;
}
Ok(())
}
/// The attention shapes of a qwen4_exp config, with a cache of
/// `max_len` positions.
pub fn shapes(cfg: &super::super::config::TextConfig, max_len: usize) -> Result<AttnShapes> {
let n_rot =
(cfg.head_dim as f64 * f64::from(cfg.rope_parameters.partial_rotary_factor)) as usize;
let a = AttnShapes {
heads: cfg.num_attention_heads,
kv_heads: cfg.num_key_value_heads,
head_dim: cfg.head_dim,
n_rot,
index_dim: cfg.indexer_head_dim,
max_len,
};
ensure!(
a.head_dim == 256 && n_rot == 64,
"native attention is built for 256-wide heads, 64 rotated"
);
ensure!(
a.heads.is_multiple_of(a.kv_heads),
"query heads must be a multiple of kv heads"
);
Ok(a)
}
@@ -0,0 +1,477 @@
//! The native decode step (#427): every layer of the model for one token,
//! over buffers allocated once.
//!
//! A step is two segments around the PLE layer: `[embedding, layers
//! before PLE]`, then (after the caller adds PLE's contribution to the
//! residual) `[layers from PLE on, the final mixer, the LM head]`. Each
//! segment is fixed work over fixed addresses, with the token and
//! position read from a device buffer filled from pinned host memory at
//! the start of the step, so each can be captured as a CUDA graph and
//! replayed. PLE's n-gram gather stays on the host for now.
use std::ffi::c_void;
use std::sync::Arc;
use anyhow::{Context, Result, bail, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaGraph, CudaSlice, DevicePtr, sys};
use super::attn::{self, AttnCache, AttnScratch, AttnShapes, AttnWeights};
use super::gdn::{self, GdnScratch, GdnShapes, GdnState, GdnWeights, check};
use super::moe::{self, MoeScratch, MoeShapes, MoeWeights};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
use crate::harness::arch::qwen4_exp::config::TextConfig;
use crate::harness::arch::qwen4_exp::native_experts::GgufExpertSource;
/// Positions are written for every query-head row the rotary reads.
const POSITION_SLOTS: usize = 32;
/// The step buffer: `POSITION_SLOTS` positions, then the token id.
const STEP_SLOTS: usize = POSITION_SLOTS + 1;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
enum Mixer {
Linear(GdnWeights, GdnState),
Full(AttnWeights, AttnCache),
}
struct Layer {
mixer: Mixer,
moe: MoeWeights,
}
/// Pinned host memory the step inputs are copied from.
struct HostStep(*mut i32);
// SAFETY: plain host memory, written by the device worker between steps.
unsafe impl Send for HostStep {}
impl Drop for HostStep {
fn drop(&mut self) {
// SAFETY: allocated by `neuron_strata_pinned_alloc`, freed once.
unsafe { ffi::neuron_strata_pinned_free(self.0.cast()) };
}
}
/// A captured segment.
struct Graph(CudaGraph);
// SAFETY: a graph is launched only from the device worker that owns the
// decoder, on the stream it was captured on.
unsafe impl Send for Graph {}
pub struct NativeDecoder {
/// Captured segments, once a warm step has run.
head_graph: Option<Graph>,
tail_graph: Option<Graph>,
warmed: bool,
device: CudaDevice,
s: GdnShapes,
a: AttnShapes,
m: MoeShapes,
layers: Vec<Layer>,
ple_layer: usize,
experts: Arc<GgufExpertSource>,
gdn_sc: GdnScratch,
attn_sc: AttnScratch,
moe_sc: MoeScratch,
embed: DeviceTensor,
embed_row: CudaSlice<f32>,
mixer_norm: DeviceTensor,
mixer_down: DeviceTensor,
mixer_up: DeviceTensor,
mixer_ws: CudaSlice<u8>,
mixed: CudaSlice<f32>,
unused_inject: CudaSlice<f32>,
head: DeviceTensor,
logits: CudaSlice<f32>,
/// The residual and its other half: every half-layer reads one and
/// writes the other, so each layer starts and ends in `residual[0]`.
residual: [CudaSlice<f32>; 2],
step: CudaSlice<i32>,
host_step: HostStep,
vocab: usize,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl NativeDecoder {
/// Loads every layer from the GGUF. `experts` must route on the
/// device; `max_len` sizes the attention caches.
pub fn load(
gguf: &Gguf,
cfg: &TextConfig,
experts: Arc<GgufExpertSource>,
max_len: usize,
) -> Result<Self> {
gdn::configure();
let device = gguf.device().clone();
let s = gdn::shapes(cfg)?;
let a = attn::shapes(cfg, max_len)?;
let m = moe::shapes(cfg)?;
ensure!(
a.heads <= POSITION_SLOTS,
"more query heads than position slots"
);
let ple_layers = cfg.ple_layers();
ensure!(
ple_layers.len() == 1,
"the engine expects exactly one PLE layer"
);
let mut layers = Vec::with_capacity(cfg.num_hidden_layers);
for (i, kind) in cfg
.layer_types
.iter()
.enumerate()
.take(cfg.num_hidden_layers)
{
let mixer = match kind.as_str() {
"linear_attention" => Mixer::Linear(
GdnWeights::load(gguf, i, &s)?,
GdnState::zeroed(&device, &s)?,
),
"full_attention" => Mixer::Full(
AttnWeights::load(gguf, i, &s, &a)?,
AttnCache::new(&device, &a)?,
),
other => bail!("layer {i}: unknown layer type {other}"),
};
layers.push(Layer {
mixer,
moe: MoeWeights::load(gguf, i, &s, &m)?,
});
}
let embed = gguf.upload_raw("token_embd.weight", row_bytes)?;
ensure!(
embed.dims == [s.n_embd as u64, cfg.vocab_size as u64],
"token_embd is {:?}",
embed.dims
);
let head = gguf.upload_bf16("output.weight")?;
ensure!(
head.dims == [s.n_embd as u64, cfg.vocab_size as u64],
"output is {:?}",
head.dims
);
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
// SAFETY: returns null or STEP_SLOTS i32 of pinned host memory.
let host = unsafe { ffi::neuron_strata_pinned_alloc(STEP_SLOTS * 4) }.cast::<i32>();
ensure!(!host.is_null(), "cannot pin the step buffer");
let wide = s.hc * s.n_embd;
Ok(Self {
head_graph: None,
tail_graph: None,
warmed: false,
gdn_sc: GdnScratch::new(&device, &s)?,
attn_sc: AttnScratch::new(&device, &s, &a)?,
moe_sc: MoeScratch::new(&device, &s, &m)?,
embed,
embed_row: device.alloc_zeros::<f32>(s.n_embd)?,
mixer_norm: gguf.upload_f32("output_hc_norm.weight")?,
mixer_down: gguf.upload_bf16("output_hc_down.weight")?,
mixer_up: gguf.upload_bf16("output_hc_up.weight")?,
mixer_ws: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
unused_inject: device.alloc_zeros::<f32>(s.hc)?,
head,
logits: device.alloc_zeros::<f32>(cfg.vocab_size)?,
residual: [
device.alloc_zeros::<f32>(wide)?,
device.alloc_zeros::<f32>(wide)?,
],
step: device.alloc_zeros::<i32>(STEP_SLOTS)?,
host_step: HostStep(host),
vocab: cfg.vocab_size,
ple_layer: ple_layers[0],
device,
s,
a,
m,
layers,
experts,
})
}
pub fn stream(&self) -> *mut c_void {
self.device.cuda_stream().cu_stream() as *mut c_void
}
/// The residual between the segments, `hc * n_embd` f32.
pub fn residual(&self) -> &CudaSlice<f32> {
&self.residual[0]
}
pub fn shapes(&self) -> (GdnShapes, AttnShapes, MoeShapes) {
(self.s, self.a, self.m)
}
/// Writes the step's inputs to the pinned buffer. Must come before
/// `segment_head` and after the previous step's logits were read.
pub fn set_step(&mut self, token: u32, pos: usize) -> Result<()> {
ensure!(
pos < self.a.max_len,
"position {pos} is past the {}-position cache",
self.a.max_len
);
// SAFETY: the buffer holds STEP_SLOTS i32, and no copy from it is
// in flight (the previous step's logits were read).
let host = unsafe { std::slice::from_raw_parts_mut(self.host_step.0, STEP_SLOTS) };
host[..POSITION_SLOTS].fill(pos as i32);
host[POSITION_SLOTS] = token as i32;
Ok(())
}
/// The host-side tier work between steps: what the experts learned
/// from the last step, and admissions.
pub fn adapt(&self) -> Result<()> {
for l in 0..self.layers.len() {
self.experts.adapt(l)?;
}
Ok(())
}
/// After a replay: the usage copies it made are this step's.
pub fn usage_replayed(&self) {
for l in 0..self.layers.len() {
self.experts.usage_replayed(l);
}
}
fn run_layer(&mut self, i: usize) -> Result<()> {
let stream = self.stream();
let (r0, r1) = (address(&self.residual[0]), address(&self.residual[1]));
let positions = address(&self.step);
let layer = &mut self.layers[i];
match &mut layer.mixer {
Mixer::Linear(w, state) => {
gdn::forward(w, state, &mut self.gdn_sc, &self.s, r0, r1, stream)?
}
Mixer::Full(w, cache) => attn::forward(
w,
cache,
&mut self.attn_sc,
&self.s,
&self.a,
positions,
r0,
r1,
stream,
)?,
}
moe::forward(
&layer.moe,
&self.experts,
i,
&mut self.moe_sc,
&self.s,
&self.m,
r1,
r0,
stream,
)
}
/// Segment one: the step inputs, the embedding into every stream,
/// and the layers before the PLE layer. Leaves the residual for the
/// caller to add PLE's contribution to.
pub fn segment_head(&mut self) -> Result<()> {
let stream = self.stream();
// SAFETY: the pinned source holds STEP_SLOTS i32 and the device
// buffer as many; both live as long as `self`.
let status = unsafe {
ffi::neuron_strata_copy_to_device(
address(&self.step) as *mut c_void,
self.host_step.0.cast(),
STEP_SLOTS * 4,
stream,
)
};
ensure!(
status == 0,
"step input copy failed with CUDA status {status}"
);
let (n_embd, hc) = (self.s.n_embd, self.s.hc);
let token = address(&self.step) + (POSITION_SLOTS * 4) as u64;
// SAFETY: the table holds `vocab` rows; `token` is one device id;
// the outputs are sized for one row and `hc` copies of it.
unsafe {
check(
ffi::neuron_embed_rows(
self.embed.ggml_type as i32,
self.embed.address() as *const c_void,
row_bytes(self.embed.ggml_type, n_embd as u64),
token as *const i32,
1,
n_embd as i64,
address(&self.embed_row) as *mut f32,
stream,
),
"embedding",
)?;
check(
ffi::neuron_repeat_row(
address(&self.embed_row) as *const f32,
address(&self.residual[0]) as *mut f32,
n_embd as i32,
hc as i32,
stream,
),
"embedding into the streams",
)?;
}
for i in 0..self.ple_layer {
self.run_layer(i).with_context(|| format!("layer {i}"))?;
}
Ok(())
}
/// Segment one, from its graph: captured on first use after a warm
/// eager step (which sizes every buffer the segment touches), then
/// replayed. The first call of all runs it eagerly.
pub fn run_head(&mut self) -> Result<()> {
self.run_captured(true)
}
/// Segment two, as [`Self::run_head`].
pub fn run_tail(&mut self) -> Result<()> {
self.run_captured(false)
}
fn run_captured(&mut self, head: bool) -> Result<()> {
if !self.warmed {
if head {
self.segment_head()?;
} else {
self.segment_tail()?;
self.warmed = true;
}
return Ok(());
}
let has = if head {
self.head_graph.is_some()
} else {
self.tail_graph.is_some()
};
if !has {
let stream = self.device.cuda_stream();
stream.begin_capture(sys::CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_THREAD_LOCAL)?;
let ran = if head {
self.segment_head()
} else {
self.segment_tail()
};
let graph = stream.end_capture(
sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH,
);
ran.context("while capturing")?;
let graph = graph?.context("capture produced no graph")?;
if head {
self.head_graph = Some(Graph(graph));
} else {
self.tail_graph = Some(Graph(graph));
}
}
let graph = if head {
&self.head_graph
} else {
&self.tail_graph
};
graph.as_ref().expect("captured above").0.launch()?;
if !head {
self.usage_replayed();
}
Ok(())
}
/// Adds `contribution` (`hc * n_embd` f32 on the device) to the
/// residual: the PLE layer's addition before its attention half.
pub fn add_to_residual(&mut self, contribution: u64) -> Result<()> {
let n = (self.s.hc * self.s.n_embd) as i32;
// SAFETY: both buffers hold `n` floats.
unsafe {
check(
ffi::neuron_add_inplace(
address(&self.residual[0]) as *mut f32,
contribution as *const f32,
n,
self.stream(),
),
"ple add",
)
}
}
/// Segment two: the layers from the PLE layer on, the final mixer and
/// the LM head, into the logits buffer.
pub fn segment_tail(&mut self) -> Result<()> {
for i in self.ple_layer..self.layers.len() {
self.run_layer(i).with_context(|| format!("layer {i}"))?;
}
let stream = self.stream();
let s = self.s;
// SAFETY: as in the layers; a null injection is the final
// mixer's, which collapses the streams without a write-back.
unsafe {
check(
ffi::neuron_gr_read(
address(&self.residual[0]) as *const f32,
self.mixer_norm.address() as *const f32,
self.mixer_down.address() as *const u16,
self.mixer_up.address() as *const u16,
std::ptr::null(),
s.eps,
s.n_embd as i64,
s.hc as i64,
s.hc_lr as i64,
address(&self.mixer_ws) as *mut c_void,
address(&self.mixed) as *mut f32,
address(&self.unused_inject) as *mut f32,
stream,
),
"final mixer",
)?;
check(
ffi::neuron_bf16_gemv(
address(&self.mixed) as *const f32,
self.head.address() as *const u16,
address(&self.logits) as *mut f32,
s.n_embd as i64,
self.vocab as i64,
stream,
),
"lm head",
)?;
}
Ok(())
}
/// The final mixer's output of the last step, `n_embd` f32: what the
/// LM head reads.
pub fn mixed(&self) -> &CudaSlice<f32> {
&self.mixed
}
/// The logits of the last step (waits for it).
pub fn logits(&self) -> Result<Vec<f32>> {
Ok(self.device.clone_dtoh(&self.logits)?)
}
/// Clears every sequence state, in place, for a new request.
pub fn reset(&mut self) -> Result<()> {
for layer in &mut self.layers {
match &mut layer.mixer {
Mixer::Linear(_, state) => state.clear(&self.device)?,
Mixer::Full(_, cache) => cache.clear(&self.device)?,
}
}
Ok(())
}
}
@@ -0,0 +1,373 @@
//! A linear-attention (gated delta-net) layer's mixer half, native.
//!
//! One decode token: the attention hyper-connection reads the four
//! residual streams into the mixer's input, the gated delta-net runs on
//! it, and the hyper-connection writes the result back. The MoE half of
//! the layer is separate. Ten kernel launches, against ~180 candle ops:
//!
//! 1. `gr_read`: stream norm, down/up bottleneck, gated mean, injection.
//! 2. quantize the mixer input to q8_1 for the Q8_0 projections.
//! 3. `qkv = attn_qkv @ x` (mmvq).
//! 4. causal conv + SiLU over all channels, L2 norm of the q and k heads.
//! 5. alpha/beta projections (BF16) with their softplus/sigmoid gates.
//! 6. `z = attn_gate @ x` (mmvq).
//! 7. the delta-rule step and the gated RMS norm of its readout.
//! 8. quantize that readout; 9. `out = ssm_out @ y` (mmvq).
//! 10. `gr_write`: the output added back to every stream, gated.
//!
//! Everything is in the GGUF's own layout (value heads tiled by key
//! head) and the state in Strata's: recurrent `[row][head][col]` f32,
//! conv history `[channel][3]` f32.
use std::ffi::{CStr, c_void};
use anyhow::{Result, bail, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
const Q8_1_BLOCK_VALUES: usize = 32;
const Q8_1_BLOCK_BYTES: usize = 36;
const STATE_SIZE: usize = 128;
const CONV_HISTORY: usize = 3;
/// Turns a kernel status into an error naming the step.
pub(crate) fn check(status: i32, what: &str) -> Result<()> {
if status == 0 {
return Ok(());
}
// SAFETY: returns a NUL-terminated string owned by the shim.
let message = unsafe { CStr::from_ptr(ffi::neuron_engine_last_error()) }.to_string_lossy();
bail!("{what} failed (status {status}): {message}")
}
/// Selects the kernel contracts Strata's decode uses. Idempotent.
pub fn configure() {
static ONCE: std::sync::Once = std::sync::Once::new();
// SAFETY: sets process-wide kernel selections before any launch.
ONCE.call_once(|| unsafe { ffi::neuron_engine_configure() });
}
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
/// Shapes of the hyper-connection and the gated delta-net.
#[derive(Debug, Clone, Copy)]
pub struct GdnShapes {
pub n_embd: usize,
pub hc: usize,
pub hc_lr: usize,
pub k_heads: usize,
pub v_heads: usize,
pub eps: f32,
}
impl GdnShapes {
fn qk(&self) -> usize {
self.k_heads * STATE_SIZE
}
fn value(&self) -> usize {
self.v_heads * STATE_SIZE
}
fn channels(&self) -> usize {
2 * self.qk() + self.value()
}
}
/// One layer's weights for the mixer half.
pub struct GdnWeights {
hc_norm: DeviceTensor,
hc_down: DeviceTensor,
hc_up: DeviceTensor,
hc_inject: DeviceTensor,
qkv: DeviceTensor,
gate: DeviceTensor,
out: DeviceTensor,
alpha: DeviceTensor,
beta: DeviceTensor,
conv: DeviceTensor,
norm: DeviceTensor,
dt: DeviceTensor,
ssm_a: DeviceTensor,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl GdnWeights {
pub fn load(gguf: &Gguf, layer: usize, s: &GdnShapes) -> Result<Self> {
let name = |t: &str| format!("blk.{layer}.{t}");
let projection = |t: &str, n_in: usize, n_out: usize| -> Result<DeviceTensor> {
let w = gguf.upload_raw(&name(t), row_bytes)?;
ensure!(
w.dims == [n_in as u64, n_out as u64],
"{} is {:?}, expected [{n_in}, {n_out}]",
name(t),
w.dims
);
// SAFETY: a pure function of its argument.
ensure!(
unsafe { ffi::neuron_strata_mmvq_supported(w.ggml_type as i32) } != 0,
"{}: no mmvq for type {}",
name(t),
w.ggml_type
);
Ok(w)
};
let wide = s.hc * s.n_embd;
let weights = Self {
hc_norm: gguf.upload_f32(&name("hc_attn_norm.weight"))?,
hc_down: gguf.upload_bf16(&name("hc_attn_down.weight"))?,
hc_up: gguf.upload_bf16(&name("hc_attn_up.weight"))?,
hc_inject: gguf.upload_bf16(&name("hc_attn_inject.weight"))?,
qkv: projection("attn_qkv.weight", s.n_embd, s.channels())?,
gate: projection("attn_gate.weight", s.n_embd, s.value())?,
out: projection("ssm_out.weight", s.value(), s.n_embd)?,
alpha: gguf.upload_bf16(&name("ssm_alpha.weight"))?,
beta: gguf.upload_bf16(&name("ssm_beta.weight"))?,
conv: gguf.upload_f32(&name("ssm_conv1d.weight"))?,
norm: gguf.upload_f32(&name("ssm_norm.weight"))?,
dt: gguf.upload_f32(&name("ssm_dt.bias"))?,
ssm_a: gguf.upload_f32(&name("ssm_a"))?,
};
for (t, want) in [
(&weights.hc_norm, wide),
(&weights.hc_down, s.hc_lr * wide),
(&weights.hc_up, wide * s.hc_lr),
(&weights.hc_inject, s.hc * wide),
(&weights.alpha, s.v_heads * s.n_embd),
(&weights.beta, s.v_heads * s.n_embd),
(&weights.conv, s.channels() * (CONV_HISTORY + 1)),
(&weights.norm, STATE_SIZE),
(&weights.dt, s.v_heads),
(&weights.ssm_a, s.v_heads),
] {
ensure!(
t.values() == want,
"layer {layer}: a tensor has {} values, expected {want}",
t.values()
);
}
Ok(weights)
}
}
/// A sequence's recurrent and conv state for one layer.
pub struct GdnState {
pub recurrent: CudaSlice<f32>,
pub conv: CudaSlice<f32>,
}
impl GdnState {
/// Zeroes the state in place: a captured step keeps its addresses.
pub fn clear(&mut self, device: &CudaDevice) -> Result<()> {
let stream = device.cuda_stream();
stream.memset_zeros(&mut self.recurrent)?;
stream.memset_zeros(&mut self.conv)?;
Ok(())
}
pub fn zeroed(device: &CudaDevice, s: &GdnShapes) -> Result<Self> {
Ok(Self {
recurrent: device.alloc_zeros::<f32>(STATE_SIZE * s.v_heads * STATE_SIZE)?,
conv: device.alloc_zeros::<f32>(s.channels() * CONV_HISTORY)?,
})
}
}
/// Intermediate buffers, shared by every layer of a step.
pub struct GdnScratch {
gr: CudaSlice<u8>,
mixed: CudaSlice<f32>,
inject: CudaSlice<f32>,
x_q8: CudaSlice<u8>,
qkv: CudaSlice<f32>,
h: CudaSlice<f32>,
z: CudaSlice<f32>,
gate: CudaSlice<f32>,
beta: CudaSlice<f32>,
y: CudaSlice<f32>,
y_q8: CudaSlice<u8>,
out: CudaSlice<f32>,
}
impl GdnScratch {
pub fn new(device: &CudaDevice, s: &GdnShapes) -> Result<Self> {
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
let q8 = |n: usize| n / Q8_1_BLOCK_VALUES * Q8_1_BLOCK_BYTES;
Ok(Self {
gr: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
inject: device.alloc_zeros::<f32>(s.hc)?,
x_q8: device.alloc_zeros::<u8>(q8(s.n_embd))?,
qkv: device.alloc_zeros::<f32>(s.channels())?,
h: device.alloc_zeros::<f32>(s.channels())?,
z: device.alloc_zeros::<f32>(s.value())?,
gate: device.alloc_zeros::<f32>(s.v_heads)?,
beta: device.alloc_zeros::<f32>(s.v_heads)?,
y: device.alloc_zeros::<f32>(s.value())?,
y_q8: device.alloc_zeros::<u8>(q8(s.value()))?,
out: device.alloc_zeros::<f32>(s.n_embd)?,
})
}
}
/// `y = W x` for a quantized `W` and an f32 `x` already in q8_1.
fn mmvq(w: &DeviceTensor, x_q8: u64, y: u64, stream: *mut c_void) {
// SAFETY: `w` is `dims[1]` rows of `dims[0]`, `x_q8` holds `dims[0]`
// values in q8_1 and `y` has room for `dims[1]` floats.
unsafe {
ffi::neuron_strata_mmvq(
w.ggml_type as i32,
w.address() as *const c_void,
x_q8 as *const c_void,
y as *mut f32,
w.dims[0] as i32,
w.dims[1] as i32,
1,
stream,
)
}
}
fn quantize(x: u64, n: usize, q8: u64, stream: *mut c_void) {
// SAFETY: `x` holds `n` floats and `q8` room for their q8_1 blocks.
unsafe {
ffi::neuron_strata_quantize_q8_1(x as *const f32, 1, n as i64, q8 as *mut c_void, stream)
}
}
/// The mixer half of one linear-attention layer, for one token:
/// `residual_out = residual + gated(gdn(gr_read(residual)))`.
///
/// `residual` and `residual_out` are `hc * n_embd` f32 device buffers and
/// may not alias. Nothing allocates or waits, so this can be captured.
pub fn forward(
w: &GdnWeights,
state: &mut GdnState,
sc: &mut GdnScratch,
s: &GdnShapes,
residual: u64,
residual_out: u64,
stream: *mut c_void,
) -> Result<()> {
let (n_embd, hc, hc_lr) = (s.n_embd as i64, s.hc as i64, s.hc_lr as i64);
let qk = s.qk() as u64 * 4;
// SAFETY (all calls below): every pointer is a live device buffer of
// the size its kernel reads or writes, as allocated in `GdnScratch`,
// `GdnState` and `GdnWeights`, and every launch is on `stream`.
unsafe {
check(
ffi::neuron_gr_read(
residual as *const f32,
w.hc_norm.address() as *const f32,
w.hc_down.address() as *const u16,
w.hc_up.address() as *const u16,
w.hc_inject.address() as *const u16,
s.eps,
n_embd,
hc,
hc_lr,
address(&sc.gr) as *mut c_void,
address(&sc.mixed) as *mut f32,
address(&sc.inject) as *mut f32,
stream,
),
"gr_read",
)?;
quantize(address(&sc.mixed), s.n_embd, address(&sc.x_q8), stream);
mmvq(&w.qkv, address(&sc.x_q8), address(&sc.qkv), stream);
check(
ffi::neuron_gdn_conv_l2(
address(&state.conv) as *mut f32,
address(&sc.qkv) as *const f32,
w.conv.address() as *const f32,
address(&sc.h) as *mut f32,
s.channels() as i32,
(2 * s.k_heads) as i32,
s.eps,
stream,
),
"gdn conv + l2",
)?;
check(
ffi::neuron_gdn_ab(
address(&sc.mixed) as *const f32,
w.alpha.address() as *const u16,
w.beta.address() as *const u16,
w.dt.address() as *const f32,
w.ssm_a.address() as *const f32,
address(&sc.gate) as *mut f32,
address(&sc.beta) as *mut f32,
s.n_embd as i32,
s.v_heads as i32,
stream,
),
"gdn alpha/beta",
)?;
mmvq(&w.gate, address(&sc.x_q8), address(&sc.z), stream);
let h = address(&sc.h);
check(
ffi::neuron_gdn_step_norm(
address(&state.recurrent) as *mut f32,
h as *const f32,
(h + qk) as *const f32,
(h + 2 * qk) as *const f32,
address(&sc.gate) as *const f32,
address(&sc.beta) as *const f32,
address(&sc.z) as *const f32,
w.norm.address() as *const f32,
s.eps,
address(&sc.y) as *mut f32,
s.k_heads as i32,
s.v_heads as i32,
stream,
),
"gdn step + norm",
)?;
quantize(address(&sc.y), s.value(), address(&sc.y_q8), stream);
mmvq(&w.out, address(&sc.y_q8), address(&sc.out), stream);
check(
ffi::neuron_gr_write(
residual as *const f32,
address(&sc.out) as *const f32,
address(&sc.inject) as *const f32,
n_embd,
hc,
hc_lr,
residual_out as *mut f32,
stream,
),
"gr_write",
)?;
}
Ok(())
}
/// The shapes of a qwen4_exp config.
pub fn shapes(cfg: &super::super::config::TextConfig) -> Result<GdnShapes> {
let s = GdnShapes {
n_embd: cfg.hidden_size,
hc: cfg.hc_count,
hc_lr: cfg.hc_lowrank,
k_heads: cfg.linear_num_key_heads,
v_heads: cfg.linear_num_value_heads,
eps: cfg.rms_norm_eps as f32,
};
ensure!(
cfg.linear_key_head_dim == STATE_SIZE && cfg.linear_value_head_dim == STATE_SIZE,
"the native gated delta-net is built for 128-wide heads"
);
ensure!(
s.v_heads.is_multiple_of(s.k_heads),
"value heads must be a multiple of key heads"
);
Ok(s)
}
@@ -0,0 +1,18 @@
//! The native qwen4_exp decode engine (#427).
//!
//! A decode step as fixed work over buffers allocated once: Strata's
//! kernels (and neuron's own) driven over device pointers, so the step can
//! be captured as one CUDA graph. Candle remains the loader for
//! everything else, the prompt path, and the parity oracle every layer
//! here is checked against.
pub mod weights;
#[cfg(feature = "strata-kernels")]
pub mod attn;
#[cfg(feature = "strata-kernels")]
pub mod decoder;
#[cfg(feature = "strata-kernels")]
pub mod gdn;
#[cfg(feature = "strata-kernels")]
pub mod moe;
@@ -0,0 +1,345 @@
//! A decoder layer's MoE half, native.
//!
//! One decode token: the FFN hyper-connection reads the streams into the
//! block's input; the router picks ten experts on the device; the routed
//! experts run on the grouped kernel through the device-routed expert
//! path (#425), misses gathered into the arena; the shared expert runs
//! beside them; the weighted combination is written back to every
//! stream through the hyper-connection. Every layer, linear or full
//! attention, has this half.
use std::ffi::c_void;
use anyhow::{Result, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use super::gdn::{GdnShapes, check};
use super::weights::{DeviceTensor, Gguf};
use crate::cuda::strata as ffi;
use crate::harness::arch::qwen4_exp::native_experts::GgufExpertSource;
const Q8_1_BLOCK_VALUES: usize = 32;
const Q8_1_BLOCK_BYTES: usize = 36;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
/// Routing and expert widths.
#[derive(Debug, Clone, Copy)]
pub struct MoeShapes {
pub experts: usize,
pub k: usize,
pub n_ff: usize,
}
pub struct MoeWeights {
hc_norm: DeviceTensor,
hc_down: DeviceTensor,
hc_up: DeviceTensor,
hc_inject: DeviceTensor,
router: DeviceTensor,
shared_gate: DeviceTensor,
shared_up: DeviceTensor,
shared_down: DeviceTensor,
shared_scale: DeviceTensor,
}
fn row_bytes(ggml_type: u32, n: u64) -> usize {
// SAFETY: a pure function of its arguments.
unsafe { ffi::neuron_strata_row_bytes(ggml_type as i32, n as i64) }
}
impl MoeWeights {
pub fn load(gguf: &Gguf, layer: usize, s: &GdnShapes, m: &MoeShapes) -> Result<Self> {
let name = |t: &str| format!("blk.{layer}.{t}");
let projection = |t: &str, n_in: usize, n_out: usize| -> Result<DeviceTensor> {
let w = gguf.upload_raw(&name(t), row_bytes)?;
ensure!(
w.dims == [n_in as u64, n_out as u64],
"{} is {:?}, expected [{n_in}, {n_out}]",
name(t),
w.dims
);
// SAFETY: a pure function of its argument.
ensure!(
unsafe { ffi::neuron_strata_mmvq_supported(w.ggml_type as i32) } != 0,
"{}: no mmvq for type {}",
name(t),
w.ggml_type
);
Ok(w)
};
let wide = s.hc * s.n_embd;
let w = Self {
hc_norm: gguf.upload_f32(&name("hc_ffn_norm.weight"))?,
hc_down: gguf.upload_bf16(&name("hc_ffn_down.weight"))?,
hc_up: gguf.upload_bf16(&name("hc_ffn_up.weight"))?,
hc_inject: gguf.upload_bf16(&name("hc_ffn_inject.weight"))?,
router: gguf.upload_bf16(&name("ffn_gate_inp.weight"))?,
shared_gate: projection("ffn_gate_shexp.weight", s.n_embd, m.n_ff)?,
shared_up: projection("ffn_up_shexp.weight", s.n_embd, m.n_ff)?,
shared_down: projection("ffn_down_shexp.weight", m.n_ff, s.n_embd)?,
shared_scale: gguf.upload_bf16(&name("ffn_gate_inp_shexp.weight"))?,
};
for (t, want) in [
(&w.hc_norm, wide),
(&w.hc_down, s.hc_lr * wide),
(&w.hc_up, wide * s.hc_lr),
(&w.hc_inject, s.hc * wide),
(&w.router, m.experts * s.n_embd),
(&w.shared_scale, s.n_embd),
] {
ensure!(
t.values() == want,
"layer {layer}: a tensor has {} values, expected {want}",
t.values()
);
}
Ok(w)
}
}
pub struct MoeScratch {
gr: CudaSlice<u8>,
mixed: CudaSlice<f32>,
inject: CudaSlice<f32>,
logits: CudaSlice<f32>,
ids: CudaSlice<i32>,
weights: CudaSlice<f32>,
parts: CudaSlice<f32>,
w_route: CudaSlice<f32>,
x_q8: CudaSlice<u8>,
gate: CudaSlice<f32>,
up: CudaSlice<f32>,
h: CudaSlice<f32>,
h_q8: CudaSlice<u8>,
shared: CudaSlice<f32>,
scale: CudaSlice<f32>,
out: CudaSlice<f32>,
}
impl MoeScratch {
/// The experts the last step routed to, for inspection.
pub fn routed(&self, device: &CudaDevice) -> Result<(Vec<i32>, Vec<f32>)> {
Ok((
device.clone_dtoh(&self.ids)?,
device.clone_dtoh(&self.logits)?,
))
}
pub fn new(device: &CudaDevice, s: &GdnShapes, m: &MoeShapes) -> Result<Self> {
// SAFETY: a pure function of its arguments.
let gr_bytes =
unsafe { ffi::neuron_gr_workspace_bytes(s.n_embd as i64, s.hc as i64, s.hc_lr as i64) };
let q8 = |n: usize| n / Q8_1_BLOCK_VALUES * Q8_1_BLOCK_BYTES;
Ok(Self {
gr: device.alloc_zeros::<u8>(gr_bytes)?,
mixed: device.alloc_zeros::<f32>(s.n_embd)?,
inject: device.alloc_zeros::<f32>(s.hc)?,
logits: device.alloc_zeros::<f32>(m.experts)?,
ids: device.alloc_zeros::<i32>(m.k)?,
weights: device.alloc_zeros::<f32>(m.k)?,
parts: device.alloc_zeros::<f32>(m.k * s.n_embd)?,
w_route: device.alloc_zeros::<f32>(m.k)?,
x_q8: device.alloc_zeros::<u8>(q8(s.n_embd))?,
gate: device.alloc_zeros::<f32>(m.n_ff)?,
up: device.alloc_zeros::<f32>(m.n_ff)?,
h: device.alloc_zeros::<f32>(m.n_ff)?,
h_q8: device.alloc_zeros::<u8>(q8(m.n_ff))?,
shared: device.alloc_zeros::<f32>(s.n_embd)?,
scale: device.alloc_zeros::<f32>(1)?,
out: device.alloc_zeros::<f32>(s.n_embd)?,
})
}
}
fn mmvq(w: &DeviceTensor, x_q8: u64, y: u64, stream: *mut c_void) {
// SAFETY: `w` is `dims[1]` rows of `dims[0]`, `x_q8` holds `dims[0]`
// values in q8_1 and `y` has room for `dims[1]` floats.
unsafe {
ffi::neuron_strata_mmvq(
w.ggml_type as i32,
w.address() as *const c_void,
x_q8 as *const c_void,
y as *mut f32,
w.dims[0] as i32,
w.dims[1] as i32,
1,
stream,
)
}
}
fn quantize(x: u64, n: usize, q8: u64, stream: *mut c_void) {
// SAFETY: `x` holds `n` floats and `q8` room for their q8_1 blocks.
unsafe {
ffi::neuron_strata_quantize_q8_1(x as *const f32, 1, n as i64, q8 as *mut c_void, stream)
}
}
/// The MoE half of layer `layer`, for one token:
/// `residual_out = residual + gated(moe(gr_read(residual)))`.
///
/// The experts come from `experts`, which must route on the device. It
/// does not adapt the expert tier; the caller does that between steps.
#[allow(clippy::too_many_arguments)]
pub fn forward(
w: &MoeWeights,
experts: &GgufExpertSource,
layer: usize,
sc: &mut MoeScratch,
s: &GdnShapes,
m: &MoeShapes,
residual: u64,
residual_out: u64,
stream: *mut c_void,
) -> Result<()> {
let (n_embd, hc, hc_lr) = (s.n_embd as i64, s.hc as i64, s.hc_lr as i64);
// SAFETY (all calls below): every pointer is a live device buffer of
// the size its kernel reads or writes, as allocated in `MoeScratch`
// and `MoeWeights`, and every launch is on `stream`.
unsafe {
check(
ffi::neuron_gr_read(
residual as *const f32,
w.hc_norm.address() as *const f32,
w.hc_down.address() as *const u16,
w.hc_up.address() as *const u16,
w.hc_inject.address() as *const u16,
s.eps,
n_embd,
hc,
hc_lr,
address(&sc.gr) as *mut c_void,
address(&sc.mixed) as *mut f32,
address(&sc.inject) as *mut f32,
stream,
),
"ffn gr_read",
)?;
check(
ffi::neuron_bf16_gemv(
address(&sc.mixed) as *const f32,
w.router.address() as *const u16,
address(&sc.logits) as *mut f32,
n_embd,
m.experts as i64,
stream,
),
"router",
)?;
check(
ffi::neuron_router_top10(
address(&sc.logits) as *const f32,
address(&sc.ids) as *mut i32,
address(&sc.weights) as *mut f32,
stream,
),
"router top-10",
)?;
}
experts.launch_routed(
layer,
address(&sc.mixed),
address(&sc.ids),
address(&sc.weights),
1,
m.k,
address(&sc.parts),
address(&sc.w_route),
stream,
)?;
experts.record_usage(layer, address(&sc.ids), m.k)?;
quantize(address(&sc.mixed), s.n_embd, address(&sc.x_q8), stream);
mmvq(&w.shared_gate, address(&sc.x_q8), address(&sc.gate), stream);
mmvq(&w.shared_up, address(&sc.x_q8), address(&sc.up), stream);
// SAFETY: as above.
unsafe {
check(
ffi::neuron_swiglu(
address(&sc.gate) as *const f32,
address(&sc.up) as *const f32,
address(&sc.h) as *mut f32,
m.n_ff as i32,
stream,
),
"shared swiglu",
)?;
}
quantize(address(&sc.h), m.n_ff, address(&sc.h_q8), stream);
mmvq(
&w.shared_down,
address(&sc.h_q8),
address(&sc.shared),
stream,
);
// SAFETY: as above.
unsafe {
check(
ffi::neuron_bf16_gemv(
address(&sc.mixed) as *const f32,
w.shared_scale.address() as *const u16,
address(&sc.scale) as *mut f32,
n_embd,
1,
stream,
),
"shared gate",
)?;
check(
ffi::neuron_scale_by_sigmoid(
address(&sc.shared) as *mut f32,
address(&sc.scale) as *const f32,
s.n_embd as i32,
stream,
),
"shared gate apply",
)?;
check(
ffi::neuron_moe_combine(
address(&sc.parts) as *const f32,
address(&sc.w_route) as *const f32,
address(&sc.shared) as *const f32,
address(&sc.out) as *mut f32,
n_embd,
m.k as i64,
stream,
),
"moe combine",
)?;
check(
ffi::neuron_gr_write(
residual as *const f32,
address(&sc.out) as *const f32,
address(&sc.inject) as *const f32,
n_embd,
hc,
hc_lr,
residual_out as *mut f32,
stream,
),
"ffn gr_write",
)?;
}
Ok(())
}
/// The MoE shapes of a qwen4_exp config.
pub fn shapes(cfg: &super::super::config::TextConfig) -> Result<MoeShapes> {
let m = MoeShapes {
experts: cfg.num_experts,
k: cfg.num_experts_per_tok,
n_ff: cfg.moe_intermediate_size,
};
ensure!(
m.experts == 512 && m.k == 10,
"the native router is built for 512 experts, top 10"
);
ensure!(
cfg.shared_expert_intermediate_size == m.n_ff,
"the shared expert is assumed as wide as a routed one"
);
Ok(m)
}
@@ -0,0 +1,346 @@
//! GGUF tensors as the native decode engine (#427) holds them.
//!
//! The engine reads the GGUF as it is stored: llama.cpp's layout and
//! head order (the linear-attention value heads tiled by key head), the
//! norm weights already `1 + w`, `ssm_a` already `-exp(A_log)`. That is
//! the form Strata's kernels take. Quantized projections stay quantized;
//! the tensors Strata's pack converts to BF16 (the hyper-connection mixes
//! and injections, the GDN alpha/beta, the routers) are converted the
//! same way here, rounding to nearest even.
/// ggml type ids the engine handles.
pub const GGML_F32: u32 = 0;
pub const GGML_F16: u32 = 1;
pub const GGML_Q8_0: u32 = 8;
pub const GGML_Q6_K: u32 = 14;
pub const GGML_BF16: u32 = 30;
const Q8_0_BLOCK_VALUES: usize = 32;
const Q8_0_BLOCK_BYTES: usize = 34;
/// IEEE half to single, subnormals included.
pub fn f16_to_f32(h: u16) -> f32 {
let sign = ((h >> 15) & 1) as u32;
let exp = ((h >> 10) & 0x1f) as u32;
let man = (h & 0x3ff) as u32;
let bits = match (exp, man) {
(0, 0) => sign << 31,
(0, _) => {
// Subnormal: renormalise.
let shift = man.leading_zeros() - 21;
let man = (man << shift) & 0x3ff;
(sign << 31) | ((113 - shift) << 23) | (man << 13)
}
(0x1f, _) => (sign << 31) | (0xff << 23) | (man << 13),
_ => (sign << 31) | ((exp + 112) << 23) | (man << 13),
};
f32::from_bits(bits)
}
/// Single to BF16 bits, round to nearest even (NaN stays NaN).
pub fn f32_to_bf16(x: f32) -> u16 {
let bits = x.to_bits();
if x.is_nan() {
return ((bits >> 16) | 0x40) as u16;
}
let round = 0x7fff + ((bits >> 16) & 1);
(bits.wrapping_add(round) >> 16) as u16
}
/// Q8_0 blocks (an f16 scale, then 32 signed bytes) to f32.
pub fn q8_0_to_f32(bytes: &[u8]) -> Vec<f32> {
let mut out = Vec::with_capacity(bytes.len() / Q8_0_BLOCK_BYTES * Q8_0_BLOCK_VALUES);
for block in bytes.as_chunks::<Q8_0_BLOCK_BYTES>().0 {
let d = f16_to_f32(u16::from_le_bytes([block[0], block[1]]));
out.extend(block[2..].iter().map(|&q| d * f32::from(q as i8)));
}
out
}
const Q6_K_BLOCK_VALUES: usize = 256;
const Q6_K_BLOCK_BYTES: usize = 210;
/// Q6_K blocks to f32, as ggml's `dequantize_row_q6_K`: per 256 values,
/// 128 bytes of low nibbles, 64 of high bit pairs, 16 signed scales and
/// an f16 scale.
pub fn q6_k_to_f32(bytes: &[u8]) -> Vec<f32> {
let mut out = Vec::with_capacity(bytes.len() / Q6_K_BLOCK_BYTES * Q6_K_BLOCK_VALUES);
for block in bytes.as_chunks::<Q6_K_BLOCK_BYTES>().0 {
let (ql, rest) = block.split_at(128);
let (qh, rest) = rest.split_at(64);
let (sc, d) = rest.split_at(16);
let d = f16_to_f32(u16::from_le_bytes([d[0], d[1]]));
let mut y = [0f32; Q6_K_BLOCK_VALUES];
for half in 0..2 {
let (ql, qh, sc) = (&ql[64 * half..], &qh[32 * half..], &sc[8 * half..]);
let y = &mut y[128 * half..];
for l in 0..32 {
let is = l / 16;
let q = |low: u8, shift: u32| -> f32 {
f32::from(((low | (((qh[l] >> shift) & 3) << 4)) as i8) - 32)
};
let s = |i: usize| f32::from(sc[i] as i8);
y[l] = d * s(is) * q(ql[l] & 0xf, 0);
y[l + 32] = d * s(is + 2) * q(ql[l + 32] & 0xf, 2);
y[l + 64] = d * s(is + 4) * q(ql[l] >> 4, 4);
y[l + 96] = d * s(is + 6) * q(ql[l + 32] >> 4, 6);
}
}
out.extend_from_slice(&y);
}
out
}
/// A tensor's values as f32, from the GGUF types the engine converts.
pub fn to_f32(bytes: &[u8], ggml_type: u32) -> Option<Vec<f32>> {
Some(match ggml_type {
GGML_F32 => bytes
.as_chunks::<4>()
.0
.iter()
.map(|&b| f32::from_le_bytes(b))
.collect(),
GGML_F16 => bytes
.as_chunks::<2>()
.0
.iter()
.map(|&b| f16_to_f32(u16::from_le_bytes(b)))
.collect(),
GGML_BF16 => bytes
.as_chunks::<2>()
.0
.iter()
.map(|&b| f32::from_bits(u32::from(u16::from_le_bytes(b)) << 16))
.collect(),
GGML_Q8_0 => q8_0_to_f32(bytes),
GGML_Q6_K => q6_k_to_f32(bytes),
_ => return None,
})
}
/// Bytes a tensor of `ggml_type` with `values` elements occupies, for
/// the types the engine reads whole.
pub fn tensor_bytes(ggml_type: u32, values: usize) -> Option<usize> {
Some(match ggml_type {
GGML_F32 => values * 4,
GGML_F16 | GGML_BF16 => values * 2,
GGML_Q8_0 if values.is_multiple_of(Q8_0_BLOCK_VALUES) => {
values / Q8_0_BLOCK_VALUES * Q8_0_BLOCK_BYTES
}
GGML_Q6_K if values.is_multiple_of(Q6_K_BLOCK_VALUES) => {
values / Q6_K_BLOCK_VALUES * Q6_K_BLOCK_BYTES
}
_ => return None,
})
}
#[cfg(feature = "strata-kernels")]
pub use device::{DeviceTensor, Gguf};
#[cfg(feature = "strata-kernels")]
mod device {
use std::fs::File;
use std::path::Path;
use anyhow::{Context, Result, bail, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use memmap2::Mmap;
use super::{GGML_BF16, GGML_F32, f32_to_bf16, tensor_bytes, to_f32};
use crate::harness::arch::qwen4_exp::gguf_index::{GgufIndex, GgufTensor};
/// A tensor on the device, in whatever form it was uploaded.
pub struct DeviceTensor {
buf: CudaSlice<u8>,
pub ggml_type: u32,
/// ggml order: `dims[0]` is the fastest-varying (the input width
/// of a projection).
pub dims: Vec<u64>,
}
impl DeviceTensor {
pub fn address(&self) -> u64 {
self.buf.device_ptr(self.buf.stream()).0
}
pub fn values(&self) -> usize {
self.dims.iter().product::<u64>() as usize
}
}
/// The GGUF's shards, mapped, and the device tensors go to.
pub struct Gguf {
pub index: GgufIndex,
maps: Vec<Mmap>,
device: CudaDevice,
}
impl Gguf {
pub fn open(first: &Path, device: &CudaDevice) -> Result<Self> {
let index = GgufIndex::open(first)?;
let mut maps = Vec::with_capacity(index.shards.len());
for path in &index.shards {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
// SAFETY: model files are not modified while serving.
maps.push(
unsafe { Mmap::map(&file) }
.with_context(|| format!("map {}", path.display()))?,
);
}
Ok(Self {
index,
maps,
device: device.clone(),
})
}
fn tensor(&self, name: &str) -> Result<&GgufTensor> {
self.index
.tensors
.get(name)
.with_context(|| format!("the GGUF has no {name}"))
}
/// The tensor's stored bytes. Only for the types whose size the
/// engine knows; quantized projections use `upload_raw`.
fn bytes(&self, name: &str, size: usize) -> Result<&[u8]> {
let t = self.tensor(name)?;
let map = &self.maps[t.shard];
let start = t.offset as usize;
ensure!(start + size <= map.len(), "{name} runs past its shard");
Ok(&map[start..start + size])
}
fn upload(&self, host: &[u8], ggml_type: u32, dims: Vec<u64>) -> Result<DeviceTensor> {
// SAFETY: written in full by the copy below.
let mut buf = unsafe { self.device.alloc::<u8>(host.len().max(1)) }?;
self.device.memcpy_htod(host, &mut buf)?;
Ok(DeviceTensor {
buf,
ggml_type,
dims,
})
}
/// The tensor as stored, for the kernels that read its format.
/// `row_bytes` gives the size of one `dims[0]`-wide row.
pub fn upload_raw(
&self,
name: &str,
row_bytes: impl Fn(u32, u64) -> usize,
) -> Result<DeviceTensor> {
let t = self.tensor(name)?;
let rows: u64 = t.dims.iter().skip(1).product();
let size = row_bytes(t.ggml_type, t.dims[0]) * rows as usize;
ensure!(size > 0, "{name}: no row size for type {}", t.ggml_type);
let host = self.bytes(name, size)?;
self.upload(host, t.ggml_type, t.dims.clone())
}
fn values_f32(&self, name: &str) -> Result<(Vec<f32>, Vec<u64>)> {
let t = self.tensor(name)?;
let n: u64 = t.dims.iter().product();
let Some(size) = tensor_bytes(t.ggml_type, n as usize) else {
bail!("{name}: the engine cannot convert type {}", t.ggml_type);
};
let values = to_f32(self.bytes(name, size)?, t.ggml_type)
.with_context(|| format!("{name}: unconvertible type {}", t.ggml_type))?;
Ok((values, t.dims.clone()))
}
/// The tensor as f32.
pub fn upload_f32(&self, name: &str) -> Result<DeviceTensor> {
let (values, dims) = self.values_f32(name)?;
let host: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
self.upload(&host, GGML_F32, dims)
}
/// The tensor as BF16, rounded to nearest even.
pub fn upload_bf16(&self, name: &str) -> Result<DeviceTensor> {
let (values, dims) = self.values_f32(name)?;
let host: Vec<u8> = values
.iter()
.flat_map(|&v| f32_to_bf16(v).to_le_bytes())
.collect();
self.upload(&host, GGML_BF16, dims)
}
pub fn device(&self) -> &CudaDevice {
&self.device
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn half_precision_converts_exactly() {
assert_eq!(f16_to_f32(0x3c00), 1.0);
assert_eq!(f16_to_f32(0xc000), -2.0);
assert_eq!(f16_to_f32(0x0000), 0.0);
assert_eq!(f16_to_f32(0x7bff), 65504.0);
// Smallest subnormal, 2^-24, and a larger one, 2^-15.
assert_eq!(f16_to_f32(0x0001), 2f32.powi(-24));
assert_eq!(f16_to_f32(0x0200), 2f32.powi(-15));
assert!(f16_to_f32(0x7c00).is_infinite());
}
/// Ties go to the even mantissa, and anything past half rounds up.
#[test]
fn bf16_rounds_to_nearest_even() {
assert_eq!(f32_to_bf16(1.0), 0x3f80);
// 1 + 2^-8 is exactly halfway between 1 and 1 + 2^-7: to even.
assert_eq!(f32_to_bf16(1.0 + 2f32.powi(-8)), 0x3f80);
// 1 + 3 * 2^-8 is halfway between 1 + 2^-7 (odd) and 1 + 2^-6.
assert_eq!(f32_to_bf16(1.0 + 3.0 * 2f32.powi(-8)), 0x3f82);
// Just past halfway rounds up.
assert_eq!(f32_to_bf16(1.0 + 2f32.powi(-8) + 2f32.powi(-20)), 0x3f81);
assert_eq!(f32_to_bf16(-2.5), 0xc020);
}
/// One Q6_K block built by hand: every 6-bit value is assembled from
/// its low nibble and high bit pair, offset by 32, and scaled by its
/// group's scale and the block scale.
#[test]
fn q6_k_assembles_six_bit_values() {
let mut block = vec![0u8; 210];
// Value 0: low nibble 5, high bits 0b10 -> 0b10_0101 = 37, -32 = 5.
block[0] = 0x05;
block[128] = 0b10;
// Value 96 (fourth quarter: ql[32]'s high nibble, qh[0] bits 6-7):
// nibble 0xf, high bits 0b01 -> 0b01_1111 = 31, -32 = -1.
block[32] = 0xf0;
block[128] |= 0b01 << 6;
// Scales: group 0 = 3, group 6 (value 96's) = -2.
block[192] = 3;
block[198] = (-2i8) as u8;
block[208..210].copy_from_slice(&0x3800u16.to_le_bytes()); // 0.5
let y = q6_k_to_f32(&block);
assert_eq!(y.len(), 256);
assert_eq!(y[0], 0.5 * 3.0 * 5.0);
// scale 0.5, group scale -2, value -1.
assert_eq!(y[96], 1.0);
// An all-zero position reads 0 - 32 = -32 times its scale.
assert_eq!(y[1], 0.5 * 3.0 * -32.0);
assert_eq!(tensor_bytes(GGML_Q6_K, 512), Some(420));
}
#[test]
fn q8_0_blocks_scale_their_bytes() {
let mut block = vec![0u8; 34];
block[..2].copy_from_slice(&0x3800u16.to_le_bytes()); // 0.5
for (i, b) in block[2..].iter_mut().enumerate() {
*b = (i as i8 - 16) as u8;
}
let values = q8_0_to_f32(&block);
assert_eq!(values.len(), 32);
assert_eq!(values[0], -8.0);
assert_eq!(values[16], 0.0);
assert_eq!(values[31], 7.5);
assert_eq!(tensor_bytes(GGML_Q8_0, 64), Some(68));
assert_eq!(tensor_bytes(GGML_Q8_0, 33), None);
}
}
@@ -36,6 +36,8 @@
pub mod config;
pub mod decoder;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod engine;
pub mod full_attn;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod gguf_dense;
@@ -238,6 +238,25 @@ impl Qwen4ExpForCausalLM {
Ok(self.lm_head.forward(&x)?)
}
/// The PLE contribution for one decode token, from the native
/// engine's residual `h` (`(1, 1, hidden * hc)`, any float dtype): the
/// n-gram rows are gathered for `input_ids` (advancing the carried
/// ids, as a forward would) and the PLE layer's block run on them.
/// `None` without PLE. Returned in `h`'s dtype.
pub fn ple_contribution(&mut self, input_ids: &Tensor, h: &Tensor) -> Result<Option<Tensor>> {
let Some(ngram) = &mut self.ngram else {
return Ok(None);
};
let e = ngram.forward(&ids_to_i64(input_ids)?, &self.device, self.dtype)?;
let hm = h.to_dtype(self.dtype)?;
for layer in &mut self.layers {
if let Some(out) = layer.ple_contribution(&hm, &e)? {
return Ok(Some(out.to_dtype(h.dtype())?));
}
}
Ok(None)
}
/// Logits for the **last** position, `(B, 1, vocab)`.
pub fn forward(&mut self, input_ids: &Tensor, offset: usize) -> Result<Tensor> {
Ok(self.forward_inner(input_ids, offset)?.0)
@@ -513,7 +532,7 @@ fn ids_to_i64(input_ids: &Tensor) -> Result<Vec<Vec<i64>>> {
/// identically to Qwen3.6 (spec §7) — so `qwen3_5`'s module is reused
/// as-is, through the parts it actually needs rather than through a
/// fabricated config.
fn rotary_for(cfg: &TextConfig, dtype: DType, device: &Device) -> Result<RotaryEmbedding> {
pub fn rotary_for(cfg: &TextConfig, dtype: DType, device: &Device) -> Result<RotaryEmbedding> {
RotaryEmbedding::from_parts(
dtype,
cfg.head_dim,
@@ -117,39 +117,60 @@ impl Drop for HostStore {
}
}
/// A CUDA event, for knowing when a queued copy has landed.
struct Event(*mut c_void);
// SAFETY: a CUDA event handle may be used from any thread.
unsafe impl Send for Event {}
impl Event {
fn new() -> candle_core::Result<Self> {
// SAFETY: returns a fresh event or null.
let e = unsafe { ffi::neuron_strata_event_new() };
if e.is_null() {
candle_core::bail!("cannot create a CUDA event");
}
Ok(Self(e))
}
}
impl Drop for Event {
fn drop(&mut self) {
// SAFETY: created by `new`, destroyed once.
unsafe { ffi::neuron_strata_event_free(self.0) };
}
}
/// One layer's last device-routed ids, on their way to the host so the
/// tier can learn from them between steps.
///
/// No event guards the read: every caller adapts only after it has read
/// the previous step's logits, which waits for the whole step, and an
/// event recorded inside a captured step cannot be waited on from the
/// host.
struct Pending {
ids: PinnedBuffer,
ids: MappedIds,
entries: usize,
event: Event,
recorded: bool,
}
/// Mapped pinned host memory for a layer's ids: written by a kernel
/// through `device`, read by the host at `ptr` (#427).
struct MappedIds {
ptr: *mut u32,
device: u64,
len: usize,
}
// SAFETY: plain host memory, read by the host only after the step whose
// kernel writes it has been waited on.
unsafe impl Send for MappedIds {}
impl MappedIds {
fn new(words: usize) -> candle_core::Result<Self> {
// SAFETY: returns null or `words * 4` bytes of mapped host memory.
let ptr = unsafe { ffi::neuron_strata_host_alloc_mapped(words * 4) }.cast::<u32>();
if ptr.is_null() {
candle_core::bail!("cannot pin {words} words for expert usage");
}
// SAFETY: as allocated just above.
let device = unsafe { ffi::neuron_strata_host_device_ptr(ptr.cast()) };
if device == 0 {
// SAFETY: allocated above, freed once.
unsafe { ffi::neuron_strata_pinned_free(ptr.cast()) };
candle_core::bail!("the device cannot address the expert usage buffer");
}
Ok(Self {
ptr,
device,
len: words,
})
}
}
impl Drop for MappedIds {
fn drop(&mut self) {
// SAFETY: allocated by `neuron_strata_host_alloc_mapped`, freed once.
unsafe { ffi::neuron_strata_pinned_free(self.ptr.cast()) };
}
}
/// Decode-sized MoE layers routed on the device (#425).
struct DeviceRouting {
store: HostStore,
@@ -161,6 +182,12 @@ struct DeviceRouting {
pending: Vec<Mutex<Option<Pending>>>,
/// Misses a layer may admit to the tier per step.
admit_per_layer: usize,
/// Buffers for device-routed layers only, sized once for the largest
/// decode batch so they never move: a captured decode step holds
/// their addresses (#427). Prompt chunks use the source's workspace.
workspace: Mutex<Workspace>,
/// The largest blob of any layer, which sizes the decode arena.
max_blob_bytes: usize,
}
/// A CUDA memory pool for the tier's experts alone.
@@ -676,6 +703,8 @@ impl GgufExpertSource {
host_table: host_table_d,
pending,
admit_per_layer,
workspace: Mutex::new(Workspace::default()),
max_blob_bytes: self.layers.iter().map(|l| l.blob_bytes).max().unwrap_or(0),
})
}
@@ -709,7 +738,7 @@ impl GgufExpertSource {
/// Lets the tier learn from `layer`'s previous device-routed step:
/// counts its uses and admits up to `admit_per_layer` misses, each a
/// queued copy from the host store and a table write.
fn adapt(&self, layer_index: usize) -> candle_core::Result<()> {
pub fn adapt(&self, layer_index: usize) -> candle_core::Result<()> {
let (Some(routing), Some(tier)) = (&self.routing, &self.tier) else {
return Ok(());
};
@@ -717,11 +746,6 @@ impl GgufExpertSource {
let Some(pending) = guard.as_mut().filter(|p| p.recorded) else {
return Ok(());
};
// SAFETY: recorded after the copy into `ids` was queued.
let status = unsafe { ffi::neuron_strata_event_sync(pending.event.0) };
if status != 0 {
candle_core::bail!("expert usage copy failed with CUDA status {status}");
}
pending.recorded = false;
// SAFETY: the copy above wrote `entries` ids, and the next copy
// into this buffer is only queued after this read.
@@ -784,40 +808,9 @@ impl GgufExpertSource {
weights: &Tensor,
k: usize,
) -> candle_core::Result<Tensor> {
let routing = self
.routing
.as_ref()
.ok_or_else(|| candle_err("device routing is not enabled"))?;
let layer = &self.layers[layer_index];
let (rows, hidden) = xs.dims2()?;
let entries = rows * k;
let experts = routing.table.len() / self.layers.len();
self.adapt(layer_index)?;
let mut workspace = self.workspace.lock().map_err(candle_err)?;
let ws = &mut *workspace;
let cap_groups = entries.min(experts);
ensure_capacity(&self.device, &mut ws.grp_ptr, cap_groups)?;
ensure_capacity(&self.device, &mut ws.grp_start, cap_groups + 1)?;
ensure_capacity(&self.device, &mut ws.n_groups, 1)?;
ensure_capacity(&self.device, &mut ws.ent_dst, entries)?;
ensure_capacity(&self.device, &mut ws.ent_tok, entries)?;
ensure_capacity(&self.device, &mut ws.miss_src, cap_groups)?;
ensure_capacity(&self.device, &mut ws.n_miss, 1)?;
// A miss is copied into the arena by the gather below, so the
// expert kernel reads VRAM only: reading host memory from the
// kernel itself is latency-bound at decode's few warps.
ensure_capacity(&self.device, &mut ws.arena, cap_groups * layer.blob_bytes)?;
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 ids = ids.to_dtype(DType::U32)?.contiguous()?;
let weights = weights.to_dtype(DType::F32)?.contiguous()?;
let x = xs.to_dtype(DType::F32)?.contiguous()?;
@@ -826,18 +819,111 @@ impl GgufExpertSource {
// SAFETY: written in full by the expert kernel.
let out = unsafe { self.device.alloc::<f32>(entries * hidden)? };
let stream = self.device.cuda_stream().cu_stream() as *mut c_void;
self.launch_routed(
layer_index,
tensor_address::<f32>(&x)?,
tensor_address::<u32>(&ids)?,
tensor_address::<f32>(&weights)?,
rows,
k,
device_address(&out),
device_address(&w_route),
stream,
)?;
self.record_usage(layer_index, tensor_address::<u32>(&ids)?, entries)?;
let out = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
(rows, k, hidden),
));
let w_route = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(w_route, self.device.clone())),
(rows, k, 1),
));
out.broadcast_mul(&w_route)?.sum(1)
}
/// The routed experts of one device-routed layer, over device
/// pointers: `x` is `(rows, n_embd)` f32, `ids` `(rows, k)` 32-bit
/// expert ids and `weights` `(rows, k)` f32. Writes `parts`
/// `(rows, k, n_embd)` f32, each token's outputs ordered by ascending
/// expert id, and `w_route` `(rows, k)`, the weights in that order.
///
/// Once its buffers exist (first call) this allocates nothing and
/// does not wait, so it can be captured. It does not adapt the tier:
/// the caller does that between steps.
#[allow(clippy::too_many_arguments)]
pub fn launch_routed(
&self,
layer_index: usize,
x: u64,
ids: u64,
weights: u64,
rows: usize,
k: usize,
parts: u64,
w_route: u64,
stream: *mut c_void,
) -> candle_core::Result<()> {
let routing = self
.routing
.as_ref()
.ok_or_else(|| candle_err("device routing is not enabled"))?;
if rows > TIER_ADMIT_MAX_ROWS {
candle_core::bail!(
"device routing takes at most {TIER_ADMIT_MAX_ROWS} rows, got {rows}"
);
}
let layer = &self.layers[layer_index];
let hidden = self.n_embd;
let entries = rows * k;
let experts = routing.table.len() / self.layers.len();
let mut workspace = routing.workspace.lock().map_err(candle_err)?;
let ws = &mut *workspace;
let cap_groups = entries.min(experts);
// Sized for the largest batch this path takes, once, so nothing
// here is reallocated under a captured step.
let max_entries = TIER_ADMIT_MAX_ROWS * k;
let max_groups = max_entries.min(experts);
ensure_capacity(&self.device, &mut ws.grp_ptr, max_groups)?;
ensure_capacity(&self.device, &mut ws.grp_start, max_groups + 1)?;
ensure_capacity(&self.device, &mut ws.n_groups, 1)?;
ensure_capacity(&self.device, &mut ws.ent_dst, max_entries)?;
ensure_capacity(&self.device, &mut ws.ent_tok, max_entries)?;
ensure_capacity(&self.device, &mut ws.miss_src, max_groups)?;
ensure_capacity(&self.device, &mut ws.n_miss, 1)?;
// A miss is copied into the arena by the gather below, so the
// expert kernel reads VRAM only: reading host memory from the
// kernel itself is latency-bound at decode's few warps.
ensure_capacity(
&self.device,
&mut ws.arena,
max_groups * routing.max_blob_bytes,
)?;
ensure_capacity(
&self.device,
&mut ws.q8,
TIER_ADMIT_MAX_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(max_entries as i64, self.n_ff as i64)
};
ensure_capacity(&self.device, &mut ws.scratch, scratch_bytes)?;
let table_row = device_address(&routing.table) + (layer_index * experts * 8) as u64;
let host_row = device_address(&routing.host_table) + (layer_index * experts * 8) as u64;
let arena = device_address(ws.arena.as_ref().expect("allocated"));
let miss_src = device_address(ws.miss_src.as_ref().expect("allocated"));
let n_miss = device_address(ws.n_miss.as_ref().expect("allocated"));
let q8 = device_address(ws.q8.as_ref().expect("allocated"));
// SAFETY: every pointer is a live device allocation sized above,
// and every kernel is ordered on the one stream.
// SAFETY: every pointer is a live device allocation sized above or
// by the caller, and every kernel is ordered on the one stream.
unsafe {
let status = ffi::neuron_strata_route_groups(
tensor_address::<u32>(&ids)? as *const u32,
tensor_address::<f32>(&weights)? as *const f32,
ids as *const u32,
weights as *const f32,
rows as i32,
k as i32,
table_row as *const u64,
@@ -850,7 +936,7 @@ impl GgufExpertSource {
device_address(ws.n_groups.as_ref().expect("allocated")) as *mut i32,
device_address(ws.ent_dst.as_ref().expect("allocated")) as *mut i32,
device_address(ws.ent_tok.as_ref().expect("allocated")) as *mut i32,
device_address(&w_route) as *mut f32,
w_route as *mut f32,
miss_src as *mut u64,
n_miss as *mut i32,
stream,
@@ -870,12 +956,16 @@ impl GgufExpertSource {
candle_core::bail!("miss gather failed with status {status}");
}
ffi::neuron_strata_quantize_q8_1(
tensor_address::<f32>(&x)? as *const f32,
x as *const f32,
rows as i64,
hidden as i64,
q8 as *mut c_void,
stream,
);
let status = ffi::neuron_strata_last_error();
if status != 0 {
candle_core::bail!("expert activation quantize failed with CUDA status {status}");
}
ffi::neuron_strata_expert_grouped(
layer.gu_type,
layer.d_type,
@@ -890,68 +980,69 @@ impl GgufExpertSource {
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,
parts as *mut f32,
stream,
);
let status = ffi::neuron_strata_last_error();
if status != 0 {
candle_core::bail!("grouped expert kernel failed with CUDA status {status}");
}
}
drop(workspace);
self.record_usage(layer_index, &ids, entries)?;
let out = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
(rows, k, hidden),
));
let w_route = Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(w_route, self.device.clone())),
(rows, k, 1),
));
out.broadcast_mul(&w_route)?.sum(1)
Ok(())
}
/// Queues this step's ids for the host, for `adapt` to read next
/// time the layer runs.
fn record_usage(
/// time the layer runs. `ids` is `entries` 32-bit ids on the device.
pub fn record_usage(
&self,
layer_index: usize,
ids: &Tensor,
ids: u64,
entries: usize,
) -> candle_core::Result<()> {
let (Some(routing), Some(_)) = (&self.routing, &self.tier) else {
return Ok(());
};
let mut guard = routing.pending[layer_index].lock().map_err(candle_err)?;
if guard.as_ref().is_none_or(|p| p.ids.len < entries * 4) {
if guard.as_ref().is_none_or(|p| p.ids.len < entries) {
// Sized once for the largest batch: a captured step writes
// this address on every replay.
*guard = Some(Pending {
ids: PinnedBuffer::new((entries * 4).max(256))?,
ids: MappedIds::new((TIER_ADMIT_MAX_ROWS * 64).max(entries))?,
entries: 0,
event: Event::new()?,
recorded: false,
});
}
let pending = guard.as_mut().expect("set above");
let stream = self.device.cuda_stream().cu_stream() as *mut c_void;
// SAFETY: the buffer holds `entries` ids and is not read until
// the event below has completed.
// SAFETY: the buffer holds `entries` ids and is not read until the
// step has been waited on.
unsafe {
let status = ffi::neuron_strata_copy_to_host(
pending.ids.ptr.cast(),
tensor_address::<u32>(ids)? as *const c_void,
entries * 4,
let status = ffi::neuron_strata_copy_words(
pending.ids.device as *mut u32,
ids as *const u32,
entries as i32,
stream,
);
if status != 0 {
candle_core::bail!("expert usage copy failed with CUDA status {status}");
}
let status = ffi::neuron_strata_event_record(pending.event.0, stream);
if status != 0 {
candle_core::bail!("event record failed with CUDA status {status}");
}
}
pending.entries = entries;
pending.recorded = true;
Ok(())
}
/// After a captured step's replay: the usage copies it queued are
/// the ones its capture recorded, so mark them for `adapt`.
pub fn usage_replayed(&self, layer_index: usize) {
if let Some(routing) = &self.routing
&& let Ok(mut guard) = routing.pending[layer_index].lock()
&& let Some(pending) = guard.as_mut()
{
pending.recorded = true;
}
}
fn forward_layer(
&self,
layer_index: usize,
+9
View File
@@ -10,3 +10,12 @@ their relative includes work and so they can be diffed against upstream.
To update, copy the same paths from a newer upstream commit and change the commit above.
Do not edit these files in place; neuron's adapter is `crates/neuron/src/cuda/strata_adapter/strata_shim.cu`.
## Decode kernels for the native engine (#427)
Added from the same Strata revision for neuron's native qwen4_exp decode
engine, unmodified: `native_gdn`, `native_gdn_preprocess`, `fused_gdn`,
`native_gr_norm`, `native_gr_postops`, `gr`, `native_router`, `native_moe`,
`quantize_act`, `bf16_gemv` and `native_bf16` (`engine/src/kernels/cuda/`),
with the headers they include. neuron calls them through
`src/cuda/strata_adapter/engine_shim.cu`.
@@ -0,0 +1,21 @@
// strata/core/bw_dense_defaults.hpp - defaults of the bitwise load-ordering variants from the Blackwell Qwen speed work (BW-DENSE).
//
// Each is bitwise equal to the kernel it replaces (the screens and the engine A/Bs are in phaseA-tests/blackwell/decisions/E15.md and
// E21-small-kernel-loads.md), measured on an RTX PRO 5000 Blackwell (compute capability 12.0), so they are on there and nowhere else
// (unmeasured on other cards). STRATA_SM120_PERF=0 and STRATA_DEFAULTS=026 turn them off like the rest of the 12.0 set; an explicit variable
// (STRATA_GR_V3_PF, STRATA_SMALL_UNR) wins on any card in both directions.
#pragma once
#include "strata/core/defaults_026.hpp"
#include "strata/core/sm120_series.hpp"
namespace strata {
/// STRATA_GR_V3_PF when unset (gr_down_v3 / gr_up_v3 load-ordering variants): bits 0 (gr_down batched staging loads), 2 (gr_up batched loads) and 7 (gr_down: windows of 5+ rows
/// take 2 rows a warp with the activations read from shared memory once for both rows; bitwise the same dots, DF2-MORE: down 16.1 / 16.2 / 17.6 / 19.5 -> 13.3 / 14.1 / 14.7 / 15.6 us at T 5-8).
inline int gr_v3_pf_default(int major, int minor) { return sm12x_default(major, minor, kGb10GrV3Pf) && !qwen_defaults_026() ? 133 : 0; }
/// STRATA_SMALL_UNR when unset: bit 0 the bf16 router read, bit 1 the GDN a/b projection (constant-trip loops).
inline int small_unr_default(int major, int minor) { return sm12x_default(major, minor, kGb10SmallUnr) && !qwen_defaults_026() ? 3 : 0; }
} // namespace strata
@@ -0,0 +1,61 @@
// include/strata/kernels/bf16_bits.hpp - the bf16 conversions, written out, as bits.
//
// bf16 is the TOP HALF of an f32, so `f32_from_bf16` is a shift and needs no rounding at all. The forward
// direction does: ggml's `ggml_compute_fp32_to_bf16` adds `((i >> 16) & 1) + 0x7FFF` and truncates 16 bits.
//
// **THE `& 1` IS ON BIT 16**, the lowest KEPT bit, which is what makes an exact tie round to EVEN. Using bit
// 15 there is a plausible mistake: it differs only on exact ties, i.e. almost never on real data, which is
// exactly why it would survive any amount of end-to-end testing. `ref/quant.py` documents the same rule for
// the same reason.
//
// WHY THIS IS SEPARATE FROM `f16_bits.hpp`: fp16 and bf16 are not two spellings of one idea. fp16 has 5
// exponent bits and 10 mantissa bits; bf16 has 8 and 7. A conversion routine written for one and reused for
// the other is wrong in a way that produces plausible numbers - bf16's 2^-9 relative precision looks like a
// small fp16 error and is not small at all next to fp16's 2^-11.
//
// `gr.cu` carried a private copy of `f32_to_bf16_bits` until this header existed. It now includes this.
#pragma once
#include <cstdint>
#include <cstring>
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_BF16_HD __host__ __device__
#else
#define STRATA_BF16_HD
#endif
namespace strata::kernels {
/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16.
///
/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone
/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so
/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the
/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input,
/// infinities included, rounds exactly as before.
STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {
uint32_t i;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&i, &f, 4);
#else
std::memcpy(&i, &f, 4);
#endif
if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u);
i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
return (uint16_t) (i >> 16);
}
/// bf16 bits -> f32. Exact, and no rounding: the low 16 bits of an f32 are simply zero.
STRATA_BF16_HD inline float f32_from_bf16(uint16_t h) {
const uint32_t i = (uint32_t) h << 16;
float f;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&f, &i, 4);
#else
std::memcpy(&f, &i, 4);
#endif
return f;
}
} // namespace strata::kernels
@@ -0,0 +1,70 @@
// include/strata/kernels/bf16_gemv.hpp - the GEMV for a BF16 weight, P2.S5.
//
// WHY THIS EXISTS WHEN `s_gemv` ALREADY DOES. `s_gemv` decodes the S-family canonical forms (S2/S4/S8) from
// `codes` + `scales`, and a BF16 weight is not one of them - it has no codes and no scales, it is a plain
// 16-bit matrix. Six tensors per layer are in that state:
//
// ssm_alpha.weight, ssm_beta.weight GDN, [n_embd, 48]
// indexer.q_proj.weight, indexer.k_proj.weight QSA, [n_embd, 512] and [n_embd, 128]
// ple_value.weight layer 1, [n_embd, n_embd]
// ffn_gate_inp.weight handled inside `router_top10`
//
// The original entry points take BF16 activation bits for the historical CPU-derived contract. The explicit
// FP32 entry point below follows the pinned CUDA single-token MMVF contract. See docs/activation-contract.md
// for why activation precision depends on backend and batch geometry rather than weight type alone.
#pragma once
#include <cstdint>
namespace strata::kernels {
/// `y[o] = sum_i f32(x[i]) * f32(w[o*n_in + i])`, with both sides bf16-valued so every product is exact in
/// f32 and only the summation order differs.
///
/// THE WEIGHT LAYOUT IS THE MANIFEST'S: shape [n_in, n_out] with ne0 = n_in CONTIGUOUS, so row `o` is a
/// contiguous run of `n_in` bf16 values. That is the same convention `s_gemv` uses, and it is what
/// `strata::core::WeightRef::ne0/ne1` already report.
void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream);
/// TWO weight matrices from ONE kernel (llama.cpp's `*_mul_mat_multi` shape): `y1 = w1 @ x`, `y2 = w2 @ x`.
/// One warp computes row o of both matrices with two accumulators over one lane-strided pass, so each output
/// is bitwise what `bf16_gemv` produced for that matrix wherever `bf16_gemv` used its warp kernel
/// (`n_out >= 64`); a matrix below that threshold falls back to the plain call to keep the naive kernel's
/// summation order. `n_out1` or `n_out2` may be 0 for a one-sided call.
void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2,
float* y2, int64_t n_out2, int64_t n_in, void* stream);
/// The row-split variant, for the same reason `s_gemv_split` exists: with one thread per output row the
/// parallelism IS the output width, and `ssm_alpha` has 48 of them over 48 SMs. One warp per row, lanes
/// striding the reduction axis - which is also what makes the access pattern coalesced in this layout.
///
/// NOT bit-identical to `bf16_gemv`: the partial sums are added in a different order. Both are kept and both
/// are tested, because the naive one is the reference the split one is checked against.
void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out,
int threads_per_row, void* stream);
/// Single-token, contiguous 2D BF16-weight/F32-activation MMVF from the pinned llama.cpp CUDA path.
/// Preserves pair accumulation, adaptive block size and warp-XOR reduction order. This is a separate
/// opt-in entry point; the legacy BF16-activation kernels above retain their behavior.
/// `w[o*n_in+i]` is BF16 bits; x/y are F32. n_in must be positive and even, n_out positive, both <= INT_MAX.
/// x must be 8-byte aligned, w 4-byte aligned, and y 4-byte aligned. Throws on invalid geometry/pointers.
/// The device buffers must not overlap; allocation bounds remain the caller's responsibility.
/// No allocations or synchronization, including when stream is null (the CUDA default stream).
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
int64_t n_in, int64_t n_out, void* stream);
/// `ncols` columns at once: x is [ncols][n_in], y is [ncols][n_out]; each column bitwise equal to a
/// `bf16_gemv_fp32_mmvf` call on it.
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
void* stream);
/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch,
/// the weight read once, every output bit-identical to its own single-row call.
void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
int64_t n_in, int64_t n_out, int n_tok, void* stream);
/// S26 STRATA_LFUSE: bf16_gemv_fp32_mmvf_multi(x, ldx, w, y, ldy, n_in, n_out, n_tok) plus the 1-row
/// bf16_gemv_fp32_mmvf_multi(x, ldx, w_aux, y_aux, ldy_aux, n_in, 1, n_tok) in ONE launch, every output bitwise the
/// two calls'. Returns false (nothing launched) unless the rows path applies (STRATA_MMVF_ROWS=1, n_out >= 64, 2-8 rows).
bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux,
int64_t ldy_aux, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,104 @@
// include/strata/kernels/f16_bits.hpp - the fp16 conversions, written out, as bits.
//
// WHY THIS IS NOT `__float2half`. Round 193 found `__float2half` producing 0x2600 for a value whose correct
// fp16 encoding is 0x26DB, and 0x3C01 for a value that is exactly 1.0 - i.e. wrong bits, not a rounding
// difference. The cause was never isolated (it is either `__float2half` itself or `__half_as_ushort`), so
// `src/kernels/cuda/quantize_act.cu` replaced it with the version below, which then came out byte-exact over
// all 20,480 blocks of the fixture. `shared_expert.cu` carries the same function privately for the same
// reason. Three copies of a converter whose failure mode is silent wrong bits is two copies too many, so the
// copy lives here and the kernel and its TEST both include it - with the test checking it against vectors
// generated by numpy's float16 (an oracle that shares no code with this), which is what neither private copy
// had.
//
// The rounding is ROUND-TO-NEAREST-EVEN, which is what numpy's `.astype(np.float16)` does and what IEEE-754
// specifies for the default mode. The three interesting regimes are all handled explicitly and all three are
// covered by the test's oracle vectors:
//
// * normal - exponent fits, mantissa is rounded from 13 surviving bits with a sticky remainder
// * subnormal - the implicit 1 is restored and the result is shifted right, so the rounding point MOVES
// * overflow - exp >= 31 saturates to inf (0x7C00) and keeps the sign; a NaN input stays a NaN
//
// `f32_from_f16` deliberately does NOT round: it is used to compare against a reference that holds the same
// bits, so it only has to be exact.
#pragma once
#include <cstdint>
#include <cstring>
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_HD __host__ __device__
#else
#define STRATA_HD
#endif
namespace strata::kernels {
/// Round-to-nearest-even f32 -> fp16, returned as raw bits.
STRATA_HD inline uint16_t f16_from_f32(float f) {
uint32_t x;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&x, &f, 4);
#else
std::memcpy(&x, &f, 4);
#endif
const uint32_t sign = (x >> 16) & 0x8000u;
const uint32_t rawexp = (x >> 23) & 0xFFu;
int exp = (int) rawexp - 127 + 15;
uint32_t man = x & 0x7FFFFFu;
// TWO different things reach here and they must not be conflated: an f32 inf/NaN (raw exponent 255) stays
// an inf/NaN, and a FINITE value too large for fp16 (1e30) SATURATES TO INF. The version of this function
// in quantize_act.cu and shared_expert.cu tests `if (exp >= 31) return sign | 0x7C00 | (man ? 0x200 : 0)`
// and therefore returns a NaN for every overflowing finite value - which their own fixtures cannot see,
// because all of their values are O(1). Round 198's numpy oracle caught it here on the first run (1e30,
// 65536, 1e45: numpy says inf, the conflated test said NaN).
if (rawexp == 0xFFu) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u)); // inf, or a quiet/NaN
if (exp >= 31) return (uint16_t) (sign | 0x7C00u); // finite overflow -> inf
if (exp <= 0) {
if (exp < -10) return (uint16_t) sign; // underflows to a signed zero
man |= 0x800000u; // restore the implicit 1
const uint32_t sh = (uint32_t) (14 - exp);
uint32_t h = (man >> sh) & 0x3FFu;
const uint32_t rem = man & ((1u << sh) - 1u);
if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h;
return (uint16_t) (sign | h);
}
uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13));
const uint32_t rem = man & 0x1FFFu;
if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; // the carry may bump the exponent
return h;
}
/// Exact fp16 bits -> f32. No rounding, no exceptions: every one of the 65,536 inputs maps to a value f32
/// represents exactly, including the subnormals (which is why the `ex == 0` case cannot be skipped).
STRATA_HD inline float f32_from_f16(uint16_t h) {
const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
const uint32_t ex = (h >> 10) & 0x1Fu, man = h & 0x3FFu;
uint32_t out;
if (ex == 0) {
// Subnormal or zero. The value is `man * 2^-24`, so after `s` left shifts the leading 1 reaches bit
// 10 and the value is `(1 + frac) * 2^(-14-s)`: the f32 exponent field is 113 - s and `frac` is the low
// ten bits. Flushing these to zero - which the two private copies of this function in the tree do -
// maps 0x0001 to 0.0 instead of 2^-24, a 100% relative error on any KL-quant scale that lands here.
if (man == 0) {
out = sign;
} else {
uint32_t m = man;
int s = 0;
while ((m & 0x400u) == 0) { m <<= 1; ++s; }
out = sign | ((uint32_t) (113 - s) << 23) | ((m & 0x3FFu) << 13);
}
} else if (ex == 31) {
out = sign | 0x7F800000u | (man << 13);
} else {
out = sign | ((ex - 15 + 127) << 23) | (man << 13);
}
float f;
#if defined(__HIP_DEVICE_COMPILE__)
__builtin_memcpy(&f, &out, 4);
#else
std::memcpy(&f, &out, 4);
#endif
return f;
}
} // namespace strata::kernels
@@ -0,0 +1,41 @@
// include/strata/kernels/fused_gdn.hpp - plan v0.3 P3: the gated delta-net step and its output norm in ONE kernel.
//
// The native step (after llama.cpp's gated_delta_net.cu) gives each warp one (head, column) and strides its 32
// lanes over the 128 ROWS of the state, which is stored `[row][head][col]`: every lane's load is 24.5 KB from its
// neighbour's, so each 32 B sector delivers 4 useful bytes - 47.6 us per layer for 6.3 MB of state traffic. Here a
// block owns one whole head, its 512 threads are (row group of 32, column), and a row's 128 columns are one
// contiguous 512 B load. With the head in one block, the per-head RMS norm, the norm weight and the sigmoid(z)
// gate of `gdn_out_norm` run in the same kernel.
//
// S <- g S + k (beta (v - g S^T k))^T (g = exp(gate[head]), per value head; q/k shared by h_v / h_k heads)
// o = (S^T q) / sqrt(128)
// y = rmsnorm(o) * gamma * sigmoid(z)
#pragma once
#include <cstdint>
namespace strata::kernels {
/// The 4-tap causal conv + SiLU over all `channels` (history is `[channel][3]`, updated), then the L2 norm of
/// each of the first `qk_heads` 128-channel heads (q then k), eps as the native `l2_norm` (x / sqrt(sum + eps)).
/// One block per 128-channel head; replaces conv_silu + two l2_norm launches.
void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
float eps, void* stream);
/// alpha and beta, both `(h_v, n_embd)` BF16 against the FP32 activation, with their epilogues:
/// gate = softplus(alpha + dt) * ssm_a, beta = sigmoid(beta). One warp per row; replaces two MMVF launches and
/// two elementwise kernels.
void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
float* gate, float* beta, int n_embd, int h_v, void* stream);
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
void* stream);
/// The same step with the SiLU output gate, y = rmsnorm(o) * gamma * silu(z): Qwen3.6-35B-A3B's (qwen35moe) GDN
/// (CUDA / HIP; the SYCL port has no qwen35moe path).
void fused_gdn_step_norm_silu(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k,
int h_v, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,97 @@
// include/strata/kernels/gdn.hpp - the gated delta-net (GDN) layer's non-projection parts, P2.S2.
//
// Transcribed from `ref/gdn.py`, which is itself transcribed from `build_layer_attn_linear` and
// `build_delta_net_autoregressive`. The projections (`wqkv`, `wqkv_gate`, `ssm_out`) are the existing
// `s_gemv`/`s2_gemv` kernels; what lives here is everything BETWEEN them.
//
// Geometry of the real artifact (48 layers are GDN, 12 are QSA):
//
// S = state_size = 128 head_k_dim == head_v_dim
// h_k = 16 k/q heads h_v = 48 v heads (idx[h] = h % h_k)
// C = 2*128*16 + 128*48 = 10240 channels d_conv = 4
//
// STATE LAYOUT. This is the one place the kernels deliberately differ from the reference, and the reason is
// coalescing. `ref/gdn.py` carries the state as (S, S, H_v) = (i, j, h); here it is **(S, H_v, S)** =
// (i, h, j), so that for a fixed i a warp walking consecutive j reads CONTIGUOUS memory. The state is a
// runtime buffer, not a weight, so this costs nothing to choose - but it must be said, because the two
// layouts index the same three numbers and a mismatch is silent.
//
// WHAT MAKES THE RECURRENCE PARALLEL, and it is worth stating because it is not obvious:
//
// dec = exp(gate) (h_v,)
// st = state * dec
// sk[h,j] = sum_i st[i,j,h] * k[idx[h]][i]
// d[h,j] = (v[h,j] - sk[h,j]) * beta[h]
// st[i,j,h] += k[idx[h]][i] * d[h,j]
// o[h,j] = sum_i st[i,j,h] * q[idx[h]][i]
//
// Every line touches ONLY the (j, h) column. Nothing couples one column to another, so one thread can own a
// column for the whole step and no barrier is needed anywhere in the recurrence. (The decay must still be
// applied BEFORE the rank-1 update - `ref/gdn.py` PROPERTY 5 pins that, and the test re-pins it here.)
#pragma once
#include <cstdint>
namespace strata::kernels {
/// Geometry of one GDN layer. The real artifact: S = 128, h_k = 16, h_v = 48.
struct GdnShapes {
int64_t S = 0; ///< head dim, and the state's contracted axis
int64_t h_k = 0; ///< key/query heads (q and k are (h_k, S))
int64_t h_v = 0; ///< value heads (v, z, o are (h_v, S)); h_v must be a multiple of h_k
};
/// One step of the delta-rule recurrence, IN PLACE on `state`.
///
/// state (S, h_v, S) f32, j fastest, updated in place
/// q, k (h_k, S) already L2-normalised, and q ALREADY SCALED by 1/sqrt(S) - the two llama.cpp paths
/// apply that scale in different places, so the caller owns it
/// v (h_v, S)
/// gate (h_v,) the PRE-exp value; `dec = exp(gate)` is formed here
/// beta (h_v,)
/// o (h_v, S)
///
/// The head pairing is `h % h_k` (MODULO), not `h / (h_v/h_k)` (INTERLEAVE). `ref/gdn.py` PROPERTY 8 and 11
/// pin this and the test re-pins it, because both conventions produce well-formed output.
void gdn_step(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, float* o, const GdnShapes& s, void* stream);
/// `ggml_ssm_conv` with the carried state prepended. Updates `conv_state` in place.
///
/// conv_state (d_conv-1, channels) the previous d_conv-1 input columns, OLDEST FIRST
/// x (channels,) the new column
/// kW (channels, d_conv) the weight in GGML-NATIVE layout: `kW[c*d_conv + i]` is tap i of
/// channel c. The manifest gives `ssm_conv1d.weight` ne = [4, 10240],
/// i.e. ne0 = d_conv is the FAST axis, which is this and NOT the
/// reference's row-major (d_conv, channels).
/// out (channels,)
///
/// out[c] = sum_{i<d_conv} inp[i][c] * kW[c*d_conv + i], inp = [conv_state | x]
///
/// `kernel[0]` reads the OLDEST state row and the new input lands in the LAST state row.
void gdn_conv_step(float* conv_state, const float* x, const float* kW, float* out, int64_t channels,
int64_t d_conv, void* stream);
/// `build_gdn_l2_norm`: `x / sqrt(sum(x^2) + eps)`, over the LAST axis.
///
/// The `+ eps` is an absolute floor on the SQUARED NORM, not on the mean - so the sum is formed first and
/// there is NO division by the width. The plausible wrong reading (`x / sqrt(mean(x^2) + eps)`) differs by
/// sqrt(S) = 11.3x here, which is why the test asserts the two are distinguishable.
void gdn_l2_norm(float* x, int64_t rows, int64_t cols, float eps, void* stream);
/// `beta = sigmoid(beta)`, in place over `h_v` values.
///
/// **`gdn_step` DOES NOT DO THIS AND THE LAYER MUST.** `build_layer_attn_linear` L889 is
/// `beta = ggml_sigmoid(beta)` and the step kernel's contract is `d = (v - sk) * beta`, so what it receives has
/// to be a fraction. Passing the raw `ssm_beta @ cur` leaves the delta-net write strength unbounded and signed.
/// `ref/gdn.py` and `ref/model.py` both sigmoid it; this call is what makes the C++ agree with them.
void gdn_beta_gate(float* beta, int64_t h_v, void* stream);
/// The layer's closing norm: `y = rms_norm(o, eps) * ssm_norm * sigmoid(z)`.
///
/// Note SIGMOID, not SiLU - qwen3.5 used SiLU and this artifact does not, and `ref/gdn.py` says so outright.
/// The norm is over the LAST axis: one RMS per head, so it is per-ROW here and not over the whole (h_v, S).
void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S,
float eps, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,132 @@
// include/strata/kernels/gr.hpp - the gated residual (hyper-connection), P2.S2.
//
// `ref/gr.py::gr_read` / `gr_write`, which are transcribed from
// `llama_model_qwen4exp::graph::build_hc_mix` / `build_hc_combine` (qwen4exp.cpp L267-350 at 3cf03257).
//
// The residual is a STACK of `hc` streams, each `n_embd` wide - not one vector with a gate. `gr_read`
// collapses the stack to the one vector the mixer consumes and produces a per-stream injection; `gr_write`
// puts the mixer's output back into every stream, weighted per stream.
//
// WEIGHTS ARE BF16, stored as the high 16 bits of an f32 in a `uint16_t`. That is not a shortcut: every one
// of these tensors has source type BF16 in the pack (288 of the shard's 483 BF16 tensors are `hc_*`), so the
// pack's 32-bit promotion is lossless padding and re-rounding to 16 bits costs nothing. It is also worth
// 1.374 GiB of the 5.305 GiB dense file, which is the difference between the dense weights fitting in VRAM
// beside the expert cache and not fitting at all.
//
// The default activation contract is the historical BF16-rounded reference. The opt-in FP32 contract
// matches the pinned llama.cpp CUDA single-token BF16 MMVF input precision: BF16 weights multiply FP32
// activations. The CPU oracle and some batched CUDA paths instead round activations to BF16. Therefore
// activation precision must be pinned with the oracle backend and batch geometry, not inferred from weights.
#pragma once
#include <cstdint>
#include <cstddef>
namespace strata::kernels {
/// Select the activation precision for subsequent gr_read launches (default: false/BF16).
/// Configure before creating/capturing a session, and do not mutate concurrently with gr_read.
/// A captured graph retains the kernel variants chosen at capture; changing this flag cannot alter it.
/// This changes activation precision only; the existing FP32 reduction trees remain unchanged.
void gr_set_fp32_activations(bool enabled);
/// Select pinned single-token BF16/F32 MMVF projections for subsequent gr_read launches (default false).
/// This implies FP32 activations regardless of gr_set_fp32_activations. Configure before session capture;
/// a captured graph retains its selected kernels. Requires even hc*n_embd and hc_lr, as MMVF reads pairs.
/// This also selects pinned weighted F32 RMSNorm and nonlinear/combine arithmetic.
/// Layer reads use fused HC pre; the final mixer (null w_inject) retains its unfused graph order.
/// Subsequent gr_write calls select pinned sigmoid/scatter arithmetic under the same setting.
void gr_set_native_mmvf(bool enabled);
/// Whether gr_write currently uses the native write (native_gr_post).
bool gr_native_mmvf_enabled();
/// Geometry of the hyper-connection. The real model: n_embd = 2560, hc = 4, hc_lr = 320.
struct GrShapes {
int64_t n_embd = 0; ///< width of one residual stream
int64_t hc = 0; ///< number of streams in the stack
int64_t hc_lr = 0; ///< rank of the down/up bottleneck
};
/// Scratch for `gr_read`. EXPLICIT and caller-owned, because P2.T10 requires ZERO token-path allocations:
/// a hidden `cudaMalloc` on first use would satisfy every test here and fail the memory test in P2.S10.
///
/// **IT MUST BE DEVICE MEMORY.** `gr_workspace_init` takes a raw pointer and does no checking, so handing it
/// a host buffer produces device kernels writing to a truncated host address - an illegal access whose
/// reported fault address is the low 32 bits of a host pointer, which reads as a wild pointer rather than as
/// the mistake it is. That cost one round in `gr_parity`;
///
/// xn hc*n_embd floats the unrounded activated streams (the gated mean needs the unrounded value)
/// xq hc*n_embd uint16 bf16(xn), used by the default activation contract
/// lq hc_lr uint16 bf16(lo), used by the default activation contract
/// gated hc*n_embd floats xn * sigmoid(gate), before the mean over streams
/// lo hc_lr floats SiLU bottleneck, used by the FP32 activation contract
///
/// `cudaMalloc(gr_workspace_bytes(s))`, then `gr_workspace_init(s, ptr, ws)` to carve it.
struct GrWorkspace {
float* xn = nullptr;
uint16_t* xq = nullptr;
uint16_t* lq = nullptr;
float* gated = nullptr;
float* lo = nullptr;
/// Set by `gr_workspace_init`. `gr_read` CHECKS it, so an under-sized buffer is a loud failure at the
/// first call instead of silent corruption - which is what a mis-ordered region table used to produce.
size_t bytes = 0;
};
/// Carves `base` (which must be DEVICE memory, or null to size only) into `out` and returns the bytes needed.
/// 16-byte aligned between regions.
size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out);
inline size_t gr_workspace_bytes(const GrShapes& s) { GrWorkspace w; return gr_workspace_init(s, nullptr, w); }
/// `build_hc_mix`. ONE token: `R` is (hc, n_embd) with n_embd fastest, i.e. stream c starts at c*n_embd.
///
/// w_norm (hc*n_embd) per-stream RMSNorm gamma, STORED AS (1 + w) by the converter
/// w_down (hc_lr, hc*n_embd) MANIFEST LAYOUT - row k is contiguous, `w_down[k*hc*n_embd + i]`
/// w_up (hc*n_embd, hc_lr) MANIFEST LAYOUT - row i is contiguous, `w_up[i*hc_lr + k]`
/// w_inject (hc, hc*n_embd) null for the FINAL mixer, which has no write-back to gate
///
/// mixed (n_embd) = mean over streams of xn * sigmoid(bf16(lo) @ w_up.T)
/// inject (hc) = bf16(xn) @ w_inject.T, or untouched when w_inject is null
///
/// `lo = silu((bf16(xn) @ w_down.T) / hc)` - the division by hc is INSIDE the silu, which is easy to read
/// past and changes the result materially.
/// With gr_set_fp32_activations(true), replace bf16(xn) and bf16(lo) by xn and lo respectively.
///
/// **NO PERMUTATION: both matrices are taken exactly as the manifest stores them**, so the loader does nothing
/// to them. Both are coalesced because each projection assigns ONE WARP PER OUTPUT ROW and strides the
/// reduction axis across its 32 lanes: for a fixed output, consecutive lanes touch consecutive addresses in
/// either orientation. An earlier version assigned one THREAD per row, which is coalesced with itself and 32
/// transactions away from its warp neighbours - see the history below.
///
/// **HISTORY, because this kernel was the engine's worst and the reason is instructive.** The first version
/// was launched `<<<1, 256>>>` with `xn`/`xq` in shared memory, and at the real geometry it cost **2.67 ms per
/// call, 96 calls per token = 262 ms/token, about 3.8 tok/s, 134x off the 643 GB/s memory floor.** The cause
/// was isolated by elimination: NOT memory latency (four independent accumulator chains made it 17% SLOWER),
/// NOT the SM clock (`nvidia-smi` reported 2917 MHz and 99% utilisation throughout), and only partly
/// coalescing (transposing one of the two matrices gave 31% and transposing the other gave nothing). It was
/// ISSUE THROUGHPUT - ~8.4M iterations of 6-8 instructions issued by ONE of 48 SMs.
///
/// This version splits the work the way the shapes want: `hc` blocks for the per-stream norm, one warp per
/// row for each of the two projections, and one block-tile for the mean. The transposes are gone because the
/// warp-per-row mapping makes them unnecessary.
void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed,
float* inject, void* stream);
void gr_read_multi(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws,
float* xn_multi, float* lo_multi, float* gated_multi, float* mixed, float* inject,
int n_tok, void* stream);
/// `build_hc_combine`. `R_out[i] = R[i] + block_out[d] * w[c]` with `w[c] = 2*sigmoid(inject[c]/hc)`.
///
/// The `2*sigmoid` is what CENTRES the gate on 1, so a zero injection is a plain residual add - the source
/// comment says so outright and `gr_write`'s test asserts it. Note the block output is added to EVERY stream
/// identically; only the weight is per-stream.
void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
void* stream);
void gr_write_multi(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
int n_tok, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,64 @@
// strata/kernels/mrope.hpp - multimodal rotary positions (the vision path).
//
// qwen4exp rotates with interleaved M-RoPE (llama.cpp LLAMA_ROPE_TYPE_IMROPE, rope.dimension_sections 11/11/10/0):
// each of the 32 rotated pairs takes its position from one of three streams, time t, height h and width w. Text
// has t = h = w, which is why every rope kernel here takes one position per row. An image does not: its tokens
// share t and differ in h and w (mtmd: t = p, h = p + y, w = p + x), and the text after it continues at
// p + max(nx, ny), not at its cell index.
//
// The table: nullptr (the default) keeps every kernel exactly as before - the position a caller passes is the
// rotary position. Set, it is a DEVICE int32 [cells][3] (t, h, w) and the position a caller passes is read as a
// CELL index; pair i rotates by tab[cell * 3 + mrope_sector(i)]. Every caller in the engine passes cell indices
// (pos_base is 0 everywhere), so the table covers the prompt path, the verify window and the MTP drafter at once.
// The pointer must be set before any CUDA graph is captured (kernels take it as an argument); the contents may
// change between requests.
#pragma once
#include <cstdint>
#if defined(__HIPCC__) && defined(STRATA_HIP_GFX906) // PR #638: the gfx906 compat build only
#include <hip/hip_runtime.h>
#endif
#include "strata/kernels/rope_scaling.hpp"
namespace strata::kernels {
/// The table of the CURRENT device (a layer split sets one per device; null = the identity).
void mrope_table_set(const int32_t* device_table);
const int32_t* mrope_table();
/// #280, opt-in (STRATA_ROPE_TABLE=1): the rotation angles, 32 pairs of a 64-wide rotary slice, from the session's
/// float64 table (build_rope_table, [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT
/// device. With it the rope kernels rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under
/// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode
/// (fast-math) disagree with each other.
struct RopeTab {
const float* cos = nullptr; ///< null: no table, the kernels compute the angle as they always did
const float* sin = nullptr;
int max_pos = 0;
};
/// Registers the table the session just built with `scaling` (the latest one of the device wins).
void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling);
/// Forgets the table `cos_tab` (on every device) - before the memory that holds it is freed (session_release).
void rope_table_release(const float* cos_tab);
/// The registered table when STRATA_ROPE_TABLE=1 and it was built with `scaling`; otherwise none (the default: the
/// kernels compute the angle exactly as before).
RopeTab rope_table_for(const RopeScaling& scaling);
#if defined(__CUDACC__) || defined(__HIPCC__)
/// ggml rope_multi, is_imrope, sections {11, 11, 10, 0}: sector = pair % 32; sector % 3 == 1 -> h (sector < 33),
/// == 2 -> w (sector < 30), == 0 -> t (sector < 33). For pairs 0..31 all three bounds hold, so it is pair % 3.
__device__ __forceinline__ int mrope_pos(const int32_t* tab, int pos, int pair) {
return tab ? __ldg(tab + (size_t) pos * 3 + pair % 3) : pos;
}
/// cos and sin of rotary position p, pair `pair` (0..31) from the table (scaling and magnitude included); false
/// when there is no table or p lies past it - then the caller computes the angle as it always did
__device__ __forceinline__ bool rope_tab_cs(const RopeTab& t, int p, int pair, float& c, float& s) {
if (t.cos == nullptr || p < 0 || p >= t.max_pos) return false;
c = __ldg(t.cos + (size_t) p * 32 + pair);
s = __ldg(t.sin + (size_t) p * 32 + pair);
return true;
}
#endif
} // namespace strata::kernels
@@ -0,0 +1,22 @@
#pragma once
#include "strata/kernels/gdn.hpp"
namespace strata::kernels {
// Configure before creating/capturing a session. Existing captures retain their
// selected kernel, so changing the flag does not change an existing graph.
void native_gdn_set_enabled(bool enabled);
bool native_gdn_enabled();
// Pinned CUDA gated_delta_net recurrence for one token, S=128 and h_v % h_k=0.
// q/k are normalized F32 inputs; q MUST NOT be pre-scaled by 1/sqrt(S).
// Scaling is applied to the completed readout, as in the pinned fused operator.
// State retains Strata's layout: state[(i*h_v+h)*S+j]. The caller owns it and
// output; both must be disjoint from each other and from every read-only input.
// All spans must be aligned to four bytes. A nonnull ordered stream is required.
// No allocation, wait, or change to normalization/gate preprocessing occurs.
void native_gdn_step(float* state, const float* q, const float* k, const float* v,
const float* gate, const float* beta, float* output,
const GdnShapes& shapes, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,37 @@
#pragma once
#include <cstdint>
namespace strata::kernels {
// Optional pinned CUDA GDN preprocessing. The layer selects these functions with
// native_gdn_enabled(); direct callers explicitly select them by calling them.
// Require a nonnull ordered stream, finite inputs, and four-byte aligned spans.
// No function allocates or synchronizes. All pointers are caller-owned.
// Four-tap convolution, then FP32 fast-math SiLU. History is [channels,3], oldest
// first; weights are [channels,4]. Both outputs are required, mutually disjoint,
// and disjoint from input/weights/history. History must not alias other spans.
void native_gdn_conv_silu(float* history, const float* input, const float* weights,
float* raw_output, float* silu_output, int64_t channels,
int64_t d_conv, void* stream);
// In-place [rows,128]: scale(rms_norm(x,epsilon/128),1/sqrt(128)). This includes
// the L2 normalization scale, but NOT the recurrence's readout scale.
// Epsilon is finite/nonnegative; epsilon=0 additionally requires nonzero rows.
void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream);
// In-place sigmoid over per-head beta; one token.
void native_gdn_beta_gate(float* beta, int64_t heads, void* stream);
// One token: gate[h] = softplus(alpha[h]+dt[h])*ssm_a[h], using the pinned CUDA
// log(1+exp(x)) expression and threshold 20. Output is disjoint from inputs.
void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a,
float* gate, int64_t heads, void* stream);
// [heads,128]: rms_norm(output,epsilon)*gamma*sigmoid(z). Gamma contains only
// 128 floats and broadcasts across heads. Destination is disjoint from inputs.
void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
float* destination, int64_t heads, int64_t cols,
float epsilon, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,21 @@
#pragma once
namespace strata::kernels {
// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d CUDA weighted F32
// RMSNorm for contiguous [n_cols, n_rows] data and equally shaped F32 gamma.
// Every row has independent norm statistics. Output is (scale * input) * gamma.
// Uses 256 threads below n_cols=1024, otherwise 1024, with the pinned XOR tree.
// Compile the implementation with --use_fast_math; no FP64, allocation, or wait.
// All buffers are caller-owned, nonoverlapping, and at least four-byte aligned.
// Require positive dimensions and finite nonnegative epsilon. Inputs/gamma and
// intermediate sums must be finite; epsilon=0 additionally requires nonzero rows.
// Enqueues on the supplied CUDA stream. A null handle explicitly selects CUDA's
// default stream, preserving gr_read's existing API; this function never syncs.
void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output,
int n_cols, int n_rows, float epsilon, void* stream);
void native_gr_rms_norm_weighted_multi(const float* input, const float* gamma, float* output,
int n_cols, int n_rows, int n_tok, float epsilon, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,39 @@
#pragma once
namespace strata::kernels {
// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d contiguous F32
// single-token GR post-operations. Explicit stream, no allocation or wait; null
// selects the default stream. Positive dimensions with n*hc <= INT_MAX, finite
// values/intermediates, and four-byte alignment are required.
// Buffers must not overlap except the explicitly in-place arguments below.
// Implementation compiles separately with --use_fast_math.
// In-place pinned SCALE(1/hc), then SiLU, applied to the raw down projection.
void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream);
// xn and raw gate contain [n_embd,hc]. gate is overwritten with xn*sigmoid(gate).
// Layer path: pinned DSV4_HC_PRE_GATED ordered FMA accumulation, then scale.
// Head path (fused_layer=false): individually rounded products, ordered adds
// starting from stream zero, then SCALE. This retains the oracle's il=-1 graph.
void native_gr_pre_gated(const float* xn, float* gate, float* mixed,
int n_embd, int hc, bool fused_layer, void* stream);
void native_gr_pre_gated_multi(const float* xn, float* gate, float* mixed,
int n_embd, int hc, int n_tok, bool fused_layer, void* stream);
// inject[hc] -> SCALE(1/hc), sigmoid, SCALE(2), identity DSV4_HC_POST.
// residual/output contain [n_embd,hc], block_out has n_embd elements.
// output may equal residual exactly; all other overlaps are invalid.
void native_gr_post(const float* residual, const float* block_out, const float* inject,
float* output, int n_embd, int hc, void* stream);
/// native_gr_post for n_tok tokens in one launch, token t's operands at t times the given strides (floats): the same
/// expression per element. output may equal residual exactly.
void native_gr_post_multi(const float* residual, const float* block_out, const float* inject, float* output,
int n_embd, int hc, int n_tok, long long r_stride, long long b_stride, long long i_stride,
void* stream);
void native_gr_post_multi(const float* residual, const float* block_out, const float* inject,
float* output, int n_embd, int hc, int n_tok, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,37 @@
#pragma once
#include <cstdint>
namespace strata::kernels {
// Configure before constructing/capturing sessions. Existing captures keep their
// selected kernels; changing this flag does not rewrite an existing graph.
void native_moe_combine_set_enabled(bool enabled);
bool native_moe_combine_enabled();
// Pinned CUDA weighted-reduction contract for one token, k in [1, 15].
// The backend fuses k=2..15; k=1 is its ordinary multiply/contiguous/add path.
// parts: k contiguous F32 rows of n_embd; weights: k F32 values. The first
// product rounds to F32, following products accumulate with FMA in expert order,
// and optional shared is added once afterward. Shared is not router weighted.
// Requires a nonnull ordered stream and disjoint output. No allocation or sync.
void native_moe_combine(const float* parts, const float* weights, const float* shared,
float* output, int64_t n_embd, int64_t k, void* stream);
/// n_tok rows (parts [n,k,N], weights [n,k], shared/output [n,N]) in one launch, each as the single call.
/// 143-amdk: native_moe_combine_multi with moe_hit_add folded in: for the rows listed in dst[0, *count) (entry index = token * k + expert,
/// relative to `parts` and `hits`) the expert's part is parts + hits (the add moe_hit_add made in place), then the combine as before.
/// Only the k = 10 vec4 case; `native_moe_combine_hits_supported` says whether a call may use it.
bool native_moe_combine_hits_supported(const float* parts, const float* shared, const float* output, int64_t n_embd, int64_t k, int n_tok);
void native_moe_combine_multi_hits_added(const float* parts, const float* hits, const int32_t* dst, const int32_t* count,
const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k,
int n_tok, void* stream);
void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output,
int64_t n_embd, int64_t k, int n_tok, void* stream);
/// STRATA_VERIFY_RESIDENT: the same, reading every part as `0.0f + hit[i]` - bitwise what a zeroed part row plus
/// moe_hit_add (parts += hit) gave, without the zero fill and the add launch.
void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output,
int64_t n_embd, int64_t k, int n_tok, void* stream);
/// S26 STRATA_LFUSE: the same with `shared` unscaled and shared_gate[t] the shared expert's raw gate logit: the
/// row is scaled by sigmoid(shared_gate[t]) here, bitwise what shared_expert_multi's sigmoid + scale gave.
void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared,
const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok,
void* stream);
}
@@ -0,0 +1,31 @@
#pragma once
#include "strata/kernels/rope_scaling.hpp"
namespace strata::kernels {
void native_rope_set_enabled(bool enabled);
bool native_rope_enabled();
// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, equal text positions in all four
// IMRoPE sections. Each device position must be nonnegative. The position buffer remains live
// through graph replay. Supports head_dim 128/256 and exact x==out; partial overlap is rejected.
// Explicit stream required. No allocation or synchronization.
//
// The scaling (rope_scaling.hpp) rides in as the resolved process config: none reproduces the
// original contract exactly, linear/YaRN apply ggml's rope_yarn - the interpolation mix, the
// corr_dims ramp along the pairs, and the mscale magnitude correction folded into cos and sin.
// The struct's knobs are process constants, so kernel arguments baked at graph capture stay valid.
void native_rope_apply(const float* x, float* out, int rows, int head_dim,
int n_rot, const RopeScaling& scaling, const int* positions, void* stream);
/// (#783 PR-f, stuchapin909) native_qsa_rms_norm_weighted + native_rope_apply in one launch, bit-identical to the pair
/// (rope_parity check 6): x rows are `in_stride` apart (2 * head_dim reads a q row out of a q|gate row), out rows are
/// head_dim apart, x may equal out when in_stride == head_dim. head_dim 128 or 256 and n_rot 64 only.
void native_qsa_rms_norm_rope(const float* x, int in_stride, const float* gamma, float* out,
int rows, int head_dim, int n_rot, float epsilon,
const RopeScaling& scaling, const int* positions, void* stream);
/// Whether callers should take the fused kernel (and the in-place rope's 32-thread launch) for this geometry. On the
/// CUDA build it is on unless STRATA_NO_NORM_ROPE=1; on the HIP build it is off until the AMD parity check passes there
/// (rope_parity check 6) and only STRATA_NORM_ROPE=1 turns it on.
bool native_norm_rope_usable(int head_dim, int n_rot);
}
@@ -0,0 +1,27 @@
#pragma once
#include <cstdint>
namespace strata::kernels {
// Configure before session capture. Existing graphs retain their selected kernels.
// This experiment is off by default and does not modify the legacy router.
void native_router_set_enabled(bool enabled);
bool native_router_enabled();
// Pinned CUDA topk-moe contract for ONE token, 512 experts, top 10, softmax,
// no selection bias, lower normalization clamp 2^-14, and scale 1.
// Reads 512 finite F32 logits; writes 10 I32 IDs and 10 F32 weights. Equal
// computed probabilities select the lower expert index. All spans must be
// four-byte aligned and outputs disjoint from each other and the input.
// Requires a nonnull ordered CUDA stream. No allocation or synchronization.
void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream);
/// n_tok rows at once (logits [n,512], ids/weights [n,10]); each row exactly as the single call.
void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream);
/// The same contract for a model family's (experts, top-k): 512 / 10 (Flash-Next: the two calls above, unchanged) and
/// 256 / 8 (Qwen3.6-35B-A3B). logits [n_tok, n_expert], ids / weights [n_tok, k]. CUDA / HIP.
bool native_router_topk_supported(int n_expert, int k);
void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream);
/// STRATA_ROUTE_RESIDENT: swap non-resident tail-rank experts for resident ones within `margin` logits (see the .cu).
/// `stats` is nullptr or 4 device uint64 counters: tail entries seen, swaps, non-resident before, non-resident after.
void native_route_resident(const float* logits, int32_t* ids, float* weights, const int32_t* res_layer, int n_tok, float margin,
int rank_lo, int rank_hi, unsigned long long* stats, void* stream);
}
@@ -0,0 +1,105 @@
// include/strata/kernels/pdl.hpp - programmatic dependent launch (PDL) for the verify window's kernel chain.
//
// On sm_90+ a kernel launched with cudaLaunchAttributeProgrammaticStreamSerialization may start while the kernel
// before it is still running: everything before `pdl_wait()` overlaps that kernel (and its launch latency), everything
// after it sees the kernel's writes, exactly as after an ordinary launch. The kernels that opt in only LOAD constant
// weights before `pdl_wait()` and write nothing, so every value they compute is unchanged. `pdl_trigger()` lets the
// next kernel launch early (it still waits for this grid to finish before it reads anything). Their activations and
// outputs are not `__restrict__` on CUDA (STRATA_PDL_RESTRICT): with it the compiler may load them before the wait
// (the reason llama.cpp's PDL drops __restrict__ too); the weights keep it.
//
// Stream capture turns the attribute into a programmatic graph edge, which CUDA allows only between two kernel nodes.
// `launch_pdl` therefore uses it only while `pdl_scope()` is set (the verify window's recorder, on a device where
// `pdl_supported()`), only for a kernel whose code was built for sm_90+ (PTX of an older architecture, JIT-compiled,
// has no griddepcontrol.wait: such a kernel would race), and only when every node the capturing stream's next node
// depends on is a kernel - never after a memcpy, a memset, a host node or an event node. After a join of branches
// (several kernels) each edge is programmatic and the wait covers them all; STRATA_DF_PDL=2 allows one predecessor
// only. Everything else is an ordinary launch. On HIP all of this is an ordinary launch, the device functions are
// no-ops and the kernels keep their plain loops (kPdlPrefetch).
#pragma once
#include <cuda_runtime.h>
#include "strata/core/dispatch_stats.hpp"
#include <utility>
namespace strata::kernels {
/// Whether launches on this thread may carry the PDL attribute (set by the verify window's recorder).
bool& pdl_scope();
/// The current device runs PDL: a CUDA 12.3+ build, sm_90+ (STRATA_EMULATE_CC counts), code built for it, and
/// STRATA_DF_PDL is set (1, or 2 for single-predecessor edges only). Always false on HIP.
bool pdl_supported();
#if (defined(__CUDACC__) || defined(__HIPCC__))
// STRATA_PDL_RESTRICT never goes on a __global__ signature: the host pass and the stub must see the same signature on
// every architecture (MSVC rejects the template stubs otherwise, and so does g++ when the stub is generated from a
// device pass). A kernel takes plain pointers and declares `const T* STRATA_PDL_RESTRICT p = p_;` locals in its body.
// On CUDA the activation pointers lose __restrict__ so the compiler cannot load them before pdl_wait() - but only
// where PDL can run (sm_70 and newer here). On Pascal and older (__CUDA_ARCH__ < 700, no PDL) `__restrict__` is what
// lets the compiler use the read-only data path (LDG.CI): without it decode on sm_61 halves (#1469).
#if defined(__HIPCC__)
#define STRATA_PDL_RESTRICT __restrict__
#elif defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700)
#define STRATA_PDL_RESTRICT __restrict__
#else
#define STRATA_PDL_RESTRICT
#endif
#if defined(__HIPCC__)
inline constexpr bool kPdlPrefetch = false; // HIP: no PDL, the kernels keep their plain loops
#else
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700)
inline constexpr bool kPdlPrefetch = false; // Pascal and older: no PDL, the prefetch only costs registers (#1469)
#else
inline constexpr bool kPdlPrefetch = true; // CUDA: the weights a kernel can load before pdl_wait() are loaded there
#endif
/// `kernel` may be launched with the PDL attribute into `stream` now (see the header comment).
bool pdl_launch_ok(const void* kernel, cudaStream_t stream);
#endif
__device__ __forceinline__ void pdl_wait() {
#if !defined(__HIPCC__) && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)
asm volatile("griddepcontrol.wait;" ::: "memory");
#endif
}
__device__ __forceinline__ void pdl_trigger() {
#if !defined(__HIPCC__) && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)
asm volatile("griddepcontrol.launch_dependents;" :::);
#endif
}
/// `kernel<<<grid, block, smem, stream>>>(args...)`, with the PDL attribute when `pdl_launch_ok` says so. A launch
/// error stays the thread's last error for the caller's own check (cudaGetLastError) to report.
template <typename... KArgs, typename... Args>
inline void launch_pdl(void (*kernel)(KArgs...), dim3 grid, dim3 block, size_t smem, cudaStream_t stream,
Args&&... args) {
#if !defined(__HIPCC__)
// BW-MEASURE: inside the verify recorder with STRATA_DF_PDL on, the two notes below say whether a launch got the programmatic edge
if (pdl_scope() && pdl_launch_ok((const void*) kernel, stream)) {
strata::dispatch::note("pdl: launch with a programmatic edge");
cudaLaunchConfig_t cfg = {};
cfg.gridDim = grid;
cfg.blockDim = block;
cfg.dynamicSmemBytes = smem;
cfg.stream = stream;
cudaLaunchAttribute attr[1];
attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attr[0].val.programmaticStreamSerializationAllowed = 1;
cfg.attrs = attr;
cfg.numAttrs = 1;
(void) cudaLaunchKernelEx(&cfg, kernel, std::forward<Args>(args)...);
return;
}
if (pdl_scope()) strata::dispatch::note("pdl: ordinary launch inside a PDL window (kernel not sm_90 code, or a predecessor is not a kernel)");
#endif
kernel<<<grid, block, smem, stream>>>(std::forward<Args>(args)...);
}
#endif // __CUDACC__ || __HIPCC__
} // namespace strata::kernels
@@ -0,0 +1,90 @@
// include/strata/kernels/quantize_act.hpp - activation quantization, host-callable (P2.S2).
//
// `ggml_mul_mat` converts src1 (the ACTIVATION) to the weight's `vec_dot_type` before the dot product. The
// CPU expert path already does this (`bench/micro/cpu_s2.cpp`, int8 + vpdpbusd, parity 1.461e-06); the GPU
// kernels take FP16 activations. Leaving the two inconsistent means the same token computes different
// numbers for different experts, so this is the GPU half of the same rule.
//
// Q2_0 -> Q8_0 is the case that matters most: the routed experts are all Q2_0, which is 31.64 GiB of the 38
// GiB pack. Q8_K is the OTHER HALF of `VEC_DOT_TYPE` (Q3_K/Q4_K/Q5_K/Q6_K/IQ4_XS) and covers 2.89 GiB of
// dense weights - the attention projections and `ssm_out`, i.e. the numerically sensitive ones.
//
// `docs/activation-contract.md` records the decision that BOTH must exist and be used: an FP16 activation
// against a quantized weight disagrees with the oracle by 0.6-0.9%, which is 6-9x P2.S2's 1e-3 tolerance.
#pragma once
#include <cstdint>
namespace strata::kernels {
// x (n floats) -> ggml's block_q8_0 layout: 34 bytes per 32 elements, { fp16 d ; int8 qs[32] }.
// n must be a multiple of 32. `stream` may be null, in which case the call synchronises.
void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream);
// **R4.2h: THE SAME BLOCKS, PLUS THE CPU's fp32 SCALE - and the CPU's rounding rule with it.** The engine
// computes each routed expert twice (misses on the CPU through `act_quant_q8_1`, hits on the GPU through
// `quantize_q8_0`) and the two disagreed: `ActQ::scale` is fp32 while a `block_q8_0` stores fp16 `d`, which is
// **4.761e-04 relative on 80 of 80 chunks** (`bench/micro/act_quant_parity.cu`). This variant exists so the
// hit path can use the CPU's multiplier. Writes `blocks[n/32 * 34]` and `scales[n/32]`; `scales` must not be
// null. `quantize_q8_0` is unchanged and still matches ggml's bytes, which is what `moe_hit_parity` checks.
void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream);
// ===================== fused silu(gate) * up + quantize =====================
//
// One kernel where two ran: the standalone SwiGLU pass wrote the products and the quantizer read them back.
// The products are computed in registers, stored to `gate_out` exactly as the standalone kernels stored them,
// and quantized from those same values - the bytes out are what the two-kernel pipeline produced, with one
// launch and one round trip over the intermediate gone. `gate_out` may alias `gate`.
//
// `swilu_kind` selects the SwiGLU expression this replaces: 0 = the double-precision `ref/moe.py` form
// (`shared_expert`'s legacy kernel), 1 = the S2 expert path's float `__expf` form, 2 = the pinned CUDA
// native form. The expressions live in `strata/kernels/swiglu.cuh`, one copy each.
// n pairs -> ggml block_q8_0 for the products.
void swilu_quantize_q8_0(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream);
// The same blocks plus the CPU contract's fp32 scales (`quantize_q8_0_scaled`).
void swilu_quantize_q8_0_scaled(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, float* scales, void* stream);
// The same for the Q8_K contract (n a multiple of 256).
void swilu_quantize_q8_K(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream);
// ===================== every activation image of x in ONE pass =====================
//
// The layer start wants 2-3 images of the SAME x (ggml block_q8_0, block_q8_K, bf16) and the engine ran one
// kernel per image - three reads and three launches. This produces whichever images the caller asks for in
// one pass; a null pointer skips that image. The bytes of each image are what its standalone kernel wrote
// (the per-block math is shared with those kernels). n must be a multiple of 256 (the Q8_K block).
void quantize_act_images(const float* x, int64_t n, uint8_t* q8_0_blocks, uint8_t* q8_K_blocks,
uint16_t* bf16, void* stream);
// The inverse, for round-trip checks: each element becomes `q * d16`.
void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream);
// x (n floats) -> ggml's block_q8_K layout: 292 bytes per 256 elements
// { float d ; int8_t qs[256] ; int16_t bsums[16] }
// n must be a multiple of 256. `stream` may be null, in which case the call synchronises.
//
// This is `quantize_row_q8_K_ref` (ggml-quants.c L2768) transcribed, including the two things that look like
// mistakes and are not:
//
// * the scale is `-127/max`, NOT `-128/max`. The source carries the `-128` version COMMENTED OUT with the
// note that IQ2_XXS needs the change for an awkward AVX implementation. Getting this wrong is a 0.79%
// scaling error - the same order as the quantisation step, so it yields a working-looking activation that
// ggml never sees. It cost round 120.
// * `max` is the SIGNED value at the position of the largest magnitude, so a POSITIVE max gives a NEGATIVE
// iscale and the `+max` element maps to -127 while the `-max` element maps to +127.
//
// The rounding is `nearest_int`, which is round-half-to-EVEN via the 12582912.0f magic number - not
// `roundf`'s half-away-from-zero. They differ only on exact ties, i.e. almost never on real data, which is
// precisely why the wrong one would survive any amount of end-to-end testing; the parity test constructs
// exact ties on purpose.
void quantize_q8_K(const float* x, uint8_t* blocks, int64_t n, void* stream);
// The inverse: each element becomes `d * qs[j]`, with `d = 1/iscale` stored as f32.
void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream);
} // namespace strata::kernels
@@ -0,0 +1,113 @@
// include/strata/kernels/quantize_act_dev.cuh - the per-block activation quantizers, ONE copy each.
//
// The fusion work (V100) folds `silu(gate) * up` and the activation quantizer that follows it into one
// kernel. For that to be bit-exact the fused kernel must quantize EXACTLY what `quantize_act.cu`'s
// kernels quantize - same amax order, same double `rint`, same clamps. A second copy of the math is a
// second thing to drift, so `quantize_act.cu` and the fused kernels both include this file and call the
// same functions. The standalone kernels are thin wrappers around these; there is no other difference.
#pragma once
#include "strata/kernels/f16_bits.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdint>
#include <cstring>
namespace strata::kernels {
constexpr int Q8_0_BLOCK = 32;
constexpr int Q8_0_BLOCK_BYTES = 34;
constexpr int Q8_K_BLOCK = 256;
constexpr int Q8_K_BLOCK_BYTES = 292;
/// ggml's `nearest_int` (ggml-quants.c L621). The magic constant is 1.5 * 2^23; it is transcribed rather
/// than rewritten as `rintf` because the two differ on exact ties - which is the whole point of it.
__device__ __forceinline__ int nearest_int_dev(float fval) {
const float val = fval + 12582912.0f;
int i;
memcpy(&i, &val, 4);
return (i & 0x007fffff) - 0x00400000;
}
/// `block_q8_0` for one 32-element block, ggml's bytes: `d32 = amax/127` in fp32, `d` stored fp16, the
/// QUANTIZED INTEGERS divided by `d32` (not by the stored fp16), and `rint` in DOUBLE. See the three
/// subtleties in `quantize_act.cu`'s header comment - every one of them is load-bearing.
__device__ __forceinline__ void quantize_q8_0_block(const float* __restrict__ xb, uint8_t* __restrict__ out) {
float amax = 0.0f;
for (int i = 0; i < Q8_0_BLOCK; ++i) amax = fmaxf(amax, fabsf(xb[i]));
if (amax == 0.0f) {
const uint16_t zb = f16_from_f32(0.0f);
out[0] = (uint8_t) (zb & 0xFF);
out[1] = (uint8_t) (zb >> 8);
for (int i = 0; i < Q8_0_BLOCK; ++i) out[2 + i] = 0;
return;
}
const float d32 = amax / 127.0f;
const uint16_t d16bits = f16_from_f32(d32);
out[0] = (uint8_t) (d16bits & 0xFF);
out[1] = (uint8_t) (d16bits >> 8);
for (int i = 0; i < Q8_0_BLOCK; ++i) {
double q = rint((double) xb[i] / (double) d32);
if (q > 127.0) q = 127.0;
if (q < -128.0) q = -128.0;
out[2 + i] = (uint8_t) (int8_t) q;
}
}
/// `block_q8_0` bytes PLUS the fp32 scale and the CPU's rounding rule (round half away from zero) - the
/// `quantize_q8_0_scaled_kernel` body, verbatim, so a hit and a CPU miss agree.
__device__ __forceinline__ void quantize_q8_0_scaled_block(const float* __restrict__ xb,
uint8_t* __restrict__ out, float* __restrict__ scale_out) {
float amax = 0.0f;
for (int i = 0; i < Q8_0_BLOCK; ++i) amax = fmaxf(amax, fabsf(xb[i]));
const float s = amax > 0.f ? amax / 127.f : 0.f;
const float inv = s > 0.f ? 1.f / s : 0.f;
*scale_out = s;
const uint16_t d16bits = f16_from_f32(s);
out[0] = (uint8_t) (d16bits & 0xFF);
out[1] = (uint8_t) (d16bits >> 8);
for (int i = 0; i < Q8_0_BLOCK; ++i) {
const float t = xb[i] * inv;
const float r = t + (t >= 0.f ? 0.5f : -0.5f);
int v = (int) r;
v = v < -127 ? -127 : (v > 127 ? 127 : v);
out[2 + i] = (uint8_t) (int8_t) v;
}
}
/// `block_q8_K` for one 256-element block - the `quantize_q8_K_kernel` body, verbatim (including the
/// zero-block divergence note: bsums are zeroed where ggml leaves them unwritten).
__device__ __forceinline__ void quantize_q8_K_block(const float* __restrict__ xb, uint8_t* __restrict__ out) {
float* d = (float*) out;
int8_t* qs = (int8_t*) (out + 4);
int16_t* bsums = (int16_t*) (out + 4 + Q8_K_BLOCK);
float max = 0.0f, amax = 0.0f;
for (int j = 0; j < Q8_K_BLOCK; ++j) {
const float ax = fabsf(xb[j]);
if (ax > amax) {
amax = ax;
max = xb[j];
}
}
if (amax == 0.0f) {
*d = 0.0f;
for (int j = 0; j < Q8_K_BLOCK; ++j) qs[j] = 0;
for (int j = 0; j < Q8_K_BLOCK / 16; ++j) bsums[j] = 0;
return;
}
const float iscale = -127.0f / max;
for (int j = 0; j < Q8_K_BLOCK; ++j) {
const int v = nearest_int_dev(__fmul_rn(iscale, xb[j]));
qs[j] = (int8_t) min(127, v);
}
for (int j = 0; j < Q8_K_BLOCK / 16; ++j) {
int sum = 0;
for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii];
bsums[j] = (int16_t) sum;
}
*d = 1.0f / iscale;
}
} // namespace strata::kernels
@@ -0,0 +1,193 @@
// include/strata/kernels/rope_scaling.hpp - rope scaling: extending the context past the trained one.
//
// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no
// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by
// rescaling the rotation angles. Three types, the llama.cpp set:
//
// none freq_scale 1, no correction - today's behaviour, exactly
// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all
// frequencies compressed uniformly
// yarn YaRN: high-frequency pairs keep their trained angles (extrapolate), low-frequency
// pairs are interpolated, and the pairs in between blend - plus a magnitude correction
// `mscale` that keeps the attention temperature where training put it
//
// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the
// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the
// interpolation mix and the mscale formula below are line-for-line that source, with the MIT
// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel
// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel
// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against
// `corr_dims` directly. Same numbers, one less division per call site.
//
// HOW IT REACHES THE ROPE. Two forms, one config:
//
// - the TABLE path (the default decode path, the indexer's pooled key) never changes its kernels:
// scaling is baked into the cos/sin contents by `build_rope_table`, which the parity test checks
// bit-exactly against a float64 reference;
// - the ANALYTIC paths (`--native-rope`, the native indexer, prefill) get the resolved constants
// as kernel arguments.
//
// **PROCESS CONSTANTS, SET ONCE BEFORE CAPTURE.** A CUDA graph bakes kernel ARGUMENTS at capture
// time, so the scaling must be fixed before `session_init` captures the layers - which is exactly
// the constraint the per-token values already respect by living in device memory (`st.pos_dev`).
// `rope_scaling_set()` is called once from the engine's startup, after CLI and GGUF defaults meet,
// before any graph exists. There is deliberately no way to change it mid-process: the K already in
// the cache is stored POST-RoPE, so a mid-run change would mix two scalings in one cache.
#pragma once
#include <cmath>
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_ROPE_SCALING_HD __host__ __device__
#else
#define STRATA_ROPE_SCALING_HD
#endif
namespace strata::kernels {
enum class RopeScalingType { None, Linear, YaRN };
/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are
/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f`
/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit.
struct RopeKernelArgs {
float freq_scale = 1.0f;
float corr_low = 0.0f;
float corr_high = 0.0f;
float ext_factor = 0.0f;
float attn_factor = 1.0f;
};
/// The one rope configuration, as the CLI flag family and the (future) GGUF rope keys resolve to.
///
/// Default-constructed this is EXACTLY today's engine: freq_scale 1, mscale 1, no correction. That
/// identity is a regression gate, not a coincidence - the parity test compares the default's table
/// against the pre-scaling builder bit for bit.
struct RopeScaling {
RopeScalingType type = RopeScalingType::None;
double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`)
double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes
double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor
double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over
double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN
double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor)
double beta_fast = 32.0; ///< `--yarn-beta-fast`
double beta_slow = 1.0; ///< `--yarn-beta-slow`
/// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes
/// `factor` positions into the trained range.
double freq_scale() const {
if (type == RopeScalingType::None) return 1.0;
return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor;
}
/// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term
/// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the
/// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction.
double mscale() const {
if (ext_factor == 0) return attn_factor;
return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale()));
}
/// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained
/// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's
/// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below).
void corr_dims(int n_rot, double out[2]) const {
const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base));
const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base));
out[0] = start < 0 ? 0 : start;
out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end;
}
/// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold -
/// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an
/// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn`
/// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting).
RopeKernelArgs kernel_args(int n_rot) const {
RopeKernelArgs a;
if (type == RopeScalingType::None) return a;
double cd[2];
corr_dims(n_rot, cd);
a.freq_scale = (float) freq_scale();
a.corr_low = (float) cd[0];
a.corr_high = (float) cd[1];
a.ext_factor = (float) ext_factor;
a.attn_factor = (float) attn_factor;
return a;
}
private:
/// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)`
/// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`".
/// float64 rather than ggml's float32: the table path computes in float64 and is held to a
/// bit-exact float64 reference, so its inputs are float64 too.
static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) {
return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) /
(2.0 * std::log(base));
}
};
/// The ramp between extrapolation (1) and interpolation (0).
///
/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with
/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes
/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The
/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high.
STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) {
const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f);
const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y);
return 1.0f - clamped;
}
/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic).
///
/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle
/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor`
/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant;
/// this helper keeps that shape so the native path reads against ggml line by line).
STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low,
float corr_high, float ext_factor, float mscale_in,
int pair, float& cos_out, float& sin_out) {
// The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn).
float theta = freq_scale * theta_extrap;
float mscale = mscale_in;
if (ext_factor != 0.0f) {
const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor;
theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix;
// "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting.
mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale);
}
cos_out = cosf(theta) * mscale;
sin_out = sinf(theta) * mscale;
}
/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation
/// site that takes the struct, so a bad knob cannot pass one site and trip (or silently NaN) another. Returns
/// nullptr when the configuration is usable, else what is wrong. Every value is tested with `std::isfinite`
/// FIRST: a NaN passes every `<`/`<=` range comparison, which is how a `--rope-scale nan` would otherwise slip
/// through. `none` passes with any knob values - the knobs are inert there (the resolution resets them).
inline const char* rope_scaling_invalid(const RopeScaling& s) {
if (!std::isfinite(s.freq_base) || s.freq_base <= 1.0) return "the frequency base must be a finite value above 1";
if (s.type == RopeScalingType::None) return nullptr;
if (!std::isfinite(s.factor) || s.factor < 1.0) return "the scaling factor must be a finite value >= 1";
if (!std::isfinite(s.freq_scale_in) || s.freq_scale_in < 0.0)
return "the frequency scale must be finite and positive (0 = 1/factor)";
const double fs = s.freq_scale();
if (!std::isfinite(fs) || fs <= 0.0) return "the resolved frequency scale must be a finite positive value";
if (!std::isfinite(s.orig_ctx) || s.orig_ctx < 1.0) return "the original (trained) context must be finite and > 0";
if (!std::isfinite(s.ext_factor) || s.ext_factor < 0.0) return "the YaRN ext factor must be finite and >= 0";
if (!std::isfinite(s.attn_factor) || s.attn_factor <= 0.0) return "the attention factor must be finite and > 0";
if (!std::isfinite(s.beta_fast) || s.beta_fast <= 0.0 || !std::isfinite(s.beta_slow) || s.beta_slow <= 0.0)
return "the YaRN betas must be finite and > 0";
if (!std::isfinite(s.mscale()) || s.mscale() <= 0.0) return "the resolved magnitude correction must be finite and > 0";
return nullptr;
}
/// The process's one rope configuration. Set it ONCE at startup, after the CLI and the model file
/// have agreed on the values and BEFORE `session_init` (which builds the rope table and captures the
/// graphs); read it at table build time and when launching the analytic kernels. Plain storage, no
/// atomics: one writer on the startup thread, every reader after it.
void rope_scaling_set(const RopeScaling& scaling);
const RopeScaling& rope_scaling();
} // namespace strata::kernels
@@ -0,0 +1,42 @@
// include/strata/kernels/swiglu.cuh - the SwiGLU expressions, ONE copy each.
//
// The fusion work (V100) moves `silu(gate) * up` into the epilogue of the projection that computes `up`.
// For that to be bit-exact the fused epilogue must compute EXACTLY the expression the standalone kernel
// computed - same operations, same precision, same order. A second copy of the expression is a second
// thing to drift, so every caller (the standalone kernels and the fused epilogues) includes this file.
//
// THREE VARIANTS, because the engine really has three:
//
// `swilu_legacy` the `ref/moe.py` transcription: silu in DOUBLE then cast, multiply in float
// (`shared_expert.cu`'s `swiglu_kernel`, and the S2 expert path used to use this shape).
// `swilu_fast` the S2 expert path's float expression with `__expf`
// (`s2_expert_grouped.cu`'s `swiglu_kernel`).
// `swilu_native` the pinned CUDA contract: `__fdividef` and `__expf`
// (`shared_expert.cu`'s `native_swiglu_kernel`).
//
// Bit-exactness across translation units: both call sites compile this with the same CUDA flags (no
// `--use_fast_math` on the files that use the legacy and fast variants), the expressions are straight-line
// IEEE ops around one libdevice call, and the parity tests compare the fused and unfused pipelines bitwise.
#pragma once
#include <cuda_runtime.h>
namespace strata::kernels {
/// `out = (float)((double)g / (1.0 + exp(-(double)g))) * u` - `shared_expert.cu`'s `swiglu_kernel`.
__device__ __forceinline__ float swilu_legacy(float g, float u) {
const double x = (double) g;
return (float) (x / (1.0 + exp(-x))) * u;
}
/// `out = (g / (1.0f + __expf(-g))) * u` - `s2_expert_grouped.cu`'s `swiglu_kernel`.
__device__ __forceinline__ float swilu_fast(float g, float u) {
return (g / (1.0f + __expf(-g))) * u;
}
/// `out = __fdividef(g, 1.0f + __expf(-g)) * u` - `shared_expert.cu`'s `native_swiglu_kernel`.
__device__ __forceinline__ float swilu_native(float g, float u) {
return __fdividef(g, 1.0f + __expf(-g)) * u;
}
} // namespace strata::kernels
@@ -0,0 +1,258 @@
// include/strata/kernels/verify_kernels.hpp - plan v0.3 P6: kernels for the speculative VERIFY window, where T
// tokens (the last accepted token and T-1 drafts) go through a layer at once.
//
// The GDN recurrence is the one piece of state that cannot simply be overwritten by the next window, so its
// kernels come in two halves:
//
// * the verify half reads the conv history and the recurrent state, runs all T tokens in order (bitwise the
// single-token kernels' arithmetic per token) and writes ONLY the per-token outputs - the state is left
// untouched;
// * the commit half, launched once acceptance is known, replays the first `n_keep` tokens from the inputs the
// verify half stored and writes the state. Rejected tokens therefore never touch the state and there is no
// snapshot of the 113 MB recurrent state to keep.
//
// Everything that varies per window (token ids, `n_keep`) is read from DEVICE memory so the kernels can be captured.
#pragma once
#include "strata/kernels/window_limits.hpp"
#include <cstdint>
namespace strata::kernels {
/// The most rows one verify / batch window holds (8; 16 in the CUDA / HIP builds, window_limits.hpp). A window of up to
/// kVerifyNarrowT rows runs the kernels it always ran.
inline constexpr int kVerifyMaxT = kWindowMaxT;
/// --lookup-max-t: the longest one-conversation window (a prompt-lookup window). In a build whose windows hold 8 rows, a
/// window past kVerifyMaxT tokens runs as two token groups of at most kVerifyMaxT each (the --spec-split layout), so every
/// per-group kernel, the CPU experts and the drafter keep their kVerifyMaxT rows; only the window-wide parts (staging,
/// head, commit) take more. A build whose windows already hold 16 rows runs the 16 as one group.
/// Batch and pipelined windows stay at kVerifyMaxT.
inline constexpr int kVerifyLongT = kVerifyMaxT > kVerifyNarrowT ? kVerifyMaxT : 2 * kVerifyMaxT;
/// For token t of T: conv over [history(3) | qkv_0 .. qkv_t] -> SiLU -> L2 norm of the q/k heads -> h[t].
/// `history` is NOT written, but with `commit` (one token): it then keeps the token, as gdn_conv_commit. Bitwise
/// `fused_gdn_conv_l2` per token.
void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels,
int qk_heads, float eps, int n_tok, void* stream, int t_begin = 0, bool commit = false);
/// history <- the last 3 entries of [history | qkv_0 .. qkv_{n-1}], n = *n_keep (0 leaves it as it was).
void gdn_conv_commit(float* history, const float* qkv, int channels, const int32_t* n_keep, void* stream);
/// alpha/beta for T columns of x (T, n_embd): gate (T, h_v), beta (T, h_v). Bitwise `fused_gdn_ab` per column.
/// gdn_conv_l2_multi and gdn_ab_multi in one launch (143-amdk)
void gdn_conv_ab_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
float eps, int n_tok, int t_begin, bool commit, const float* x, const uint16_t* w_alpha,
const uint16_t* w_beta, const float* dt, const float* ssm_a, float* gate, float* beta, int n_embd,
int h_v, void* stream);
void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
float* gate, float* beta, int n_embd, int h_v, int n_tok, void* stream);
/// The recurrence + output norm for T tokens (h = (T, conv_channels) as q|k|v, gate/beta (T, h_v), z/y
/// (T, value_dim)). With `n_keep == nullptr` the state is read and NOT written (verify); otherwise the first
/// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`.
/// Batch windows: up to 8 slot groups in one launch - group i is rows [first[i], first[i] + ntok[i]) of the
/// window's buffers, recurring over its own slot's state[i] (and committing keep[i] tokens when keep is given).
struct GdnGroups {
float* state[8] = {};
const int32_t* keep[8] = {};
int first[8] = {};
int ntok[8] = {};
int n = 0;
};
/// gdn_step_norm_multi over several slots' groups at once (the generic kernel, grid.y = group; per group the
/// same arithmetic as one call each: bit-identical). `commit`: every group keeps *keep[i] tokens, no outputs used.
void gdn_step_norm_groups(const GdnGroups& groups, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, bool commit,
void* stream);
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
const int32_t* n_keep, void* stream, int t_out_begin = 0, void* xq_out = nullptr);
/// The commit of `n_layers` GDN layers in two launches (engine-latency): layer i's conv history is
/// `state + i * state_stride + conv_off` and its qkv rows `qkv + i * qkv_stride`, as gdn_conv_commit; its recurrence
/// state `state + i * state_stride` over the first *n_keep rows of `h + i * h_stride` / `gate|beta + i * gb_stride`, as
/// gdn_step_norm_multi's commit (n_keep set, no outputs). Every layer's arithmetic is the per-layer call's, so the result
/// is bitwise the loop of per-layer calls. Returns false (nothing launched) when the per-layer commit would not take the
/// state-only kernel (STRATA_GDN_SPLIT=1, STRATA_GDN_COMMIT_SPLIT=0, STRATA_DBG_GDN=1): the caller then keeps the loop.
bool gdn_commit_layers(float* state, int64_t state_stride, int64_t conv_off, const float* qkv, int64_t qkv_stride,
const float* h, int64_t h_stride, const float* gate, const float* beta, int64_t gb_stride,
int conv_channels, int h_k, int h_v, int n_max, int n_layers, const int32_t* n_keep, void* stream);
/// (xq_out, S26 STRATA_QFUSE: also write the q8_1 image of output rows [t_out_begin, n_tok) there - the bytes
/// native_quantize_q8_1(y + t_out_begin * value_dim, xq_out, value_dim, n_tok - t_out_begin) would write.)
/// Spin until *flag >= value (a mapped host flag). The value is fixed at capture, so several rings can be
/// outstanding at once (the split verify window keeps two).
void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream);
/// BW-5 (STRATA_L2_PF=1): device ranges to pull into the L2 cache. `l2_prefetch_ranges` issues a prefetch hint for every
/// byte of them (`cp.async.bulk.prefetch.L2` on sm_90+, `prefetch.global.L2` below); it reads and writes nothing, so every
/// value the window computes is unchanged. A no-op on HIP.
struct L2PrefetchSet {
static constexpr int kMax = 32;
unsigned long long ptr[kMax];
unsigned long long bytes[kMax];
unsigned first_chunk[kMax + 1]; ///< filled by l2_prefetch_finish
int n = 0;
unsigned long long total_bytes = 0;
void add(const void* p, unsigned long long b) {
if (p == nullptr || b < 16 || n >= kMax) return;
const unsigned long long a = (unsigned long long) (uintptr_t) p;
const unsigned long long lo = a & ~15ull;
ptr[n] = lo;
bytes[n] = (b + (a - lo)) & ~15ull;
total_bytes += bytes[n];
++n;
}
};
void l2_prefetch_ranges(const L2PrefetchSet& set, void* stream);
/// wait_flag_ge and copy_i32_from_mapped in ONE launch (143-amdk): thread 0 spins on *flag >= value, the block then
/// copies dst[0, n) = src[0, n) (mapped host memory, volatile reads). One kernel node fewer per layer: a dependent
/// kernel costs ~2.4 us on a gfx1201 graph whatever it does. n <= 128 * k for any k (a strided loop).
void wait_copy_i32_from_mapped(const uint32_t* flag, uint32_t value, int32_t* dst, const int32_t* src, int64_t n,
void* stream);
/// Layer split, overlapped hand-off (STRATA_SPLIT_OVERLAP): dst (mapped) = [a (na) | b (nb) | c (nc)] with volatile
/// stores, then the LAST block to finish raises *flag = 1 (mapped) after a system fence, so the next stage's GPU can
/// start (wait_flag_ge(flag, 1)) without the host syncing this stage first. `counter` is one device word, 0 between
/// calls (the last block resets it). Volatile because on RDNA a plain store to mapped memory can sit in the L2.
/// `drop` (mapped, may be null): a test hook - nonzero leaves the flag down, as if the publish were lost.
void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc,
uint32_t* counter, uint32_t* flag, void* stream, const uint32_t* drop = nullptr);
/// The reading stage's hand-off wait, bounded: spin until *flag >= value, or after timeout_ns (0: no bound) set
/// *err = 1 (mapped) and return, so the window's graph completes and the host fails the window cleanly.
void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream);
/// wait_flag_ge, also writing the GPU's clock (ns, gpu_stamp's) as the kernel starts into *t_in and as it returns
/// into *t_out (either may be null): the verify window's PCIe-share balance, at no extra launch.
void wait_flag_ge_stamped(const uint32_t* flag, uint32_t value, unsigned long long* t_in, unsigned long long* t_out,
void* stream);
/// the GPU's %globaltimer (ns) into buf[i] (a one-thread kernel: the verify window's stage profiler). Inside a PDL
/// stretch (pdl.hpp) the stamp passes the early launch on, so a profiled window keeps the chain it measures.
void gpu_stamp(unsigned long long* buf, int i, void* stream);
/// an empty one-thread kernel (a graph node that does nothing: STRATA_DUMMY_NODES measures what a node costs in a window)
void gpu_noop(void* stream);
/// dst[r][0, w) = src[r][0, w) for `rows` rows of source stride `src_w` floats (the query half of each q/gate head
/// pair): the strided device-to-device cudaMemcpy2DAsync as a kernel, so the window's chain stays kernel to kernel.
/// w and src_w multiples of 4 floats, both pointers 16-byte aligned.
void copy_rows_strided(float* dst, const float* src, int64_t rows, int64_t w, int64_t src_w, void* stream);
// ---- perf-review E-6: a layer whose routed experts are all in VRAM needs nothing from the host
/// One group's plan, built on the device when every routed expert of its n*k entries is resident: the host pool's
/// layout (counts | start | dst | tok | pad | ptr | ptr2 | start2, `capx` entries) and order (distinct experts in
/// routing order, their entries ascending), no PCIe groups. *skip = ring when it did, else 0.
/// #871: without `skip` (the all-resident graph) an entry whose expert is not in VRAM cannot be planned: the plan is
/// left empty and *plan_err (mapped host memory) is set to 1, so the host sees it instead of running a stale plan.
void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert,
const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,
long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err = nullptr);
/// Partial-VRAM on-device hit plan (`STRATA_VERIFY_DEVICE_HITS=1`, `--pcie-frac 0`, CUDA / HIP): groups only the
/// resident routed experts (`res_layer[e] >= 0`) in first-occurrence routing order into `plan` (`counts = {hit_groups,
/// hit_entries, 0}`), matching `expert_pool_dispatch_multi` when `fetches == 0` without waiting on `m_flagA_`/`m_flagB_`.
void resident_hits_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert,
const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,
long long capx, void* stream);
/// Opt-in `STRATA_ROUTE_TAIL_RENORM=1` (CUDA / HIP): zeroes routing weights of missed experts (`res_layer[e] < 0`)
/// routed exclusively at rank >= `tail_rank` across the `n_tok` rows of the window, and rescales each row's remaining
/// weights so their sum equals the row's original router weight sum.
void route_tail_renorm(const int32_t* ids, float* weights, const int32_t* res_layer, int n_tok, int k, int n_expert,
int tail_rank, void* stream);
/// wait_flag_ge that also returns when *skip == value (device memory).
void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream);
/// copy_i32_from_mapped unless *skip == value.
void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value,
void* stream);
/// copy_from_mapped, or zeros when *skip == value (n a multiple of 4, 16-byte aligned).
void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value,
void* stream);
/// Rows of the S2/S4/S8 embedding for T token ids read from DEVICE memory; out (T, n). Bitwise `embedding_gather`.
void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens,
int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes,
uint64_t row_groups, float* out, void* stream);
/// R[t][c][:] = x[t][:] for the hc streams.
void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream);
/// out[:n_embd] = the mean of the hc streams of ONE row R[hc][n_embd] (the DFlash2 drafter's target features; only the
/// STRATA_TAP_FILE hook calls it).
void hc_mean_streams(const float* R, float* out, int64_t n_embd, int hc, void* stream);
/// STRATA_ROUTE_STATS only: acc[r] += the number of ids of row r (k per row, n rows <= 8) that no earlier row of the window holds
/// (duplicates inside a row count once).
void route_marginal_stats(const int32_t* ids, int n, int k, unsigned long long* acc, void* stream);
/// dst[:n] = src[(*index) * stride + :n] (index read from device memory; a negative index copies nothing).
void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream);
/// Plan v0.3 P6: copy *n (device memory) blobs of `blob_bytes` from mapped host memory (src[k], device aliases)
/// into dst + k * blob_bytes with coalesced 16-byte loads - the PCIe share of a layer's missed experts, staged
/// into VRAM before the grouped expert kernel reads them. Launched for a capacity of `cap` blobs.
void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream);
/// The same with `dst2` (device memory, may be null): blob k goes to dst2[k] instead where that is not 0
/// (STRATA_ADAPT_FETCH: a VRAM cache slot). A separate overload, so the SYCL copy keeps the one above.
void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream,
const unsigned long long* dst2);
/// table[pairs[2k]] = pairs[2k + 1] for k < n, `pairs` in mapped host memory: a residency table's changed entries,
/// stream-ordered before the window that reads it, without the copy engine (where the tier's swaps may queue).
void res_patch(int32_t* table, const int32_t* pairs, int n, void* stream);
/// ptr[k] = base + k * blob_bytes for k < *n (the staged copies `fetch_blobs` made).
void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream);
/// The same, or dst2[k] where `dst2` (may be null) is not 0 (fetch_blobs' second target).
void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream,
const unsigned long long* dst2);
// ---- the MTP draft layer (src/core/mtp.cpp)
/// R[t][c][:] = h[t][c][:] + e[t][:] (the embedding branch added to every stream).
void add_streams_broadcast(const float* h, const float* e, float* R, int64_t n_embd, int hc, int n_tok, void* stream);
/// Every routed expert is resident (slot = expert id): slot[i] = ids[i], dst[i] = i, *count = n.
void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* count, void* stream);
/// The draft chain's next input: R_dst[:] = R_src[row], tok_dst[0] = ids[row], out[j] = ids[row], with
/// row = *row_dev (device memory). `out` may be mapped host memory.
void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst,
int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs = nullptr,
float* out_p = nullptr);
/// --pipeline-windows, the drafter's chain teacher forced: `*tok = force[j]` when force[j] >= 0 (`force` is mapped
/// host memory, read when the kernel runs), else `*tok` is left as it is.
void force_token(int32_t* tok, const int32_t* force, int j, void* stream);
/// Row *row_dev of a, b and c (a_n, b_n, c_n floats a row) copied to their row 0 (the draft layer's rest runs on
/// row 0). Graph-capturable: the row is read on the device.
void copy_row_to_first(const int32_t* row_dev, float* a, int64_t a_n, float* b, int64_t b_n, float* c, int64_t c_n,
void* stream);
/// dst row i = src row ids[i] (row_bytes each, multiple of 16), for n rows.
void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream);
/// ids[t] = table[ids[t]] for n entries (a subset index back to a token id).
void map_ids(int32_t* ids, const int32_t* table, int n, void* stream);
/// probs[t] = softmax(logits[t])[ids[t]] for n_rows rows of n_vocab (the probability of each row's argmax).
void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream);
/// out[t] = the argmax of row t (n floats a row; ties to the lowest index, NaN never picked, 0 when no value is above
/// -inf): bitwise sample_tokens' greedy pick. Up to 128 blocks a row scan slices of it, the row's last block merges
/// their picks. `scratch`: argmax_rows_scratch_bytes(n_rows), zero before the first launch (each launch leaves it
/// so). Graph-capturable.
uint64_t argmax_rows_scratch_bytes(int n_rows);
void argmax_rows(const float* logits, int n_rows, int n, void* scratch, int32_t* out, void* stream);
/// Same reduction as argmax_rows, adding `idx_offset` to each winning index and optionally writing each row's winning logit to `out_val`.
void argmax_rows_val_idx(const float* logits, int n_rows, int n, int idx_offset, void* scratch, float* out_val,
int32_t* out_idx, void* stream);
/// Merge two half-vocabulary argmax results while preserving lower-index tie breaking (`b > a`).
void argmax_merge_halves(const float* v0, const int32_t* i0, const float* v1, const int32_t* i1, int n_rows,
int32_t* out, void* stream);
/// Bitwise OR `src[0..n)` into `dst[0..n)`.
void or_u32_rows(uint32_t* dst, const uint32_t* src, int n, void* stream);
/// row_top_prob over 8 blocks a row, each computing 4 of its 32 warps' sums, the row's last block adding the 32 in
/// order: bitwise row_top_prob. `scratch`: row_top_prob_scratch_bytes(n_rows), zero before the first launch.
uint64_t row_top_prob_scratch_bytes(int n_rows);
void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* scratch,
void* stream);
/// #879 guard: flags[t * kNonfiniteBlocks + b] = 1 when slice b of row t (n floats a row) holds a NaN or an infinity,
/// else 0, for n_rows rows. Every word is written on every launch (nothing to clear between windows), so `flags` can
/// be mapped host memory read after the window's own sync. Graph-capturable; CUDA and HIP.
inline constexpr int kNonfiniteBlocks = 16;
void logits_nonfinite_rows(const float* logits, int n_rows, int n, uint32_t* flags, void* stream);
/// True where row_top_prob_split runs as its own kernel (CUDA; AMD keeps the one-block row_top_prob, so it calls
/// that). STRATA_MULTI_BLOCK_ARGMAX=0: off.
bool multi_block_head_ops();
/// True where the verify head's and the draft's greedy pick should be argmax_rows: sm_80 to sm_89 (the one-block
/// kernel is slow there; sm_90+ has sample_tokens' cluster kernel, other cards keep sample_tokens).
bool argmax_rows_wanted();
/// Dense-attention step records for `n` cells: [cell, cell+1, (cell+1)/4, cell+1] from cells[i] (device memory).
void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream);
/// A sliding attention window: for `n` step records (kStepCount ints each, n_kv at [1]) the selection becomes the
/// last `window` cells: ids[q * ids_stride + j] = max(0, n_kv - window) + j and the record's width = the count.
void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream);
/// window_ids whose window starts no lower than the cell `*floor_cell` (device-visible memory, read when the kernel
/// runs; KVA: the first draft cell built from a real row). `window` may be INT_MAX for "every cell". A floor of 0
/// selects exactly what window_ids selects. CUDA / HIP only.
void window_ids_floor(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, const int32_t* floor_cell,
void* stream);
} // namespace strata::kernels
@@ -0,0 +1,27 @@
// include/strata/kernels/window_limits.hpp - how many rows one verify / batch window can hold.
//
// Until 0.2.7 a window held at most 8 rows. The CUDA and HIP engines now hold up to 16 (four pipelined groups of 16
// slots = 64 slots on a four-card split: docs/BATCHING.md), so every compile-time maximum that follows the window
// (the verifier's per-row arrays, the expert pool's per-token tables, the resident plan's one-thread-per-entry block)
// is derived from ONE number. It is a macro because the SYCL and Metal builds compile the same shared headers and
// must not change: they get the default, 8. The CUDA / HIP CMake sets STRATA_VERIFY_MAX_T from the cache variable
// STRATA_WINDOW_MAX_T (8 or 16; -DSTRATA_WINDOW_MAX_T=8 builds an engine whose windows are the 0.2.7 ones).
//
// The rule every user of the number follows: a window of up to kVerifyNarrowT rows runs EXACTLY the code it ran at 8
// (the same kernel instantiations, the same buffer sizes); the wider code is reached only by a window of 9..16 rows.
#pragma once
#ifndef STRATA_VERIFY_MAX_T
#define STRATA_VERIFY_MAX_T 8
#endif
namespace strata::kernels {
/// The window every 0.2.7 kernel was built for: windows of up to this many rows keep their instantiations.
inline constexpr int kVerifyNarrowT = 8;
/// The most rows one window can hold in this build (8 or 16).
inline constexpr int kWindowMaxT = STRATA_VERIFY_MAX_T;
static_assert(kWindowMaxT == 8 || kWindowMaxT == 12 || kWindowMaxT == 16, "STRATA_VERIFY_MAX_T is 8, 12 or 16");
} // namespace strata::kernels
@@ -0,0 +1,189 @@
// src/kernels/cuda/bf16_gemv.cu - the BF16 GEMV. See the header for why it is not `s_gemv`.
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
namespace strata::kernels {
namespace {
constexpr int THREADS = 256;
/// One thread per output row, walking it contiguously. Kept as the naive reference the split version is
/// checked against, and used directly for the shapes where the output width is already large.
__global__ void bf16_gemv_naive_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
float* __restrict__ y, long long n_in, long long n_out) {
const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (o >= n_out) return;
const uint16_t* row = w + o * n_in;
float acc = 0.0f;
for (long long i = 0; i < n_in; ++i)
acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
y[o] = acc;
}
/// One WARP per output row, lanes striding the reduction axis. For a fixed `i` consecutive lanes touch
/// consecutive addresses in this layout, so the load is coalesced - the property that took `gr_read` from
/// 262 ms/token to 8.9.
__global__ void bf16_gemv_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
float* __restrict__ y, long long n_in, long long n_out) {
const int warps_per_block = (int) (blockDim.x >> 5);
const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
if (o >= n_out) return;
const int lane = threadIdx.x & 31;
const uint16_t* row = w + o * n_in;
float acc = 0.0f;
for (long long i = lane; i < n_in; i += 32)
acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off);
if (lane == 0) y[o] = acc;
}
/// TPR lanes cooperate on ONE row's reduction: `threads_per_row` threads each take a strided slice and the
/// block reduces through shared memory. Used when the output width is too small to fill the machine.
__global__ void bf16_gemv_split_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
float* __restrict__ y, long long n_in, long long n_out, int tpr) {
extern __shared__ float scratch[];
const long long o = blockIdx.x;
if (o >= n_out) return;
const int t = threadIdx.x; // 0 .. tpr-1
const uint16_t* row = w + o * n_in;
float acc = 0.0f;
for (long long i = t; i < n_in; i += tpr)
acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
// block reduction; `tpr` is at most a few hundred, so a tree in shared is enough
scratch[t] = acc;
__syncthreads();
for (int off = tpr >> 1; off > 0; off >>= 1) {
if (t < off) scratch[t] += scratch[t + off];
__syncthreads();
}
if (t == 0) y[o] = scratch[0];
}
/// TWO weight matrices from one read of x - llama.cpp's `*_mul_mat_multi` shape. One warp computes row `o`
/// of `w1` and row `o` of `w2` with two independent accumulators over the SAME lane-strided loop, so each
/// accumulator sees the addend sequence its standalone `bf16_gemv_warp_kernel` run gave it: bitwise equal
/// (checked by `bf16_gemv_pair_parity`). Rows past a matrix's `n_out` skip that accumulator only.
__global__ void bf16_gemv_pair_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w1,
float* __restrict__ y1, long long n_out1,
const uint16_t* __restrict__ w2, float* __restrict__ y2,
long long n_out2, long long n_in) {
const int warps_per_block = (int) (blockDim.x >> 5);
const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
const int lane = threadIdx.x & 31;
const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2;
if (o >= n_out) return;
const int run1 = o < n_out1, run2 = o < n_out2;
const uint16_t* r1 = w1 + o * n_in;
const uint16_t* r2 = w2 + o * n_in;
float acc1 = 0.0f, acc2 = 0.0f;
for (long long i = lane; i < n_in; i += 32) {
const float xv = f32_from_bf16(x[i]);
if (run1) acc1 += xv * f32_from_bf16(r1[i]);
if (run2) acc2 += xv * f32_from_bf16(r2[i]);
}
if (run1) {
float a = acc1;
for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off);
if (lane == 0) y1[o] = a;
}
if (run2) {
float a = acc2;
for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off);
if (lane == 0) y2[o] = a;
}
}
inline void finish(void* stream, const char* what) {
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e));
std::exit(1);
}
if (stream != nullptr) return;
const cudaError_t s = cudaDeviceSynchronize();
if (s != cudaSuccess) {
std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(s));
std::exit(1);
}
}
} // namespace
void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream) {
if (n_in <= 0 || n_out <= 0) return;
// **THIS USED TO ALWAYS USE THE NAIVE KERNEL, AND THE NAIVE KERNEL IS UNCOALESCED.**
//
// `bf16_gemv_naive_kernel` gives one THREAD per output row and walks the row contiguously, so at a fixed
// `i` the 32 threads of a warp read `w[(o+k)*n_in + i]` - addresses `n_in * 2` bytes apart. Every load in
// the kernel's inner loop costs 32 transactions instead of 1. The comment above that kernel claims it is
// "used directly for the shapes where the output width is already large", but nothing ever made that
// choice: this function called it unconditionally, at every shape.
//
// What that costs, from the nsys per-kernel table: **4.66 ms/token across 24 calls, 194 us each** - the
// third largest kernel in the engine at the time, moving 1.19 GiB/token at ~210 GB/s where a plain read at
// this geometry measures 641 GB/s (`bench/micro/p32_floor.cu`).
//
// `bf16_gemv_warp_kernel` exists, is checked against this one by `bf16_gemv_parity`, and is coalesced -
// consecutive lanes touch consecutive addresses - which is the property `gr_read`'s comment records as
// having taken it from 262 ms/token to 8.9. The threshold below is where warp-per-row has enough rows to
// fill the machine: 8 warps per block, so 64 rows is 8 blocks and 128 is 16, against 48 SMs.
if (n_out >= 64) {
const int warps = THREADS / 32;
const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
bf16_gemv_warp_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(x, w, y, n_in, n_out);
finish(stream, "bf16_gemv(warp)");
return;
}
// Below the threshold the warp kernel would leave most of the machine idle, and the naive one is at least
// not wasting warps. It is still uncoalesced, so this is the branch to revisit if a small-output caller
// ever shows up hot in the profile.
const unsigned grid = (unsigned) ((n_out + THREADS - 1) / THREADS);
bf16_gemv_naive_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(x, w, y, n_in, n_out);
finish(stream, "bf16_gemv");
}
void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2,
float* y2, int64_t n_out2, int64_t n_in, void* stream) {
if (n_in <= 0 || (n_out1 <= 0 && n_out2 <= 0)) return;
// THE PAIR KERNEL IS THE WARP-PER-ROW ACCUMULATION on both sides, so it is bitwise what
// `bf16_gemv` (n_out >= 64) and `bf16_gemv_split` at tpr 32 produced. Callers whose standalone path
// was the NAIVE kernel (a small `n_out` with the plain entry) must not use this.
const int warps = THREADS / 32;
const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2;
const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
bf16_gemv_pair_warp_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(
x, w1, y1, n_out1, w2, y2, n_out2, n_in);
finish(stream, "bf16_gemv_pair");
}
void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out,
int threads_per_row, void* stream) {
if (n_in <= 0 || n_out <= 0) return;
// WARP-PER-ROW when the caller asks for 32, because that path needs no shared memory and no barrier - and
// with 48 output rows it is the configuration that fills the machine. A `tpr` that is not 32 and not a
// power of two is refused rather than quietly rounded, because the tree reduction below needs one.
if (threads_per_row == 32) {
const int warps = THREADS / 32;
const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
bf16_gemv_warp_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(x, w, y, n_in, n_out);
finish(stream, "bf16_gemv_split(warp)");
return;
}
if (threads_per_row <= 0 || (threads_per_row & (threads_per_row - 1)) != 0) {
std::fprintf(stderr, "bf16_gemv_split: threads_per_row %d must be a power of two (32 selects the "
"warp-per-row path)\n", threads_per_row);
std::exit(1);
}
const unsigned grid = (unsigned) n_out;
bf16_gemv_split_kernel<<<grid, threads_per_row, (size_t) threads_per_row * sizeof(float),
(cudaStream_t) stream>>>(x, w, y, n_in, n_out, threads_per_row);
finish(stream, "bf16_gemv_split");
}
} // namespace strata::kernels
@@ -0,0 +1,186 @@
// src/kernels/cuda/fused_gdn.cu - see include/strata/kernels/fused_gdn.hpp.
#include "strata/kernels/fused_gdn.hpp"
#include "strata/core/geometry.hpp"
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
namespace strata::kernels {
namespace {
constexpr int S = 128; // state size (rows = cols = 128)
static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "fused_gdn is compiled for core/geometry.hpp");
constexpr int RG = 4; // row groups
constexpr int RPG = S / RG; // 32 rows per thread
// SILU: the output gate is SiLU(z) (Qwen3.6, qwen35moe) instead of sigmoid(z) (Flash-Next); a compile-time flag, so
// the sigmoid instantiation is the kernel it was.
template <bool SILU>
__global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict__ state, const float* __restrict__ q,
const float* __restrict__ k, const float* __restrict__ v,
const float* __restrict__ gate,
const float* __restrict__ beta,
const float* __restrict__ z,
const float* __restrict__ gamma, float eps,
float* __restrict__ y, int h_k, int h_v) {
__shared__ float sk[S], sq[S];
__shared__ float red_kv[RG][S];
__shared__ float red_o[RG][S];
__shared__ float wsum[S * RG / 32];
const int head = blockIdx.x;
const int col = threadIdx.x; // 0..127
const int rg = threadIdx.y; // 0..3
const int tid = rg * S + col;
const int qh = head % h_k;
if (tid < S) { sk[tid] = k[qh * S + tid]; sq[tid] = q[qh * S + tid]; }
float s[RPG];
float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
const size_t row_stride = (size_t) h_v * S;
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
__syncthreads();
const float g = __expf(gate[head]);
float kv = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
red_kv[rg][col] = kv;
__syncthreads();
const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col];
const float delta = (v[head * S + col] - g * kv_col) * beta[head];
float o = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) {
s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
o = fmaf(s[r], sq[rg * RPG + r], o);
base[r * row_stride] = s[r];
}
red_o[rg][col] = o;
__syncthreads();
float oc = 0.0f, sq_part = 0.0f;
if (rg == 0) {
oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] + red_o[3][col]) * rsqrtf((float) S);
sq_part = oc * oc;
}
// RMS over the head's 128 outputs: warps of row group 0 are threads 0..127.
for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2);
if ((tid & 31) == 0) wsum[tid >> 5] = sq_part;
__syncthreads();
if (rg == 0) {
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
const float scale = rsqrtf(ss / (float) S + eps);
const float zz = z[head * S + col];
if constexpr (SILU) y[head * S + col] = oc * scale * gamma[col] * (zz / (1.0f + __expf(-zz)));
else y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
}
}
__global__ void __launch_bounds__(S) gdn_conv_l2_kernel(float* __restrict__ hist, const float* __restrict__ qkv,
const float* __restrict__ w, float* __restrict__ h,
int qk_heads, float eps) {
__shared__ float part[S / 32];
const int c = blockIdx.x * S + threadIdx.x;
const float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2], x = qkv[c];
float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3];
hist[c * 3] = v1;
hist[c * 3 + 1] = v2;
hist[c * 3 + 2] = x;
float y = sum / (1.0f + __expf(-sum));
if ((int) blockIdx.x < qk_heads) {
float sq = y * y;
for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o);
if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq;
__syncthreads();
const float ss = part[0] + part[1] + part[2] + part[3];
y *= rsqrtf(ss + eps);
}
h[c] = y;
}
__global__ void __launch_bounds__(256) gdn_ab_kernel(const float* __restrict__ x, const uint16_t* __restrict__ wa,
const uint16_t* __restrict__ wb, const float* __restrict__ dt,
const float* __restrict__ ssm_a, float* __restrict__ gate,
float* __restrict__ beta, int n, int h_v) {
const int row = blockIdx.x * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31;
if (row >= 2 * h_v) return;
const bool is_beta = row >= h_v;
const int r = is_beta ? row - h_v : row;
const uint4* w4 = reinterpret_cast<const uint4*>((is_beta ? wb : wa) + (size_t) r * n);
float acc = 0.0f;
for (int j = lane; j < n / 8; j += 32) {
const uint4 wv = __ldg(w4 + j);
const float4 xa = *reinterpret_cast<const float4*>(x + j * 8);
const float4 xb = *reinterpret_cast<const float4*>(x + j * 8 + 4);
acc = fmaf(__uint_as_float(wv.x << 16), xa.x, acc); acc = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, acc);
acc = fmaf(__uint_as_float(wv.y << 16), xa.z, acc); acc = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, acc);
acc = fmaf(__uint_as_float(wv.z << 16), xb.x, acc); acc = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, acc);
acc = fmaf(__uint_as_float(wv.w << 16), xb.z, acc); acc = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, acc);
}
for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, o);
if (lane != 0) return;
if (is_beta) {
beta[r] = 1.0f / (1.0f + __expf(-acc));
} else {
const float v = acc + dt[r];
const float sp = v > 20.0f ? v : log1pf(__expf(v));
gate[r] = sp * ssm_a[r];
}
}
} // namespace
void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
float eps, void* stream) {
if (!history || !qkv || !conv_w || !h || channels % S != 0 || qk_heads < 0 || qk_heads > channels / S) {
std::fprintf(stderr, "fused_gdn_conv_l2: invalid arguments\n");
std::exit(1);
}
gdn_conv_l2_kernel<<<(unsigned) (channels / S), S, 0, (cudaStream_t) stream>>>(history, qkv, conv_w, h, qk_heads, eps);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_conv_l2: %s\n", cudaGetErrorString(e)); std::exit(1); }
}
void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
float* gate, float* beta, int n_embd, int h_v, void* stream) {
if (!x || !w_alpha || !w_beta || !dt || !ssm_a || !gate || !beta || n_embd % 8 != 0 || h_v <= 0) {
std::fprintf(stderr, "fused_gdn_ab: invalid arguments\n");
std::exit(1);
}
gdn_ab_kernel<<<(unsigned) ((2 * h_v + 7) / 8), 256, 0, (cudaStream_t) stream>>>(x, w_alpha, w_beta, dt, ssm_a, gate,
beta, n_embd, h_v);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_ab: %s\n", cudaGetErrorString(e)); std::exit(1); }
}
namespace {
template <bool SILU>
void step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, void* stream) {
if (!state || !q || !k || !v || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v <= 0 || h_v % h_k) {
std::fprintf(stderr, "fused_gdn_step_norm: invalid arguments\n");
std::exit(1);
}
gdn_step_norm_kernel<SILU><<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta,
z, gamma, eps, y, h_k, h_v);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "fused_gdn_step_norm: %s\n", cudaGetErrorString(e));
std::exit(1);
}
}
} // namespace
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
void* stream) {
step_norm<false>(state, q, k, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream);
}
void fused_gdn_step_norm_silu(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k,
int h_v, void* stream) {
step_norm<true>(state, q, k, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream);
}
} // namespace strata::kernels
@@ -0,0 +1,552 @@
// src/kernels/cuda/gr.cu - P2.S2: the gated residual / hyper-connection, `gr_read` and `gr_write`.
//
// See include/strata/kernels/gr.hpp for the semantics, for why the weights are bf16, and for the history of
// this kernel's 134x-off-the-floor first version. The short form: it was launched `<<<1, 256>>>` so that
// `xn`/`xq` fit in shared memory, which used ONE of 48 SMs and cost 262 ms/token.
//
// THE SHAPE OF THE FIX is that each projection is an ordinary GEMV and is now mapped the way the shapes want:
//
// norm hc blocks, one per residual stream (each needs its own reduction)
// down ONE WARP PER OUTPUT ROW, lanes stride the 10240 reduction axis
// gate ONE WARP PER OUTPUT ROW, lanes stride the 320 reduction axis
// mean a flat elementwise pass over n_embd
//
// WARP-PER-ROW RATHER THAN THREAD-PER-ROW, and that is the whole difference. A thread walking one row is
// coalesced with ITSELF and 32 transactions away from its warp neighbours: `w_down[k*hc_dim + i]` for fixed k
// is contiguous, but two threads on rows k and k+1 are hc_dim*2 bytes apart. With the warp on one row, lanes
// i, i+1, i+2 touch consecutive addresses in EITHER orientation - which is why this version needs no
// transposed copies and takes both matrices exactly as the manifest stores them.
//
// Layouts are the MANIFEST's: `hc_attn_down.weight` is [10240, 320] with ne0 = hc*n_embd fast, so it holds
// `w_down[k][i]` with i contiguous - `ref/gr.py`'s (hc_lr, hc*n_embd) row-major. `hc_attn_up.weight` is
// [320, 10240] so it holds `w_up[i][k]` with k contiguous - `ref/gr.py`'s (hc*n_embd, hc_lr) row-major. Both
// index with no permutation at all.
#include "strata/kernels/gr.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/native_gr_norm.hpp"
#include "strata/kernels/native_gr_postops.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
namespace strata::kernels {
namespace {
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
bool fp32_activations = false;
bool native_mmvf = false;
/// The bf16 conversions live in `strata/kernels/bf16_bits.hpp`, and this file used to carry its own copies.
/// Two files with a private copy of a conversion whose failure mode is silent wrong bits is one too many -
/// and the reason the shared header exists is that `bf16` and `fp16` are NOT two spellings of one idea, so a
/// routine written for one and reused for the other is wrong in a way that still produces numbers.
///
/// The local names are kept as thin wrappers so the body below is untouched by the swap.
__device__ __forceinline__ uint16_t f32_to_bf16_bits(float f) { return bf16_from_f32(f); }
__device__ __forceinline__ float bf16_bits_to_f32(uint16_t h) { return f32_from_bf16(h); }
__device__ __forceinline__ float activation_f32(float x) { return x; }
__device__ __forceinline__ float activation_f32(uint16_t x) { return bf16_bits_to_f32(x); }
__device__ __forceinline__ void store_activation(float* dst, int i, float x) { dst[i] = x; }
__device__ __forceinline__ void store_activation(uint16_t* dst, int i, float x) {
dst[i] = f32_to_bf16_bits(x);
}
/// silu and sigmoid exactly as `ref/gr.py` writes them - in FLOAT, not double.
///
/// This is the opposite of `shared_expert.cu`, which uses double, and the difference is not stylistic:
/// `ref/gr.py`'s arrays are float32, so `x / (1.0 + np.exp(-x))` evaluates in float32 under NEP 50, while
/// `ref/moe.py` works in float64. Matching the reference's PRECISION is part of transcribing it.
__device__ __forceinline__ float silu_f(float x) { return x / (1.0f + expf(-x)); }
__device__ __forceinline__ float sigmoid_f(float x) { return 1.0f / (1.0f + expf(-x)); }
__device__ __forceinline__ double warp_sum(double v) {
for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
return __shfl_sync(0xFFFFFFFFu, v, 0);
}
__device__ __forceinline__ float warp_sumf(float v) {
for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
return __shfl_sync(0xFFFFFFFFu, v, 0);
}
/// The FP32 block-wide sum, for the reason the review's G5 states: this is a GeForce part and FP64 runs at a
/// small fraction of FP32, so a `double` reduction turns a bandwidth kernel into a latency kernel.
///
/// The scratch is taken as `double*` and reinterpreted as `float*` rather than changing the callers' shared
/// arrays, because `double scratch[8]` is 64 bytes and so is at least as large as the `float[8]` this needs -
/// the cast cannot overrun, and it keeps the change to one function instead of one per caller.
__device__ float block_sumf(float v, double* scratch_raw) {
float* scratch = (float*) scratch_raw;
// The leading barrier is not decoration - see the note on `block_sum` above: the result is read straight out
// of `scratch[0]` by every thread and a later call reuses the array, so without it a fast thread can
// overwrite `scratch[0]` before a slow one has read the previous result.
__syncthreads();
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
v = warp_sumf(v);
if (lane == 0) scratch[warp] = v;
__syncthreads();
const int nw = ((int) blockDim.x + 31) >> 5;
v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0f;
if (warp == 0) v = warp_sumf(v);
if (threadIdx.x == 0) scratch[0] = v;
__syncthreads();
return scratch[0];
}
/// Block-wide sum in DOUBLE, broadcast to every thread.
///
/// Double because `ref/gr.py` reduces in float64 for the norm and the bottleneck, and because a block-wide
/// f32 sum of 2560 squares is a different number from the reference's; the shuffle tree here also reorders
/// the additions, so the only defence is enough precision that the order stops mattering.
///
/// The leading `__syncthreads()` is not decoration: the result is read straight out of `scratch[0]` by every
/// thread, and a later call reuses the same array. Without a barrier on entry a fast thread can overwrite
/// `scratch[0]` before a slow one has read the previous result - a race that is invisible in most runs.
__device__ double block_sum(double v, double* scratch) {
__syncthreads();
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
v = warp_sum(v);
if (lane == 0) scratch[warp] = v;
__syncthreads();
const int nw = ((int) blockDim.x + 31) >> 5;
v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0;
if (warp == 0) v = warp_sum(v);
if (threadIdx.x == 0) scratch[0] = v;
__syncthreads();
return scratch[0];
}
/// `hc` blocks, one per residual stream: per-stream RMSNorm, then the activated stream in both forms.
///
/// ggml_rms_norm reduces over ne[0], and ne[0] is n_embd, so the reduction is PER STREAM. The `[n_embd, hc]`
/// gamma then scales each stream individually.
///
/// A per-thread accumulator is only a sum when the block is narrower than the row, which is why this is a
/// block reduction: with `n_embd` equal to the thread count every thread would hold exactly one element and
/// normalise by its own square. That mistake is silent - it produces a plausible vector of the right shape -
/// and it is what `gr_parity`'s `mixed vs reference` caught at 2.0e+01 in round 196.
template <bool FP32_ACT>
__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w_norm, float eps,
int n_embd, float* __restrict__ xn, uint16_t* __restrict__ xq) {
__shared__ double scratch[8];
const int c = blockIdx.x;
const float* Rc = R + (size_t) c * n_embd;
float* xnc = xn + (size_t) c * n_embd;
uint16_t* xqc = xq + (size_t) c * n_embd;
// FP32, for the same reason as `gr_down_kernel` and `gr_inject_kernel`: this is a GeForce part, FP64 runs
// at a small fraction of FP32, and the sum of squares is a pure reduction. It was the last `double` on the
// `gr_read` path. `gr_norm` is only 0.80 ms/token, so this is hygiene rather than a headline - but it is
// 12 of the FP64 sites the review's G5 counted in this file, and the rule it states ("no FP64 on any decode
// or prefill path") is worth being able to check mechanically rather than case by case.
float ss = 0.0f;
for (int d = threadIdx.x; d < n_embd; d += blockDim.x) {
const float v = Rc[d];
ss += v * v;
}
const float ms = block_sumf(ss, scratch) / (float) n_embd;
const float rs = rsqrtf(ms + eps);
for (int d = threadIdx.x; d < n_embd; d += blockDim.x) {
const float x = Rc[d] * rs * w_norm[(size_t) c * n_embd + d];
xnc[d] = x;
if constexpr (!FP32_ACT) xqc[d] = f32_to_bf16_bits(x);
}
}
/// `lo = silu((bf16(xn) @ w_down.T) / hc)`, ONE BLOCK PER OUTPUT ROW with its warps splitting the reduction.
template <typename Activation>
__global__ void gr_down_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_down, int hc_dim,
int hc_lr, int hc, Activation* __restrict__ lq,
const uint16_t* __restrict__ w_inject, float* __restrict__ inject, bool do_inject) {
const int k = blockIdx.x;
if (do_inject && k == hc_lr) {
// Track F: the inject projection is the down grid's last block. One warp per stream, the same
// lane stride and warp_sumf as `gr_inject_kernel`, so the four values are bitwise the old kernel's.
const int c = threadIdx.x >> 5;
if (c >= hc) return;
const int lane = threadIdx.x & 31;
const uint16_t* row = w_inject + (size_t) c * hc_dim;
float acc = 0.0f;
for (int i = lane; i < hc_dim; i += 32)
acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]);
acc = warp_sumf(acc);
if (lane == 0) inject[c] = acc;
return;
}
if (k >= hc_lr) return;
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
const int nw = (int) (blockDim.x >> 5); // warps per row == warps per block
const uint16_t* row = w_down + (size_t) k * hc_dim;
// **THE OCCUPANCY HERE IS 10% AND IT IS REAL, BUT FIXING IT DOES NOT PAY.** `hc_lr` is 320, one warp per
// row, 8 warps per block, so this launches 40 blocks = 320 warps: **6.7 warps per SM out of the 64 a
// Blackwell SM holds**, each lane walking 10,240 elements in 320 dependent steps.
//
// Four independent accumulators were tried to break the dependency chain and put four loads in flight per
// lane. **Measured: 39.86 ms/token of pure GPU against 39.80, i.e. no change**, with `gr_parity` green
// either way. Removed, on the rule this file already states about `#pragma unroll 4`: a hint that does not
// change the timing is a claim that is not true.
//
// The reason is that `gr_read`'s cost is not here. Its four kernels are the norm (4 blocks), this (40),
// `gr_gate_kernel` (1,280) and the mean (10), and the 1,280-block gate kernel reads 6.55 MB of weights with
// good occupancy - so `gr_read`'s ~93 us is mostly the gate kernel at its own memory rate, and the ~165 GB/s
// whole-call figure is an average over kernels that do not share a rate.
// **FP32, AND THE FP64 THAT WAS HERE COST MORE THAN EVERYTHING ELSE IN `gr_read`.**
//
// This accumulated in `double`. GeForce Blackwell executes FP64 at a small fraction of FP32 - 1/64 on
// recent parts - so a 320-step dependent FP64 chain per lane turned a memory-bound reduction into a
// latency-bound one. The `nsys` per-kernel table (round 2) measured it at **5.07 ms/token, 15.3% of all
// GPU time**, against `gr_gate_kernel`'s 1.23 ms - which REFUTES the comment that used to sit here, that
// "gr_read's ~93 us is mostly the gate kernel at its own memory rate". It was not: down + inject were
// 8.77 of gr_read's 10.8 ms, and the gate was 1.23.
//
// The justification for `double` was matching `ref/gr.py`'s float64 transcription. **The ground truth is
// llama.cpp, and llama.cpp accumulates in FP32** - so this does not move away from the oracle, it moves
// toward it, and the review's G1 lists it first.
//
// Four independent accumulators were tried here BEFORE, against the FP64 version, and measured no change
// (39.86 vs 39.80 ms/token) - because FP64 throughput was the limit, not the dependency chain. With FP32
// the kernel becomes memory-bound: it reads ~13 MB per call across xq and w_down, which at the measured
// 641 GB/s is ~20 us against the 52 us this took.
// **THE OCCUPANCY CONCLUSION ABOVE IS STALE, AND THIS IS THE RETEST IT ASKED FOR.**
//
// "Fixing it does not pay" was measured against the FP64 version, where FP64 THROUGHPUT was the limit and
// more parallelism could not help. The kernel is FP32 now (round 282: 5.07 -> 2.38 ms/token) and the limit
// moved to memory - which is the regime where occupancy does pay, because at 6.7 warps/SM there are not
// enough bytes in flight to cover DRAM latency. The old result is not wrong; it is about a different kernel.
//
// One BLOCK per row, its 8 warps splitting the 10,240-element reduction: 320 blocks x 8 = **2,560 warps =
// 53 warps/SM instead of 6.7**, with no second kernel and no partial buffer - the eight partials meet in
// shared memory. Lanes within a warp still read consecutive addresses, because warp `w` starts at
// `w * 32` and strides by `nw * 32`.
float acc = 0.0f;
for (int i = warp * 32 + lane; i < hc_dim; i += nw * 32)
acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]);
acc = warp_sumf(acc);
__shared__ float part[WARPS];
if (lane == 0) part[warp] = acc;
__syncthreads();
if (warp == 0) {
float t = (lane < nw) ? part[lane] : 0.0f;
t = warp_sumf(t);
// NOTE: the reduction order differs from the one-warp version, so this is a NUMERICS CHANGE. C1 is the
// gate that judges it - not this comment, and not `gr_parity`, which compares against the reference on
// a fixture that a changed summation order can still pass.
if (lane == 0) store_activation(lq, k, silu_f(t / (float) hc));
}
}
/// `gated[i] = xn[i] * sigmoid(bf16(lo) @ w_up.T)`, one warp per output row, lanes striding hc_lr.
template <typename Activation>
__global__ void gr_gate_kernel(const Activation* __restrict__ lq, const uint16_t* __restrict__ w_up,
const float* __restrict__ xn, int hc_dim, int hc_lr, float* __restrict__ gated) {
const int i = blockIdx.x * WARPS + (threadIdx.x >> 5);
if (i >= hc_dim) return;
const int lane = threadIdx.x & 31;
const uint16_t* row = w_up + (size_t) i * hc_lr;
float acc = 0.0f;
for (int k = lane; k < hc_lr; k += 32)
acc += activation_f32(lq[k]) * bf16_bits_to_f32(row[k]);
acc = warp_sumf(acc);
// Every lane computes the sigmoid (the shuffle broadcasts acc), so there is no second sync point and no
// branch; lane 0 stores.
if (lane == 0) gated[i] = xn[i] * sigmoid_f(acc);
}
/// `mixed[d] = mean over c of gated[c][d]`. Flat elementwise: the mean is over the streams, which are
/// strided by n_embd, so no cross-thread reduction is needed at all.
__global__ void gr_mean_kernel(const float* __restrict__ gated, int n_embd, int hc, float* __restrict__ mixed) {
const int d = blockIdx.x * blockDim.x + threadIdx.x;
if (d >= n_embd) return;
float m = 0.0f;
for (int c = 0; c < hc; ++c) m += gated[(size_t) c * n_embd + d];
mixed[d] = m / (float) hc;
}
/// Track F: `gr_gate_kernel` and `gr_mean_kernel` in one launch. One block owns WARPS columns for every
/// stream; a warp computes one column's dot per stream (the same lane stride and warp_sumf as the old gate),
/// the per-stream values meet in shared, and the mean adds them in the same c order as the old kernel.
template <typename Activation>
__global__ void gr_gate_mean_kernel(const Activation* __restrict__ lq, const uint16_t* __restrict__ w_up,
const float* __restrict__ xn, int hc_lr, int n_embd, int hc,
float* __restrict__ mixed) {
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
const int d = blockIdx.x * WARPS + warp;
__shared__ float g[4][WARPS];
if (d < n_embd) {
for (int c = 0; c < hc; ++c) {
const int i = c * n_embd + d;
const uint16_t* row = w_up + (size_t) i * hc_lr;
float acc = 0.0f;
for (int k = lane; k < hc_lr; k += 32)
acc += activation_f32(lq[k]) * bf16_bits_to_f32(row[k]);
acc = warp_sumf(acc);
if (lane == 0) g[c][warp] = xn[i] * sigmoid_f(acc);
}
}
__syncthreads();
if (threadIdx.x < WARPS) {
const int dd = blockIdx.x * WARPS + threadIdx.x;
if (dd < n_embd) {
float m = 0.0f;
for (int c = 0; c < hc; ++c) m += g[c][threadIdx.x];
mixed[dd] = m / (float) hc;
}
}
}
/// `inject[c] = bf16(xn) @ w_inject[c]`, one value per stream: ONE WARP PER STREAM, lanes striding hc_dim.
///
/// This mirrors `gr_down_kernel` rather than using a block-wide reduction. `hc` is 4 at the real geometry,
/// so a block per stream would put 256 threads on a 10240-element dot and leave the reduction to do all the
/// work; a warp per stream is the same shape as the down projection and reuses its pattern exactly. The
/// whole kernel is one block of `32*hc` threads, which is small - and it is a 4-value output, so it is.
template <typename Activation>
__global__ void gr_inject_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_inject,
int hc_dim, int hc, float* __restrict__ inject) {
const int c = threadIdx.x >> 5;
if (c >= hc) return;
const int lane = threadIdx.x & 31;
const uint16_t* row = w_inject + (size_t) c * hc_dim;
// FP32, for the same reason as `gr_down_kernel` - and this one is worse. A ONE-BLOCK kernel doing four
// 10,240-element FP64 reductions measured **3.70 ms/token, 11.1% of all GPU time, from a single SM out of
// 48.** It is the fourth largest consumer of GPU time in the engine and it cannot use more than 1/48th of
// the machine. In FP32 the same reduction is a few microseconds and the block size stops mattering.
float acc = 0.0f;
for (int i = lane; i < hc_dim; i += 32)
acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]);
acc = warp_sumf(acc);
if (lane == 0) inject[c] = acc;
}
__global__ void gr_write_kernel(const float* __restrict__ R, const float* __restrict__ block_out,
const float* __restrict__ inject, int n_embd, int hc, float* __restrict__ out) {
// w = 2*sigmoid(inject/hc), computed once per stream in shared rather than per element.
extern __shared__ unsigned char smem_raw[];
float* w = (float*) smem_raw;
if ((int) threadIdx.x < hc) w[threadIdx.x] = 2.0f * sigmoid_f(inject[threadIdx.x] / (float) hc);
__syncthreads();
const long long n = (long long) hc * n_embd;
for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n;
i += (long long) gridDim.x * blockDim.x) {
const int c = (int) (i / n_embd), d = (int) (i % n_embd);
// every stream adds the SAME block output; only the weight differs per stream
out[i] = R[i] + block_out[d] * w[c];
}
}
} // namespace
void gr_set_fp32_activations(bool enabled) { fp32_activations = enabled; }
void gr_set_native_mmvf(bool enabled) { native_mmvf = enabled; }
bool gr_native_mmvf_enabled() { return native_mmvf; }
size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out) {
const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;
// ONE table, indexed by the same `k` that assigns the pointers below. The first version of this function
// sized three locals named `xn`, `xq`, `lq` in a DIFFERENT order from the pointer assignments - `xq` got
// hc_lr*2 while `lq` got hc_dim*4 - so for the real geometry xq was given 640 bytes where it needed
// 20,480 and every region overlapped its neighbour.
//
// What that looked like is worth recording: `inject` came out ~20% wrong, and rewriting its reduction
// from block-wide to warp-wide produced BYTE-IDENTICAL wrong answers. Two different reductions agreeing
// exactly is not a coincidence to investigate - it means the reduction is not where the bug is, and the
// inputs are. Chasing the reduction instead cost most of a round.
const size_t sz[5] = {
hc_dim * sizeof(float), // 0: xn
hc_dim * sizeof(uint16_t), // 1: xq
(size_t) s.hc_lr * sizeof(uint16_t), // 2: lq
hc_dim * sizeof(float), // 3: gated
(size_t) s.hc_lr * sizeof(float), // 4: lo (FP32 activation experiment)
};
size_t al[5], bytes = 0;
for (int k = 0; k < 5; ++k) {
al[k] = (sz[k] + 15) & ~(size_t) 15;
bytes += al[k];
}
out.bytes = bytes;
if (base != nullptr) {
unsigned char* p = (unsigned char*) base;
void* ptr[5];
for (int k = 0; k < 5; ++k) {
ptr[k] = p;
p += al[k];
}
out.xn = (float*) ptr[0];
out.xq = (uint16_t*) ptr[1];
out.lq = (uint16_t*) ptr[2];
out.gated = (float*) ptr[3];
out.lo = (float*) ptr[4];
}
return bytes;
}
void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed,
float* inject, void* stream) {
if (s.n_embd <= 0 || s.hc <= 0 || s.hc_lr <= 0) return;
if (ws.xn == nullptr || ws.xq == nullptr || ws.lq == nullptr || ws.gated == nullptr || ws.lo == nullptr) {
std::fprintf(stderr, "gr_read: GrWorkspace is not initialised (see gr_workspace_init)\n");
std::exit(1);
}
if (ws.bytes < gr_workspace_bytes(s)) {
std::fprintf(stderr, "gr_read: GrWorkspace is %zu bytes but this geometry needs %zu\n",
ws.bytes, gr_workspace_bytes(s));
std::exit(1);
}
const int n_embd = (int) s.n_embd, hc = (int) s.hc, hc_lr = (int) s.hc_lr;
const int hc_dim = (int) (s.hc * s.n_embd);
cudaStream_t st = (cudaStream_t) stream;
// One setting selects every projection in this call. Captured graphs retain these kernel variants.
const bool use_native = native_mmvf;
const bool use_fp32 = fp32_activations || use_native;
const bool fused_gm = hc <= 4; // gr_gate_mean_kernel's shared array holds hc <= 4 streams
if (use_native) {
if ((hc_dim & 1) != 0 || (hc_lr & 1) != 0)
throw std::invalid_argument("gr_read native MMVF requires even hc*n_embd and hc_lr");
native_gr_rms_norm_weighted(R, w_norm, ws.xn, n_embd, hc, eps, stream);
bf16_gemv_fp32_mmvf(ws.xn, w_down, ws.lo, hc_dim, hc_lr, stream);
native_gr_down_silu(ws.lo, hc_lr, hc, stream);
bf16_gemv_fp32_mmvf(ws.lo, w_up, ws.gated, hc_lr, hc_dim, stream);
// The existing null-injection contract identifies the final mixer.
// Pinned qwen4exp uses fused HC pre for layers and the unfused graph for il=-1.
native_gr_pre_gated(ws.xn, ws.gated, mixed, n_embd, hc, w_inject != nullptr, stream);
} else if (use_fp32) {
gr_norm_kernel<true><<<hc, THREADS, 0, st>>>(R, w_norm, eps, n_embd, ws.xn, ws.xq);
gr_down_kernel<float><<<hc_lr + (w_inject != nullptr ? 1 : 0), THREADS, 0, st>>>(
ws.xn, w_down, hc_dim, hc_lr, hc, ws.lo, w_inject, inject, w_inject != nullptr);
if (fused_gm)
gr_gate_mean_kernel<float><<<(n_embd + WARPS - 1) / WARPS, THREADS, 0, st>>>(
ws.lo, w_up, ws.xn, hc_lr, n_embd, hc, mixed);
else
gr_gate_kernel<float><<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>(
ws.lo, w_up, ws.xn, hc_dim, hc_lr, ws.gated);
} else {
gr_norm_kernel<false><<<hc, THREADS, 0, st>>>(R, w_norm, eps, n_embd, ws.xn, ws.xq);
gr_down_kernel<uint16_t><<<hc_lr + (w_inject != nullptr ? 1 : 0), THREADS, 0, st>>>(
ws.xq, w_down, hc_dim, hc_lr, hc, ws.lq, w_inject, inject, w_inject != nullptr);
if (fused_gm)
gr_gate_mean_kernel<uint16_t><<<(n_embd + WARPS - 1) / WARPS, THREADS, 0, st>>>(
ws.lq, w_up, ws.xn, hc_lr, n_embd, hc, mixed);
else
gr_gate_kernel<uint16_t><<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>(
ws.lq, w_up, ws.xn, hc_dim, hc_lr, ws.gated);
}
if (!use_native && !fused_gm)
gr_mean_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(ws.gated, n_embd, hc, mixed);
// Absent for the final mixer, and then nothing is written - computing an injection nobody reads would be
// a claim, not a convenience. The non-native calls compute it in the down grid's last block (Track F).
if (w_inject != nullptr && use_native)
bf16_gemv_fp32_mmvf(ws.xn, w_inject, inject, hc_dim, hc, stream);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "gr_read launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) {
const cudaError_t se = cudaDeviceSynchronize();
if (se != cudaSuccess) {
std::fprintf(stderr, "gr_read: %s\n", cudaGetErrorString(se));
std::exit(1);
}
}
}
static bool no_multi_gr() {
static const bool off = [] {
const char* v = std::getenv("STRATA_NO_MULTI_GR");
return v != nullptr && v[0] != '\0' && v[0] != '0';
}();
return off;
}
void gr_read_multi(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws,
float* xn_multi, float* lo_multi, float* gated_multi, float* mixed, float* inject,
int n_tok, void* stream) {
if (n_tok <= 0 || s.n_embd <= 0 || s.hc <= 0 || s.hc_lr <= 0) return;
if (!no_multi_gr() && native_mmvf && n_tok > 1 && xn_multi != nullptr && lo_multi != nullptr && gated_multi != nullptr) {
const int n_embd = (int) s.n_embd, hc = (int) s.hc, hc_lr = (int) s.hc_lr;
const int hc_dim = (int) (s.hc * s.n_embd);
if ((hc_dim & 1) != 0 || (hc_lr & 1) != 0)
throw std::invalid_argument("gr_read native MMVF requires even hc*n_embd and hc_lr");
native_gr_rms_norm_weighted_multi(R, w_norm, xn_multi, n_embd, hc, n_tok, eps, stream);
bf16_gemv_fp32_mmvf_multi(xn_multi, hc_dim, w_down, lo_multi, hc_lr, hc_dim, hc_lr, n_tok, stream);
native_gr_down_silu(lo_multi, hc_lr * n_tok, hc, stream);
bf16_gemv_fp32_mmvf_multi(lo_multi, hc_lr, w_up, gated_multi, hc_dim, hc_lr, hc_dim, n_tok, stream);
native_gr_pre_gated_multi(xn_multi, gated_multi, mixed, n_embd, hc, n_tok, w_inject != nullptr, stream);
if (w_inject != nullptr)
bf16_gemv_fp32_mmvf_multi(xn_multi, hc_dim, w_inject, inject, hc, hc_dim, hc, n_tok, stream);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "gr_read_multi launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) {
const cudaError_t se = cudaDeviceSynchronize();
if (se != cudaSuccess) {
std::fprintf(stderr, "gr_read_multi: %s\n", cudaGetErrorString(se));
std::exit(1);
}
}
return;
}
const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;
for (int t = 0; t < n_tok; ++t) {
gr_read(R + (size_t) t * hc_dim, w_norm, w_down, w_up, w_inject, eps, s, ws,
mixed + (size_t) t * s.n_embd, inject ? inject + (size_t) t * s.hc : nullptr, stream);
}
}
void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
void* stream) {
if (s.n_embd <= 0 || s.hc <= 0) return;
const long long n = (long long) s.hc * s.n_embd;
const int blocks = (int) ((n + THREADS - 1) / THREADS);
if (native_mmvf)
native_gr_post(R, block_out, inject, R_out, (int) s.n_embd, (int) s.hc, stream);
else
gr_write_kernel<<<blocks, THREADS, (size_t) s.hc * sizeof(float), (cudaStream_t) stream>>>(
R, block_out, inject, (int) s.n_embd, (int) s.hc, R_out);
if (stream == nullptr) {
const cudaError_t e = cudaDeviceSynchronize();
if (e != cudaSuccess) {
std::fprintf(stderr, "gr_write: %s\n", cudaGetErrorString(e));
std::exit(1);
}
}
}
void gr_write_multi(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
int n_tok, void* stream) {
if (n_tok <= 0 || s.n_embd <= 0 || s.hc <= 0) return;
if (!no_multi_gr() && native_mmvf && n_tok > 1) {
native_gr_post_multi(R, block_out, inject, R_out, (int) s.n_embd, (int) s.hc, n_tok, stream);
if (stream == nullptr) {
const cudaError_t e = cudaDeviceSynchronize();
if (e != cudaSuccess) {
std::fprintf(stderr, "gr_write_multi: %s\n", cudaGetErrorString(e));
std::exit(1);
}
}
return;
}
const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;
for (int t = 0; t < n_tok; ++t) {
gr_write(R + (size_t) t * hc_dim, block_out + (size_t) t * s.n_embd, inject + (size_t) t * s.hc, s,
R_out + (size_t) t * hc_dim, stream);
}
}
} // namespace strata::kernels
@@ -0,0 +1,521 @@
#include "strata/core/bw_dense_defaults.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/window_limits.hpp"
#include "s26_tsum.cuh"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/pdl.hpp"
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <stdexcept>
#include <string>
namespace strata::kernels {
namespace {
// The FP32-activation MMVF implementation below is adapted from llama.cpp
// 3cf03257f219afbe7334045ff7c6a06ac68c627d, ggml/src/ggml-cuda/{mmvf.cu,common.cuh}.
// Scope: ordinary contiguous BF16 matrix, one FP32 activation vector, no fusion/ids/channels.
//
// 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.
__device__ __forceinline__ float mmvf_warp_sum(float value) {
#pragma unroll
for (int offset = 16; offset > 0; offset >>= 1)
value += __shfl_xor_sync(0xffffffffu, value, offset, 32);
return value;
}
// STRATA_MMVF_CHECK=1 (diagnostic): the constant-trip fast path also runs the plain loop with volatile loads (so the loads happen again, later) and
// compares each thread's accumulator bit for bit: g_mmvf_chk[0] checks, [1] differing accumulators, [2..4] block / thread / n_in of the first one.
// A difference means the activations or weights changed between the early and the late loads (no arithmetic differs between the two loops).
__device__ unsigned long long g_mmvf_chk[8];
__device__ __forceinline__ void mmvf_chk_note(float a, float b, int blk, int t, int n_in) {
atomicAdd(&g_mmvf_chk[0], 1ull);
if (__float_as_uint(a) != __float_as_uint(b)) {
if (atomicAdd(&g_mmvf_chk[1], 1ull) == 0ull) { g_mmvf_chk[2] = (unsigned long long) blk; g_mmvf_chk[3] = (unsigned long long) t; g_mmvf_chk[4] = (unsigned long long) n_in;
g_mmvf_chk[5] = __float_as_uint(a); g_mmvf_chk[6] = __float_as_uint(b); }
}
}
template <int BLOCK_SIZE>
__global__ void bf16_f32_mmvf_kernel(const float* __restrict__ x, const uint16_t* __restrict__ w,
float* __restrict__ y, int n_in, int fast) {
const int t = threadIdx.x;
const uint16_t* row = w + (size_t) blockIdx.x * n_in;
const uint32_t* weights2 = reinterpret_cast<const uint32_t*>(row);
const float2* inputs2 = reinterpret_cast<const float2*>(x);
__shared__ float partials[32];
if (t < 32) partials[t] = 0.0f;
__syncthreads();
float acc = 0.0f;
if (BLOCK_SIZE == 256 && fast != 0 && n_in == 2560) {
// STRATA_SMALL_UNR bit 0: the router-shaped single-column read, five passes of one weight pair each (all in range), constant
// trip count so the weight and activation loads of the five passes are in flight together. The same FMAs in the same order.
uint32_t wv[5];
float2 xv[5];
#pragma unroll
for (int qq = 0; qq < 5; ++qq) { wv[qq] = weights2[t + qq * BLOCK_SIZE]; xv[qq] = inputs2[t + qq * BLOCK_SIZE]; }
#pragma unroll
for (int qq = 0; qq < 5; ++qq) {
acc = __fmaf_rn(f32_from_bf16((uint16_t) wv[qq]), xv[qq].x, acc);
acc = __fmaf_rn(f32_from_bf16((uint16_t) (wv[qq] >> 16)), xv[qq].y, acc);
}
if (fast == 2) {
float acc2 = 0.0f;
for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {
const uint32_t weight = *(const volatile uint32_t*) (weights2 + pair);
const volatile float* ip = reinterpret_cast<const volatile float*>(inputs2 + pair);
const float2 input = make_float2(ip[0], ip[1]);
acc2 = __fmaf_rn(f32_from_bf16((uint16_t) weight), input.x, acc2);
acc2 = __fmaf_rn(f32_from_bf16((uint16_t) (weight >> 16)), input.y, acc2);
}
mmvf_chk_note(acc, acc2, (int) blockIdx.x, t, n_in);
}
} else
for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {
const uint32_t weight = weights2[pair];
const float2 input = inputs2[pair];
// Match the two ordered multiply-adds in ggml_cuda_mad, not a pair sum followed by one add.
acc = __fmaf_rn(f32_from_bf16((uint16_t) weight), input.x, acc);
acc = __fmaf_rn(f32_from_bf16((uint16_t) (weight >> 16)), input.y, acc);
}
acc = mmvf_warp_sum(acc);
if constexpr (BLOCK_SIZE > 32) {
// All lanes have the same reduced value; one store avoids a same-value shared-memory race.
if ((t & 31) == 0) partials[t / 32] = acc;
__syncthreads();
if (t < 32) acc = mmvf_warp_sum(partials[t]);
}
if (t == 0) y[blockIdx.x] = acc;
}
// the same kernel for up to 8 activation rows - the weight row is read ONCE and every
// token keeps its own accumulator with exactly the single-row kernel's order (pairs, two ordered FMAs, the same warp
// and block reductions), so each output is bit-identical to a bf16_f32_mmvf_kernel launch of its own.
template <int BLOCK_SIZE, int NT, bool EXACT_T = true>
__global__ void bf16_f32_mmvf_multi_kernel(const float* x_, int64_t ldx, const uint16_t* __restrict__ w,
float* y_, int64_t ldy, int n_in, int n_tok, int fast) {
const float* STRATA_PDL_RESTRICT x = x_; // __restrict__ below sm_70 only (pdl.hpp, #1469)
float* STRATA_PDL_RESTRICT y = y_;
const int t = threadIdx.x;
const uint16_t* row = w + (size_t) blockIdx.x * n_in;
const uint32_t* weights2 = reinterpret_cast<const uint32_t*>(row);
__shared__ float partials[NT][32];
if (t < 32) {
#pragma unroll
for (int k = 0; k < NT; ++k) partials[k][t] = 0.0f;
}
__syncthreads();
float acc[NT];
#pragma unroll
for (int k = 0; k < NT; ++k) acc[k] = 0.0f;
// PDL (pdl.hpp): this thread's first PRE weight pairs are loaded before waiting for the activations
constexpr int PRE = kPdlPrefetch ? 8 : 0;
uint32_t wpre[PRE > 0 ? PRE : 1];
#pragma unroll
for (int q = 0; q < PRE; ++q) {
const int pair = t + q * BLOCK_SIZE;
wpre[q] = pair < n_in / 2 ? __ldg(weights2 + pair) : 0u;
}
pdl_wait();
if (BLOCK_SIZE == 256 && fast != 0 && n_in == 2560) {
// BW-DENSE (STRATA_SMALL_UNR bit 0): the router-shaped read (2560 inputs, 256 threads: five passes of one weight pair each, all
// in range) with constant trip counts, so the activation loads of every pass are in flight together instead of one memory
// latency a pass. The same FMAs in the same order (pass ascending, w0 then w1): bitwise the loop below.
float2 xin[NT][5];
#pragma unroll
for (int qq = 0; qq < 5; ++qq)
#pragma unroll
for (int k = 0; k < NT; ++k)
if (EXACT_T || k < n_tok) xin[k][qq] = __ldg(reinterpret_cast<const float2*>(x + (size_t) k * ldx) + (t + qq * BLOCK_SIZE));
#pragma unroll
for (int qq = 0; qq < 5; ++qq) {
uint32_t weight;
if constexpr (PRE >= 5) weight = wpre[qq];
else weight = __ldg(weights2 + t + qq * BLOCK_SIZE);
const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16));
#pragma unroll
for (int k = 0; k < NT; ++k) {
if (EXACT_T || k < n_tok) {
acc[k] = __fmaf_rn(w0, xin[k][qq].x, acc[k]);
acc[k] = __fmaf_rn(w1, xin[k][qq].y, acc[k]);
}
}
}
if (fast == 2) {
#pragma unroll
for (int k = 0; k < NT; ++k) {
if (EXACT_T || k < n_tok) {
float acc2 = 0.0f;
for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {
const uint32_t weight = *(const volatile uint32_t*) (weights2 + pair);
const volatile float* ip = reinterpret_cast<const volatile float*>(reinterpret_cast<const float2*>(x + (size_t) k * ldx) + pair);
const float2 input = make_float2(ip[0], ip[1]);
acc2 = __fmaf_rn(f32_from_bf16((uint16_t) weight), input.x, acc2);
acc2 = __fmaf_rn(f32_from_bf16((uint16_t) (weight >> 16)), input.y, acc2);
}
mmvf_chk_note(acc[k], acc2, (int) blockIdx.x, t, n_in);
}
}
}
} else {
int q = 0;
for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE, ++q) {
const uint32_t weight = q < PRE ? wpre[q] : __ldg(weights2 + pair);
const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16));
#pragma unroll
for (int k = 0; k < NT; ++k) {
if (EXACT_T || k < n_tok) {
const float2 input = __ldg(reinterpret_cast<const float2*>(x + (size_t) k * ldx) + pair);
acc[k] = __fmaf_rn(w0, input.x, acc[k]);
acc[k] = __fmaf_rn(w1, input.y, acc[k]);
}
}
}
}
#pragma unroll
for (int k = 0; k < NT; ++k)
if (EXACT_T || k < n_tok) acc[k] = mmvf_warp_sum(acc[k]);
if constexpr (BLOCK_SIZE > 32) {
if ((t & 31) == 0)
#pragma unroll
for (int k = 0; k < NT; ++k)
if (EXACT_T || k < n_tok) partials[k][t / 32] = acc[k];
__syncthreads();
if (t < 32)
#pragma unroll
for (int k = 0; k < NT; ++k)
if (EXACT_T || k < n_tok) acc[k] = mmvf_warp_sum(partials[k][t]);
}
if (t == 0)
#pragma unroll
for (int k = 0; k < NT; ++k)
if (EXACT_T || k < n_tok) y[(size_t) k * ldy + blockIdx.x] = acc[k];
}
// S25 (STRATA_MMVF_ROWS=1): RPB output rows per block. Each block read its row's weights once but all T activation
// rows again (n_out blocks x T x n_in floats through L2 - the part that grew with T); here a block reads the
// activations once for RPB rows. Per output, thread t still walks pairs t, t + BLOCK_SIZE, ... with the same two
// ordered FMAs and the same warp and block reductions: bit-identical to bf16_f32_mmvf_multi_kernel.
// S26 STRATA_LFUSE=1 (AUX): one more block computes row 0 of w_aux into y_aux[k * ldy_aux] - the same per-output
// code, so each aux output is bitwise what its own bf16_f32_mmvf_multi_kernel launch gave (the shared expert's gate)
template <int BLOCK_SIZE, int NT, int RPB, bool TS = false, bool AUX = false>
__global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w,
float* __restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok,
const uint16_t* __restrict__ w_aux = nullptr, float* __restrict__ y_aux = nullptr,
int64_t ldy_aux = 0) {
const int t = threadIdx.x;
int o0 = blockIdx.x * RPB;
if constexpr (AUX) {
if (blockIdx.x == gridDim.x - 1) { w = w_aux; y = y_aux; ldy = ldy_aux; n_out = 1; o0 = 0; }
}
__shared__ float partials[RPB][NT][32];
if constexpr (BLOCK_SIZE > 32) {
if (t < 32)
#pragma unroll
for (int r = 0; r < RPB; ++r)
#pragma unroll
for (int k = 0; k < NT; ++k) partials[r][k][t] = 0.0f;
__syncthreads();
}
float acc[RPB][NT];
#pragma unroll
for (int r = 0; r < RPB; ++r)
#pragma unroll
for (int k = 0; k < NT; ++k) acc[r][k] = 0.0f;
for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {
float2 in[NT];
#pragma unroll
for (int k = 0; k < NT; ++k)
if (k < n_tok) in[k] = reinterpret_cast<const float2*>(x + (size_t) k * ldx)[pair];
#pragma unroll
for (int r = 0; r < RPB; ++r) {
if (o0 + r >= n_out) break;
const uint32_t weight = reinterpret_cast<const uint32_t*>(w + (size_t) (o0 + r) * n_in)[pair];
const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16));
#pragma unroll
for (int k = 0; k < NT; ++k) {
if (k < n_tok) {
acc[r][k] = __fmaf_rn(w0, in[k].x, acc[r][k]);
acc[r][k] = __fmaf_rn(w1, in[k].y, acc[r][k]);
}
}
}
}
if constexpr (TS) { // S26 STRATA_TSUM=1: the RPB x NT warp sums (both stages) as transposed butterflies, bitwise the same
constexpr int V = RPB * NT, P = s26ts::pow2_ceil(V);
const int lane = t & 31, j = s26ts::tsum_token<P>(lane);
const bool own = lane == s26ts::tsum_lane<P>(j) && j < V;
float v[P];
#pragma unroll
for (int q = 0; q < P; ++q) v[q] = q < V ? acc[q / NT][q % NT] : 0.0f;
float sum = s26ts::tsum<P>(v, lane);
if constexpr (BLOCK_SIZE > 32) {
if (own) partials[j / NT][j % NT][t / 32] = sum;
__syncthreads();
if (t >= 32) return;
#pragma unroll
for (int q = 0; q < P; ++q) v[q] = q < V ? partials[q / NT][q % NT][t] : 0.0f;
sum = s26ts::tsum<P>(v, lane);
}
const int r = j / NT, k = j % NT;
if (own && o0 + r < n_out && k < n_tok) y[(size_t) k * ldy + o0 + r] = sum;
return;
}
#pragma unroll
for (int r = 0; r < RPB; ++r)
#pragma unroll
for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(acc[r][k]);
if constexpr (BLOCK_SIZE > 32) {
if ((t & 31) == 0)
#pragma unroll
for (int r = 0; r < RPB; ++r)
#pragma unroll
for (int k = 0; k < NT; ++k) partials[r][k][t / 32] = acc[r][k];
__syncthreads();
if (t < 32)
#pragma unroll
for (int r = 0; r < RPB; ++r)
#pragma unroll
for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(partials[r][k][t]);
}
if (t == 0)
#pragma unroll
for (int r = 0; r < RPB; ++r)
if (o0 + r < n_out)
#pragma unroll
for (int k = 0; k < NT; ++k)
if (k < n_tok) y[(size_t) k * ldy + o0 + r] = acc[r][k];
}
template <int B>
void launch_rows(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int n_in, int n_out, int n_tok,
cudaStream_t st, const uint16_t* w_aux = nullptr, float* y_aux = nullptr, int64_t ldy_aux = 0) {
constexpr int RPB = 4;
const unsigned nb = (unsigned) ((n_out + RPB - 1) / RPB);
static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();
if (w_aux != nullptr) { // S26 STRATA_LFUSE: + one aux row block
#define S26_AUX(TSV) \
if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<B, 4, RPB, TSV, true><<<nb + 1, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok, w_aux, y_aux, ldy_aux); \
else bf16_f32_mmvf_rows_kernel<B, 8, RPB, TSV, true><<<nb + 1, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok, w_aux, y_aux, ldy_aux);
if (ts) { S26_AUX(true) } else { S26_AUX(false) }
#undef S26_AUX
return;
}
if (ts) {
if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<B, 4, RPB, true><<<nb, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok);
else bf16_f32_mmvf_rows_kernel<B, 8, RPB, true><<<nb, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok);
return;
}
if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<B, 4, RPB><<<nb, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok);
else bf16_f32_mmvf_rows_kernel<B, 8, RPB><<<nb, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok);
}
void mmvf_chk_report() {
unsigned long long h[8] = {};
if (cudaMemcpyFromSymbol(h, g_mmvf_chk, sizeof(h)) != cudaSuccess) return;
std::fprintf(stderr, "strata mmvf check: %llu accumulators compared, %llu differ; first: block %llu thread %llu n_in %llu fast %08llx plain %08llx\n", h[0], h[1], h[2], h[3], h[4], h[5], h[6]);
}
// BW-DENSE STRATA_SMALL_UNR bit 0: see bf16_f32_mmvf_multi_kernel (bw_dense_defaults.hpp: on for a 12.0 card, else off; the variable wins)
int mmvf_fast_bit() {
static int per_dev[64]; // 0 unknown, else bit + 1
const char* e = std::getenv("STRATA_SMALL_UNR");
if (e != nullptr) return std::atoi(e) & 1;
#if defined(__HIPCC__)
return 0;
#else
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }
if (!per_dev[dev]) {
int ma = 0, mi = 0;
const bool ok = cudaDeviceGetAttribute(&ma, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
cudaDeviceGetAttribute(&mi, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
if (!ok) cudaGetLastError();
per_dev[dev] = 1 + (ok ? (strata::small_unr_default(ma, mi) & 1) : 0);
}
return per_dev[dev] - 1;
#endif
}
// AMD-Q STRATA_MMVF_CHECK=1 (with the switch on): the kernel also computes the plain read and counts the accumulators that differ (2 = check mode)
int mmvf_fast() {
const int b = mmvf_fast_bit();
if (b == 0) return 0;
static const bool chk = [] {
const char* c = std::getenv("STRATA_MMVF_CHECK");
const bool on = c != nullptr && c[0] == '1';
if (on) std::atexit(mmvf_chk_report);
return on;
}();
return chk ? 2 : b;
}
int mmvf_block_size(int64_t n_in) {
int best = 32;
int64_t best_iterations = (n_in + 63) / 64;
for (int candidate = 64; candidate <= 256; candidate += 32) {
const int64_t iterations = (n_in + 2 * candidate - 1) / (2 * candidate);
if (iterations < best_iterations) {
best_iterations = iterations;
best = candidate;
}
}
return best;
}
} // namespace
bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux,
int64_t ldy_aux, void* stream) {
static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }();
// exactly the conditions under which both calls would take the rows / multi kernels at the same block size
if (!rows || n_out < 64 || n_tok < 2 || n_tok > 8 || n_in <= 0 || (n_in & 1) != 0 || (ldx & 1) != 0 || x == nullptr ||
w == nullptr || y == nullptr || w_aux == nullptr || y_aux == nullptr || (reinterpret_cast<uintptr_t>(x) & 7u) != 0)
return false;
const cudaStream_t st = (cudaStream_t) stream;
const int ni = (int) n_in, no = (int) n_out;
switch (mmvf_block_size(n_in)) {
case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;
}
const cudaError_t result = cudaGetLastError();
if (result != cudaSuccess)
throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi_aux launch: ") + cudaGetErrorString(result));
return true;
}
void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
int64_t n_in, int64_t n_out, int n_tok, void* stream) {
if (n_tok == 1 && ldy >= n_out) { bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); return; }
if (n_tok < 1 || n_tok > STRATA_VERIFY_MAX_T || n_in <= 0 || (n_in & 1) != 0 || n_out <= 0 || (ldx & 1) != 0 ||
x == nullptr || w == nullptr || y == nullptr || (reinterpret_cast<uintptr_t>(x) & 7u) != 0)
throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows (16 in a wide build), even n_in/ldx, aligned pointers");
const cudaStream_t st = (cudaStream_t) stream;
static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }();
if (rows && n_out >= 64 && n_tok <= 8) { // (the opt-in rows kernels hold 8 columns: a wider window takes the switch below)
const int ni = (int) n_in, no = (int) n_out;
switch (mmvf_block_size(n_in)) {
case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
}
const cudaError_t result = cudaGetLastError();
if (result != cudaSuccess)
throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result));
return;
}
// 9..16 rows (wide builds only): one exact instantiation per row count, each row's dot independent of the others. 7 and 8
// rows stay with the default case below, the instantiation they always had.
#if STRATA_VERIFY_MAX_T > 8
#define STRATA_MMVF_W(N, T) case T: launch_pdl(bf16_f32_mmvf_multi_kernel<N, T, true>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break;
#if STRATA_VERIFY_MAX_T > 12
#define STRATA_MMVF_W13(N) STRATA_MMVF_W(N, 13) STRATA_MMVF_W(N, 14) STRATA_MMVF_W(N, 15) STRATA_MMVF_W(N, 16)
#else
#define STRATA_MMVF_W13(N)
#endif
#define STRATA_MMVF_WIDE(N) \
STRATA_MMVF_W(N, 9) STRATA_MMVF_W(N, 10) STRATA_MMVF_W(N, 11) STRATA_MMVF_W(N, 12) \
STRATA_MMVF_W13(N)
#else
#define STRATA_MMVF_WIDE(N)
#endif
#define STRATA_MMVF_M(N) case N: \
switch (n_tok) { \
STRATA_MMVF_WIDE(N) \
case 1: launch_pdl(bf16_f32_mmvf_multi_kernel<N, 1, true>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break; \
case 2: launch_pdl(bf16_f32_mmvf_multi_kernel<N, 2, true>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break; \
case 3: launch_pdl(bf16_f32_mmvf_multi_kernel<N, 3, true>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break; \
case 4: launch_pdl(bf16_f32_mmvf_multi_kernel<N, 4, true>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break; \
case 5: launch_pdl(bf16_f32_mmvf_multi_kernel<N, 5, true>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break; \
case 6: launch_pdl(bf16_f32_mmvf_multi_kernel<N, 6, true>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break; \
default: launch_pdl(bf16_f32_mmvf_multi_kernel<N, 8, false>, dim3((unsigned) n_out), dim3(N), 0, st, x, ldx, w, y, ldy, (int) n_in, n_tok, mmvf_fast()); break; \
} break
switch (mmvf_block_size(n_in)) {
STRATA_MMVF_M(32); STRATA_MMVF_M(64); STRATA_MMVF_M(96); STRATA_MMVF_M(128);
STRATA_MMVF_M(160); STRATA_MMVF_M(192); STRATA_MMVF_M(224); STRATA_MMVF_M(256);
}
#undef STRATA_MMVF_M
#undef STRATA_MMVF_WIDE
#ifdef STRATA_MMVF_W
#undef STRATA_MMVF_W
#endif
const cudaError_t result = cudaGetLastError();
if (result != cudaSuccess)
throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result));
}
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
int64_t n_in, int64_t n_out, void* stream) {
if (n_in <= 0 || (n_in & 1) != 0 || n_in > std::numeric_limits<int>::max() ||
n_out <= 0 || n_out > std::numeric_limits<int>::max())
throw std::invalid_argument("bf16_gemv_fp32_mmvf: require positive even n_in and positive n_out <= INT_MAX");
if (x == nullptr || w == nullptr || y == nullptr ||
(reinterpret_cast<uintptr_t>(x) & 7u) != 0 ||
(reinterpret_cast<uintptr_t>(w) & 3u) != 0 ||
(reinterpret_cast<uintptr_t>(y) & 3u) != 0)
throw std::invalid_argument("bf16_gemv_fp32_mmvf: null or misaligned pointer");
const cudaStream_t st = (cudaStream_t) stream;
#define STRATA_MMVF_CASE(N) case N: \
bf16_f32_mmvf_kernel<N><<<(unsigned) n_out, N, 0, st>>>(x, w, y, (int) n_in, mmvf_fast()); break
switch (mmvf_block_size(n_in)) {
STRATA_MMVF_CASE(32);
STRATA_MMVF_CASE(64);
STRATA_MMVF_CASE(96);
STRATA_MMVF_CASE(128);
STRATA_MMVF_CASE(160);
STRATA_MMVF_CASE(192);
STRATA_MMVF_CASE(224);
STRATA_MMVF_CASE(256);
}
#undef STRATA_MMVF_CASE
const cudaError_t result = cudaGetLastError();
if (result != cudaSuccess)
throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf launch: ") + cudaGetErrorString(result));
}
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
void* stream) {
// columns contiguous: the existing multi-row kernel (weight read once, each output bitwise its one-row call),
// up to 8 rows per launch
for (int c0 = 0; c0 < ncols; c0 += 8) {
const int nc = ncols - c0 < 8 ? ncols - c0 : 8;
if (nc == 1) bf16_gemv_fp32_mmvf(x + (size_t) c0 * n_in, w, y + (size_t) c0 * n_out, n_in, n_out, stream);
else bf16_gemv_fp32_mmvf_multi(x + (size_t) c0 * n_in, n_in, w, y + (size_t) c0 * n_out, n_out, n_in, n_out, nc,
stream);
}
}
} // namespace strata::kernels
@@ -0,0 +1,124 @@
// Arithmetic adapted from gated_delta_net.cu at pinned llama.cpp
// 3cf03257f219afbe7334045ff7c6a06ac68c627d. Only state addressing differs:
// each warp owns one Strata (head,column) and retains its four rows in registers.
// Compile with --use_fast_math to match the pinned CUDA implementation.
//
// 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.
#include "strata/kernels/native_gdn.hpp"
#include "strata/core/geometry.hpp"
#include <cuda_runtime.h>
#include <atomic>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
namespace strata::kernels {
namespace {
std::atomic<bool> enabled{false};
constexpr int S = 128;
static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "native_gdn is compiled for core/geometry.hpp");
__device__ __forceinline__ float warp_sum(float value) {
#pragma unroll
for (int offset = 16; offset > 0; offset >>= 1)
value += __shfl_xor_sync(0xffffffff, value, offset, 32);
return value;
}
__global__ void __launch_bounds__(128, 2)
step(float* __restrict__ state, const float* __restrict__ q, const float* __restrict__ k,
const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta,
float* __restrict__ output, int h_k, int h_v, float scale) {
const int head = blockIdx.x;
const int lane = threadIdx.x;
const int col = blockIdx.z * blockDim.y + threadIdx.y;
const int q_head = head % h_k;
float s_shard[4], k_reg[4], q_reg[4];
#pragma unroll
for (int r = 0; r < 4; ++r) {
const int i = r * 32 + lane;
s_shard[r] = state[(size_t(i) * h_v + head) * S + col];
k_reg[r] = k[q_head * S + i];
q_reg[r] = q[q_head * S + i];
}
const float g_val = expf(gate[head]);
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < 4; ++r) kv_shard += s_shard[r] * k_reg[r];
const float kv_col = warp_sum(kv_shard);
const float delta_col = (v[head * S + col] - g_val * kv_col) * beta[head];
float attn_partial = 0.0f;
#pragma unroll
for (int r = 0; r < 4; ++r) {
s_shard[r] = g_val * s_shard[r] + k_reg[r] * delta_col;
attn_partial += s_shard[r] * q_reg[r];
}
const float attn_col = warp_sum(attn_partial);
if (lane == 0) output[head * S + col] = attn_col * scale;
#pragma unroll
for (int r = 0; r < 4; ++r) {
const int i = r * 32 + lane;
state[(size_t(i) * h_v + head) * S + col] = s_shard[r];
}
}
bool valid_span(const void* pointer, size_t bytes) {
const auto address = reinterpret_cast<uintptr_t>(pointer);
return pointer && address % sizeof(float) == 0 && bytes <= UINTPTR_MAX - address;
}
bool overlap(const void* a, size_t an, const void* b, size_t bn) {
const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
return ap < bp + bn && bp < ap + an;
}
}
void native_gdn_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
bool native_gdn_enabled() { return enabled.load(std::memory_order_relaxed); }
void native_gdn_step(float* state, const float* q, const float* k, const float* v,
const float* gate, const float* beta, float* output,
const GdnShapes& shape, void* stream) {
if (!stream || shape.S != S || shape.h_k <= 0 || shape.h_v <= 0 ||
shape.h_v > 65535 || shape.h_v % shape.h_k != 0)
throw std::invalid_argument("native GDN requires a stream, S=128 and positive divisible head counts <=65535");
const size_t state_bytes = size_t(S) * S * size_t(shape.h_v) * sizeof(float);
const size_t qk_bytes = size_t(S) * size_t(shape.h_k) * sizeof(float);
const size_t output_bytes = size_t(S) * size_t(shape.h_v) * sizeof(float);
const size_t head_bytes = size_t(shape.h_v) * sizeof(float);
if (!valid_span(state, state_bytes) || !valid_span(output, output_bytes) ||
overlap(state, state_bytes, output, output_bytes))
throw std::invalid_argument("native GDN requires aligned, disjoint state and output spans");
const void* inputs[] = {q, k, v, gate, beta};
const size_t bytes[] = {qk_bytes, qk_bytes, output_bytes, head_bytes, head_bytes};
for (int i = 0; i < 5; ++i) {
if (!valid_span(inputs[i], bytes[i]) || overlap(state, state_bytes, inputs[i], bytes[i]) ||
overlap(output, output_bytes, inputs[i], bytes[i]))
throw std::invalid_argument("native GDN requires aligned input spans disjoint from state and output");
}
const float scale = 1.0f / sqrtf(float(S));
step<<<dim3(unsigned(shape.h_v), 1, S / 4), dim3(32, 4), 0, static_cast<cudaStream_t>(stream)>>>(
state, q, k, v, gate, beta, output, int(shape.h_k), int(shape.h_v), scale);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
} // namespace strata::kernels
@@ -0,0 +1,199 @@
// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu,unary.cuh,ssm-conv.cu,scale.cu}.
// Compile with --use_fast_math, as the pinned backend does.
//
// 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.
#include "strata/kernels/native_gdn_preprocess.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <stdexcept>
namespace strata::kernels {
namespace {
constexpr int S = 128;
__device__ __forceinline__ float warp_sum(float value) {
#pragma unroll
for (int offset = 16; offset > 0; offset >>= 1)
value += __shfl_xor_sync(0xffffffffu, value, offset, 32);
return value;
}
__device__ __forceinline__ float norm_sum(float value, float* sums) {
const int lane = threadIdx.x % 32;
value = warp_sum(value);
if (lane == 0) sums[threadIdx.x / 32] = value;
__syncthreads();
value = lane < 8 ? sums[lane] : 0.0f;
return warp_sum(value);
}
__device__ __forceinline__ float sigmoid(float value) { return 1.0f / (1.0f + expf(-value)); }
__global__ void conv_silu(float* __restrict__ history, const float* __restrict__ input,
const float* __restrict__ weights, float* __restrict__ raw_output,
float* __restrict__ silu_output, int channels) {
const int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= channels) return;
float values[4] = {history[c * 3], history[c * 3 + 1], history[c * 3 + 2], input[c]};
float sum = 0.0f;
#pragma unroll
for (int tap = 0; tap < 4; ++tap) sum += values[tap] * weights[c * 4 + tap];
// The native SSM kernel adds its zero bias even when there is no bias input.
sum = __fadd_rn(sum, 0.0f);
raw_output[c] = sum;
silu_output[c] = sum / (1.0f + expf(-sum));
#pragma unroll
for (int tap = 0; tap < 3; ++tap) history[c * 3 + tap] = values[tap + 1];
}
__global__ void l2_norm(float* input, float epsilon, float scale_after) {
const int col = threadIdx.x;
input += size_t(blockIdx.x) * S;
const float value = col < S ? input[col] : 0.0f;
float partial = 0.0f;
if (col < S) partial += value * value;
__shared__ float sums[32];
partial = norm_sum(partial, sums);
const float scale = rsqrtf(partial / S + epsilon);
if (col < S) {
// Preserve the FP32 store boundary between RMSNorm and ggml_scale.
const float normalized = __fmul_rn(scale, value);
input[col] = __fmaf_rn(normalized, scale_after, 0.0f);
}
}
__global__ void beta_sigmoid(float* beta, int count) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < count) beta[i] = sigmoid(beta[i]);
}
__global__ void gate_softplus(const float* __restrict__ alpha, const float* __restrict__ dt,
const float* __restrict__ ssm_a, float* __restrict__ gate, int count) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= count) return;
const float value = __fadd_rn(alpha[i], dt[i]);
const float softplus = value > 20.0f ? value : log1pf(expf(value)); // 1 + e^v loses e^v below ~1e-7
gate[i] = softplus * ssm_a[i];
}
__global__ void out_norm(const float* __restrict__ input, const float* __restrict__ z,
const float* __restrict__ gamma, float* __restrict__ output, float epsilon) {
const int col = threadIdx.x;
const size_t offset = size_t(blockIdx.x) * S;
const float value = col < S ? input[offset + col] : 0.0f;
float partial = 0.0f;
if (col < S) partial += value * value;
__shared__ float sums[32];
partial = norm_sum(partial, sums);
const float scale = rsqrtf(partial / S + epsilon);
if (col < S) {
// RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul.
const float weighted = __fmul_rn(__fmul_rn(scale, value), gamma[col]);
output[offset + col] = weighted * sigmoid(z[offset + col]);
}
}
struct Span { const void* pointer; size_t bytes; };
void valid(Span span) {
const auto address = reinterpret_cast<uintptr_t>(span.pointer);
if (!span.pointer || address % sizeof(float) || span.bytes > UINTPTR_MAX - address)
throw std::invalid_argument("native GDN preprocessing requires aligned nonnull valid spans");
}
void disjoint(Span a, Span b) {
const auto ap = reinterpret_cast<uintptr_t>(a.pointer), bp = reinterpret_cast<uintptr_t>(b.pointer);
if (ap < bp + b.bytes && bp < ap + a.bytes)
throw std::invalid_argument("native GDN preprocessing requires disjoint writable spans");
}
void count_and_stream(int64_t count, void* stream) {
if (!stream || count <= 0 || count > 65535)
throw std::invalid_argument("native GDN preprocessing requires a stream and count in [1,65535]");
}
void norm_geometry(int64_t rows, int64_t cols, float epsilon, void* stream) {
count_and_stream(rows, stream);
if (cols != S || !std::isfinite(epsilon) || epsilon < 0.0f)
throw std::invalid_argument("native GDN norm requires width 128 and finite nonnegative epsilon");
}
void check_launch() {
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
}
void native_gdn_conv_silu(float* history, const float* input, const float* weights,
float* raw_output, float* silu_output, int64_t channels,
int64_t d_conv, void* stream) {
count_and_stream(channels, stream);
if (d_conv != 4) throw std::invalid_argument("native GDN convolution requires four taps");
const size_t bytes = size_t(channels) * sizeof(float);
const Span writable[] = {{history, 3 * bytes}, {raw_output, bytes}, {silu_output, bytes}};
const Span inputs[] = {{input, bytes}, {weights, 4 * bytes}};
for (auto span : writable) valid(span);
for (auto span : inputs) valid(span);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < i; ++j) disjoint(writable[i], writable[j]);
for (auto span : inputs) disjoint(writable[i], span);
}
conv_silu<<<unsigned((channels + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(
history, input, weights, raw_output, silu_output, int(channels));
check_launch();
}
void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream) {
norm_geometry(rows, cols, epsilon, stream);
valid({input, size_t(rows) * S * sizeof(float)});
l2_norm<<<unsigned(rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(input, epsilon / S, 1.0f / sqrtf(float(S)));
check_launch();
}
void native_gdn_beta_gate(float* beta, int64_t heads, void* stream) {
count_and_stream(heads, stream);
valid({beta, size_t(heads) * sizeof(float)});
beta_sigmoid<<<unsigned((heads + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(beta, int(heads));
check_launch();
}
void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a,
float* gate, int64_t heads, void* stream) {
count_and_stream(heads, stream);
const size_t bytes = size_t(heads) * sizeof(float);
const Span output{gate, bytes};
valid(output);
for (auto input : {Span{alpha, bytes}, Span{dt, bytes}, Span{ssm_a, bytes}}) {
valid(input);
disjoint(output, input);
}
gate_softplus<<<unsigned((heads + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(alpha, dt, ssm_a, gate, int(heads));
check_launch();
}
void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
float* destination, int64_t heads, int64_t cols,
float epsilon, void* stream) {
norm_geometry(heads, cols, epsilon, stream);
const size_t bytes = size_t(heads) * S * sizeof(float);
const Span writable{destination, bytes};
valid(writable);
for (auto input : {Span{output, bytes}, Span{z, bytes}, Span{gamma, S * sizeof(float)}}) {
valid(input);
disjoint(writable, input);
}
out_norm<<<unsigned(heads), 256, 0, static_cast<cudaStream_t>(stream)>>>(output, z, gamma, destination, epsilon);
check_launch();
}
} // namespace strata::kernels
@@ -0,0 +1,109 @@
// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
// ggml/src/ggml-cuda/{norm.cu,common.cuh}. Scope: contiguous weighted F32 RMSNorm.
//
// 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.
#include "strata/kernels/native_gr_norm.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <string>
namespace strata::kernels {
namespace {
__device__ __forceinline__ float norm_warp_sum(float value) {
#pragma unroll
for (int offset = 16; offset > 0; offset >>= 1) {
value += __shfl_xor_sync(0xffffffffu, value, offset, 32);
}
return value;
}
template<int BlockSize>
__global__ void weighted_rms_norm(const float* __restrict__ input,
const float* __restrict__ gamma,
float* __restrict__ output, int n_cols, float epsilon) {
const int tid = threadIdx.x;
const std::size_t row = std::size_t(blockIdx.y) * gridDim.x + blockIdx.x;
const std::size_t row_offset = row * n_cols;
input += row_offset;
gamma += std::size_t(blockIdx.x) * n_cols;
output += row_offset;
float partial = 0.0f;
for (int col = tid; col < n_cols; col += BlockSize) {
const float value = input[col];
partial += value * value;
}
// Pinned block_reduce<SUM,BlockSize>: every warp repeats the final XOR
// reduction. There is no warp-0-only broadcast or downward-shuffle tree.
__shared__ float sums[32];
partial = norm_warp_sum(partial);
const int lane = tid % 32;
if (lane == 0) sums[tid / 32] = partial;
__syncthreads();
partial = 0.0f;
if (lane < BlockSize / 32) partial = sums[lane];
partial = norm_warp_sum(partial);
const float mean = partial / n_cols;
const float scale = rsqrtf(mean + epsilon);
for (int col = tid; col < n_cols; col += BlockSize) {
output[col] = scale * input[col] * gamma[col];
}
}
void check_pointer(const void* p) {
if (!p || reinterpret_cast<std::uintptr_t>(p) % alignof(float) != 0)
throw std::invalid_argument("native GR RMSNorm requires non-null four-byte aligned pointers");
}
} // namespace
void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output,
int n_cols, int n_rows, float epsilon, void* stream) {
native_gr_rms_norm_weighted_multi(input, gamma, output, n_cols, n_rows, 1, epsilon, stream);
}
void native_gr_rms_norm_weighted_multi(const float* input, const float* gamma, float* output,
int n_cols, int n_rows, int n_tok, float epsilon, void* stream) {
if (n_cols <= 0 || n_rows <= 0 || n_tok <= 0 || !std::isfinite(epsilon) || epsilon < 0.0f)
throw std::invalid_argument("native GR RMSNorm requires positive dimensions and finite nonnegative epsilon");
check_pointer(input);
check_pointer(gamma);
check_pointer(output);
const auto cuda_stream = static_cast<cudaStream_t>(stream);
const dim3 grid{unsigned(n_rows), unsigned(n_tok), 1u};
if (n_cols < 1024)
weighted_rms_norm<256><<<grid, 256, 0, cuda_stream>>>(input, gamma, output, n_cols, epsilon);
else
weighted_rms_norm<1024><<<grid, 1024, 0, cuda_stream>>>(input, gamma, output, n_cols, epsilon);
const auto error = cudaGetLastError();
if (error != cudaSuccess)
throw std::runtime_error(std::string("native GR RMSNorm launch: ") + cudaGetErrorString(error));
}
} // namespace strata::kernels
@@ -0,0 +1,161 @@
// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
// ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh}.
//
// 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.
#include "strata/kernels/native_gr_postops.hpp"
#include <cuda_runtime.h>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <string>
namespace strata::kernels {
namespace {
constexpr int THREADS = 256;
__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); }
// ggml SCALE uses scale*x+bias, including its +0 bias. Retain this operation
// explicitly so compile-time zero does not change signed-zero behavior.
__device__ __forceinline__ float scale_zero_bias(float x, float scale) {
return __fmaf_rn(scale, x, 0.0f);
}
__global__ void down_silu(float* lo, int count, float scale) {
const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (i >= std::size_t(count)) return;
const float x = scale_zero_bias(lo[i], scale);
lo[i] = x / (1.0f + expf(-x));
}
template<bool Fused>
__global__ void pre_gated(const float* __restrict__ xn, float* __restrict__ gate,
float* __restrict__ mixed, int n_embd, int hc, float scale) {
const std::size_t d = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (d >= std::size_t(n_embd)) return;
const std::size_t t = blockIdx.y;
xn += t * std::size_t(n_embd) * hc;
gate += t * std::size_t(n_embd) * hc;
mixed += t * std::size_t(n_embd);
float sum = 0.0f;
for (int c = 0; c < hc; ++c) {
const std::size_t i = std::size_t(c) * n_embd + d;
const float x = xn[i], w = sigmoid(gate[i]);
const float product = __fmul_rn(x, w);
gate[i] = product;
if constexpr (Fused) sum = __fmaf_rn(x, w, sum);
else sum = c == 0 ? product : __fadd_rn(sum, product);
}
if constexpr (Fused) mixed[d] = scale * sum;
else mixed[d] = scale_zero_bias(sum, scale);
}
__global__ void post(const float* residual, const float* __restrict__ block_out,
const float* __restrict__ inject, float* output,
int n_embd, int hc, float scale) {
const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (i >= std::size_t(n_embd) * hc) return;
const std::size_t t = blockIdx.y;
residual += t * std::size_t(n_embd) * hc;
block_out += t * std::size_t(n_embd);
inject += t * std::size_t(hc);
output += t * std::size_t(n_embd) * hc;
const int c = int(i / n_embd), d = int(i % n_embd);
const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f);
// Exact residual/output alias is supported; no other thread reads residual[i].
output[i] = __fmaf_rn(block_out[d], weight, residual[i]);
}
// `post` for n tokens (blockIdx.y = token): the same expression per element
__global__ void post_multi(const float* residual, const float* __restrict__ block_out,
const float* __restrict__ inject, float* output, int n_embd, int hc, float scale,
long long r_stride, long long b_stride, long long i_stride) {
const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (i >= std::size_t(n_embd) * hc) return;
const long long t = blockIdx.y;
residual += t * r_stride; output += t * r_stride; block_out += t * b_stride; inject += t * i_stride;
const int c = int(i / n_embd), d = int(i % n_embd);
const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f);
// Exact residual/output alias is supported; no other thread reads residual[i].
output[i] = __fmaf_rn(block_out[d], weight, residual[i]);
}
void check_pointer(const void* p) {
if (!p || reinterpret_cast<std::uintptr_t>(p) % alignof(float))
throw std::invalid_argument("native GR postops require non-null four-byte aligned pointers");
}
void check_shape(int n, int hc) {
if (n <= 0 || hc <= 0 || std::uint64_t(n) * hc > std::uint64_t(std::numeric_limits<int>::max()))
throw std::invalid_argument("native GR postops require positive bounded dimensions");
}
unsigned blocks(std::size_t n) { return unsigned((n + THREADS - 1) / THREADS); }
void check_launch() {
const auto error = cudaGetLastError();
if (error != cudaSuccess)
throw std::runtime_error(std::string("native GR postops launch: ") + cudaGetErrorString(error));
}
} // namespace
void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream) {
check_shape(hc_lr, hc);
check_pointer(lo);
down_silu<<<blocks(hc_lr), THREADS, 0, static_cast<cudaStream_t>(stream)>>>(lo, hc_lr, 1.0f / float(hc));
check_launch();
}
void native_gr_pre_gated(const float* xn, float* gate, float* mixed,
int n_embd, int hc, bool fused_layer, void* stream) {
native_gr_pre_gated_multi(xn, gate, mixed, n_embd, hc, 1, fused_layer, stream);
}
void native_gr_pre_gated_multi(const float* xn, float* gate, float* mixed,
int n_embd, int hc, int n_tok, bool fused_layer, void* stream) {
if (n_tok <= 0)
throw std::invalid_argument("native GR postops require positive n_tok");
check_shape(n_embd, hc);
check_pointer(xn); check_pointer(gate); check_pointer(mixed);
const dim3 grid{blocks(n_embd), unsigned(n_tok), 1u};
if (fused_layer)
pre_gated<true><<<grid, THREADS, 0, static_cast<cudaStream_t>(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc));
else
pre_gated<false><<<grid, THREADS, 0, static_cast<cudaStream_t>(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc));
check_launch();
}
void native_gr_post(const float* residual, const float* block_out, const float* inject,
float* output, int n_embd, int hc, void* stream) {
native_gr_post_multi(residual, block_out, inject, output, n_embd, hc, 1, stream);
}
void native_gr_post_multi(const float* residual, const float* block_out, const float* inject,
float* output, int n_embd, int hc, int n_tok, void* stream) {
if (n_tok <= 0)
throw std::invalid_argument("native GR postops require positive n_tok");
check_shape(n_embd, hc);
check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output);
const dim3 grid{blocks(std::size_t(n_embd) * hc), unsigned(n_tok), 1u};
post<<<grid, THREADS, 0, static_cast<cudaStream_t>(stream)>>>(
residual, block_out, inject, output, n_embd, hc, 1.0f / float(hc));
check_launch();
}
void native_gr_post_multi(const float* residual, const float* block_out, const float* inject, float* output,
int n_embd, int hc, int n_tok, long long r_stride, long long b_stride, long long i_stride,
void* stream) {
check_shape(n_embd, hc);
check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output);
if (n_tok < 1) return;
post_multi<<<dim3(blocks(std::size_t(n_embd) * hc), unsigned(n_tok)), THREADS, 0, static_cast<cudaStream_t>(stream)>>>(
residual, block_out, inject, output, n_embd, hc, 1.0f / float(hc), r_stride, b_stride, i_stride);
check_launch();
}
} // namespace strata::kernels
@@ -0,0 +1,239 @@
// Arithmetic adapted from the MIT-licensed pinned ggml CUDA
// moe-weighted-reduction.cu at 3cf03257f219afbe7334045ff7c6a06ac68c627d.
// 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.
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include "strata/core/geometry.hpp"
#include <cuda_runtime.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
namespace strata::kernels {
namespace {
constexpr int KU = strata::core::kCompiledGeometry.n_expert_used; // 10 for Flash-Next: the combine kernels below are written for exactly this many ranks (<= 16: the hit mask is an int)
static_assert(KU >= 1 && KU <= 16, "native_moe: top-k must be 1..16");
std::atomic<bool> enabled{false};
// GATED (S26 STRATA_LFUSE): `shared` is the shared expert's unscaled output and sg its raw gate logit per token;
// the row is scaled here as shared_expert_multi did (native_scalar_sigmoid_multi_kernel's expression, then one
// rounded multiply = scale_rows_kernel's `out *= g`), then added as before
template<bool ZADD = false, bool GATED = false>
__global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights,
const float* __restrict__ shared, float* __restrict__ output,
int64_t n_embd, int k, const float* __restrict__ sg = nullptr) {
// blockIdx.y = the token of a multi-token launch (0 for the single one)
const int64_t tk = blockIdx.y;
parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd;
const int64_t col = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (col >= n_embd) return;
// ZADD: a part is 0.0f + hit (the zeroed row plus moe_hit_add of the verify window), rounded as that add
float p0 = parts[col];
if (ZADD) p0 = 0.0f + p0;
float sum = p0 * weights[0];
for (int expert = 1; expert < k; ++expert) {
float p = parts[int64_t(expert) * n_embd + col];
if (ZADD) p = 0.0f + p;
sum += p * weights[expert];
}
if constexpr (GATED) {
// contraction off in this block only: the product is rounded on its own (scale_rows' store), then added
#if defined(__HIPCC__)
#pragma clang fp contract(off)
#endif
const float g = __fdividef(1.0f, 1.0f + __expf(-sg[tk]));
#if defined(__HIPCC__)
const float sh = shared[col] * g;
#else
const float sh = __fmul_rn(shared[col], g); // nvcc ignores the clang pragma and fuses the product into the add (#5100): a rounded multiply by hand
#endif
sum += sh;
} else {
if (shared) sum += shared[col];
}
output[col] = sum;
}
__global__ void combine_k10_vec4(const float4* __restrict__ parts4, const float* __restrict__ weights,
const float4* __restrict__ shared4, float4* __restrict__ output4,
int64_t n4) {
const int64_t tk = blockIdx.y;
parts4 += tk * KU * n4;
weights += tk * KU;
shared4 += tk * n4;
output4 += tk * n4;
const int64_t c4 = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (c4 >= n4) return;
const float w0 = __ldg(weights + 0);
const float4 p0 = parts4[c4];
float4 sum = make_float4(p0.x * w0, p0.y * w0, p0.z * w0, p0.w * w0);
#pragma unroll
for (int expert = 1; expert < KU; ++expert) {
const float w = __ldg(weights + expert);
const float4 p = parts4[int64_t(expert) * n4 + c4];
// the documented contract spelled out: the first product rounded, then one FMA per expert in order. Left to the
// compiler's contraction, a build may fuse a different product (gfx1151: the float4 kernel then differed from the
// scalar one, native_multi_parity)
sum.x = fmaf(p.x, w, sum.x);
sum.y = fmaf(p.y, w, sum.y);
sum.z = fmaf(p.z, w, sum.z);
sum.w = fmaf(p.w, w, sum.w);
}
const float4 sh = shared4[c4];
sum.x += sh.x;
sum.y += sh.y;
sum.z += sh.z;
sum.w += sh.w;
output4[c4] = sum;
}
__global__ void combine_k10_vec4_hits(const float4* __restrict__ parts4, const float4* __restrict__ hits4,
const int32_t* __restrict__ dst, const int32_t* __restrict__ count,
const float* __restrict__ weights, const float4* __restrict__ shared4,
float4* __restrict__ output4, int64_t n4) {
const int64_t tk = blockIdx.y;
__shared__ int hit_mask;
if (threadIdx.x == 0) hit_mask = 0;
__syncthreads();
const int nh = *count;
for (int h = threadIdx.x; h < nh; h += blockDim.x) {
const int r = dst[h];
if (r / KU == (int) tk) atomicOr(&hit_mask, 1 << (r % KU));
}
__syncthreads();
const int mask = hit_mask;
parts4 += tk * KU * n4;
hits4 += tk * KU * n4;
weights += tk * KU;
shared4 += tk * n4;
output4 += tk * n4;
const int64_t c4 = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (c4 >= n4) return;
const float w0 = __ldg(weights + 0);
float4 p0 = parts4[c4];
if (mask & 1) { const float4 hh = hits4[c4]; p0.x += hh.x; p0.y += hh.y; p0.z += hh.z; p0.w += hh.w; }
float4 sum = make_float4(p0.x * w0, p0.y * w0, p0.z * w0, p0.w * w0);
#pragma unroll
for (int expert = 1; expert < KU; ++expert) {
const float w = __ldg(weights + expert);
float4 p = parts4[int64_t(expert) * n4 + c4];
if ((mask >> expert) & 1) { const float4 hh = hits4[int64_t(expert) * n4 + c4]; p.x += hh.x; p.y += hh.y; p.z += hh.z; p.w += hh.w; }
sum.x = fmaf(p.x, w, sum.x);
sum.y = fmaf(p.y, w, sum.y);
sum.z = fmaf(p.z, w, sum.z);
sum.w = fmaf(p.w, w, sum.w);
}
const float4 sh = shared4[c4];
sum.x += sh.x;
sum.y += sh.y;
sum.z += sh.z;
sum.w += sh.w;
output4[c4] = sum;
}
bool valid_span(const void* p, size_t bytes) {
const auto address = reinterpret_cast<uintptr_t>(p);
return p && address % alignof(float) == 0 && bytes <= UINTPTR_MAX - address;
}
bool overlap(const void* a, size_t an, const void* b, size_t bn) {
const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
return ap < bp + bn && bp < ap + an;
}
}
void native_moe_combine_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
bool native_moe_combine_enabled() { return enabled.load(std::memory_order_relaxed); }
void native_moe_combine(const float* parts, const float* weights, const float* shared,
float* output, int64_t n_embd, int64_t k, void* stream) {
if (!stream || n_embd <= 0 || n_embd > std::numeric_limits<int>::max() || k < 1 || k > 15)
throw std::invalid_argument("native MoE combine requires a stream, positive width and 1..15 experts");
const size_t row_bytes = size_t(n_embd) * sizeof(float);
const size_t part_bytes = row_bytes * size_t(k), weight_bytes = size_t(k) * sizeof(float);
if (!valid_span(parts, part_bytes) || !valid_span(weights, weight_bytes) || !valid_span(output, row_bytes)
|| (shared && !valid_span(shared, row_bytes))
|| overlap(output, row_bytes, parts, part_bytes)
|| overlap(output, row_bytes, weights, weight_bytes)
|| (shared && overlap(output, row_bytes, shared, row_bytes)))
throw std::invalid_argument("native MoE combine requires aligned spans and disjoint output");
if (k == KU && shared != nullptr && (n_embd & 3) == 0 &&
(((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {
const int64_t n4 = n_embd >> 2;
combine_k10_vec4<<<unsigned((n4 + 127) / 128), 128, 0, static_cast<cudaStream_t>(stream)>>>(
reinterpret_cast<const float4*>(parts), weights, reinterpret_cast<const float4*>(shared),
reinterpret_cast<float4*>(output), n4);
} else {
combine<<<unsigned((n_embd + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(
parts, weights, shared, output, n_embd, int(k));
}
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
bool native_moe_combine_hits_supported(const float* parts, const float* shared, const float* output, int64_t n_embd, int64_t k, int n_tok) {
return k == KU && shared != nullptr && n_tok >= 1 && n_tok <= kVerifyMaxT && n_embd > 0 && (n_embd & 3) == 0 &&
(((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0;
}
void native_moe_combine_multi_hits_added(const float* parts, const float* hits, const int32_t* dst, const int32_t* count,
const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k,
int n_tok, void* stream) {
if (!stream || !native_moe_combine_hits_supported(parts, shared, output, n_embd, k, n_tok) || ((uintptr_t) hits & 15u) != 0)
throw std::invalid_argument("native MoE combine (hits added) requires k = 10, aligned spans, 1..8 tokens (16 in a wide build)");
const int64_t n4 = n_embd >> 2;
combine_k10_vec4_hits<<<dim3(unsigned((n4 + 127) / 128), (unsigned) n_tok), 128, 0, static_cast<cudaStream_t>(stream)>>>(
reinterpret_cast<const float4*>(parts), reinterpret_cast<const float4*>(hits), dst, count, weights,
reinterpret_cast<const float4*>(shared), reinterpret_cast<float4*>(output), n4);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output,
int64_t n_embd, int64_t k, int n_tok, void* stream) {
if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)
throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens");
if (k == KU && shared != nullptr && (n_embd & 3) == 0 &&
(((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {
const int64_t n4 = n_embd >> 2;
combine_k10_vec4<<<dim3(unsigned((n4 + 127) / 128), (unsigned) n_tok), 128, 0, static_cast<cudaStream_t>(stream)>>>(
reinterpret_cast<const float4*>(parts), weights, reinterpret_cast<const float4*>(shared),
reinterpret_cast<float4*>(output), n4);
} else {
combine<<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>(
parts, weights, shared, output, n_embd, int(k));
}
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared,
const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok,
void* stream) {
if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1 || !shared || !shared_gate)
throw std::invalid_argument("native MoE combine (hits, gated) requires a stream, width, 1..15 experts, tokens");
combine<true, true><<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>(
hits, weights, shared, output, n_embd, int(k), shared_gate);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output,
int64_t n_embd, int64_t k, int n_tok, void* stream) {
if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)
throw std::invalid_argument("native MoE combine (hits) requires a stream, width, 1..15 experts, tokens");
combine<true><<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>(
hits, weights, shared, output, n_embd, int(k));
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
}
@@ -0,0 +1,250 @@
// Numerical contract: pinned ggml/src/ggml-cuda/rope.cu, rope_multi/rope_yarn.
// Text positions are equal across the four IMRoPE sections, so section routing
// reduces to the one position associated with each contiguous row.
// 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.
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/mrope.hpp"
#include <cuda_runtime.h>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <stdexcept>
namespace strata::kernels {
namespace {
std::atomic<bool> enabled{false};
bool overlaps(const void* a, size_t an, const void* b, size_t bn) {
auto x = reinterpret_cast<uintptr_t>(a), y = reinterpret_cast<uintptr_t>(b);
return x <= y ? y - x < an : x - y < bn;
}
// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches <false> whenever
// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
// with it merely skipped at run time, the compiled default path changed its results).
template <bool TAB>
__global__ void apply(const float* x, float* out, int rows, int width,
int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high,
float ext_factor, float mscale, const int* positions, const int32_t* mtab, RopeTab rt) {
const int row = blockIdx.y;
const int pair = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= rows || pair >= width / 2) return;
const size_t start = size_t(row) * width;
if (pair >= n_rot / 2) {
if (x != out) {
out[start + 2 * pair] = x[start + 2 * pair];
out[start + 2 * pair + 1] = x[start + 2 * pair + 1];
}
return;
}
float c, s;
if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {
const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair));
rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
}
const float a = x[start + pair], b = x[start + pair + n_rot / 2];
out[start + pair] = a * c - b * s;
out[start + pair + n_rot / 2] = a * s + b * c;
}
template <bool TAB>
__global__ void norm_rope_kernel(const float* x, int in_stride, const float* __restrict__ gamma, float* out,
int n_cols, int n_rot, float epsilon, float theta_scale,
float freq_scale, float corr_low, float corr_high,
float ext_factor, float mscale, const int* positions,
const int32_t* mtab, RopeTab rt) {
const int tid = threadIdx.x;
const int row = blockIdx.x;
const float* in_row = x + size_t(row) * in_stride;
float* out_row = out + size_t(row) * n_cols;
float partial = 0.0f;
for (size_t col = tid; col < size_t(n_cols); col += 256) {
const float xv = in_row[col];
partial += xv * xv;
}
const int half_rot = n_rot / 2;
const float x_tid = tid < n_cols ? in_row[tid] : 0.0f;
const float x_hi = tid < half_rot ? in_row[tid + half_rot] : 0.0f;
__shared__ float sums[32];
#pragma unroll
for (int offset = 16; offset; offset >>= 1)
partial += __shfl_xor_sync(0xffffffffu, partial, offset, 32);
const int lane = tid % 32;
if (lane == 0) sums[tid / 32] = partial;
__syncthreads();
partial = lane < 256 / 32 ? sums[lane] : 0.0f;
#pragma unroll
for (int offset = 16; offset; offset >>= 1)
partial += __shfl_xor_sync(0xffffffffu, partial, offset, 32);
const float mean = partial / n_cols;
const float scale = rsqrtf(mean + epsilon);
if (tid >= n_rot && tid < n_cols) {
out_row[tid] = (scale * x_tid) * gamma[tid];
} else if (tid < half_rot) {
const int pair = tid;
float a = (scale * x_tid) * gamma[pair];
float b = (scale * x_hi) * gamma[pair + half_rot];
#if defined(__CUDA_ARCH__) && !defined(__HIP_DEVICE_COMPILE__)
asm volatile("mov.f32 %0, %1;" : "=f"(a) : "f"(a));
asm volatile("mov.f32 %0, %1;" : "=f"(b) : "f"(b));
#endif
float c, s;
if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {
const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair));
rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
}
float bs = b * s;
float bc = b * c;
#if defined(__CUDA_ARCH__) && !defined(__HIP_DEVICE_COMPILE__)
asm volatile("mov.f32 %0, %1;" : "=f"(bs) : "f"(bs));
asm volatile("mov.f32 %0, %1;" : "=f"(bc) : "f"(bc));
#endif
out_row[pair] = fmaf(a, c, -bs);
#if defined(__HIP_DEVICE_COMPILE__)
// HIP contracts apply's `a * s + b * c` as fma(b, c, a * s); match it (rope_parity check 6)
out_row[pair + half_rot] = fmaf(b, c, a * s);
#else
out_row[pair + half_rot] = fmaf(a, s, bc);
#endif
}
}
}
// one table per device (a layer split runs the rope kernels on several): set and read for the current device
namespace {
constexpr int kMropeDevices = 64;
std::atomic<const int32_t*> mrope_tab[kMropeDevices] = {};
int mrope_dev() {
int d = 0;
if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kMropeDevices) d = 0;
return d;
}
} // namespace
void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); }
const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); }
namespace {
// #280: the float64 angle table of each device, set at session init (before any graph is captured)
struct RopeReg {
RopeTab tab;
RopeScaling scaling;
};
RopeReg rope_tab[kMropeDevices] = {};
bool same_scaling(const RopeScaling& a, const RopeScaling& b) {
return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in &&
a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor &&
a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow;
}
// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move)
bool rope_table_enabled() {
static const bool on = [] {
const char* e = std::getenv("STRATA_ROPE_TABLE");
return e != nullptr && e[0] == '1';
}();
return on;
}
} // namespace
void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) {
rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling};
}
void rope_table_release(const float* cos_tab) {
// every device's entry that points at it (the caller may free it from another current device)
for (RopeReg& r : rope_tab)
if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{};
}
RopeTab rope_table_for(const RopeScaling& scaling) {
if (!rope_table_enabled()) return {};
const RopeReg& r = rope_tab[mrope_dev()];
return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{};
}
void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); }
bool native_norm_rope_usable(int head_dim, int n_rot) {
static const bool on = [] {
const char* off = std::getenv("STRATA_NO_NORM_ROPE");
if (off != nullptr && off[0] != '\0' && off[0] != '0') return false;
#if defined(__HIPCC__)
const char* v = std::getenv("STRATA_NORM_ROPE"); // AMD: opt in until rope_parity check 6 passes there
return v != nullptr && v[0] != '\0' && v[0] != '0';
#else
return true;
#endif
}();
return on && (head_dim == 128 || head_dim == 256) && n_rot == 64;
}
void native_rope_apply(const float* x, float* out, int rows, int head_dim,
int n_rot, const RopeScaling& scaling, const int* positions, void* stream) {
if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 ||
(head_dim != 128 && head_dim != 256) || n_rot != 64 ||
rope_scaling_invalid(scaling) != nullptr ||
reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(out) % 4 ||
reinterpret_cast<uintptr_t>(positions) % 4) {
throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream");
}
const size_t bytes = size_t(rows) * head_dim * sizeof(float);
if ((x != out && overlaps(x, bytes, out, bytes)) ||
overlaps(positions, size_t(rows) * sizeof(int), out, bytes) ||
overlaps(positions, size_t(rows) * sizeof(int), x, bytes)) {
throw std::invalid_argument("native RoPE buffers partially overlap");
}
// Match pinned host-side float powf before device fast powf/trigonometry.
const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);
const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants
const RopeTab rt = rope_table_for(scaling);
const unsigned threads = (x == out && n_rot == 64 && native_norm_rope_usable(head_dim, n_rot)) ? 32u : 128u;
const dim3 grid(threads == 32u ? 1u : unsigned((head_dim / 2 + 127) / 128), rows);
if (rt.cos != nullptr)
apply<true><<<grid, threads, 0, static_cast<cudaStream_t>(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale,
k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
else
apply<false><<<grid, threads, 0, static_cast<cudaStream_t>(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale,
k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_qsa_rms_norm_rope(const float* x, int in_stride, const float* gamma, float* out,
int rows, int head_dim, int n_rot, float epsilon,
const RopeScaling& scaling, const int* positions, void* stream) {
if (!x || !gamma || !out || !positions || !stream || rows < 1 || rows > 65535 ||
(head_dim != 128 && head_dim != 256) || in_stride < head_dim || n_rot != 64 ||
!std::isfinite(epsilon) || epsilon < 0.0f ||
rope_scaling_invalid(scaling) != nullptr ||
reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(gamma) % 4 ||
reinterpret_cast<uintptr_t>(out) % 4 || reinterpret_cast<uintptr_t>(positions) % 4) {
throw std::invalid_argument("native_qsa_rms_norm_rope: invalid arguments");
}
const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);
const RopeKernelArgs k = scaling.kernel_args(n_rot);
const RopeTab rt = rope_table_for(scaling);
if (rt.cos != nullptr)
norm_rope_kernel<true><<<unsigned(rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(
x, in_stride, gamma, out, head_dim, n_rot, epsilon, theta_scale,
k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
else
norm_rope_kernel<false><<<unsigned(rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(
x, in_stride, gamma, out, head_dim, n_rot, epsilon, theta_scale,
k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
}
@@ -0,0 +1,329 @@
// Adapted from topk-moe.cu/common.cuh in llama.cpp
// 3cf03257f219afbe7334045ff7c6a06ac68c627d; finite F32, 512-expert/10-output path.
// 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.
#include "strata/kernels/native_router.hpp"
#include <cuda_runtime.h>
#include <atomic>
#include <cfloat>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
namespace strata::kernels {
namespace {
std::atomic<bool> enabled{false};
__device__ __forceinline__ float warp_sum(float value) {
#pragma unroll
for (int mask = 16; mask; mask >>= 1) value += __shfl_xor_sync(0xffffffffu, value, mask, 32);
return value;
}
__device__ __forceinline__ float warp_max(float value) {
#pragma unroll
for (int mask = 16; mask; mask >>= 1) value = fmaxf(value, __shfl_xor_sync(0xffffffffu, value, mask, 32));
return value;
}
__launch_bounds__(256, 1)
__global__ void route(const float* __restrict__ logits, int32_t* __restrict__ ids,
float* __restrict__ weights) {
// Preserve the pinned 32x8 block geometry; only row zero is active here.
// blockIdx.x = the token (a multi-token launch; 0 for the single one)
logits += (size_t) blockIdx.x * 512; ids += (size_t) blockIdx.x * 10; weights += (size_t) blockIdx.x * 10;
if (threadIdx.y != 0) return;
const int lane = threadIdx.x;
float values[16];
#pragma unroll
for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32];
__syncthreads();
float maximum = -INFINITY;
#pragma unroll
for (int i = 0; i < 16; ++i) maximum = max(maximum, values[i]);
maximum = warp_max(maximum);
float sum = 0.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
values[i] = expf(values[i] - maximum);
sum += values[i];
}
const float reciprocal = 1.0f / warp_sum(sum);
#pragma unroll
for (int i = 0; i < 16; ++i) {
values[i] *= reciprocal;
if (__isnanf(values[i])) values[i] = -FLT_MAX;
}
float selected = 0.0f, selected_sum = 0.0f;
for (int rank = 0; rank < 10; ++rank) {
float best = values[0];
int expert = lane;
#pragma unroll
for (int i = 1; i < 16; ++i) {
if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
}
#pragma unroll
for (int mask = 16; mask; mask >>= 1) {
const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
}
if ((expert & 31) == lane) {
values[expert / 32] = -INFINITY;
ids[rank] = expert;
// Deliberately accumulate by WINNING EXPERT lane, not output rank.
// Multiple selected experts in one lane add in selection order.
selected_sum += best;
}
if (rank == lane) selected = best;
}
selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f);
const float inverse_selected_sum = 1.0f / selected_sum;
if (lane < 10) weights[lane] = selected * inverse_selected_sum;
}
__launch_bounds__(256, 1)
__global__ void route_multi(const float* __restrict__ logits, int32_t* __restrict__ ids,
float* __restrict__ weights, int n_tok) {
const int tk = (int) blockIdx.x * 8 + (int) threadIdx.y;
if (tk >= n_tok) return;
logits += (size_t) tk * 512; ids += (size_t) tk * 10; weights += (size_t) tk * 10;
const int lane = threadIdx.x;
float values[16];
#pragma unroll
for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32];
__syncwarp();
float maximum = -INFINITY;
#pragma unroll
for (int i = 0; i < 16; ++i) maximum = max(maximum, values[i]);
maximum = warp_max(maximum);
float sum = 0.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
values[i] = expf(values[i] - maximum);
sum += values[i];
}
const float reciprocal = 1.0f / warp_sum(sum);
#pragma unroll
for (int i = 0; i < 16; ++i) {
values[i] *= reciprocal;
if (__isnanf(values[i])) values[i] = -FLT_MAX;
}
float selected = 0.0f, selected_sum = 0.0f;
for (int rank = 0; rank < 10; ++rank) {
float best = values[0];
int expert = lane;
#pragma unroll
for (int i = 1; i < 16; ++i) {
if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
}
#pragma unroll
for (int mask = 16; mask; mask >>= 1) {
const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
}
if ((expert & 31) == lane) {
values[expert / 32] = -INFINITY;
ids[rank] = expert;
selected_sum += best;
}
if (rank == lane) selected = best;
}
selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f);
const float inverse_selected_sum = 1.0f / selected_sum;
if (lane < 10) weights[lane] = selected * inverse_selected_sum;
}
// The same contract for other (experts, top-k) shapes - Qwen3.6-35B-A3B's 256 / 8 - one warp per token, n_tok tokens
// (8 per block). The 512 / 10 path keeps its own kernels above (the Flash-Next bits), this template is only used
// for the other shapes.
template <int NE, int K>
__launch_bounds__(256, 1)
__global__ void route_topk(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ weights,
int n_tok) {
static_assert(NE % 32 == 0 && K <= 32, "experts in whole warps, at most 32 picks");
constexpr int V = NE / 32;
const int tk = (int) blockIdx.x * 8 + (int) threadIdx.y;
if (tk >= n_tok) return;
logits += (size_t) tk * NE; ids += (size_t) tk * K; weights += (size_t) tk * K;
const int lane = threadIdx.x;
float values[V];
#pragma unroll
for (int i = 0; i < V; ++i) values[i] = logits[lane + i * 32];
float maximum = -INFINITY;
#pragma unroll
for (int i = 0; i < V; ++i) maximum = max(maximum, values[i]);
maximum = warp_max(maximum);
float sum = 0.0f;
#pragma unroll
for (int i = 0; i < V; ++i) {
values[i] = expf(values[i] - maximum);
sum += values[i];
}
const float reciprocal = 1.0f / warp_sum(sum);
#pragma unroll
for (int i = 0; i < V; ++i) {
values[i] *= reciprocal;
if (__isnanf(values[i])) values[i] = -FLT_MAX;
}
float selected = 0.0f, selected_sum = 0.0f;
for (int rank = 0; rank < K; ++rank) {
float best = values[0];
int expert = lane;
#pragma unroll
for (int i = 1; i < V; ++i) {
if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
}
#pragma unroll
for (int mask = 16; mask; mask >>= 1) {
const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
}
if ((expert & 31) == lane) {
values[expert / 32] = -INFINITY;
ids[rank] = expert;
selected_sum += best;
}
if (rank == lane) selected = best;
}
selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f);
const float inverse_selected_sum = 1.0f / selected_sum;
if (lane < K) weights[lane] = selected * inverse_selected_sum;
}
bool valid(const void* p, size_t bytes) {
const auto address = reinterpret_cast<uintptr_t>(p);
return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address;
}
bool overlap(const void* a, size_t an, const void* b, size_t bn) {
const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
return ap < bp + bn && bp < ap + an;
}
}
void native_router_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
bool native_router_enabled() { return enabled.load(std::memory_order_relaxed); }
void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream) {
if (!stream || !valid(logits, 512 * 4) || !valid(ids, 10 * 4) || !valid(weights, 10 * 4)
|| overlap(logits, 512 * 4, ids, 10 * 4) || overlap(logits, 512 * 4, weights, 10 * 4)
|| overlap(ids, 10 * 4, weights, 10 * 4))
throw std::invalid_argument("native router requires a stream, aligned spans, and disjoint outputs");
route<<<1, dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(logits, ids, weights);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream) {
if (!stream || n_tok < 1 || !valid(logits, (size_t) n_tok * 512 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) ||
!valid(weights, (size_t) n_tok * 10 * 4))
throw std::invalid_argument("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers");
route_multi<<<(unsigned) ((n_tok + 7) / 8), dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(logits, ids, weights, n_tok);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
bool native_router_topk_supported(int n_expert, int k) { return (n_expert == 512 && k == 10) || (n_expert == 256 && k == 8); }
void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream) {
if (n_expert == 512 && k == 10) { // Flash-Next: the pinned kernels above, unchanged
if (n_tok == 1) native_router_top10(logits, ids, weights, stream);
else native_router_top10_multi(logits, ids, weights, n_tok, stream);
return;
}
if (!stream || n_tok < 1 || !native_router_topk_supported(n_expert, k) ||
!valid(logits, (size_t) n_tok * n_expert * 4) || !valid(ids, (size_t) n_tok * k * 4) ||
!valid(weights, (size_t) n_tok * k * 4))
throw std::invalid_argument("native_router_topk: a stream, a supported (experts, k) and aligned buffers");
route_topk<256, 8><<<(unsigned) ((n_tok + 7) / 8), dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(
logits, ids, weights, n_tok);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
// STRATA_ROUTE_RESIDENT (EXPERIMENTAL, opt-in, changes the output): residency-biased routing for 512 x 10.
// After the top-10: for the ranks lo..hi a non-resident expert is replaced by the best resident expert not already
// picked when its logit is within `margin` of the replaced one; the weights are then the softmax of the selected
// logits (the router's renormalisation). Tokens without a swap keep the router's exact bits.
// stats (device, 4 x uint64): [0] tail entries seen, [1] swaps, [2] non-resident entries before, [3] after.
//
// One warp per token. This used to be one THREAD per token scanning all 512 experts (4 ranks x 512 x 12 scalar
// ops on up to 6 threads): 45 us per layer, 2.2 ms of a 19.4 ms window, which is exactly what the option saved in
// PCIe experts (~2.4 ms) - the swap cost as much as the misses it removed. The ranks are still visited in order
// (a swap changes the set already picked), but the scan is coalesced (lane j reads f = j, j + 32, ...) and reduced
// within the warp. The bits are unchanged: a strictly greater logit wins, the smallest expert index breaks ties,
// and the softmax is the same expression.
__global__ void route_resident_k(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ weights,
const int32_t* __restrict__ res, int n_tok, float margin, int lo, int hi,
unsigned long long* __restrict__ stats) {
const int t = blockIdx.x;
if (t >= n_tok) return;
const int lane = (int) threadIdx.x;
const float* l = logits + (size_t) t * 512;
int32_t* id = ids + (size_t) t * 10;
int32_t my[10];
for (int r = 0; r < 10; ++r) my[r] = id[r];
int swaps = 0, tail = 0, before = 0;
if (lane == 0)
for (int r = 0; r < 10; ++r) before += res[my[r]] < 0;
for (int r = lo; r <= hi && r < 10; ++r) {
const int e = my[r];
if (res[e] >= 0) continue; // already resident: uniform across the warp
if (lane == 0) ++tail;
float bv = -INFINITY;
int bi = -1;
for (int f = lane; f < 512; f += 32) {
if (res[f] < 0) continue;
bool used = false;
for (int q = 0; q < 10; ++q) used |= my[q] == f;
if (used) continue;
if (l[f] > bv) { bv = l[f]; bi = f; }
}
#pragma unroll
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_down_sync(0xffffffffu, bv, off);
const int oi = __shfl_down_sync(0xffffffffu, bi, off);
if (ov > bv || (ov == bv && oi >= 0 && (bi < 0 || oi < bi))) { bv = ov; bi = oi; }
}
if (lane == 0 && bi >= 0 && l[e] - bv <= margin) { my[r] = bi; ++swaps; }
my[r] = __shfl_sync(0xffffffffu, my[r], 0); // all lanes keep the same picked set
}
int after = 0;
if (lane == 0)
for (int r = 0; r < 10; ++r) after += res[my[r]] < 0;
const int sw = __shfl_sync(0xffffffffu, swaps, 0);
if (sw) {
float m = -INFINITY;
for (int r = 0; r < 10; ++r) m = fmaxf(m, l[my[r]]);
float ex[10], sum = 0.0f;
for (int r = 0; r < 10; ++r) { ex[r] = expf(l[my[r]] - m); sum += ex[r]; }
for (int r = 0; r < 10; ++r) weights[(size_t) t * 10 + r] = ex[r] / sum;
}
if (lane == 0) {
for (int r = 0; r < 10; ++r) id[r] = my[r];
if (stats) {
atomicAdd(stats + 0, (unsigned long long) tail);
atomicAdd(stats + 1, (unsigned long long) sw);
atomicAdd(stats + 2, (unsigned long long) before);
atomicAdd(stats + 3, (unsigned long long) after);
}
}
}
void native_route_resident(const float* logits, int32_t* ids, float* weights, const int32_t* res_layer, int n_tok, float margin,
int rank_lo, int rank_hi, unsigned long long* stats, void* stream) {
if (!stream || n_tok < 1 || !res_layer) throw std::invalid_argument("native_route_resident: bad arguments");
route_resident_k<<<(unsigned) n_tok, 32, 0, static_cast<cudaStream_t>(stream)>>>(
logits, ids, weights, res_layer, n_tok, margin, rank_lo, rank_hi, stats);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
}
@@ -0,0 +1,439 @@
// src/kernels/cuda/quantize_act.cu - P2.S2: quantize an activation the way ggml converts src1.
//
// WHY THIS EXISTS AT ALL. `ggml_mul_mat` converts the ACTIVATION (src1) to the weight's `vec_dot_type`
// before the dot product - the rule established over rounds 119-136 and written into `ref/quant.py` as
// `apply_src1`. The CPU expert path already honours it (`bench/micro/cpu_s2.cpp` quantizes to int8 and uses
// `vpdpbusd`), and its P0.T2 parity passes at 1.461e-06. The GPU kernels added in rounds 166-177 take FP16
// activations instead. **Left that way, the two paths would compute different numbers for different experts
// of the SAME token** - not a tolerance question, an inconsistency inside one forward pass.
//
// Q2_0 IS THE CASE THAT MATTERS: the routed experts are all Q2_0, `Q2_0 -> Q8_0`, and that is 31.64 GiB of the
// 38 GiB pack. Q8_K (for the K-quants and IQ4_XS) is the other half of the table and is not here yet.
//
// THE THREE SUBTLETIES, each of which was paid for once already and is transcribed rather than recalled:
//
// 1. `d32 = amax / 127.0f` is computed in FP32, and the QUANTIZED INTEGERS divide by **d32**, not by the
// fp16-rounded value that gets stored. Conflating the two shifts every quant near a rounding boundary -
// measured against ggml's own bytes, 18 of 80 blocks differed, and because Q2_0 experts convert to Q8_0
// the error landed in all 48 MoE blocks and made the end-to-end KL WORSE.
// 2. The reference divides in FLOAT64 (`blk.astype(np.float64) / float(np.float32(d32))`) and rounds with
// `rint` - half to even. This kernel therefore divides in double too: an FP32 division followed by
// `rintf` differs from the reference wherever the f32 quotient rounds across a .5 boundary.
// 3. The DEQUANTIZED value is `q * d16`, the fp16 scale, not `q * d32`. The block stores fp16 and that is
// what a reader multiplies by.
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/quantize_act_dev.cuh"
#include "strata/kernels/swiglu.cuh"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/f16_bits.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
namespace strata::kernels {
namespace {
constexpr int QK8_0 = 32;
// THE fp16 CONVERSION LIVES IN `strata/kernels/f16_bits.hpp`, and this file used to carry its own copy.
//
// Round 198 found the private copy wrong in a way no fixture here could see: it tested `if (exp >= 31)` to
// detect an out-of-range exponent, which conflates an f32 INF/NAN (raw exponent 255) with a FINITE value too
// large for fp16. Every finite overflow - 1e30, 65536, 1e45 - came back as a NaN instead of saturating to
// inf, and this file's fixture is O(1) throughout, so it passed. A numpy-generated oracle caught it on its
// first run. Three copies of a converter whose failure mode is silent wrong bits was two copies too many.
__global__ void quantize_q8_0_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,
long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
quantize_q8_0_block(x + b * QK8_0, blocks + b * 34);
}
/// **THE HIT PATH'S QUANTIZER, AND IT EXISTS TO REPRODUCE `act_quant_q8_1` EXACTLY (R4.2h, round 331).**
///
/// The engine computes every routed expert twice. MISSES go through `cpu/expert.cpp:138 act_quant_q8_1`
/// into the VNNI kernel; HITS went through `quantize_q8_0` above. **Those are not the same quantization**,
/// and round 330 measured the difference with both real implementations linked
/// (`bench/micro/act_quant_parity.cu`):
///
/// int8 activations differing : 0 of 2560 <- this rule's ties are measure-zero
/// chunks whose SCALE differs : 80 of 80, max rel 4.761e-04 <- 2^-11: fp32 vs the block's fp16
///
/// The scale is the difference that matters: `ActQ::scale` is `float` and the CPU kernel multiplies by it
/// (`expert.cpp:92`), while `row_dot_s2_q8` read `f16_at(xb)` out of the `block_q8_0`. So this variant
/// writes the SAME 34-byte blocks (the kernel's indexing is unchanged) **and** a parallel fp32 scale array
/// carrying `d32` unrounded.
///
/// It also adopts the CPU's ROUNDING RULE - multiply by the reciprocal, round half AWAY FROM ZERO - rather
/// than this file's `rint`. That is deliberate and it is the opposite of the direction the comment above
/// argues for. `quantize_q8_0` was tuned to match **ggml's Q8_0 bytes**, which is right for the pack and for
/// `moe_hit_parity`. This function's job is different: it must match **this engine's own CPU reference**,
/// because a hit and a miss for the same expert on the same layer have to produce the same number. The CPU
/// path is the reference - C1 passes on it - so the hit path is brought to it, not the reverse.
__global__ void quantize_q8_0_scaled_thread_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,
float* __restrict__ scales, long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
quantize_q8_0_scaled_block(x + b * QK8_0, blocks + b * 34, scales + b);
}
// A warp a block, lane i on value i: the block's |max| is a max over the same values (0 for none above it, as the
// serial scan from 0 through fmaxf), so every byte is the per-thread loop's.
__global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,
float* __restrict__ scales, long long n_blocks) {
const long long b = ((long long) blockIdx.x * blockDim.x + threadIdx.x) >> 5;
const int i = (int) (threadIdx.x & 31);
if (b >= n_blocks) return;
const float xi = x[b * QK8_0 + i];
uint8_t* out = blocks + b * 34;
float amax = fmaxf(0.0f, fabsf(xi));
for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
// VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here
// is bit-identical to the `s` the CPU path used.
const float s = amax > 0.f ? amax / 127.f : 0.f;
const float inv = s > 0.f ? 1.f / s : 0.f;
if (i == 0) {
scales[b] = s;
const uint16_t d16bits = f16_from_f32(s);
out[0] = (uint8_t) (d16bits & 0xFF);
out[1] = (uint8_t) (d16bits >> 8);
}
// VERBATIM from `cpu/expert.cpp:159-162`: reciprocal multiply, then `t + copysign(0.5, t)` truncated
// toward zero, which is `lround`'s rule - round half away from zero.
const float t = xi * inv;
const float r = t + (t >= 0.f ? 0.5f : -0.5f);
int v = (int) r;
v = v < -127 ? -127 : (v > 127 ? 127 : v);
out[2 + i] = (uint8_t) (int8_t) v;
}
__global__ void dequant_q8_0_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x,
long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
const uint8_t* blk = blocks + b * 34;
const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8));
const float d = f32_from_f16(dbits);
float* out = x + b * QK8_0;
for (int i = 0; i < QK8_0; ++i) out[i] = (float) (int8_t) blk[2 + i] * d;
}
// ===================== Q8_K =====================
//
// `block_q8_K` = { float d ; int8_t qs[256] ; int16_t bsums[16] } = 292 bytes, no padding
// (`static_assert` in ggml-common.h). QK_K = 256.
constexpr int QK_K = 256;
constexpr int Q8K_BYTES = 292;
// `nearest_int_dev` and the per-block quantizers live in `quantize_act_dev.cuh` (shared with the fused
// kernels); the comment that used to justify this copy is there.
__global__ void quantize_q8_K_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,
long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
quantize_q8_K_block(x + b * QK_K, blocks + b * Q8K_BYTES);
}
__global__ void dequant_q8_K_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x,
long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
const uint8_t* blk = blocks + b * Q8K_BYTES;
float d;
memcpy(&d, blk, 4);
const int8_t* qs = (const int8_t*) (blk + 4);
float* out = x + b * QK_K;
for (int i = 0; i < QK_K; ++i) out[i] = (float) qs[i] * d;
}
// ===================== fused silu(gate) * up + quantize =====================
//
// ONE kernel where two ran: `swiglu_kernel` wrote the products and the quantizer read them back. The
// products land in `gate_out` exactly as the standalone kernels stored them and the blocks are the same
// bytes the standalone quantizers produced - the quantizer bodies (`quantize_act_dev.cuh`) run verbatim over
// the shared products. The swilu is PARALLEL (one lane per element): the first version ran 32 exp calls
// serially per thread and measured SLOWER than the two kernels it replaced (M=8: +22.9%).
//
// `SwiluKind` selects the expression because the engine really has three (see `swiglu.cuh`); each is the
// verbatim expression of the standalone kernel that this replaces.
template <int KIND>
__device__ __forceinline__ float swilu_apply(float g, float u) {
if constexpr (KIND == 0) return swilu_legacy(g, u);
else if constexpr (KIND == 1) return swilu_fast(g, u);
else return swilu_native(g, u);
}
// One WARP per 32-element block of pairs: lane j computes pair j (parallel exp), the products stage through
// shared memory, then the quantizer body runs on them exactly as `quantize_q8_0_kernel` did.
template <int KIND, bool SCALED>
__global__ void swilu_quantize_q8_0_kernel(const float* __restrict__ gate, const float* __restrict__ up,
float* __restrict__ gate_out, uint8_t* __restrict__ blocks,
float* __restrict__ scales, long long n_blocks) {
__shared__ float p[4][Q8_0_BLOCK]; // one row per warp (4 warps per block)
const int warps_per_block = (int) (blockDim.x >> 5);
const long long b = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
if (b >= n_blocks) return;
const long long i0 = b * Q8_0_BLOCK;
const float v = swilu_apply<KIND>(gate[i0 + lane], up[i0 + lane]);
gate_out[i0 + lane] = v;
p[warp][lane] = v;
__syncwarp();
if (lane == 0) {
if constexpr (SCALED) quantize_q8_0_scaled_block(p[warp], blocks + b * 34, scales + b);
else quantize_q8_0_block(p[warp], blocks + b * 34);
}
}
// The same for the Q8_K contract (the shared expert's down projection): one warp per 256-element block,
// lane j taking pairs j, j+32, ... so the 256 exp calls spread over the warp.
template <int KIND>
__global__ void swilu_quantize_q8_K_kernel(const float* __restrict__ gate, const float* __restrict__ up,
float* __restrict__ gate_out, uint8_t* __restrict__ blocks,
long long n_blocks) {
__shared__ float p[2][QK_K]; // one row per warp (2 warps per block)
const int warps_per_block = (int) (blockDim.x >> 5);
const long long b = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
if (b >= n_blocks) return;
const long long i0 = b * QK_K;
for (int j = lane; j < QK_K; j += 32) {
const float v = swilu_apply<KIND>(gate[i0 + j], up[i0 + j]);
gate_out[i0 + j] = v;
p[warp][j] = v;
}
__syncwarp();
if (lane == 0) quantize_q8_K_block(p[warp], blocks + b * Q8K_BYTES);
}
template <int KIND>
void swilu_quantize_q8_0_launch(const float* gate, const float* up, float* gate_out, int64_t n, uint8_t* blocks,
float* scales, void* stream) {
const long long nb = n / QK8_0;
const int threads = 128; // 4 warps = 4 blocks of 32 pairs
const unsigned grid = (unsigned) ((nb + 3) / 4);
if (scales != nullptr)
swilu_quantize_q8_0_kernel<KIND, true><<<grid, threads, 0, (cudaStream_t) stream>>>(
gate, up, gate_out, blocks, scales, nb);
else
swilu_quantize_q8_0_kernel<KIND, false><<<grid, threads, 0, (cudaStream_t) stream>>>(
gate, up, gate_out, blocks, nullptr, nb);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "swilu_quantize_q8_0 launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
// ===================== every activation image of x in ONE pass =====================
//
// The layer start quantized `x` with two or three kernels (Q8_0, Q8_K, bf16) - three reads of the same
// buffer and three launches, per layer. One kernel here produces whichever images the caller asks for;
// every image's bytes are what its standalone kernel produced (the per-block math is shared, and each block
// reads the same `x` values). Null pointers skip that image.
__global__ void quantize_images_kernel(const float* __restrict__ x, uint8_t* __restrict__ b80,
uint8_t* __restrict__ bK, uint16_t* __restrict__ b16, long long n) {
const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
const long long nb80 = n / Q8_0_BLOCK; // 32-element blocks
if (i < nb80) {
if (b80 != nullptr) quantize_q8_0_block(x + i * Q8_0_BLOCK, b80 + i * Q8_0_BLOCK_BYTES);
if (b16 != nullptr)
for (int j = 0; j < Q8_0_BLOCK; ++j) b16[i * Q8_0_BLOCK + j] = bf16_from_f32(x[i * Q8_0_BLOCK + j]);
}
// q8_K blocks are 256 wide: the thread whose 32-block starts a super-block computes it (256 values in
// one thread, exactly as `quantize_q8_K_kernel` did).
if (bK != nullptr && (i % (Q8_K_BLOCK / Q8_0_BLOCK)) == 0) {
const long long k = i / (Q8_K_BLOCK / Q8_0_BLOCK);
if (i < nb80 && k < n / Q8_K_BLOCK) quantize_q8_K_block(x + k * Q8_K_BLOCK, bK + k * Q8_K_BLOCK_BYTES);
}
}
} // namespace
void swilu_quantize_q8_0(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream) {
if (n <= 0) return;
if (n % QK8_0 != 0) {
std::fprintf(stderr, "swilu_quantize_q8_0: n %lld is not a multiple of %d\n", (long long) n, QK8_0);
std::exit(1);
}
switch (swilu_kind) {
case 0: swilu_quantize_q8_0_launch<0>(gate, up, gate_out, n, blocks, nullptr, stream); break;
case 1: swilu_quantize_q8_0_launch<1>(gate, up, gate_out, n, blocks, nullptr, stream); break;
default: swilu_quantize_q8_0_launch<2>(gate, up, gate_out, n, blocks, nullptr, stream); break;
}
}
void swilu_quantize_q8_0_scaled(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, float* scales, void* stream) {
if (n <= 0) return;
if (n % QK8_0 != 0) {
std::fprintf(stderr, "swilu_quantize_q8_0_scaled: n %lld is not a multiple of %d\n", (long long) n, QK8_0);
std::exit(1);
}
if (scales == nullptr) {
std::fprintf(stderr, "swilu_quantize_q8_0_scaled: scales is null\n");
std::exit(1);
}
switch (swilu_kind) {
case 0: swilu_quantize_q8_0_launch<0>(gate, up, gate_out, n, blocks, scales, stream); break;
case 1: swilu_quantize_q8_0_launch<1>(gate, up, gate_out, n, blocks, scales, stream); break;
default: swilu_quantize_q8_0_launch<2>(gate, up, gate_out, n, blocks, scales, stream); break;
}
}
void swilu_quantize_q8_K(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream) {
if (n <= 0) return;
if (n % QK_K != 0) {
std::fprintf(stderr, "swilu_quantize_q8_K: n %lld is not a multiple of %d\n", (long long) n, QK_K);
std::exit(1);
}
const long long nb = n / QK_K;
const int threads = 64; // 2 warps = 2 blocks of 256 pairs
const unsigned grid = (unsigned) ((nb + 1) / 2);
switch (swilu_kind) {
case 0: swilu_quantize_q8_K_kernel<0><<<grid, threads, 0, (cudaStream_t) stream>>>(gate, up, gate_out, blocks, nb); break;
case 1: swilu_quantize_q8_K_kernel<1><<<grid, threads, 0, (cudaStream_t) stream>>>(gate, up, gate_out, blocks, nb); break;
default: swilu_quantize_q8_K_kernel<2><<<grid, threads, 0, (cudaStream_t) stream>>>(gate, up, gate_out, blocks, nb); break;
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "swilu_quantize_q8_K launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream) {
if (n <= 0) return;
if (n % QK8_0 != 0) {
std::fprintf(stderr, "quantize_q8_0: n %lld is not a multiple of %d\n", (long long) n, QK8_0);
std::exit(1);
}
const long long nb = n / QK8_0;
const int threads = 128;
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
quantize_q8_0_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, blocks, nb);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "quantize_q8_0 launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
/// See `quantize_q8_0_scaled_kernel`. Writes the same 34-byte `block_q8_0` layout as `quantize_q8_0`, plus
/// `scales[n/32]` carrying the fp32 `s` the CPU path used - so a hit can be computed with the CPU's
/// multiplier instead of the block's fp16 `d`. `scales` must not be null.
void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream) {
if (n <= 0) return;
if (n % QK8_0 != 0) {
std::fprintf(stderr, "quantize_q8_0_scaled: n %lld is not a multiple of %d\n", (long long) n, QK8_0);
std::exit(1);
}
if (scales == nullptr) {
std::fprintf(stderr, "quantize_q8_0_scaled: scales is null\n");
std::exit(1);
}
const long long nb = n / QK8_0;
const int threads = 128;
static const bool old_q80 = [] {
const char* e = std::getenv("STRATA_OLD_Q80_SCALED");
return e != nullptr && e[0] == '1';
}();
if (old_q80) {
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
quantize_q8_0_scaled_thread_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, blocks, scales, nb);
} else {
const unsigned grid = (unsigned) ((nb + threads / 32 - 1) / (threads / 32)); // a warp a block
quantize_q8_0_scaled_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, blocks, scales, nb);
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "quantize_q8_0_scaled launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream) {
if (n <= 0) return;
const long long nb = n / QK8_0;
const int threads = 128;
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
dequant_q8_0_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(blocks, x, nb);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "dequant_q8_0 launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
void quantize_q8_K(const float* x, uint8_t* blocks, int64_t n, void* stream) {
if (n <= 0) return;
if (n % QK_K != 0) {
std::fprintf(stderr, "quantize_q8_K: n %lld is not a multiple of %d\n", (long long) n, QK_K);
std::exit(1);
}
const long long nb = n / QK_K;
const int threads = 64; // one block per thread, and a block is 256 elements
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
quantize_q8_K_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, blocks, nb);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "quantize_q8_K launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream) {
if (n <= 0) return;
const long long nb = n / QK_K;
const int threads = 64;
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
dequant_q8_K_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(blocks, x, nb);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "dequant_q8_K launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
void quantize_act_images(const float* x, int64_t n, uint8_t* q8_0_blocks, uint8_t* q8_K_blocks,
uint16_t* bf16, void* stream) {
if (n <= 0) return;
if (q8_0_blocks == nullptr && q8_K_blocks == nullptr && bf16 == nullptr) return;
if (n % Q8_0_BLOCK != 0 || (q8_K_blocks != nullptr && n % QK_K != 0)) {
std::fprintf(stderr, "quantize_act_images: n %lld must be a multiple of %d (and %d for Q8_K)\n",
(long long) n, Q8_0_BLOCK, QK_K);
std::exit(1);
}
const long long nb = n / Q8_0_BLOCK;
const int threads = 128;
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
quantize_images_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, q8_0_blocks, q8_K_blocks, bf16, n);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "quantize_act_images launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
} // namespace strata::kernels