Compare commits

..
Author SHA1 Message Date
grenadeandClaude Opus 5.5 e5c1f5f320 style(neuron): use a line comment rustfmt versions format alike
CI / Config consistency (push) Successful in 16s
CI / Classify changes (push) Successful in 28s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 19s
CI / Clippy (push) Successful in 2m59s
CI / Test (push) Successful in 7m54s
CI / CUDA type-check (push) Successful in 19m23s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
The block comment's continuation line is indented differently by the
rustfmt in CI and the current stable one, so one of them always failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 13:03:10 +02:00
grenadeandClaude Opus 5.5 2afc8a742a build(neuron): stock candle 0.11.1, Z-Image vendored, cudarc on v0.19.10 (#426)
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) Failing after 17s
CI / Clippy (push) Successful in 2m50s
CI / Test (push) Successful in 6m36s
CI / CUDA type-check (push) Successful in 22m12s
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 candle fork carried only Z-Image changes on top of 0.11.0, 71
upstream commits back (among them a CUDA strided-copy over-copy fix,
#3944, and the CUDA kernel optimisations of #3600). The z_image module,
with neuron's four changes to it, now lives in neuron
(`harness/arch/z_image`), so neuron depends on candle 0.11.1 from
crates.io and the candle patch is gone.

cudarc's three NCCL commits are rebased onto v0.19.10 (12 commits
ahead of the old base, including #591, which stops slice teardown from
waiting on events in single-stream mode, and #600's graph instantiation
flags). Upstream PR chelsea0x3b/cudarc#585 remains open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TzeoVo6NTkUwfS8KUGLVDr
2026-11-24 12:30:51 +02:00
115 changed files with 4217 additions and 27172 deletions
Generated
+169 -308
View File
@@ -546,36 +546,38 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "candle-core"
version = "0.11.0"
source = "git+https://github.com/grenade/candle?rev=f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940#f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d11c8be87cfbaef9ebb62fb3f850d1fc8e00cc1d11d393fdbe55a4d5c2cdb325"
dependencies = [
"byteorder",
"candle-kernels",
"candle-ug",
"cudarc 0.19.8",
"cudarc",
"float8",
"gemm 0.19.0",
"gemm",
"half",
"libc",
"libm",
"memmap2",
"num-traits",
"num_cpus",
"parking_lot",
"rand 0.9.4",
"rand_distr",
"rayon",
"safetensors 0.8.0",
"safetensors",
"thiserror 2.0.18",
"tokenizers",
"yoke 0.8.2",
"tokenizers 0.23.2",
"yoke",
"zerocopy",
"zip",
"zip 9.8.2",
]
[[package]]
name = "candle-flash-attn"
version = "0.11.0"
source = "git+https://github.com/grenade/candle?rev=f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940#f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8f233a5d78ac84fac2b097330faae4a26eae4c4009c54fdb0ec8b7b3c23a15b"
dependencies = [
"anyhow",
"candle-core",
@@ -585,37 +587,40 @@ dependencies = [
[[package]]
name = "candle-kernels"
version = "0.11.0"
source = "git+https://github.com/grenade/candle?rev=f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940#f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8dc057aec95c3b1a0e595227cd039c1436da596f79ccc9e025ba17d070315851"
dependencies = [
"cudaforge",
]
[[package]]
name = "candle-nn"
version = "0.11.0"
source = "git+https://github.com/grenade/candle?rev=f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940#f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "437fabe77547c2447c7bdf3cc946e19db29a2832440176b419f77c80b0a9a05e"
dependencies = [
"candle-core",
"half",
"libc",
"num-traits",
"rayon",
"safetensors 0.8.0",
"safetensors",
"serde",
"thiserror 2.0.18",
]
[[package]]
name = "candle-transformers"
version = "0.11.0"
source = "git+https://github.com/grenade/candle?rev=f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940#f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b1e1abeac23d7df4f94e8a3852b3dbb661d332e37c3bef479507bac867187b2"
dependencies = [
"byteorder",
"candle-core",
"candle-flash-attn",
"candle-nn",
"fancy-regex",
"fancy-regex 0.19.2",
"num-traits",
"rand 0.9.4",
"rayon",
@@ -625,15 +630,6 @@ dependencies = [
"tracing",
]
[[package]]
name = "candle-ug"
version = "0.11.0"
source = "git+https://github.com/grenade/candle?rev=f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940#f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940"
dependencies = [
"ug",
"ug-cuda",
]
[[package]]
name = "castaway"
version = "0.2.4"
@@ -791,6 +787,15 @@ version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]]
name = "constant_time_eq"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9"
dependencies = [
"rustversion",
]
[[package]]
name = "convert_case"
version = "0.10.0"
@@ -1026,24 +1031,20 @@ dependencies = [
[[package]]
name = "cudarc"
version = "0.17.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf99ab37ee7072d64d906aa2dada9a3422f1d975cdf8c8055a573bc84897ed8"
dependencies = [
"half",
"libloading 0.8.9",
]
[[package]]
name = "cudarc"
version = "0.19.8"
source = "git+https://github.com/grenade/cudarc?rev=6904cf2e651a0384eac318f003ce6417f47f5d94#6904cf2e651a0384eac318f003ce6417f47f5d94"
version = "0.19.10"
source = "git+https://github.com/grenade/cudarc?rev=89d05580391bcede857e178ce6f4d853baa885aa#89d05580391bcede857e178ce6f4d853baa885aa"
dependencies = [
"float8",
"half",
"libloading 0.9.0",
"libloading",
]
[[package]]
name = "daachorse"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d"
[[package]]
name = "darling"
version = "0.20.11"
@@ -1461,9 +1462,20 @@ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fancy-regex"
version = "0.18.0"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e1dacd0d2082dfcf1351c4bdd566bbe89a2b263235a2b50058f1e130a47277"
checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8"
dependencies = [
"bit-set",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "fancy-regex"
version = "0.19.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"
dependencies = [
"bit-set",
"regex-automata",
@@ -1751,26 +1763,6 @@ dependencies = [
"slab",
]
[[package]]
name = "gemm"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab96b703d31950f1aeddded248bc95543c9efc7ac9c4a21fda8703a83ee35451"
dependencies = [
"dyn-stack",
"gemm-c32 0.18.2",
"gemm-c64 0.18.2",
"gemm-common 0.18.2",
"gemm-f16 0.18.2",
"gemm-f32 0.18.2",
"gemm-f64 0.18.2",
"num-complex",
"num-traits",
"paste",
"raw-cpuid",
"seq-macro",
]
[[package]]
name = "gemm"
version = "0.19.0"
@@ -1778,27 +1770,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb"
dependencies = [
"dyn-stack",
"gemm-c32 0.19.0",
"gemm-c64 0.19.0",
"gemm-common 0.19.0",
"gemm-f16 0.19.0",
"gemm-f32 0.19.0",
"gemm-f64 0.19.0",
"num-complex",
"num-traits",
"paste",
"raw-cpuid",
"seq-macro",
]
[[package]]
name = "gemm-c32"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6db9fd9f40421d00eea9dd0770045a5603b8d684654816637732463f4073847"
dependencies = [
"dyn-stack",
"gemm-common 0.18.2",
"gemm-c32",
"gemm-c64",
"gemm-common",
"gemm-f16",
"gemm-f32",
"gemm-f64",
"num-complex",
"num-traits",
"paste",
@@ -1813,22 +1790,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c"
dependencies = [
"dyn-stack",
"gemm-common 0.19.0",
"num-complex",
"num-traits",
"paste",
"raw-cpuid",
"seq-macro",
]
[[package]]
name = "gemm-c64"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfcad8a3d35a43758330b635d02edad980c1e143dc2f21e6fd25f9e4eada8edf"
dependencies = [
"dyn-stack",
"gemm-common 0.18.2",
"gemm-common",
"num-complex",
"num-traits",
"paste",
@@ -1843,7 +1805,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f"
dependencies = [
"dyn-stack",
"gemm-common 0.19.0",
"gemm-common",
"num-complex",
"num-traits",
"paste",
@@ -1851,27 +1813,6 @@ dependencies = [
"seq-macro",
]
[[package]]
name = "gemm-common"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a352d4a69cbe938b9e2a9cb7a3a63b7e72f9349174a2752a558a8a563510d0f3"
dependencies = [
"bytemuck",
"dyn-stack",
"half",
"libm",
"num-complex",
"num-traits",
"once_cell",
"paste",
"pulp 0.21.5",
"raw-cpuid",
"rayon",
"seq-macro",
"sysctl",
]
[[package]]
name = "gemm-common"
version = "0.19.0"
@@ -1886,31 +1827,13 @@ dependencies = [
"num-traits",
"once_cell",
"paste",
"pulp 0.22.2",
"pulp",
"raw-cpuid",
"rayon",
"seq-macro",
"sysctl",
]
[[package]]
name = "gemm-f16"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cff95ae3259432f3c3410eaa919033cd03791d81cebd18018393dc147952e109"
dependencies = [
"dyn-stack",
"gemm-common 0.18.2",
"gemm-f32 0.18.2",
"half",
"num-complex",
"num-traits",
"paste",
"raw-cpuid",
"rayon",
"seq-macro",
]
[[package]]
name = "gemm-f16"
version = "0.19.0"
@@ -1918,8 +1841,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e"
dependencies = [
"dyn-stack",
"gemm-common 0.19.0",
"gemm-f32 0.19.0",
"gemm-common",
"gemm-f32",
"half",
"num-complex",
"num-traits",
@@ -1929,21 +1852,6 @@ dependencies = [
"seq-macro",
]
[[package]]
name = "gemm-f32"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc8d3d4385393304f407392f754cd2dc4b315d05063f62cf09f47b58de276864"
dependencies = [
"dyn-stack",
"gemm-common 0.18.2",
"num-complex",
"num-traits",
"paste",
"raw-cpuid",
"seq-macro",
]
[[package]]
name = "gemm-f32"
version = "0.19.0"
@@ -1951,22 +1859,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c"
dependencies = [
"dyn-stack",
"gemm-common 0.19.0",
"num-complex",
"num-traits",
"paste",
"raw-cpuid",
"seq-macro",
]
[[package]]
name = "gemm-f64"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35b2a4f76ce4b8b16eadc11ccf2e083252d8237c1b589558a49b0183545015bd"
dependencies = [
"dyn-stack",
"gemm-common 0.18.2",
"gemm-common",
"num-complex",
"num-traits",
"paste",
@@ -1981,7 +1874,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a"
dependencies = [
"dyn-stack",
"gemm-common 0.19.0",
"gemm-common",
"num-complex",
"num-traits",
"paste",
@@ -2033,10 +1926,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"wasip2",
"wasip3",
"wasm-bindgen",
]
[[package]]
@@ -2583,7 +2478,7 @@ dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke 0.8.2",
"yoke",
"zerofrom",
"zerovec",
]
@@ -2650,7 +2545,7 @@ dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke 0.8.2",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
@@ -2891,16 +2786,6 @@ version = "0.2.185"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]]
name = "libloading"
version = "0.9.0"
@@ -3233,7 +3118,7 @@ dependencies = [
"claxon",
"cortex-core",
"cudaforge",
"cudarc 0.19.8",
"cudarc",
"figment",
"flacenc",
"futures",
@@ -3248,12 +3133,12 @@ dependencies = [
"minijinja-contrib",
"rayon",
"reqwest",
"safetensors 0.8.0",
"safetensors",
"serde",
"serde_json",
"tempfile",
"thiserror 2.0.18",
"tokenizers",
"tokenizers 0.22.2",
"tokio",
"tokio-stream",
"toml",
@@ -3261,7 +3146,7 @@ dependencies = [
"tracing-subscriber",
"unicode-normalization",
"unicode-properties",
"zip",
"zip 8.6.0",
]
[[package]]
@@ -3270,6 +3155,18 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.31.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d6d0705320c1e6ba1d912b5e37cf18071b6c2e9b7fa8215a1e8a7651966f5d3"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nom"
version = "7.1.3"
@@ -3298,20 +3195,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
dependencies = [
"num-bigint",
"num-complex",
"num-integer",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.6"
@@ -3374,17 +3257,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -3831,20 +3703,6 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]]
name = "pulp"
version = "0.21.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96b86df24f0a7ddd5e4b95c94fc9ed8a98f1ca94d3b01bdce2824097e7835907"
dependencies = [
"bytemuck",
"cfg-if",
"libm",
"num-complex",
"reborrow",
"version_check",
]
[[package]]
name = "pulp"
version = "0.22.2"
@@ -4177,9 +4035,9 @@ dependencies = [
[[package]]
name = "regex-automata"
version = "0.4.14"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
@@ -4188,9 +4046,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.8.10"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "reqwest"
@@ -4412,16 +4270,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "safetensors"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44560c11236a6130a46ce36c836a62936dc81ebf8c36a37947423571be0e55b6"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "safetensors"
version = "0.8.0"
@@ -5362,6 +5210,39 @@ dependencies = [
"unicode_categories",
]
[[package]]
name = "tokenizers"
version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc"
dependencies = [
"ahash",
"compact_str",
"daachorse",
"dary_heap",
"derive_builder",
"esaxx-rs",
"fancy-regex 0.17.0",
"getrandom 0.3.4",
"itertools",
"log",
"macro_rules_attribute",
"monostate",
"paste",
"rand 0.9.4",
"rayon",
"rayon-cond",
"regex",
"regex-syntax",
"serde",
"serde_json",
"spm_precompiled",
"thiserror 2.0.18",
"unicode-normalization-alignments",
"unicode-segmentation",
"unicode_categories",
]
[[package]]
name = "tokio"
version = "1.52.3"
@@ -5612,46 +5493,18 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
[[package]]
name = "typed-path"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
[[package]]
name = "typenum"
version = "1.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
[[package]]
name = "ug"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76b761acf8af3494640d826a8609e2265e19778fb43306c7f15379c78c9b05b0"
dependencies = [
"gemm 0.18.2",
"half",
"libloading 0.8.9",
"memmap2",
"num",
"num-traits",
"num_cpus",
"rayon",
"safetensors 0.4.5",
"serde",
"thiserror 1.0.69",
"tracing",
"yoke 0.7.5",
]
[[package]]
name = "ug-cuda"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f0a1fa748f26166778c33b8498255ebb7c6bffb472bcc0a72839e07ebb1d9b5"
dependencies = [
"cudarc 0.17.8",
"half",
"serde",
"thiserror 1.0.69",
"ug",
]
[[package]]
name = "uncased"
version = "0.9.10"
@@ -6499,18 +6352,6 @@ dependencies = [
"time",
]
[[package]]
name = "yoke"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40"
dependencies = [
"serde",
"stable_deref_trait",
"yoke-derive 0.7.5",
"zerofrom",
]
[[package]]
name = "yoke"
version = "0.8.2"
@@ -6518,22 +6359,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"
dependencies = [
"stable_deref_trait",
"yoke-derive 0.8.2",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
"synstructure",
]
[[package]]
name = "yoke-derive"
version = "0.8.2"
@@ -6589,9 +6418,23 @@ dependencies = [
[[package]]
name = "zeroize"
version = "1.8.2"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "zerotrie"
@@ -6600,7 +6443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
dependencies = [
"displaydoc",
"yoke 0.8.2",
"yoke",
"zerofrom",
]
@@ -6610,7 +6453,7 @@ version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
dependencies = [
"yoke 0.8.2",
"yoke",
"zerofrom",
"zerovec-derive",
]
@@ -6635,7 +6478,25 @@ dependencies = [
"crc32fast",
"indexmap 2.14.0",
"memchr",
"typed-path",
"typed-path 0.12.3",
]
[[package]]
name = "zip"
version = "9.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
dependencies = [
"constant_time_eq",
"crc32fast",
"getrandom 0.4.2",
"indexmap 2.14.0",
"libc",
"memchr",
"nix",
"typed-path 0.13.0",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
+6 -17
View File
@@ -68,21 +68,10 @@ eventsource-stream = "0.2"
cortex-core = { path = "crates/cortex-core" }
cortex-gateway = { path = "crates/cortex-gateway" }
# Patched cudarc (affects neuron's 0.19.x only; candle's 0.17.x is
# untouched since the fork is 0.19.8, rebased for the candle 0.11 bump, and now also serves candle's ^0.19.8 req — one unified cudarc). Adds
# Comm::abort / get_async_error / raw comm() — needed for #17 Stage 2 TP
# hang-recovery (abort a wedged collective from another thread, then
# rebuild the comm). Pinned to a fork revision pending upstream review
# (grenade/cudarc @ nccl-comm-abort).
# Patched cudarc: upstream v0.19.10 plus three NCCL commits —
# Comm::abort / get_async_error / raw cu_comm(), and a Drop that does not
# panic — needed for #17's TP hang recovery (abort a wedged collective
# from another thread, then rebuild the comm). Upstream PR:
# chelsea0x3b/cudarc#585. Drop the patch when it is released (#426).
[patch.crates-io]
cudarc = { git = "https://github.com/grenade/cudarc", rev = "6904cf2e651a0384eac318f003ce6417f47f5d94" }
# Patched candle (#199): z_image all-ones attention-mask elision so the
# flash-attn path actually engages — unlocks >=1536^2 denoising on the
# blackwell (flash-attn) builds. Upstream PR:
# https://github.com/huggingface/candle/pull/3798 — drop this pin (and
# the fork) when it lands in a release. All four crates pin to the same
# rev so candle types unify across the graph.
candle-core = { git = "https://github.com/grenade/candle", rev = "f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940" }
candle-nn = { git = "https://github.com/grenade/candle", rev = "f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940" }
candle-transformers = { git = "https://github.com/grenade/candle", rev = "f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940" }
candle-flash-attn = { git = "https://github.com/grenade/candle", rev = "f8fa85fd2753b334cb4f42e7357f8ba9d9bb2940" }
cudarc = { git = "https://github.com/grenade/cudarc", rev = "89d05580391bcede857e178ce6f4d853baa885aa" }
+4 -22
View File
@@ -16,21 +16,6 @@ path = "src/main.rs"
# Not shipped in the RPM: it loads a checkpoint directly and reports
# numbers, and exists so the go/no-go gate is a measurement rather than
# an argument.
[[bin]]
name = "neuron-strata-expert-probe"
path = "src/bin/strata_expert_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-engine-layer-probe"
path = "src/bin/engine_layer_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-engine-step-probe"
path = "src/bin/engine_step_probe.rs"
required-features = ["strata-kernels"]
[[bin]]
name = "neuron-mtp-probe"
path = "src/bin/mtp_probe.rs"
@@ -63,9 +48,6 @@ flash-attn = [
"candle-transformers/flash-attn",
"dep:candle-flash-attn",
]
# The expert kernels vendored from Strata (`vendor/strata`, MIT). Needs
# nvcc with C++20 and `CUDA_COMPUTE_CAP`.
strata-kernels = ["cuda"]
# Reserved for GPU-only integration tests in later stages.
cuda-integration = ["cuda"]
@@ -104,13 +86,13 @@ unicode-properties = "0.1"
# candle for in-process inference. CUDA support is gated behind the
# crate's `cuda` feature (default off) so the workspace builds on
# non-CUDA hosts and CI runners.
candle-core = "0.11.0"
candle-nn = "0.11.0"
candle-transformers = "0.11.0"
candle-core = "0.11.1"
candle-nn = "0.11.1"
candle-transformers = "0.11.1"
# Direct dependency so `candle_flash_attn::flash_attn` is nameable in
# the attention core (#95); the candle-transformers feature alone only
# enables flash inside ITS models.
candle-flash-attn = { version = "0.11.0", optional = true }
candle-flash-attn = { version = "0.11.1", optional = true }
# Direct dep on cudarc (matching candle's transitive version) so the
# TP worker pool can call cudarc::nccl::{Comm, Id} directly. Gated on
# the `cuda` feature; same toolchain requirement as candle's CUDA path.
-103
View File
@@ -54,8 +54,6 @@ fn main() {
.expect("neuron cuda build failed");
println!("cargo:rustc-link-search={}", build_dir.display());
println!("cargo:rustc-link-lib=neuroncuda");
#[cfg(feature = "strata-kernels")]
build_strata_kernels(&build_dir);
println!("cargo:rustc-link-lib=dylib=cudart");
if target.contains("msvc") {
@@ -73,107 +71,6 @@ fn main() {
}
}
/// Compile the vendored Strata expert kernels and neuron's C shim.
///
/// They need C++20 and must not get the `--use_fast_math` the kernels
/// above are built with: upstream builds this file without it, and
/// contraction would change the rounding its parity relies on.
#[cfg(feature = "strata-kernels")]
fn build_strata_kernels(build_dir: &std::path::Path) {
println!("cargo:rerun-if-changed=vendor/strata");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_shim.cu");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/strata_probe.cu");
println!("cargo:rerun-if-changed=src/cuda/strata_adapter/engine_shim.cu");
println!("cargo:rerun-if-env-changed=CUDA_COMPUTE_CAP");
let cap = std::env::var("CUDA_COMPUTE_CAP").expect("strata-kernels needs CUDA_COMPUTE_CAP");
let root = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let vendor = root.join("vendor/strata/engine");
let mut sources = vec![
// UD-IQ4_XS has no NVFP4 experts, so upstream's stub satisfies
// the reference from the grouped dispatch.
(
"strata_nvfp4_absent.o".to_string(),
vendor.join("src/kernels/cuda/nvfp4_decode_sm120_absent.cpp"),
),
(
"strata_shim.o".to_string(),
root.join("src/cuda/strata_adapter/strata_shim.cu"),
),
(
"strata_probe.o".to_string(),
root.join("src/cuda/strata_adapter/strata_probe.cu"),
),
(
"engine_shim.o".to_string(),
root.join("src/cuda/strata_adapter/engine_shim.cu"),
),
];
// The experts, then the decode kernels the native engine (#427)
// drives: linear attention, hyper-connections, router, MoE combine,
// activation quantisation and the BF16 projections.
for kernel in [
"iq_kernels",
"native_gdn",
"native_gdn_preprocess",
"fused_gdn",
"native_gr_norm",
"native_gr_postops",
"gr",
"native_router",
"native_rope",
"native_moe",
"quantize_act",
"bf16_gemv",
"native_bf16",
] {
sources.push((
format!("strata_{kernel}.o"),
vendor.join(format!("src/kernels/cuda/{kernel}.cu")),
));
}
// Independent translation units: compile them side by side.
let objects: Vec<std::path::PathBuf> = std::thread::scope(|scope| {
let jobs: Vec<_> = sources
.iter()
.map(|(name, source)| {
let object = build_dir.join(name);
let (cap, vendor) = (&cap, &vendor);
scope.spawn(move || {
let status = Command::new("nvcc")
.args(["-O3", "-DNDEBUG", "-std=c++20"])
.arg(format!(
"--generate-code=arch=compute_{cap},code=[compute_{cap},sm_{cap}]"
))
.args(["-DSTRATA_Q6K_EXPERTS=1", "-DSTRATA_VERIFY_MAX_T=8"])
.arg(format!("-I{}", vendor.join("third_party/ggml").display()))
.arg(format!("-I{}", vendor.join("include").display()))
.args(["--compiler-options", "-fPIC", "-c"])
.arg(source)
.arg("-o")
.arg(&object)
.status()
.expect("run nvcc");
assert!(status.success(), "nvcc failed on {}", source.display());
object
})
})
.collect();
jobs.into_iter()
.map(|j| j.join().expect("nvcc thread"))
.collect()
});
let library = build_dir.join("libneuronstrata.a");
let _ = std::fs::remove_file(&library);
let status = Command::new("ar")
.arg("rcs")
.arg(&library)
.args(&objects)
.status()
.expect("run ar");
assert!(status.success(), "ar failed");
println!("cargo:rustc-link-lib=static=neuronstrata");
}
/// Emit `cargo:rustc-env=` vars consumed by `env!()` in `src/version.rs`
/// so the daemon can report its own build identity from `GET /version`.
///
-420
View File
@@ -1,420 +0,0 @@
//! 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
@@ -1,326 +0,0 @@
//! 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(())
}
@@ -1,54 +0,0 @@
//! Checks the vendored Strata expert kernels against real GGUF weights.
//!
//! ```sh
//! neuron-strata-expert-probe SHARD GU_TYPE DOWN_TYPE GATE_OFF UP_OFF DOWN_OFF [EXPERT] [TOKENS]
//! ```
//!
//! Offsets are the absolute file offsets of the layer's fused tensors.
use std::ffi::CString;
use neuron::cuda::strata::neuron_strata_expert_probe;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 7 {
eprintln!(
"usage: {} SHARD GU DOWN GATE_OFF UP_OFF DOWN_OFF [EXPERT] [TOKENS]",
args[0]
);
std::process::exit(64);
}
let int = |i: usize, default: u64| -> u64 {
args.get(i)
.map(|v| v.parse().expect("integer argument"))
.unwrap_or(default)
};
let path = CString::new(args[1].as_str()).expect("path");
let (mut error, mut ms) = (f64::NAN, f64::NAN);
let (expert, tokens) = (int(7, 0) as i32, int(8, 8) as i32);
// SAFETY: the path is NUL-terminated and both out-pointers are live
// for the call; the probe owns every device allocation it makes.
let rc = unsafe {
neuron_strata_expert_probe(
path.as_ptr(),
int(2, 0) as i32,
int(3, 0) as i32,
int(4, 0),
int(5, 0),
int(6, 0),
expert,
tokens,
&mut error,
&mut ms,
)
};
if rc != 0 {
eprintln!("probe failed: code {rc}");
std::process::exit(rc);
}
println!(
"gu={} down={} expert={expert} tokens={tokens} relative_error={error:.5} kernel_ms={ms:.3}",
args[2], args[3]
);
}
-2
View File
@@ -13,5 +13,3 @@
pub mod ffi;
#[cfg(feature = "cuda")]
pub mod gdn;
#[cfg(feature = "strata-kernels")]
pub mod strata;
-316
View File
@@ -1,316 +0,0 @@
//! FFI to the expert kernels vendored from Strata (`vendor/strata`).
//!
//! Pointers are device addresses unless a parameter says otherwise, and
//! `stream` is a CUDA stream handle (null for the default stream).
use std::ffi::{c_char, c_void};
unsafe extern "C" {
/// Parity of two real experts against a CPU recomputation. Returns 0
/// on success.
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_expert_probe(
path: *const c_char,
gu: i32,
down: i32,
gate_off: u64,
up_off: u64,
down_off: u64,
first_expert: i32,
tokens: i32,
relative_error: *mut f64,
kernel_ms: *mut f64,
) -> i32;
pub fn neuron_strata_pinned_alloc(bytes: usize) -> *mut c_void;
pub fn neuron_strata_pinned_free(p: *mut c_void);
/// Queues a copy on `stream`. `pinned_src` must stay unchanged until
/// the stream has passed it. Returns the CUDA status.
pub fn neuron_strata_copy_to_device(
dst: *mut c_void,
pinned_src: *const c_void,
bytes: usize,
stream: *mut c_void,
) -> i32;
/// Page-locked host memory mapped into the device's address space,
/// or null. Freed with `neuron_strata_pinned_free`.
pub fn neuron_strata_host_alloc_mapped(bytes: usize) -> *mut c_void;
/// The device address of mapped host memory, or 0.
pub fn neuron_strata_host_device_ptr(host: *mut c_void) -> u64;
/// Queues `*entry = value` on `stream`. Returns the CUDA status.
pub fn neuron_strata_table_set(entry: *mut u64, value: u64, stream: *mut c_void) -> i32;
/// Builds the grouped expert kernel's arrays from one layer's
/// routing (`ids`, `w`: rows x k) and its expert address table.
/// Experts whose entry equals `host_table`'s are given arena slots
/// and listed in `miss_src`; a null `host_table` disables that.
/// Returns the CUDA status, or -1 for too many experts.
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_route_groups(
ids: *const u32,
w: *const f32,
rows: i32,
k: i32,
table: *const u64,
host_table: *const u64,
arena: u64,
blob_bytes: u64,
n_experts: i32,
grp_ptr: *mut u64,
grp_start: *mut i32,
n_groups: *mut i32,
ent_dst: *mut i32,
ent_tok: *mut i32,
w_out: *mut f32,
miss_src: *mut u64,
n_miss: *mut i32,
stream: *mut c_void,
) -> i32;
/// Copies the first `*n_miss` of `src`'s blobs (`bytes` each) to
/// consecutive slots at `dst`; `cap` bounds the launch.
pub fn neuron_strata_gather_blobs(
src: *const u64,
n_miss: *const i32,
cap: i32,
dst: u64,
bytes: u64,
stream: *mut c_void,
) -> i32;
/// `cudaGetLastError`: the error of the most recent failing call,
/// cleared by reading.
pub fn neuron_strata_last_error() -> i32;
/// Queues a kernel copying `n` 32-bit words (`dst` may be the device
/// address of mapped pinned host memory).
pub fn neuron_strata_copy_words(
dst: *mut u32,
src: *const u32,
n: i32,
stream: *mut c_void,
) -> i32;
/// Queues a device-to-host copy into pinned memory.
pub fn neuron_strata_copy_to_host(
pinned_dst: *mut c_void,
src: *const c_void,
bytes: usize,
stream: *mut c_void,
) -> i32;
pub fn neuron_strata_event_new() -> *mut c_void;
pub fn neuron_strata_event_record(event: *mut c_void, stream: *mut c_void) -> i32;
pub fn neuron_strata_event_sync(event: *mut c_void) -> i32;
pub fn neuron_strata_event_free(event: *mut c_void);
pub fn neuron_strata_expert_supported(gu_type: i32, d_type: i32, n_embd: i64, n_ff: i64)
-> i32;
pub fn neuron_strata_row_bytes(ggml_type: i32, n: i64) -> usize;
pub fn neuron_strata_expert_bytes(gu_type: i32, d_type: i32, n_embd: i64, n_ff: i64) -> usize;
pub fn neuron_strata_expert_scratch_bytes(cap_entries: i64, n_ff: i64) -> usize;
pub fn neuron_strata_quantize_q8_1(
x: *const f32,
n_rows: i64,
n_cols: i64,
y: *mut c_void,
stream: *mut c_void,
);
/// Whether `neuron_strata_mmvq` takes weights of `ggml_type`.
pub fn neuron_strata_mmvq_supported(ggml_type: i32) -> i32;
/// `y[c][r] = W[r] . x[c]` for `ncols` q8_1 activation rows.
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_mmvq(
ggml_type: i32,
w: *const c_void,
x_q8_1: *const c_void,
y: *mut f32,
n_in: i32,
n_out: i32,
ncols: i32,
stream: *mut c_void,
);
pub fn neuron_strata_dequant_f32(
ggml_type: i32,
src: *const c_void,
n: i64,
dst: *mut f32,
stream: *mut c_void,
);
#[allow(clippy::too_many_arguments)]
pub fn neuron_strata_expert_grouped(
gu_type: i32,
d_type: i32,
n_embd: i64,
n_ff: i64,
grp_ptr: *const u64,
grp_start: *const i32,
n_groups: *const i32,
ent_dst: *const i32,
ent_tok: *const i32,
cap_groups: i64,
cap_entries: i64,
x_q8_1: *const c_void,
scratch: *mut c_void,
out: *mut f32,
stream: *mut c_void,
);
// ---- the native decode engine's kernels (#427): see engine_shim.cu.
// Each returns 0, a CUDA error code, or -1 with a message from
// `neuron_engine_last_error`.
pub fn neuron_engine_last_error() -> *const c_char;
pub fn neuron_engine_configure();
pub fn neuron_gr_workspace_bytes(n_embd: i64, hc: i64, hc_lr: i64) -> usize;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gr_read(
residual: *const f32,
w_norm: *const f32,
w_down: *const u16,
w_up: *const u16,
w_inject: *const u16,
eps: f32,
n_embd: i64,
hc: i64,
hc_lr: i64,
workspace: *mut c_void,
mixed: *mut f32,
inject: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gr_write(
residual: *const f32,
block_out: *const f32,
inject: *const f32,
n_embd: i64,
hc: i64,
hc_lr: i64,
residual_out: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_conv_l2(
history: *mut f32,
qkv: *const f32,
conv_w: *const f32,
h: *mut f32,
channels: i32,
qk_heads: i32,
eps: f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_ab(
x: *const f32,
w_alpha: *const u16,
w_beta: *const u16,
dt: *const f32,
ssm_a: *const f32,
gate: *mut f32,
beta: *mut f32,
n_embd: i32,
h_v: i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_gdn_step_norm(
state: *mut f32,
q: *const f32,
k: *const f32,
v: *const f32,
gate: *const f32,
beta: *const f32,
z: *const f32,
gamma: *const f32,
eps: f32,
y: *mut f32,
h_k: i32,
h_v: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_bf16_gemv(
x: *const f32,
w: *const u16,
y: *mut f32,
n_in: i64,
n_out: i64,
stream: *mut c_void,
) -> i32;
pub fn neuron_router_top10(
logits: *const f32,
ids: *mut i32,
weights: *mut f32,
stream: *mut c_void,
) -> i32;
pub fn neuron_moe_combine(
parts: *const f32,
weights: *const f32,
shared: *const f32,
output: *mut f32,
n_embd: i64,
k: i64,
stream: *mut c_void,
) -> i32;
pub fn neuron_swiglu(
gate: *const f32,
up: *const f32,
out: *mut f32,
n: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_scale_by_sigmoid(
x: *mut f32,
gate: *const f32,
n: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_append_rows(
src_a: *const f32,
src_b: *const f32,
dst_a: *mut f32,
dst_b: *mut f32,
pos: *const i32,
width: i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_decode_attn(
q: *const f32,
kc: *const f32,
vc: *const f32,
pos: *const i32,
heads: i32,
kv_heads: i32,
head_dim: i32,
scale: f32,
gate: *const f32,
gate_stride: i32,
out: *mut f32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_norm_rope(
x: *const f32,
in_stride: i32,
gamma: *const f32,
out: *mut f32,
rows: i32,
head_dim: i32,
n_rot: i32,
eps: f32,
positions: *const i32,
stream: *mut c_void,
) -> i32;
#[allow(clippy::too_many_arguments)]
pub fn neuron_embed_rows(
ggml_type: i32,
table: *const c_void,
row_bytes: usize,
tokens: *const i32,
n_tok: i64,
n_embd: i64,
out: *mut f32,
stream: *mut c_void,
) -> i32;
pub fn neuron_repeat_row(
src: *const f32,
dst: *mut f32,
n: i32,
times: i32,
stream: *mut c_void,
) -> i32;
pub fn neuron_add_inplace(x: *mut f32, y: *const f32, n: i32, stream: *mut c_void) -> i32;
}
@@ -1,307 +0,0 @@
// 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"
@@ -1,164 +0,0 @@
// Parity probe for the vendored expert kernels on real GGUF weights.
//
// Runs two experts over random activations through the grouped kernels,
// then recomputes the SwiGLU on the CPU from independently dequantised
// weights. The kernels read 8-bit activations, so a small error is
// expected; a wrong layout or block format produces a large one.
#include <cuda_runtime.h>
#include <fcntl.h>
#include <unistd.h>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
#include "strata/kernels/iq_kernels.hpp"
namespace k = strata::kernels;
namespace {
constexpr int64_t kEmbd = 2560;
constexpr int64_t kFf = 640;
constexpr size_t kQ81Block = 36; // fp16 scale, fp16 sum, 32 int8 values
template <typename T>
T* device_alloc(size_t count) {
T* p = nullptr;
if (cudaMalloc(&p, count * sizeof(T)) != cudaSuccess) return nullptr;
return p;
}
bool read_at(int fd, uint8_t* dst, size_t bytes, uint64_t offset) {
size_t done = 0;
while (done < bytes) {
const ssize_t n = pread(fd, dst + done, bytes - done, offset + done);
if (n <= 0) return false;
done += static_cast<size_t>(n);
}
return true;
}
std::vector<float> dequant(int type, const uint8_t* device_src, int64_t n) {
float* d = device_alloc<float>(n);
std::vector<float> host(n);
k::iq_dequant_f32(type, device_src, n, d, nullptr);
cudaMemcpy(host.data(), d, n * sizeof(float), cudaMemcpyDeviceToHost);
cudaFree(d);
return host;
}
float silu(float x) { return x / (1.0f + std::exp(-x)); }
} // namespace
extern "C" int neuron_strata_expert_probe(const char* path, int gu, int dn, uint64_t gate_off, uint64_t up_off,
uint64_t down_off, int first_expert, int tokens, double* relative_error,
double* kernel_ms) {
if (!k::native_expert_supported(gu, dn, kEmbd, kFf) || tokens < 1) return 2;
const k::NativeExpertLayout L = k::native_expert_layout(gu, dn, kEmbd, kFf);
const size_t gate_bytes = kFf * L.gu_row, down_bytes = kEmbd * L.d_row;
const int fd = open(path, O_RDONLY);
if (fd < 0) return 3;
constexpr int groups = 2;
std::vector<uint8_t> blobs(groups * L.bytes);
for (int g = 0; g < groups; ++g) {
const uint64_t e = first_expert + g;
uint8_t* blob = blobs.data() + g * L.bytes;
if (!read_at(fd, blob, gate_bytes, gate_off + e * gate_bytes) ||
!read_at(fd, blob + L.up_off, gate_bytes, up_off + e * gate_bytes) ||
!read_at(fd, blob + L.down_off, down_bytes, down_off + e * down_bytes)) {
close(fd);
return 4;
}
}
close(fd);
std::mt19937 rng(1234);
std::uniform_real_distribution<float> dist(-2.0f, 2.0f);
std::vector<float> x(tokens * kEmbd);
for (float& v : x) v = dist(rng);
const int64_t entries = groups * tokens;
auto* d_blobs = device_alloc<uint8_t>(blobs.size());
auto* d_x = device_alloc<float>(x.size());
auto* d_q = device_alloc<uint8_t>(tokens * (kEmbd / 32) * kQ81Block);
auto* d_ptr = device_alloc<unsigned long long>(groups);
auto* d_start = device_alloc<int32_t>(groups + 1);
auto* d_n = device_alloc<int32_t>(1);
auto* d_dst = device_alloc<int32_t>(entries);
auto* d_tok = device_alloc<int32_t>(entries);
auto* d_out = device_alloc<float>(entries * kEmbd);
auto* d_scratch = device_alloc<uint8_t>(k::native_expert_scratch_bytes(entries, kFf));
if (!d_blobs || !d_x || !d_q || !d_ptr || !d_start || !d_n || !d_dst || !d_tok || !d_out || !d_scratch) return 5;
std::vector<unsigned long long> ptrs(groups);
std::vector<int32_t> start(groups + 1), dst(entries), tok(entries);
for (int g = 0; g < groups; ++g) {
ptrs[g] = reinterpret_cast<unsigned long long>(d_blobs + g * L.bytes);
start[g] = g * tokens;
for (int t = 0; t < tokens; ++t) {
dst[g * tokens + t] = g * tokens + t;
tok[g * tokens + t] = t;
}
}
start[groups] = entries;
const int32_t n_groups = groups;
cudaMemcpy(d_blobs, blobs.data(), blobs.size(), cudaMemcpyHostToDevice);
cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_ptr, ptrs.data(), groups * sizeof(unsigned long long), cudaMemcpyHostToDevice);
cudaMemcpy(d_start, start.data(), start.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
cudaMemcpy(d_n, &n_groups, sizeof(int32_t), cudaMemcpyHostToDevice);
cudaMemcpy(d_dst, dst.data(), dst.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
cudaMemcpy(d_tok, tok.data(), tok.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
k::quantize_q8_1_rows(d_x, tokens, kEmbd, d_q, nullptr);
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
k::native_expert_grouped(L, d_ptr, d_start, d_n, d_dst, d_tok, groups, entries, d_q, d_scratch, d_out, nullptr);
if (cudaDeviceSynchronize() != cudaSuccess) return 6;
*kernel_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
std::vector<float> out(entries * kEmbd);
cudaMemcpy(out.data(), d_out, out.size() * sizeof(float), cudaMemcpyDeviceToHost);
double err = 0.0, norm = 0.0;
std::vector<float> h(kFf);
for (int g = 0; g < groups; ++g) {
const uint8_t* blob = d_blobs + g * L.bytes;
const auto gate = dequant(L.gu_type, blob, kFf * kEmbd);
const auto up = dequant(L.gu_type, blob + L.up_off, kFf * kEmbd);
const auto down = dequant(L.d_type, blob + L.down_off, kEmbd * kFf);
for (int t = 0; t < tokens; ++t) {
const float* xt = x.data() + t * kEmbd;
for (int64_t r = 0; r < kFf; ++r) {
float a = 0.0f, b = 0.0f;
for (int64_t c = 0; c < kEmbd; ++c) {
a += gate[r * kEmbd + c] * xt[c];
b += up[r * kEmbd + c] * xt[c];
}
h[r] = silu(a) * b;
}
const float* got = out.data() + (g * tokens + t) * kEmbd;
for (int64_t r = 0; r < kEmbd; ++r) {
float y = 0.0f;
for (int64_t c = 0; c < kFf; ++c) y += down[r * kFf + c] * h[c];
err += (double(got[r]) - y) * (double(got[r]) - y);
norm += double(y) * y;
}
}
}
*relative_error = std::sqrt(err / norm);
for (void* p : {static_cast<void*>(d_blobs), static_cast<void*>(d_x), static_cast<void*>(d_q),
static_cast<void*>(d_ptr), static_cast<void*>(d_start), static_cast<void*>(d_n),
static_cast<void*>(d_dst), static_cast<void*>(d_tok), static_cast<void*>(d_out),
static_cast<void*>(d_scratch)}) {
cudaFree(p);
}
return 0;
}
@@ -1,241 +0,0 @@
// C ABI over the vendored Strata expert kernels (`vendor/strata`).
//
// Rust cannot name the C++ layout struct or its default arguments, so
// every call here takes the expert's formats and rebuilds the layout.
#include <cstddef>
#include <cstdint>
#include <cuda_runtime.h>
#include "strata/kernels/iq_kernels.hpp"
namespace k = strata::kernels;
namespace {
__global__ void table_set_kernel(unsigned long long* entry, unsigned long long value) { *entry = value; }
// Turns one layer's routing, `ids`/`w` (rows x k, row-major), into the
// grouped kernel's arrays. Groups are the routed experts in ascending id,
// entries within a group in ascending token, and each token's k outputs
// are ranked by ascending expert id: the order the host-side builder
// uses, so the arithmetic downstream is unchanged.
constexpr int kMaxExperts = 1024;
// An expert whose table entry is its host copy is a miss: it gets the
// next arena slot, and `miss_src` records where the gather copies it
// from. With `host_table` null every expert is read where the table says.
__global__ void route_groups_kernel(const uint32_t* ids, const float* w, int rows, int k,
const unsigned long long* table, const unsigned long long* host_table,
unsigned long long arena, unsigned long long blob_bytes, int n_experts,
unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups,
int32_t* ent_dst, int32_t* ent_tok, float* w_out, unsigned long long* miss_src,
int32_t* n_miss) {
__shared__ int counts[kMaxExperts];
__shared__ int base[kMaxExperts];
const int entries = rows * k;
for (int i = threadIdx.x; i < n_experts; i += blockDim.x) counts[i] = 0;
__syncthreads();
for (int e = threadIdx.x; e < entries; e += blockDim.x) {
const uint32_t x = ids[e];
if (x < (uint32_t) n_experts) atomicAdd(&counts[x], 1);
}
__syncthreads();
if (threadIdx.x == 0) {
int g = 0, off = 0, m = 0;
for (int x = 0; x < n_experts; ++x) {
const int c = counts[x];
base[x] = off;
if (c > 0) {
const unsigned long long at = table[x];
if (host_table != nullptr && at == host_table[x]) {
grp_ptr[g] = arena + (unsigned long long) m * blob_bytes;
miss_src[m] = at;
++m;
} else {
grp_ptr[g] = at;
}
grp_start[g] = off;
++g;
off += c;
}
}
grp_start[g] = off;
*n_groups = g;
if (n_miss != nullptr) *n_miss = m;
}
__syncthreads();
for (int e = threadIdx.x; e < entries; e += blockDim.x) {
const int t = e / k;
const uint32_t x = ids[e];
if (x >= (uint32_t) n_experts) continue;
int pos = base[x];
for (int tt = 0; tt < t; ++tt)
for (int jj = 0; jj < k; ++jj) pos += ids[tt * k + jj] == x;
int r = 0;
for (int jj = 0; jj < k; ++jj) r += ids[t * k + jj] < x;
const int dst = t * k + r;
ent_dst[pos] = dst;
ent_tok[pos] = t;
w_out[dst] = w[e];
}
}
// Copies blob `blockIdx.x` of the miss list into the arena, the grid's
// y dimension splitting each blob. Blocks past `*n_miss` do nothing, so
// the launch has a fixed shape whatever the routing was.
constexpr int kGatherSplit = 16;
__global__ void gather_blobs_kernel(const unsigned long long* src, const int32_t* n_miss, unsigned long long dst,
unsigned long long bytes) {
const int m = blockIdx.x;
if (m >= *n_miss) return;
const unsigned long long chunk = ((bytes + kGatherSplit - 1) / kGatherSplit + 15) & ~15ull;
const unsigned long long lo = (unsigned long long) blockIdx.y * chunk;
if (lo >= bytes) return;
const unsigned long long hi = lo + chunk < bytes ? lo + chunk : bytes;
const uint8_t* from = (const uint8_t*) src[m];
uint8_t* to = (uint8_t*) (dst + (unsigned long long) m * bytes);
const bool aligned = ((((unsigned long long) from) | ((unsigned long long) to) | lo) & 15) == 0;
unsigned long long tail = lo;
if (aligned) {
const unsigned long long words = (hi - lo) / 16;
for (unsigned long long i = threadIdx.x; i < words; i += blockDim.x)
*(uint4*) (to + lo + i * 16) = *(const uint4*) (from + lo + i * 16);
tail = lo + words * 16;
}
for (unsigned long long t = tail + threadIdx.x; t < hi; t += blockDim.x) to[t] = from[t];
}
// Copies `n` 32-bit words, e.g. into mapped pinned host memory: a kernel
// rather than a memcpy so the copy captures like any other launch.
__global__ void copy_words_kernel(uint32_t* dst, const uint32_t* src, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) dst[i] = src[i];
}
} // namespace
extern "C" {
int neuron_strata_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
return k::native_expert_supported(gu_type, d_type, n_embd, n_ff) ? 1 : 0;
}
size_t neuron_strata_row_bytes(int ggml_type, int64_t n) { return k::iq_row_bytes(ggml_type, n); }
size_t neuron_strata_expert_bytes(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
return k::native_expert_layout(gu_type, d_type, n_embd, n_ff).bytes;
}
size_t neuron_strata_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff) {
return k::native_expert_scratch_bytes(cap_entries, n_ff);
}
void neuron_strata_quantize_q8_1(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
k::quantize_q8_1_rows(x, n_rows, n_cols, y, stream);
}
int neuron_strata_mmvq_supported(int ggml_type) {
switch (ggml_type) {
// iq_kernels.cu's STRATA_MMVQ_FMTS.
case 16: case 17: case 18: case 20: case 21: case 22: case 23: case 29: case 42:
case 10: case 11: case 12: case 13: case 7: case 6: case 2: case 3: case 8: case 40:
case 144: case 145: case 146: case 147: case 148: case 149:
return 1;
default:
return 0;
}
}
void neuron_strata_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
void* stream) {
k::iq_mmvq(ggml_type, w, x_q8_1, y, n_in, n_out, ncols, stream);
}
void neuron_strata_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream) {
k::iq_dequant_f32(ggml_type, src, n, dst, stream);
}
void neuron_strata_expert_grouped(int gu_type, int d_type, int64_t n_embd, int64_t n_ff,
const unsigned long long* grp_ptr, const int32_t* grp_start,
const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok,
int64_t cap_groups, int64_t cap_entries, const void* x_q8_1, void* scratch,
float* out, void* stream) {
const k::NativeExpertLayout layout = k::native_expert_layout(gu_type, d_type, n_embd, n_ff);
k::native_expert_grouped(layout, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, cap_groups, cap_entries, x_q8_1,
scratch, out, stream);
}
void* neuron_strata_pinned_alloc(size_t bytes) {
void* p = nullptr;
return cudaHostAlloc(&p, bytes, cudaHostAllocDefault) == cudaSuccess ? p : nullptr;
}
void neuron_strata_pinned_free(void* p) { cudaFreeHost(p); }
int neuron_strata_copy_to_device(void* dst, const void* pinned_src, size_t bytes, void* stream) {
return cudaMemcpyAsync(dst, pinned_src, bytes, cudaMemcpyHostToDevice, static_cast<cudaStream_t>(stream));
}
void* neuron_strata_host_alloc_mapped(size_t bytes) {
void* p = nullptr;
return cudaHostAlloc(&p, bytes, cudaHostAllocMapped | cudaHostAllocPortable) == cudaSuccess ? p : nullptr;
}
unsigned long long neuron_strata_host_device_ptr(void* host) {
void* d = nullptr;
return cudaHostGetDevicePointer(&d, host, 0) == cudaSuccess ? (unsigned long long) d : 0ull;
}
int neuron_strata_table_set(unsigned long long* entry, unsigned long long value, void* stream) {
table_set_kernel<<<1, 1, 0, static_cast<cudaStream_t>(stream)>>>(entry, value);
return cudaGetLastError();
}
int neuron_strata_route_groups(const uint32_t* ids, const float* w, int rows, int k, const unsigned long long* table,
const unsigned long long* host_table, unsigned long long arena,
unsigned long long blob_bytes, int n_experts, unsigned long long* grp_ptr,
int32_t* grp_start, int32_t* n_groups, int32_t* ent_dst, int32_t* ent_tok, float* w_out,
unsigned long long* miss_src, int32_t* n_miss, void* stream) {
if (n_experts > kMaxExperts) return -1;
route_groups_kernel<<<1, 256, 0, static_cast<cudaStream_t>(stream)>>>(
ids, w, rows, k, table, host_table, arena, blob_bytes, n_experts, grp_ptr, grp_start, n_groups, ent_dst,
ent_tok, w_out, miss_src, n_miss);
return cudaGetLastError();
}
int neuron_strata_gather_blobs(const unsigned long long* src, const int32_t* n_miss, int cap, unsigned long long dst,
unsigned long long bytes, void* stream) {
if (cap <= 0) return 0;
gather_blobs_kernel<<<dim3((unsigned) cap, kGatherSplit), 256, 0, static_cast<cudaStream_t>(stream)>>>(
src, n_miss, dst, bytes);
return cudaGetLastError();
}
int neuron_strata_last_error() { return cudaGetLastError(); }
int neuron_strata_copy_words(uint32_t* dst, const uint32_t* src, int n, void* stream) {
copy_words_kernel<<<(n + 255) / 256, 256, 0, static_cast<cudaStream_t>(stream)>>>(dst, src, n);
return cudaGetLastError();
}
int neuron_strata_copy_to_host(void* pinned_dst, const void* src, size_t bytes, void* stream) {
return cudaMemcpyAsync(pinned_dst, src, bytes, cudaMemcpyDeviceToHost, static_cast<cudaStream_t>(stream));
}
void* neuron_strata_event_new() {
cudaEvent_t e = nullptr;
return cudaEventCreateWithFlags(&e, cudaEventDisableTiming) == cudaSuccess ? (void*) e : nullptr;
}
int neuron_strata_event_record(void* event, void* stream) {
return cudaEventRecord(static_cast<cudaEvent_t>(event), static_cast<cudaStream_t>(stream));
}
int neuron_strata_event_sync(void* event) { return cudaEventSynchronize(static_cast<cudaEvent_t>(event)); }
void neuron_strata_event_free(void* event) { cudaEventDestroy(static_cast<cudaEvent_t>(event)); }
} // extern "C"
+1
View File
@@ -27,3 +27,4 @@ pub mod phase_probe;
pub mod qwen3_5;
pub mod qwen4_exp;
pub mod snapshot;
pub mod z_image;
@@ -1,357 +0,0 @@
//! A byte-budgeted VRAM tier for host-resident routed experts (#318).
//!
//! A model whose experts exceed VRAM keeps all of them in host memory.
//! Routing is skewed, so a modest share of them serves most tokens, and
//! each expert held on the device is one the CPU does not have to
//! compute. The tier is shared by every MoE block of a model because the
//! budget is a property of the card and heat varies between layers.
//!
//! Slots are sized in bytes rather than counted: expert sizes differ
//! between layers and quantisation types, and a slot count sized for the
//! largest wastes VRAM on the rest.
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
/// The VRAM budget from `NEURON_EXPERT_CACHE_MB`, when one is set.
pub fn configured_budget_mb() -> Option<u64> {
std::env::var("NEURON_EXPERT_CACHE_MB")
.ok()
.and_then(|v| v.parse().ok())
.filter(|&mb| mb > 0)
}
/// `(block, expert)`. Blocks are numbered as they register.
type Key = (u32, u32);
struct Entry<T> {
value: Arc<T>,
bytes: u64,
stamp: u64,
}
/// Least-recently-used map with a byte budget.
struct ByteLru<T> {
capacity: u64,
used: u64,
clock: u64,
entries: HashMap<Key, Entry<T>>,
by_age: BTreeMap<u64, Key>,
}
impl<T> ByteLru<T> {
fn new(capacity: u64) -> Self {
Self {
capacity,
used: 0,
clock: 0,
entries: HashMap::new(),
by_age: BTreeMap::new(),
}
}
fn tick(&mut self) -> u64 {
self.clock += 1;
self.clock
}
fn get(&mut self, key: Key) -> Option<Arc<T>> {
let stamp = self.tick();
let entry = self.entries.get_mut(&key)?;
self.by_age.remove(&entry.stamp);
entry.stamp = stamp;
self.by_age.insert(stamp, key);
Some(entry.value.clone())
}
/// Bytes that must be released before `bytes` more can be held.
/// Returns how many entries were evicted.
fn make_room(&mut self, bytes: u64) -> u64 {
let mut evicted = 0;
while self.used + bytes > self.capacity {
let Some((_, key)) = self.by_age.pop_first() else {
break;
};
if let Some(entry) = self.entries.remove(&key) {
self.used -= entry.bytes;
evicted += 1;
}
}
evicted
}
fn insert(&mut self, key: Key, value: Arc<T>, bytes: u64) {
let stamp = self.tick();
self.used += bytes;
self.by_age.insert(stamp, key);
self.entries.insert(
key,
Entry {
value,
bytes,
stamp,
},
);
}
}
/// Cumulative counters, for measurement.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TierStats {
pub hits: u64,
pub misses: u64,
pub evictions: u64,
/// Lookups that may not admit: a prompt chunk's.
pub prompt_hits: u64,
pub prompt_misses: u64,
pub used_bytes: u64,
pub entries: u64,
}
struct State<T> {
lru: ByteLru<T>,
hits: u64,
misses: u64,
evictions: u64,
prompt_hits: u64,
prompt_misses: u64,
next_block: u32,
}
/// The tier itself. `T` is the device-resident expert.
pub struct ExpertTier<T> {
state: Mutex<State<T>>,
}
impl<T> ExpertTier<T> {
pub fn new(capacity_bytes: u64) -> Arc<Self> {
Arc::new(Self {
state: Mutex::new(State {
lru: ByteLru::new(capacity_bytes),
hits: 0,
misses: 0,
evictions: 0,
prompt_hits: 0,
prompt_misses: 0,
next_block: 0,
}),
})
}
/// A number identifying one MoE block's experts within the tier.
pub fn register_block(&self) -> u32 {
let mut state = self.state.lock().expect("expert tier lock");
let block = state.next_block;
state.next_block += 1;
block
}
/// The expert, from the tier or from `load`.
///
/// Room is made *before* `load` runs, so the outgoing expert's VRAM
/// is available to the incoming one. An expert larger than the whole
/// budget is returned without being retained.
pub fn get_or_load<E>(
&self,
block: u32,
expert: u32,
bytes: u64,
load: impl FnOnce() -> Result<T, E>,
) -> Result<Arc<T>, E> {
let key = (block, expert);
let retain = {
let mut state = self.state.lock().expect("expert tier lock");
if let Some(value) = state.lru.get(key) {
state.hits += 1;
return Ok(value);
}
state.misses += 1;
let retain = bytes <= state.lru.capacity;
if retain {
let evicted = state.lru.make_room(bytes);
state.evictions += evicted;
}
retain
};
let value = Arc::new(load()?);
if retain {
let mut state = self.state.lock().expect("expert tier lock");
state.lru.insert(key, value.clone(), bytes);
}
Ok(value)
}
/// Counts a use of the expert and refreshes it if held. Returns
/// whether it was held. A caller that admits on a budget uses this
/// for the uses it will not admit, so they still count as misses.
pub fn touch(&self, block: u32, expert: u32) -> bool {
let mut state = self.state.lock().expect("expert tier lock");
let held = state.lru.get((block, expert)).is_some();
if held {
state.hits += 1;
} else {
state.misses += 1;
}
held
}
/// The expert if it is held, without admitting it or refreshing it.
///
/// A prompt chunk touches more experts than the tier holds, once
/// each. Letting that scan admit or reorder would replace the set
/// decode keeps returning to with experts it may never use again.
pub fn peek(&self, block: u32, expert: u32) -> Option<Arc<T>> {
let mut state = self.state.lock().expect("expert tier lock");
let value = state
.lru
.entries
.get(&(block, expert))
.map(|entry| entry.value.clone());
if value.is_some() {
state.prompt_hits += 1;
} else {
state.prompt_misses += 1;
}
value
}
/// The byte budget.
pub fn capacity_bytes(&self) -> u64 {
self.state.lock().expect("expert tier lock").lru.capacity
}
pub fn stats(&self) -> TierStats {
let state = self.state.lock().expect("expert tier lock");
TierStats {
hits: state.hits,
misses: state.misses,
evictions: state.evictions,
prompt_hits: state.prompt_hits,
prompt_misses: state.prompt_misses,
used_bytes: state.lru.used,
entries: state.lru.entries.len() as u64,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn fetch(tier: &ExpertTier<u32>, expert: u32, bytes: u64, loads: &Cell<u32>) -> u32 {
*tier
.get_or_load::<()>(0, expert, bytes, || {
loads.set(loads.get() + 1);
Ok(expert)
})
.unwrap()
}
#[test]
fn a_hit_does_not_load_again() {
let tier = ExpertTier::new(100);
let loads = Cell::new(0);
assert_eq!(fetch(&tier, 7, 10, &loads), 7);
assert_eq!(fetch(&tier, 7, 10, &loads), 7);
assert_eq!(loads.get(), 1);
let stats = tier.stats();
assert_eq!((stats.hits, stats.misses, stats.used_bytes), (1, 1, 10));
}
#[test]
fn the_least_recently_used_expert_is_evicted() {
let tier = ExpertTier::new(30);
let loads = Cell::new(0);
fetch(&tier, 1, 10, &loads);
fetch(&tier, 2, 10, &loads);
fetch(&tier, 3, 10, &loads);
// Touching 1 leaves 2 as the oldest.
fetch(&tier, 1, 10, &loads);
fetch(&tier, 4, 10, &loads);
assert_eq!(loads.get(), 4);
fetch(&tier, 1, 10, &loads);
assert_eq!(loads.get(), 4, "1 was recently used and must survive");
fetch(&tier, 2, 10, &loads);
assert_eq!(loads.get(), 5, "2 was the oldest and must have gone");
}
#[test]
fn the_budget_is_in_bytes_and_is_never_exceeded() {
let tier = ExpertTier::new(50);
let loads = Cell::new(0);
for (expert, bytes) in [(1, 20), (2, 20), (3, 30), (4, 5), (5, 45)] {
fetch(&tier, expert, bytes, &loads);
assert!(tier.stats().used_bytes <= 50);
}
assert_eq!(tier.stats().used_bytes, 50);
}
#[test]
fn an_expert_larger_than_the_budget_is_served_but_not_kept() {
let tier = ExpertTier::new(10);
let loads = Cell::new(0);
fetch(&tier, 1, 5, &loads);
assert_eq!(fetch(&tier, 2, 11, &loads), 2);
let stats = tier.stats();
assert_eq!((stats.used_bytes, stats.entries), (5, 1));
fetch(&tier, 1, 5, &loads);
assert_eq!(loads.get(), 2, "the oversized expert must not evict 1");
}
#[test]
fn blocks_do_not_share_experts() {
let tier: Arc<ExpertTier<u32>> = ExpertTier::new(100);
let (a, b) = (tier.register_block(), tier.register_block());
assert_ne!(a, b);
let first = tier.get_or_load::<()>(a, 3, 10, || Ok(30)).unwrap();
let second = tier.get_or_load::<()>(b, 3, 10, || Ok(40)).unwrap();
assert_eq!((*first, *second), (30, 40));
}
#[test]
fn a_prompt_scan_neither_admits_nor_reorders() {
let tier = ExpertTier::new(20);
let loads = Cell::new(0);
fetch(&tier, 1, 10, &loads);
fetch(&tier, 2, 10, &loads);
// Peeking at 1 must not make it newer than 2.
assert_eq!(tier.peek(0, 1).as_deref(), Some(&1));
assert!(tier.peek(0, 9).is_none());
let stats = tier.stats();
assert_eq!(
(stats.prompt_hits, stats.prompt_misses, stats.entries),
(1, 1, 2)
);
fetch(&tier, 3, 10, &loads);
assert!(tier.peek(0, 1).is_none(), "1 was still the oldest");
assert!(tier.peek(0, 2).is_some());
}
/// A touch refreshes what is held, so it survives the next eviction,
/// and counts what is not as a miss without admitting it.
#[test]
fn a_touch_refreshes_without_admitting() {
let tier = ExpertTier::new(20);
let loads = Cell::new(0);
fetch(&tier, 1, 10, &loads);
fetch(&tier, 2, 10, &loads);
assert!(tier.touch(0, 1));
assert!(!tier.touch(0, 9));
fetch(&tier, 3, 10, &loads);
assert!(tier.peek(0, 1).is_some(), "the touch made 1 newer than 2");
assert!(tier.peek(0, 2).is_none());
assert!(tier.peek(0, 9).is_none(), "a touch never admits");
assert_eq!(loads.get(), 3);
let stats = tier.stats();
assert_eq!((stats.hits, stats.misses), (1, 4));
}
#[test]
fn a_failed_load_retains_nothing() {
let tier: Arc<ExpertTier<u32>> = ExpertTier::new(100);
assert!(tier.get_or_load(0, 1, 10, || Err("oom")).is_err());
let stats = tier.stats();
assert_eq!((stats.used_bytes, stats.entries), (0, 0));
}
}
@@ -154,10 +154,6 @@ pub(crate) fn attention_context(
}
}
if let AttnMask::Additive(m) = attn_mask {
return masked_attention(q, k, v, m, num_kv_groups, scale);
}
// Eager fallback: materialise GQA-repeated K/V and the score matrix.
let k = repeat_kv(k.clone(), num_kv_groups)?.contiguous()?;
let v = repeat_kv(v.clone(), num_kv_groups)?.contiguous()?;
@@ -169,77 +165,6 @@ pub(crate) fn attention_context(
probs.matmul(&v)
}
/// Score elements one query tile may hold: 2^26, about 0.75 GB across
/// the bf16 scores and the f32 softmax. A tile is as many queries as fit.
const SCORE_TILE_ELEMENTS: usize = 1 << 26;
/// Attention under an arbitrary additive mask, `(B, 1, L, S)` — the
/// path every [`AttnMask::Additive`] takes.
///
/// Equal to plain eager attention, with two changes
/// that bound its memory so long prompts can be read in large chunks:
///
/// - GQA without copying K/V: each KV head's query heads are folded
/// into the row axis, so the matmul reads the shared K/V once rather
/// than a 12x repeat of the whole cache.
/// - Queries are processed in tiles sized to [`SCORE_TILE_ELEMENTS`],
/// so a chunk of `L` queries over `S` positions never holds the full
/// `heads * L * S` scores.
///
/// The mask add and softmax run in f32, as the reference does.
fn masked_attention(
q: &Tensor,
k: &Tensor,
v: &Tensor,
mask: &Tensor,
num_kv_groups: usize,
scale: f64,
) -> candle_core::Result<Tensor> {
masked_attention_tiled(q, k, v, mask, num_kv_groups, scale, SCORE_TILE_ELEMENTS)
}
fn masked_attention_tiled(
q: &Tensor,
k: &Tensor,
v: &Tensor,
mask: &Tensor,
num_kv_groups: usize,
scale: f64,
tile_elements: usize,
) -> candle_core::Result<Tensor> {
let (b, heads, l, d) = q.dims4()?;
let (_, kv_heads, s, _) = k.dims4()?;
let kt = k.transpose(2, 3)?.contiguous()?;
let v = v.contiguous()?;
let tile = (tile_elements / (heads * s).max(1)).clamp(1, l);
let mut out = Vec::with_capacity(l.div_ceil(tile));
let mut start = 0;
while start < l {
let t = tile.min(l - start);
// (B, H, t, D) -> (B, Hkv, G * t, D): head h = kv * G + g.
let qt =
q.narrow(2, start, t)?
.contiguous()?
.reshape((b, kv_heads, num_kv_groups * t, d))?;
let scores = (qt.matmul(&kt)? * scale)?
.to_dtype(candle_core::DType::F32)?
.reshape((b, kv_heads, num_kv_groups, t, s))?;
let m = mask
.narrow(2, start, t)?
.to_dtype(candle_core::DType::F32)?
.unsqueeze(1)?;
let probs = candle_nn::ops::softmax_last_dim(&scores.broadcast_add(&m)?)?
.to_dtype(q.dtype())?
.reshape((b, kv_heads, num_kv_groups * t, s))?;
out.push(probs.matmul(&v)?.reshape((b, heads, t, d))?);
start += t;
}
if out.len() == 1 {
return Ok(out.remove(0));
}
Tensor::cat(&out, 2)
}
pub struct Qwen3_5Attention {
q_proj: Linear,
k_proj: Linear,
@@ -409,94 +334,3 @@ fn load_linear_no_bias(
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Linear::new(weight, None))
}
#[cfg(test)]
mod tests {
use super::*;
use candle_core::Device;
/// Plain eager attention: K/V repeated per query head, one score
/// matrix, f32 throughout. Independent of the code under test.
fn reference(
q: &Tensor,
k: &Tensor,
v: &Tensor,
mask: &Tensor,
groups: usize,
scale: f64,
) -> Vec<f32> {
let k = repeat_kv(k.clone(), groups).unwrap();
let v = repeat_kv(v.clone(), groups).unwrap();
let scores = (q.matmul(&k.transpose(2, 3).unwrap()).unwrap() * scale)
.unwrap()
.broadcast_add(mask)
.unwrap();
candle_nn::ops::softmax_last_dim(&scores)
.unwrap()
.matmul(&v.contiguous().unwrap())
.unwrap()
.flatten_all()
.unwrap()
.to_vec1()
.unwrap()
}
/// The tiled, copy-free GQA attention equals plain eager attention
/// under an arbitrary mask, for every tile size: one query per tile,
/// a ragged tail, and the whole chunk at once. Each KV head and each
/// row's mask differ, so a wrong head fold or a misaligned mask tile
/// changes the answer.
#[test]
fn masked_attention_matches_eager_attention_at_any_tile() {
let dev = Device::Cpu;
let (heads, kv_heads, l, s, d) = (4, 2, 5, 7, 8);
let values = |n: usize, seed: u32| -> Vec<f32> {
(0..n)
.map(|i| {
let x = (i as u32).wrapping_mul(2_654_435_761).wrapping_add(seed);
((x >> 8) % 1000) as f32 / 500.0 - 1.0
})
.collect()
};
let q = Tensor::from_vec(values(heads * l * d, 1), (1, heads, l, d), &dev).unwrap();
let k = Tensor::from_vec(values(kv_heads * s * d, 2), (1, kv_heads, s, d), &dev).unwrap();
let v = Tensor::from_vec(values(kv_heads * s * d, 3), (1, kv_heads, s, d), &dev).unwrap();
// Row i sees an irregular subset that always includes position i.
let mut mask = vec![f32::NEG_INFINITY; l * s];
for i in 0..l {
for p in 0..s {
if p == i || (p * 3 + i) % 4 == 0 {
mask[i * s + p] = 0.0;
}
}
}
let mask = Tensor::from_vec(mask, (1, 1, l, s), &dev).unwrap();
let scale = 0.35;
let want = reference(&q, &k, &v, &mask, 2, scale);
for tile_queries in [1, 2, l] {
let got: Vec<f32> =
masked_attention_tiled(&q, &k, &v, &mask, 2, scale, tile_queries * heads * s)
.unwrap()
.flatten_all()
.unwrap()
.to_vec1()
.unwrap();
for (g, w) in got.iter().zip(&want) {
assert!(
(g - w).abs() < 1e-5,
"tile of {tile_queries}: got {got:?} want {want:?}"
);
}
}
// And the dispatcher routes an additive mask here.
let routed: Vec<f32> = attention_context(&q, &k, &v, AttnMask::Additive(&mask), 2, scale)
.unwrap()
.flatten_all()
.unwrap()
.to_vec1()
.unwrap();
for (g, w) in routed.iter().zip(&want) {
assert!((g - w).abs() < 1e-5);
}
}
}
@@ -67,7 +67,6 @@ use candle_nn::var_builder::ShardedVarBuilder;
#[cfg(test)]
use super::RopeParameters;
use super::TextConfig;
use super::proj::{LinearSource, Proj, load_proj};
use super::rmsnorm::{OutputGate, Qwen3_5RmsNormGated, l2norm};
/// Per-rank, per-layer state for the linear-attention block.
@@ -82,11 +81,11 @@ pub struct GatedDeltaNetState {
pub struct GatedDeltaNet {
// Projections.
in_proj_qkv: Proj,
in_proj_z: Proj,
in_proj_qkv: Linear,
in_proj_z: Linear,
in_proj_b: Linear,
in_proj_a: Linear,
out_proj: Proj,
out_proj: Linear,
// Depthwise causal Conv1d weight; shape (conv_dim, 1, kernel_size).
// No bias (Python sets bias=False).
@@ -171,16 +170,6 @@ impl GatedDeltaNet {
}
pub fn load_with_params(cfg: GatedDeltaNetParams, vb: &ShardedVarBuilder) -> Result<Self> {
Self::load_with_source(cfg, vb, None)
}
/// As [`Self::load_with_params`], taking `in_proj_qkv`, `in_proj_z`
/// and `out_proj` from `source` where it has them.
pub fn load_with_source(
cfg: GatedDeltaNetParams,
vb: &ShardedVarBuilder,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let num_v_heads = cfg.num_value_heads;
let num_k_heads = cfg.num_key_heads;
let head_k_dim = cfg.key_head_dim;
@@ -227,20 +216,20 @@ impl GatedDeltaNet {
split_fused_qkvz(&qkvz, num_k_heads, num_v_heads, head_k_dim, head_v_dim)?;
let (b_w, a_w) = split_fused_ba(&ba, num_k_heads, num_v_heads)?;
(
Linear::new(qkv_w, None).into(),
Linear::new(z_w, None).into(),
Linear::new(qkv_w, None),
Linear::new(z_w, None),
Linear::new(b_w, None),
Linear::new(a_w, None),
)
} else {
(
load_proj(vb, "in_proj_qkv", cfg.hidden_size, conv_dim, source)?,
load_proj(vb, "in_proj_z", cfg.hidden_size, value_dim, source)?,
load_linear_no_bias(vb, "in_proj_qkv", cfg.hidden_size, conv_dim)?,
load_linear_no_bias(vb, "in_proj_z", cfg.hidden_size, value_dim)?,
load_linear_no_bias(vb, "in_proj_b", cfg.hidden_size, num_v_heads)?,
load_linear_no_bias(vb, "in_proj_a", cfg.hidden_size, num_v_heads)?,
)
};
let out_proj = load_proj(vb, "out_proj", value_dim, cfg.hidden_size, source)?;
let out_proj = load_linear_no_bias(vb, "out_proj", value_dim, cfg.hidden_size)?;
// ----- Conv1d weight (depthwise, bias=False). -----
let conv1d_weight = vb
@@ -1446,11 +1435,11 @@ mod tests {
let value_dim = cfg.linear_value_head_dim * cfg.linear_num_value_heads;
let conv_dim = key_dim * 2 + value_dim;
let mut net = GatedDeltaNet {
in_proj_qkv: Linear::new(zeros(&[conv_dim, cfg.hidden_size]), None).into(),
in_proj_z: Linear::new(zeros(&[value_dim, cfg.hidden_size]), None).into(),
in_proj_qkv: Linear::new(zeros(&[conv_dim, cfg.hidden_size]), None),
in_proj_z: Linear::new(zeros(&[value_dim, cfg.hidden_size]), None),
in_proj_b: Linear::new(zeros(&[cfg.linear_num_value_heads, cfg.hidden_size]), None),
in_proj_a: Linear::new(zeros(&[cfg.linear_num_value_heads, cfg.hidden_size]), None),
out_proj: Linear::new(zeros(&[cfg.hidden_size, value_dim]), None).into(),
out_proj: Linear::new(zeros(&[cfg.hidden_size, value_dim]), None),
conv1d_weight: zeros(&[conv_dim, 1, cfg.linear_conv_kernel_dim]),
dt_bias: zeros(&[cfg.linear_num_value_heads]),
a_log: zeros(&[cfg.linear_num_value_heads]),
+25 -27
View File
@@ -3,17 +3,17 @@
//! Identical to plain Qwen3's MLP: `down(silu(gate(x)) * up(x))` with
//! no bias on any of the three projections.
use anyhow::Result;
use anyhow::{Context, Result};
use candle_core::{Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
use super::TextConfig;
use super::proj::{LinearSource, Proj, load_proj};
pub struct Qwen3_5MLP {
gate_proj: Proj,
up_proj: Proj,
down_proj: Proj,
gate_proj: Linear,
up_proj: Linear,
down_proj: Linear,
}
impl Qwen3_5MLP {
@@ -25,15 +25,11 @@ impl Qwen3_5MLP {
/// test that proves banking neutral still needs it, to express the
/// same weights in the layout it is being compared against.
#[cfg(test)]
pub(crate) fn from_weights(
gate_proj: candle_nn::Linear,
up_proj: candle_nn::Linear,
down_proj: candle_nn::Linear,
) -> Self {
pub(crate) fn from_weights(gate_proj: Linear, up_proj: Linear, down_proj: Linear) -> Self {
Self {
gate_proj: gate_proj.into(),
up_proj: up_proj.into(),
down_proj: down_proj.into(),
gate_proj,
up_proj,
down_proj,
}
}
@@ -50,20 +46,9 @@ impl Qwen3_5MLP {
hidden: usize,
intermediate: usize,
) -> Result<Self> {
Self::load_with_source(vb, hidden, intermediate, None)
}
/// As [`Self::load_with_dims`], taking projections from `source`
/// where it has them.
pub fn load_with_source(
vb: &ShardedVarBuilder,
hidden: usize,
intermediate: usize,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let gate_proj = load_proj(vb, "gate_proj", hidden, intermediate, source)?;
let up_proj = load_proj(vb, "up_proj", hidden, intermediate, source)?;
let down_proj = load_proj(vb, "down_proj", intermediate, hidden, source)?;
let gate_proj = load_linear_no_bias(vb, "gate_proj", hidden, intermediate)?;
let up_proj = load_linear_no_bias(vb, "up_proj", hidden, intermediate)?;
let down_proj = load_linear_no_bias(vb, "down_proj", intermediate, hidden)?;
Ok(Self {
gate_proj,
up_proj,
@@ -79,3 +64,16 @@ impl Module for Qwen3_5MLP {
self.down_proj.forward(&(lhs * rhs)?)
}
}
fn load_linear_no_bias(
vb: &ShardedVarBuilder,
name: &str,
in_dim: usize,
out_dim: usize,
) -> Result<Linear> {
let weight = vb
.pp(name)
.get((out_dim, in_dim), "weight")
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Linear::new(weight, None))
}
@@ -73,13 +73,11 @@ use serde::Deserialize;
use std::sync::Arc;
pub mod decoder;
pub mod expert_tier;
pub mod full_attn;
pub mod linear_attn;
pub mod mlp;
pub mod moe;
pub mod mtp;
pub mod proj;
pub mod rmsnorm;
pub mod rope;
pub mod vision;
+26 -375
View File
@@ -29,7 +29,7 @@
//! replaces the loop behind the same `forward` signature.
use anyhow::{Context, Result};
use candle_core::quantized::{GgmlDType, QMatMul, QStorage, QTensor};
use candle_core::quantized::{GgmlDType, QMatMul, QTensor};
use candle_core::{DType, Device, IndexOp, Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
@@ -70,11 +70,6 @@ pub(crate) enum Experts {
/// dropped once its 512 experts are quantised, so the full 241.6 GB
/// never exists at once.
Quantized(Vec<QuantizedExpert>),
/// Weights and execution live outside candle.
External {
count: usize,
inner: Box<dyn ExternalExperts>,
},
Banked {
/// `(num_experts, 2 * intermediate, hidden)` — gate rows first,
/// then up. Reversing them computes `silu(up) * gate`, which is
@@ -86,50 +81,8 @@ pub(crate) enum Experts {
},
}
/// Routed experts executed outside candle.
///
/// Routing stays with the block. `xs` is `(tokens, hidden)`;
/// `tokens_for[e]` and `weights_for[e]` are expert `e`'s rows and mixing
/// weights. Returns the weighted sum of each token's `k` experts,
/// `(tokens, hidden)`.
pub trait ExternalExperts: Send + Sync {
fn forward(
&self,
xs: &Tensor,
tokens_for: &[Vec<u32>],
weights_for: &[Vec<f32>],
k: usize,
) -> candle_core::Result<Tensor>;
/// Whether [`Self::forward_device`] takes a forward of `rows` rows.
fn routes_on_device(&self, _rows: usize) -> bool {
false
}
/// The same, from routing left on the device: `ids` is `(rows, k)`
/// u32 and `weights` `(rows, k)` f32, both where `xs` is. Saves the
/// host round-trip a per-expert token list costs (#425).
fn forward_device(
&self,
_xs: &Tensor,
_ids: &Tensor,
_weights: &Tensor,
_k: usize,
) -> candle_core::Result<Tensor> {
candle_core::bail!("these experts do not take device routing")
}
}
/// Supplies each MoE layer's [`ExternalExperts`] at load.
pub trait ExternalExpertSource: Send + Sync {
fn block(&self, layer: usize) -> Result<Box<dyn ExternalExperts>>;
}
/// The VRAM tier as host-resident quantised experts use it (#318).
pub type DeviceExpertTier = super::expert_tier::ExpertTier<QuantizedExpert>;
/// One expert's three projections, quantised.
pub struct QuantizedExpert {
pub(crate) struct QuantizedExpert {
gate: QMatMul,
up: QMatMul,
down: QMatMul,
@@ -147,76 +100,6 @@ impl QuantizedExpert {
_ => None,
}
}
/// Bytes of quantised weights, for the tier's budget.
fn storage_bytes(&self) -> u64 {
[&self.gate, &self.up, &self.down]
.into_iter()
.map(|m| match m {
QMatMul::QTensor(t) => t.storage_size_in_bytes() as u64,
_ => 0,
})
.sum()
}
/// A copy of this expert on `device`.
fn on_device(&self, device: &Device) -> candle_core::Result<Self> {
Ok(Self {
gate: quantized_on(&self.gate, device)?,
up: quantized_on(&self.up, device)?,
down: quantized_on(&self.down, device)?,
})
}
/// The SwiGLU on `xs`, which must be on this expert's device. The
/// kernels accumulate in f32; the result returns in `xs`'s dtype.
fn forward_here(&self, xs: &Tensor) -> candle_core::Result<Tensor> {
let dtype = xs.dtype();
let xs32 = xs.to_dtype(DType::F32)?;
let lhs = candle_nn::ops::silu(&self.gate.forward(&xs32)?)?;
let rhs = self.up.forward(&xs32)?;
self.down.forward(&(lhs * rhs)?)?.to_dtype(dtype)
}
}
/// Rows at which host-resident experts run on the GPU instead (#318).
///
/// A prompt chunk routes many tokens to each active expert, so moving
/// the expert's weights once is cheaper than computing every row on the
/// CPU. A decode step routes one token to ten experts, where the copy
/// would cost more than the arithmetic. Unset leaves execution on the
/// host.
fn expert_stream_min_rows() -> Option<usize> {
static MIN_ROWS: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
*MIN_ROWS.get_or_init(|| {
std::env::var("NEURON_EXPERT_STREAM_MIN_ROWS")
.ok()
.and_then(|v| v.parse().ok())
.filter(|&rows| rows > 0)
})
}
/// The most rows a forward may have and still admit experts to the VRAM
/// tier. Decode windows are below it; prompt chunks are not.
pub(crate) const TIER_ADMIT_MAX_ROWS: usize = 16;
/// Whether a prompt chunk may have left transient expert copies in the
/// allocator pool, which holds freed VRAM until it is trimmed.
pub(crate) fn prompt_chunk_streams_experts(rows: usize) -> bool {
rows > TIER_ADMIT_MAX_ROWS
&& (expert_stream_min_rows().is_some()
|| super::expert_tier::configured_budget_mb().is_some())
}
/// A transient copy of a quantised projection on `device`.
fn quantized_on(m: &QMatMul, device: &Device) -> candle_core::Result<QMatMul> {
match m {
QMatMul::QTensor(t) => {
let storage = QStorage::from_data(t.data()?, device, t.dtype())?;
QMatMul::from_qtensor(QTensor::new(storage, t.shape().clone())?)
}
_ => candle_core::bail!("only a quantised expert can be streamed"),
}
}
/// The quantisation type actually usable for rows of `row` elements.
@@ -290,7 +173,6 @@ impl Experts {
Experts::PerExpert(v) => v.len(),
Experts::Banked { gate_up, .. } => gate_up.dims()[0],
Experts::Quantized(v) => v.len(),
Experts::External { count, .. } => *count,
}
}
@@ -443,9 +325,6 @@ impl Experts {
pub(crate) fn forward_one(&self, e: usize, xs: &Tensor) -> candle_core::Result<Tensor> {
match self {
Experts::PerExpert(v) => v[e].forward(xs),
Experts::External { .. } => {
candle_core::bail!("external experts run per layer, not per expert")
}
Experts::Banked {
gate_up,
down,
@@ -485,41 +364,6 @@ impl Experts {
}
}
}
/// Expert `e` computed on `xs`'s device from a transient copy of
/// its weights. Layouts that are not quantised run as usual.
pub(crate) fn forward_streamed(&self, e: usize, xs: &Tensor) -> candle_core::Result<Tensor> {
let Experts::Quantized(v) = self else {
return self.forward_one(e, xs);
};
v[e].on_device(xs.device())?.forward_here(xs)
}
/// Expert `e` computed on `xs`'s device from the VRAM tier, loading
/// it there if it is not already held.
pub(crate) fn forward_tiered(
&self,
e: usize,
xs: &Tensor,
tier: &DeviceExpertTier,
block: u32,
admit: bool,
) -> candle_core::Result<Tensor> {
let Experts::Quantized(v) = self else {
return self.forward_one(e, xs);
};
let q = &v[e];
if !admit {
return match tier.peek(block, e as u32) {
Some(resident) => resident.forward_here(xs),
None => q.on_device(xs.device())?.forward_here(xs),
};
}
let resident = tier.get_or_load(block, e as u32, q.storage_bytes(), || {
q.on_device(xs.device())
})?;
resident.forward_here(xs)
}
}
pub struct Qwen3_5MoeBlock {
@@ -536,8 +380,6 @@ pub struct Qwen3_5MoeBlock {
shared_expert_gate: Option<Linear>,
num_experts_per_tok: usize,
norm_topk_prob: bool,
/// The model's VRAM tier and this block's number in it (#318).
tier: Option<(std::sync::Arc<DeviceExpertTier>, u32)>,
}
impl Qwen3_5MoeBlock {
@@ -564,19 +406,9 @@ impl Qwen3_5MoeBlock {
shared_expert_gate,
num_experts_per_tok,
norm_topk_prob,
tier: None,
}
}
/// Serve this block's host-resident experts through `tier`.
pub(crate) fn with_tier(mut self, tier: Option<std::sync::Arc<DeviceExpertTier>>) -> Self {
self.tier = tier.map(|t| {
let block = t.register_block();
(t, block)
});
self
}
pub fn load(cfg: &TextConfig, vb: &ShardedVarBuilder) -> Result<Self> {
anyhow::ensure!(
cfg.num_experts > 0 && cfg.num_experts_per_tok > 0 && cfg.moe_intermediate_size > 0,
@@ -633,7 +465,6 @@ impl Qwen3_5MoeBlock {
shared_expert_gate,
num_experts_per_tok: cfg.num_experts_per_tok,
norm_topk_prob: cfg.norm_topk_prob,
tier: None,
})
}
}
@@ -655,7 +486,21 @@ pub(crate) fn route_scatter(
norm_topk_prob: bool,
) -> candle_core::Result<ExpertAssignments> {
let n_tokens = xs_flat.dim(0)?;
let (topk_idx, topk_w) = route_topk(gate, xs_flat, num_experts_per_tok, norm_topk_prob)?;
// Router probabilities in f32 (reference uses float softmax
// regardless of activations dtype).
let router_logits = gate.forward(xs_flat)?;
let probs = candle_nn::ops::softmax_last_dim(&router_logits.to_dtype(DType::F32)?)?;
// Top-k selection: descending argsort, take the first k. The
// renormalisation (iff norm_topk_prob) divides by the sum of
// the selected global-softmax values.
let sorted = probs.arg_sort_last_dim(false)?;
let topk_idx = sorted.narrow(1, 0, num_experts_per_tok)?.contiguous()?;
let mut topk_w = probs.gather(&topk_idx, 1)?;
if norm_topk_prob {
let denom = topk_w.sum_keepdim(1)?;
topk_w = topk_w.broadcast_div(&denom)?;
}
// Host-side scatter: token row lists per expert. Cheap relative
// to the expert GEMMs; replaced by grouped-GEMM in slice 4.
@@ -673,54 +518,11 @@ pub(crate) fn route_scatter(
Ok((tokens_for, weights_for))
}
/// The router's top-k, left where the activations are: ids `(rows, k)`
/// u32 and weights `(rows, k)` f32.
pub(crate) fn route_topk(
gate: &Linear,
xs_flat: &Tensor,
num_experts_per_tok: usize,
norm_topk_prob: bool,
) -> candle_core::Result<(Tensor, Tensor)> {
// Router probabilities in f32 (reference uses float softmax
// regardless of activations dtype).
let router_logits = gate.forward(xs_flat)?;
let probs = candle_nn::ops::softmax_last_dim(&router_logits.to_dtype(DType::F32)?)?;
// Top-k selection: descending argsort, take the first k. The
// renormalisation (iff norm_topk_prob) divides by the sum of
// the selected global-softmax values.
let sorted = probs.arg_sort_last_dim(false)?;
let topk_idx = sorted.narrow(1, 0, num_experts_per_tok)?.contiguous()?;
let mut topk_w = probs.gather(&topk_idx, 1)?;
if norm_topk_prob {
let denom = topk_w.sum_keepdim(1)?;
topk_w = topk_w.broadcast_div(&denom)?;
}
Ok((topk_idx, topk_w))
}
impl Module for Qwen3_5MoeBlock {
fn forward(&self, xs: &Tensor) -> candle_core::Result<Tensor> {
let (b, l, hidden) = xs.dims3()?;
let xs_flat = xs.reshape(((), hidden))?;
if let Experts::External { inner, .. } = &self.experts
&& inner.routes_on_device(xs_flat.dim(0)?)
{
let (ids, weights) = route_topk(
&self.gate,
&xs_flat,
self.num_experts_per_tok,
self.norm_topk_prob,
)?;
let ys = inner
.forward_device(&xs_flat, &ids, &weights, self.num_experts_per_tok)?
.to_dtype(xs.dtype())?;
return self
.add_shared_expert(ys, &xs_flat)?
.reshape((b, l, hidden));
}
// Routing stays where the activations are: it is one small
// matmul against `gate` and a host-side top-k, and the router
// is device-resident even when the experts are not.
@@ -732,20 +534,6 @@ impl Module for Qwen3_5MoeBlock {
self.norm_topk_prob,
)?;
if let Experts::External { inner, .. } = &self.experts {
let ys = inner
.forward(
&xs_flat,
&tokens_for,
&weights_for,
self.num_experts_per_tok,
)?
.to_dtype(xs.dtype())?;
return self
.add_shared_expert(ys, &xs_flat)?
.reshape((b, l, hidden));
}
// Cross to the experts once for the whole layer, not once per
// expert (#318). With host-resident experts the old shape was
// 10 round trips per layer and 480 per token; this is one in
@@ -758,17 +546,7 @@ impl Module for Qwen3_5MoeBlock {
// dominates.
let home = self.experts.device();
let off_device = home.is_some();
let host_resident = xs.device().is_cuda() && home.as_ref().is_some_and(Device::is_cpu);
let tier = self.tier.as_ref().filter(|_| host_resident);
let stream = tier.is_some()
|| host_resident
&& expert_stream_min_rows()
.is_some_and(|min_rows| xs_flat.dim(0).is_ok_and(|n| n >= min_rows));
let routed_dev = if stream {
xs.device().clone()
} else {
home.unwrap_or_else(|| xs.device().clone())
};
let routed_dev = home.unwrap_or_else(|| xs.device().clone());
let xs_routed = xs_flat.to_device(&routed_dev)?;
let started = std::time::Instant::now();
@@ -779,15 +557,7 @@ impl Module for Qwen3_5MoeBlock {
}
let rows = Tensor::new(tokens_for[e].as_slice(), &routed_dev)?;
let picked = xs_routed.index_select(&rows, 0)?;
let out = if let Some((tier, block)) = tier {
let admit = xs_routed.dim(0)? <= TIER_ADMIT_MAX_ROWS;
self.experts
.forward_tiered(e, &picked, tier, *block, admit)?
} else if stream {
self.experts.forward_streamed(e, &picked)?
} else {
self.experts.forward_one(e, &picked)?
};
let out = self.experts.forward_one(e, &picked)?;
let w = Tensor::new(weights_for[e].as_slice(), &routed_dev)?
.to_dtype(out.dtype())?
.reshape(((), 1))?;
@@ -805,32 +575,18 @@ impl Module for Qwen3_5MoeBlock {
expert_ms = started.elapsed().as_secs_f64() * 1e3,
rows = xs_routed.dims()[0],
active = tokens_for.iter().filter(|t| !t.is_empty()).count(),
stream,
tier_hits = tier.map_or(0, |(t, _)| t.stats().hits),
tier_misses = tier.map_or(0, |(t, _)| t.stats().misses),
tier_prompt_hits = tier.map_or(0, |(t, _)| t.stats().prompt_hits),
tier_prompt_misses = tier.map_or(0, |(t, _)| t.stats().prompt_misses),
tier_mb = tier.map_or(0, |(t, _)| t.stats().used_bytes >> 20),
"moe: routed experts (#318)"
);
}
let ys = ys.to_device(xs.device())?;
self.add_shared_expert(ys, &xs_flat)?
.reshape((b, l, hidden))
}
}
let mut ys = ys.to_device(xs.device())?;
impl Qwen3_5MoeBlock {
/// Adds the sigmoid-gated shared expert, when the model has one.
fn add_shared_expert(&self, ys: Tensor, xs_flat: &Tensor) -> candle_core::Result<Tensor> {
match (&self.shared_expert, &self.shared_expert_gate) {
(Some(shared), Some(gate)) => {
let mix = candle_nn::ops::sigmoid(&gate.forward(xs_flat)?)?;
let shared_out = shared.forward(xs_flat)?.broadcast_mul(&mix)?;
ys + shared_out
}
_ => Ok(ys),
if let (Some(shared), Some(gate)) = (&self.shared_expert, &self.shared_expert_gate) {
let mix = candle_nn::ops::sigmoid(&gate.forward(&xs_flat)?)?;
let shared_out = shared.forward(&xs_flat)?.broadcast_mul(&mix)?;
ys = (ys + shared_out)?;
}
ys.reshape((b, l, hidden))
}
}
@@ -867,7 +623,6 @@ mod tests {
shared_expert_gate: Some(Linear::new(randn(&[1, hidden]), None)),
num_experts_per_tok: top_k,
norm_topk_prob: true,
tier: None,
};
let (b, l) = (2, 3);
@@ -953,7 +708,6 @@ mod tests {
shared_expert_gate: None,
num_experts_per_tok: 1,
norm_topk_prob: false,
tier: None,
};
let xs = randn(&[1, 1, hidden]);
let got: Vec<f32> = block
@@ -1144,109 +898,6 @@ mod tests {
}
}
/// The streamed path must run the same arithmetic as the resident
/// one. A CPU test host cannot exercise the transfer, so this pins
/// the transient copy and the dtype round trip.
#[test]
fn streamed_expert_matches_the_resident_forward() {
let (n_experts, hidden, inter) = (2usize, 2560usize, 640usize);
let gate_up = randn(&[n_experts, inter * 2, hidden]);
let down = randn(&[n_experts, hidden, inter]);
let experts =
Experts::quantize_banked_onto(&gate_up, &down, inter, GgmlDType::Q4K, &Device::Cpu)
.unwrap();
let xs = randn(&[3, hidden]);
for e in 0..n_experts {
let resident: Vec<Vec<f32>> = experts.forward_one(e, &xs).unwrap().to_vec2().unwrap();
let streamed: Vec<Vec<f32>> =
experts.forward_streamed(e, &xs).unwrap().to_vec2().unwrap();
assert_eq!(resident, streamed, "expert {e}");
}
}
/// External experts receive the block's routing and their result is
/// mixed with the shared expert exactly as resident experts' is.
#[test]
fn external_experts_receive_the_routing_and_join_the_shared_expert() {
struct Fixed;
impl ExternalExperts for Fixed {
fn forward(
&self,
xs: &Tensor,
tokens_for: &[Vec<u32>],
weights_for: &[Vec<f32>],
k: usize,
) -> candle_core::Result<Tensor> {
let routed: usize = tokens_for.iter().map(Vec::len).sum();
assert_eq!(routed, xs.dim(0)? * k);
assert_eq!(tokens_for.len(), 6);
for (t, w) in tokens_for.iter().zip(weights_for) {
assert_eq!(t.len(), w.len());
}
xs.ones_like()
}
}
let (hidden, inter, n_exp, top_k) = (8, 4, 6, 2);
let shared = rand_mlp(hidden, inter);
let shared_gate = Linear::new(randn(&[1, hidden]), None);
let xs = randn(&[1, 3, hidden]);
let flat = xs.reshape(((), hidden)).unwrap();
let mix = candle_nn::ops::sigmoid(&shared_gate.forward(&flat).unwrap()).unwrap();
let expected = (shared.forward(&flat).unwrap().broadcast_mul(&mix).unwrap()
+ flat.ones_like().unwrap())
.unwrap();
let block = Qwen3_5MoeBlock {
gate: Linear::new(randn(&[n_exp, hidden]), None),
experts: Experts::External {
count: n_exp,
inner: Box::new(Fixed),
},
shared_expert: Some(shared),
shared_expert_gate: Some(shared_gate),
num_experts_per_tok: top_k,
norm_topk_prob: true,
tier: None,
};
let got: Vec<Vec<f32>> = block
.forward(&xs)
.unwrap()
.reshape(((), hidden))
.unwrap()
.to_vec2()
.unwrap();
let want: Vec<Vec<f32>> = expected.to_vec2().unwrap();
assert_eq!(got, want);
}
/// The tiered path runs the same arithmetic as the resident one,
/// and a second use of an expert comes from the tier.
#[test]
fn tiered_expert_matches_the_resident_forward() {
let (n_experts, hidden, inter) = (2usize, 2560usize, 640usize);
let gate_up = randn(&[n_experts, inter * 2, hidden]);
let down = randn(&[n_experts, hidden, inter]);
let experts =
Experts::quantize_banked_onto(&gate_up, &down, inter, GgmlDType::Q4K, &Device::Cpu)
.unwrap();
let tier = DeviceExpertTier::new(1 << 30);
let block = tier.register_block();
let xs = randn(&[3, hidden]);
for e in 0..n_experts {
let resident: Vec<Vec<f32>> = experts.forward_one(e, &xs).unwrap().to_vec2().unwrap();
for _ in 0..2 {
let tiered: Vec<Vec<f32>> = experts
.forward_tiered(e, &xs, &tier, block, true)
.unwrap()
.to_vec2()
.unwrap();
assert_eq!(resident, tiered, "expert {e}");
}
}
let stats = tier.stats();
assert_eq!((stats.misses, stats.hits, stats.entries), (2, 2, 2));
assert!(stats.used_bytes > 0);
}
/// Host-resident experts compute the same function as device-
/// resident ones (#318).
///
@@ -1,157 +0,0 @@
//! A bias-free projection that is either a dense candle [`Linear`] or a
//! weight held in another format and run by its own kernels.
//!
//! The second form exists so a model can take its dense weights from a
//! quantized file (a GGUF's Q8_0 blocks, say) while keeping the
//! checkpoint's names and the rest of its load path. A [`LinearSource`]
//! is asked for each projection by its checkpoint name; when it has one,
//! the dense tensor is never read.
use std::sync::Arc;
use anyhow::{Context, Result};
use candle_core::{Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
/// `y = x W^T` for a weight held outside candle.
pub trait ExternalLinear: Send + Sync {
/// `x` is `(.., in_dim)`; the result is `(.., out_dim)` in `x`'s dtype.
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor>;
}
/// Supplies projections by checkpoint name, e.g.
/// `model.language_model.layers.3.self_attn.q_proj.weight`.
pub trait LinearSource: Send + Sync {
/// The projection, or `None` to load the checkpoint's own tensor.
/// `(out_dim, in_dim)` is the shape the checkpoint would have.
fn linear(
&self,
name: &str,
in_dim: usize,
out_dim: usize,
) -> Result<Option<Arc<dyn ExternalLinear>>>;
}
#[derive(Clone)]
pub enum Proj {
Dense(Linear),
External(Arc<dyn ExternalLinear>),
}
impl Module for Proj {
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
match self {
Self::Dense(linear) => linear.forward(x),
Self::External(linear) => linear.forward(x),
}
}
}
impl From<Linear> for Proj {
fn from(linear: Linear) -> Self {
Self::Dense(linear)
}
}
/// `{prefix}.{name}.weight`, from `source` when it has it, else from the
/// checkpoint.
pub fn load_proj(
vb: &ShardedVarBuilder,
name: &str,
in_dim: usize,
out_dim: usize,
source: Option<&dyn LinearSource>,
) -> Result<Proj> {
if let Some(source) = source {
let prefix = vb.prefix();
let full = if prefix.is_empty() {
format!("{name}.weight")
} else {
format!("{prefix}.{name}.weight")
};
if let Some(linear) = source.linear(&full, in_dim, out_dim)? {
return Ok(Proj::External(linear));
}
}
let weight = vb
.pp(name)
.get((out_dim, in_dim), "weight")
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Proj::Dense(Linear::new(weight, None)))
}
#[cfg(test)]
mod tests {
use super::*;
use candle_core::{DType, Device};
use std::collections::HashMap;
use std::sync::Mutex;
struct Doubling;
impl ExternalLinear for Doubling {
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
x * 2.0
}
}
/// Records the names it is asked for and serves only one of them.
struct OneName(Mutex<Vec<String>>);
impl LinearSource for OneName {
fn linear(
&self,
name: &str,
_in_dim: usize,
_out_dim: usize,
) -> Result<Option<Arc<dyn ExternalLinear>>> {
self.0.lock().unwrap().push(name.to_string());
Ok(
(name == "a.b.served.weight")
.then(|| Arc::new(Doubling) as Arc<dyn ExternalLinear>),
)
}
}
/// The source is asked by the full checkpoint name; what it serves
/// replaces the tensor, which is never read (the checkpoint here has
/// none for it), and what it declines comes from the checkpoint.
#[test]
fn a_source_is_asked_by_full_name_and_the_checkpoint_fills_the_rest() {
let dev = Device::Cpu;
let mut tensors = HashMap::new();
tensors.insert(
"a.b.kept.weight".to_string(),
Tensor::ones((2, 2), DType::F32, &dev).unwrap(),
);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("model.safetensors");
candle_core::safetensors::save(&tensors, &path).unwrap();
let vb = unsafe {
candle_nn::var_builder::ShardedSafeTensors::var_builder(&[&path], DType::F32, &dev)
.unwrap()
}
.pp("a")
.pp("b");
let source = OneName(Mutex::new(Vec::new()));
let x = Tensor::new(&[[1f32, 3.]], &dev).unwrap();
let served = load_proj(&vb, "served", 2, 2, Some(&source)).unwrap();
assert!(matches!(served, Proj::External(_)));
assert_eq!(
served.forward(&x).unwrap().to_vec2::<f32>().unwrap(),
[[2., 6.]]
);
let kept = load_proj(&vb, "kept", 2, 2, Some(&source)).unwrap();
assert!(matches!(kept, Proj::Dense(_)));
assert_eq!(
kept.forward(&x).unwrap().to_vec2::<f32>().unwrap(),
[[4., 4.]]
);
assert_eq!(
*source.0.lock().unwrap(),
["a.b.served.weight", "a.b.kept.weight"]
);
}
}
@@ -110,17 +110,12 @@ impl DecoderLayer {
opts: &super::LoadOptions<'_>,
) -> Result<Self> {
let mixer = match layer_type {
"full_attention" => Mixer::Full(Box::new(Attention::load(
cfg,
rotary,
&vb.pp("self_attn"),
opts.dense.as_deref(),
)?)),
"linear_attention" => Mixer::Linear(Box::new(linear_attn::load(
cfg,
&vb.pp("linear_attn"),
opts.dense.as_deref(),
)?)),
"full_attention" => {
Mixer::Full(Box::new(Attention::load(cfg, rotary, &vb.pp("self_attn"))?))
}
"linear_attention" => {
Mixer::Linear(Box::new(linear_attn::load(cfg, &vb.pp("linear_attn"))?))
}
other => anyhow::bail!(
"unknown layer_type '{other}' (expected 'full_attention' or \
'linear_attention')"
@@ -137,7 +132,6 @@ impl DecoderLayer {
// Decoder hyper-connections always scatter back; only
// the top-level mixer does not.
true,
opts.dense.as_deref(),
)
};
@@ -211,16 +205,6 @@ 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(),
@@ -1,390 +0,0 @@
//! 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)
}
@@ -1,477 +0,0 @@
//! 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(())
}
}
@@ -1,373 +0,0 @@
//! 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)
}
@@ -1,18 +0,0 @@
//! 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;
@@ -1,345 +0,0 @@
//! 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)
}
@@ -1,346 +0,0 @@
//! GGUF tensors as the native decode engine (#427) holds them.
//!
//! The engine reads the GGUF as it is stored: llama.cpp's layout and
//! head order (the linear-attention value heads tiled by key head), the
//! norm weights already `1 + w`, `ssm_a` already `-exp(A_log)`. That is
//! the form Strata's kernels take. Quantized projections stay quantized;
//! the tensors Strata's pack converts to BF16 (the hyper-connection mixes
//! and injections, the GDN alpha/beta, the routers) are converted the
//! same way here, rounding to nearest even.
/// ggml type ids the engine handles.
pub const GGML_F32: u32 = 0;
pub const GGML_F16: u32 = 1;
pub const GGML_Q8_0: u32 = 8;
pub const GGML_Q6_K: u32 = 14;
pub const GGML_BF16: u32 = 30;
const Q8_0_BLOCK_VALUES: usize = 32;
const Q8_0_BLOCK_BYTES: usize = 34;
/// IEEE half to single, subnormals included.
pub fn f16_to_f32(h: u16) -> f32 {
let sign = ((h >> 15) & 1) as u32;
let exp = ((h >> 10) & 0x1f) as u32;
let man = (h & 0x3ff) as u32;
let bits = match (exp, man) {
(0, 0) => sign << 31,
(0, _) => {
// Subnormal: renormalise.
let shift = man.leading_zeros() - 21;
let man = (man << shift) & 0x3ff;
(sign << 31) | ((113 - shift) << 23) | (man << 13)
}
(0x1f, _) => (sign << 31) | (0xff << 23) | (man << 13),
_ => (sign << 31) | ((exp + 112) << 23) | (man << 13),
};
f32::from_bits(bits)
}
/// Single to BF16 bits, round to nearest even (NaN stays NaN).
pub fn f32_to_bf16(x: f32) -> u16 {
let bits = x.to_bits();
if x.is_nan() {
return ((bits >> 16) | 0x40) as u16;
}
let round = 0x7fff + ((bits >> 16) & 1);
(bits.wrapping_add(round) >> 16) as u16
}
/// Q8_0 blocks (an f16 scale, then 32 signed bytes) to f32.
pub fn q8_0_to_f32(bytes: &[u8]) -> Vec<f32> {
let mut out = Vec::with_capacity(bytes.len() / Q8_0_BLOCK_BYTES * Q8_0_BLOCK_VALUES);
for block in bytes.as_chunks::<Q8_0_BLOCK_BYTES>().0 {
let d = f16_to_f32(u16::from_le_bytes([block[0], block[1]]));
out.extend(block[2..].iter().map(|&q| d * f32::from(q as i8)));
}
out
}
const Q6_K_BLOCK_VALUES: usize = 256;
const Q6_K_BLOCK_BYTES: usize = 210;
/// Q6_K blocks to f32, as ggml's `dequantize_row_q6_K`: per 256 values,
/// 128 bytes of low nibbles, 64 of high bit pairs, 16 signed scales and
/// an f16 scale.
pub fn q6_k_to_f32(bytes: &[u8]) -> Vec<f32> {
let mut out = Vec::with_capacity(bytes.len() / Q6_K_BLOCK_BYTES * Q6_K_BLOCK_VALUES);
for block in bytes.as_chunks::<Q6_K_BLOCK_BYTES>().0 {
let (ql, rest) = block.split_at(128);
let (qh, rest) = rest.split_at(64);
let (sc, d) = rest.split_at(16);
let d = f16_to_f32(u16::from_le_bytes([d[0], d[1]]));
let mut y = [0f32; Q6_K_BLOCK_VALUES];
for half in 0..2 {
let (ql, qh, sc) = (&ql[64 * half..], &qh[32 * half..], &sc[8 * half..]);
let y = &mut y[128 * half..];
for l in 0..32 {
let is = l / 16;
let q = |low: u8, shift: u32| -> f32 {
f32::from(((low | (((qh[l] >> shift) & 3) << 4)) as i8) - 32)
};
let s = |i: usize| f32::from(sc[i] as i8);
y[l] = d * s(is) * q(ql[l] & 0xf, 0);
y[l + 32] = d * s(is + 2) * q(ql[l + 32] & 0xf, 2);
y[l + 64] = d * s(is + 4) * q(ql[l] >> 4, 4);
y[l + 96] = d * s(is + 6) * q(ql[l + 32] >> 4, 6);
}
}
out.extend_from_slice(&y);
}
out
}
/// A tensor's values as f32, from the GGUF types the engine converts.
pub fn to_f32(bytes: &[u8], ggml_type: u32) -> Option<Vec<f32>> {
Some(match ggml_type {
GGML_F32 => bytes
.as_chunks::<4>()
.0
.iter()
.map(|&b| f32::from_le_bytes(b))
.collect(),
GGML_F16 => bytes
.as_chunks::<2>()
.0
.iter()
.map(|&b| f16_to_f32(u16::from_le_bytes(b)))
.collect(),
GGML_BF16 => bytes
.as_chunks::<2>()
.0
.iter()
.map(|&b| f32::from_bits(u32::from(u16::from_le_bytes(b)) << 16))
.collect(),
GGML_Q8_0 => q8_0_to_f32(bytes),
GGML_Q6_K => q6_k_to_f32(bytes),
_ => return None,
})
}
/// Bytes a tensor of `ggml_type` with `values` elements occupies, for
/// the types the engine reads whole.
pub fn tensor_bytes(ggml_type: u32, values: usize) -> Option<usize> {
Some(match ggml_type {
GGML_F32 => values * 4,
GGML_F16 | GGML_BF16 => values * 2,
GGML_Q8_0 if values.is_multiple_of(Q8_0_BLOCK_VALUES) => {
values / Q8_0_BLOCK_VALUES * Q8_0_BLOCK_BYTES
}
GGML_Q6_K if values.is_multiple_of(Q6_K_BLOCK_VALUES) => {
values / Q6_K_BLOCK_VALUES * Q6_K_BLOCK_BYTES
}
_ => return None,
})
}
#[cfg(feature = "strata-kernels")]
pub use device::{DeviceTensor, Gguf};
#[cfg(feature = "strata-kernels")]
mod device {
use std::fs::File;
use std::path::Path;
use anyhow::{Context, Result, bail, ensure};
use candle_core::CudaDevice;
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use memmap2::Mmap;
use super::{GGML_BF16, GGML_F32, f32_to_bf16, tensor_bytes, to_f32};
use crate::harness::arch::qwen4_exp::gguf_index::{GgufIndex, GgufTensor};
/// A tensor on the device, in whatever form it was uploaded.
pub struct DeviceTensor {
buf: CudaSlice<u8>,
pub ggml_type: u32,
/// ggml order: `dims[0]` is the fastest-varying (the input width
/// of a projection).
pub dims: Vec<u64>,
}
impl DeviceTensor {
pub fn address(&self) -> u64 {
self.buf.device_ptr(self.buf.stream()).0
}
pub fn values(&self) -> usize {
self.dims.iter().product::<u64>() as usize
}
}
/// The GGUF's shards, mapped, and the device tensors go to.
pub struct Gguf {
pub index: GgufIndex,
maps: Vec<Mmap>,
device: CudaDevice,
}
impl Gguf {
pub fn open(first: &Path, device: &CudaDevice) -> Result<Self> {
let index = GgufIndex::open(first)?;
let mut maps = Vec::with_capacity(index.shards.len());
for path in &index.shards {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
// SAFETY: model files are not modified while serving.
maps.push(
unsafe { Mmap::map(&file) }
.with_context(|| format!("map {}", path.display()))?,
);
}
Ok(Self {
index,
maps,
device: device.clone(),
})
}
fn tensor(&self, name: &str) -> Result<&GgufTensor> {
self.index
.tensors
.get(name)
.with_context(|| format!("the GGUF has no {name}"))
}
/// The tensor's stored bytes. Only for the types whose size the
/// engine knows; quantized projections use `upload_raw`.
fn bytes(&self, name: &str, size: usize) -> Result<&[u8]> {
let t = self.tensor(name)?;
let map = &self.maps[t.shard];
let start = t.offset as usize;
ensure!(start + size <= map.len(), "{name} runs past its shard");
Ok(&map[start..start + size])
}
fn upload(&self, host: &[u8], ggml_type: u32, dims: Vec<u64>) -> Result<DeviceTensor> {
// SAFETY: written in full by the copy below.
let mut buf = unsafe { self.device.alloc::<u8>(host.len().max(1)) }?;
self.device.memcpy_htod(host, &mut buf)?;
Ok(DeviceTensor {
buf,
ggml_type,
dims,
})
}
/// The tensor as stored, for the kernels that read its format.
/// `row_bytes` gives the size of one `dims[0]`-wide row.
pub fn upload_raw(
&self,
name: &str,
row_bytes: impl Fn(u32, u64) -> usize,
) -> Result<DeviceTensor> {
let t = self.tensor(name)?;
let rows: u64 = t.dims.iter().skip(1).product();
let size = row_bytes(t.ggml_type, t.dims[0]) * rows as usize;
ensure!(size > 0, "{name}: no row size for type {}", t.ggml_type);
let host = self.bytes(name, size)?;
self.upload(host, t.ggml_type, t.dims.clone())
}
fn values_f32(&self, name: &str) -> Result<(Vec<f32>, Vec<u64>)> {
let t = self.tensor(name)?;
let n: u64 = t.dims.iter().product();
let Some(size) = tensor_bytes(t.ggml_type, n as usize) else {
bail!("{name}: the engine cannot convert type {}", t.ggml_type);
};
let values = to_f32(self.bytes(name, size)?, t.ggml_type)
.with_context(|| format!("{name}: unconvertible type {}", t.ggml_type))?;
Ok((values, t.dims.clone()))
}
/// The tensor as f32.
pub fn upload_f32(&self, name: &str) -> Result<DeviceTensor> {
let (values, dims) = self.values_f32(name)?;
let host: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
self.upload(&host, GGML_F32, dims)
}
/// The tensor as BF16, rounded to nearest even.
pub fn upload_bf16(&self, name: &str) -> Result<DeviceTensor> {
let (values, dims) = self.values_f32(name)?;
let host: Vec<u8> = values
.iter()
.flat_map(|&v| f32_to_bf16(v).to_le_bytes())
.collect();
self.upload(&host, GGML_BF16, dims)
}
pub fn device(&self) -> &CudaDevice {
&self.device
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn half_precision_converts_exactly() {
assert_eq!(f16_to_f32(0x3c00), 1.0);
assert_eq!(f16_to_f32(0xc000), -2.0);
assert_eq!(f16_to_f32(0x0000), 0.0);
assert_eq!(f16_to_f32(0x7bff), 65504.0);
// Smallest subnormal, 2^-24, and a larger one, 2^-15.
assert_eq!(f16_to_f32(0x0001), 2f32.powi(-24));
assert_eq!(f16_to_f32(0x0200), 2f32.powi(-15));
assert!(f16_to_f32(0x7c00).is_infinite());
}
/// Ties go to the even mantissa, and anything past half rounds up.
#[test]
fn bf16_rounds_to_nearest_even() {
assert_eq!(f32_to_bf16(1.0), 0x3f80);
// 1 + 2^-8 is exactly halfway between 1 and 1 + 2^-7: to even.
assert_eq!(f32_to_bf16(1.0 + 2f32.powi(-8)), 0x3f80);
// 1 + 3 * 2^-8 is halfway between 1 + 2^-7 (odd) and 1 + 2^-6.
assert_eq!(f32_to_bf16(1.0 + 3.0 * 2f32.powi(-8)), 0x3f82);
// Just past halfway rounds up.
assert_eq!(f32_to_bf16(1.0 + 2f32.powi(-8) + 2f32.powi(-20)), 0x3f81);
assert_eq!(f32_to_bf16(-2.5), 0xc020);
}
/// One Q6_K block built by hand: every 6-bit value is assembled from
/// its low nibble and high bit pair, offset by 32, and scaled by its
/// group's scale and the block scale.
#[test]
fn q6_k_assembles_six_bit_values() {
let mut block = vec![0u8; 210];
// Value 0: low nibble 5, high bits 0b10 -> 0b10_0101 = 37, -32 = 5.
block[0] = 0x05;
block[128] = 0b10;
// Value 96 (fourth quarter: ql[32]'s high nibble, qh[0] bits 6-7):
// nibble 0xf, high bits 0b01 -> 0b01_1111 = 31, -32 = -1.
block[32] = 0xf0;
block[128] |= 0b01 << 6;
// Scales: group 0 = 3, group 6 (value 96's) = -2.
block[192] = 3;
block[198] = (-2i8) as u8;
block[208..210].copy_from_slice(&0x3800u16.to_le_bytes()); // 0.5
let y = q6_k_to_f32(&block);
assert_eq!(y.len(), 256);
assert_eq!(y[0], 0.5 * 3.0 * 5.0);
// scale 0.5, group scale -2, value -1.
assert_eq!(y[96], 1.0);
// An all-zero position reads 0 - 32 = -32 times its scale.
assert_eq!(y[1], 0.5 * 3.0 * -32.0);
assert_eq!(tensor_bytes(GGML_Q6_K, 512), Some(420));
}
#[test]
fn q8_0_blocks_scale_their_bytes() {
let mut block = vec![0u8; 34];
block[..2].copy_from_slice(&0x3800u16.to_le_bytes()); // 0.5
for (i, b) in block[2..].iter_mut().enumerate() {
*b = (i as i8 - 16) as u8;
}
let values = q8_0_to_f32(&block);
assert_eq!(values.len(), 32);
assert_eq!(values[0], -8.0);
assert_eq!(values[16], 0.0);
assert_eq!(values[31], 7.5);
assert_eq!(tensor_bytes(GGML_Q8_0, 64), Some(68));
assert_eq!(tensor_bytes(GGML_Q8_0, 33), None);
}
}
@@ -26,14 +26,14 @@
//!
//! See `doc/qwen4_exp-port-spec.md` §3 and §4.
use anyhow::Result;
use anyhow::{Context, Result};
use candle_core::{Module, Tensor};
use candle_nn::Linear;
use candle_nn::kv_cache::ConcatKvCache;
use candle_nn::var_builder::ShardedVarBuilder;
use std::sync::Arc;
use crate::harness::arch::qwen3_5::full_attn::{AttnMask, attention_context};
use crate::harness::arch::qwen3_5::proj::{LinearSource, Proj, load_proj};
use crate::harness::arch::qwen3_5::rmsnorm::Qwen3_5RmsNorm;
use crate::harness::arch::qwen3_5::rope::RotaryEmbedding;
@@ -41,10 +41,10 @@ use super::config::TextConfig;
use super::qsa::Indexer;
pub struct Attention {
q_proj: Proj,
k_proj: Proj,
v_proj: Proj,
o_proj: Proj,
q_proj: Linear,
k_proj: Linear,
v_proj: Linear,
o_proj: Linear,
q_norm: Qwen3_5RmsNorm,
k_norm: Qwen3_5RmsNorm,
/// The sparse-attention side channel. Owns its own KV cache, which
@@ -66,7 +66,6 @@ impl Attention {
cfg: &TextConfig,
rotary: Arc<RotaryEmbedding>,
vb: &ShardedVarBuilder,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let head_dim = cfg.head_dim;
let num_heads = cfg.num_attention_heads;
@@ -79,22 +78,10 @@ impl Attention {
let attn_width = num_heads * head_dim;
Ok(Self {
// Doubled output: query and gate, interleaved per head.
q_proj: load_proj(vb, "q_proj", cfg.hidden_size, attn_width * 2, source)?,
k_proj: load_proj(
vb,
"k_proj",
cfg.hidden_size,
num_kv_heads * head_dim,
source,
)?,
v_proj: load_proj(
vb,
"v_proj",
cfg.hidden_size,
num_kv_heads * head_dim,
source,
)?,
o_proj: load_proj(vb, "o_proj", attn_width, cfg.hidden_size, source)?,
q_proj: linear(vb, "q_proj", cfg.hidden_size, attn_width * 2)?,
k_proj: linear(vb, "k_proj", cfg.hidden_size, num_kv_heads * head_dim)?,
v_proj: linear(vb, "v_proj", cfg.hidden_size, num_kv_heads * head_dim)?,
o_proj: linear(vb, "o_proj", attn_width, cfg.hidden_size)?,
q_norm: Qwen3_5RmsNorm::load(&vb.pp("q_norm"), head_dim, cfg.rms_norm_eps)?,
k_norm: Qwen3_5RmsNorm::load(&vb.pp("k_norm"), head_dim, cfg.rms_norm_eps)?,
// The indexer is a submodule of the attention block, not a
@@ -223,13 +210,20 @@ impl Attention {
}
}
fn linear(vb: &ShardedVarBuilder, name: &str, in_dim: usize, out_dim: usize) -> Result<Linear> {
let weight = vb
.pp(name)
.get((out_dim, in_dim), "weight")
.with_context(|| format!("load '{}/{name}/weight'", vb.prefix()))?;
Ok(Linear::new(weight, None))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::harness::arch::qwen3_5::TextConfig as Qwen3_5TextConfig;
use crate::harness::arch::qwen4_exp::qsa::BlockSelector;
use candle_core::{DType, Device};
use candle_nn::Linear;
const HIDDEN: usize = 4;
const HEADS: usize = 2;
@@ -278,10 +272,10 @@ mod tests {
fn layer(budget: usize) -> Attention {
let attn_width = HEADS * HEAD_DIM;
Attention {
q_proj: from_first_column(&[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0], HIDDEN).into(),
k_proj: from_first_column(&[0.0; HEAD_DIM], HIDDEN).into(),
v_proj: from_first_column(&[1.0; HEAD_DIM], HIDDEN).into(),
o_proj: eye(attn_width).into(),
q_proj: from_first_column(&[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0], HIDDEN),
k_proj: from_first_column(&[0.0; HEAD_DIM], HIDDEN),
v_proj: from_first_column(&[1.0; HEAD_DIM], HIDDEN),
o_proj: eye(attn_width),
q_norm: Qwen3_5RmsNorm::from_weight(
Tensor::zeros(HEAD_DIM, DType::F32, &Device::Cpu).unwrap(),
1e-6,
@@ -1,479 +0,0 @@
//! Dense projections from a GGUF's quantized blocks, run on Strata's
//! kernels: a quantized matrix-vector product (`mmvq`) for decode-sized
//! inputs, and dequantize + cuBLAS for prompt chunks.
//!
//! Most of the model's dense tensors are stored as Q8_0 in the UD packs,
//! half of BF16. They map to the checkpoint by name, each in its own
//! layout, except the linear-attention value heads: llama.cpp's
//! converter stores them tiled by key head where the checkpoint groups
//! them. With `r = value_heads / key_heads`, GGUF head `g * key_heads +
//! k` holds checkpoint head `r * k + g`. That is undone at load by
//! moving whole quantized rows (or whole blocks within each row, where
//! the heads are the input dimension), so no value is requantized.
use anyhow::{Result, ensure};
/// How a GGUF tensor's value heads must move to match the checkpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Reorder {
None,
/// Output rows, after the first `skip_rows` (the q and k of a fused
/// qkv projection, which are stored in order).
Rows {
skip_rows: usize,
},
/// Input columns: within every row, per head of `head_dim` values.
Cols,
}
/// The GGUF tensor holding checkpoint tensor `name`, and its reorder.
pub(crate) fn gguf_name(name: &str) -> Option<(String, Reorder, bool)> {
// The bool says whether `skip_rows` must be filled in from the
// config: only the fused qkv knows its q and k widths.
if name == "lm_head.weight" {
return Some(("output.weight".into(), Reorder::None, false));
}
if let Some(rest) = name.strip_prefix("model.language_model.hyper_connection_mixer.") {
let gguf = match rest {
"input_mix_weight_up.weight" => "output_hc_up.weight",
"input_mix_weight_down.weight" => "output_hc_down.weight",
_ => return None,
};
return Some((gguf.into(), Reorder::None, false));
}
let rest = name.strip_prefix("model.language_model.layers.")?;
let (layer, rest) = rest.split_once('.')?;
let layer: usize = layer.parse().ok()?;
let (gguf, reorder, needs_skip) = match rest {
"linear_attn.in_proj_qkv.weight" => ("attn_qkv", Reorder::Rows { skip_rows: 0 }, true),
"linear_attn.in_proj_z.weight" => ("attn_gate", Reorder::Rows { skip_rows: 0 }, false),
"linear_attn.out_proj.weight" => ("ssm_out", Reorder::Cols, false),
"self_attn.q_proj.weight" => ("attn_q", Reorder::None, false),
"self_attn.k_proj.weight" => ("attn_k", Reorder::None, false),
"self_attn.v_proj.weight" => ("attn_v", Reorder::None, false),
"self_attn.o_proj.weight" => ("attn_output", Reorder::None, false),
"mlp.shared_expert.gate_proj.weight" => ("ffn_gate_shexp", Reorder::None, false),
"mlp.shared_expert.up_proj.weight" => ("ffn_up_shexp", Reorder::None, false),
"mlp.shared_expert.down_proj.weight" => ("ffn_down_shexp", Reorder::None, false),
"attn_hyper_connection.input_mix_weight_up.weight" => ("hc_attn_up", Reorder::None, false),
"attn_hyper_connection.input_mix_weight_down.weight" => {
("hc_attn_down", Reorder::None, false)
}
"mlp_hyper_connection.input_mix_weight_up.weight" => ("hc_ffn_up", Reorder::None, false),
"mlp_hyper_connection.input_mix_weight_down.weight" => {
("hc_ffn_down", Reorder::None, false)
}
_ => return None,
};
Some((format!("blk.{layer}.{gguf}.weight"), reorder, needs_skip))
}
/// The linear-attention head geometry the reorder needs.
#[derive(Debug, Clone, Copy)]
pub struct Heads {
pub key_heads: usize,
pub value_heads: usize,
pub head_dim: usize,
}
impl Heads {
/// The GGUF head that holds checkpoint head `h`.
fn source(&self, h: usize) -> usize {
let r = self.value_heads / self.key_heads;
(h % r) * self.key_heads + h / r
}
}
/// Reorders a tensor of `n_out` rows of `row_bytes` into the
/// checkpoint's layout. `head_bytes` is one head's span within a row
/// (only read for [`Reorder::Cols`]).
pub(crate) fn reorder(
src: &[u8],
n_out: usize,
row_bytes: usize,
head_bytes: usize,
how: Reorder,
heads: Heads,
) -> Result<Vec<u8>> {
ensure!(src.len() == n_out * row_bytes, "tensor is not n_out rows");
match how {
Reorder::None => Ok(src.to_vec()),
Reorder::Rows { skip_rows } => {
let per_head = heads.head_dim * row_bytes;
ensure!(
n_out == skip_rows + heads.value_heads * heads.head_dim,
"{n_out} rows are not {skip_rows} + {} value heads of {}",
heads.value_heads,
heads.head_dim
);
let mut out = src[..skip_rows * row_bytes].to_vec();
let base = skip_rows * row_bytes;
for h in 0..heads.value_heads {
let at = base + heads.source(h) * per_head;
out.extend_from_slice(&src[at..at + per_head]);
}
Ok(out)
}
Reorder::Cols => {
ensure!(
row_bytes == heads.value_heads * head_bytes,
"a {row_bytes}-byte row is not {} heads of {head_bytes}",
heads.value_heads
);
let mut out = Vec::with_capacity(src.len());
for row in src.chunks_exact(row_bytes) {
for h in 0..heads.value_heads {
let at = heads.source(h) * head_bytes;
out.extend_from_slice(&row[at..at + head_bytes]);
}
}
Ok(out)
}
}
}
#[cfg(feature = "strata-kernels")]
pub use kernels::GgufDenseSource;
#[cfg(feature = "strata-kernels")]
mod kernels {
use std::ffi::c_void;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, bail, ensure};
use candle_core::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr};
use candle_core::{CudaDevice, CudaStorage, DType, Device, Storage, Tensor};
use memmap2::{Advice, Mmap};
use super::{Heads, gguf_name, reorder};
use crate::cuda::strata as ffi;
use crate::harness::arch::qwen3_5::proj::{ExternalLinear, LinearSource};
use crate::harness::arch::qwen4_exp::gguf_index::GgufIndex;
const Q8_1_BLOCK_BYTES: usize = 36;
/// Inputs of up to this many rows take the matrix-vector kernel;
/// larger ones dequantize the weight and use a matmul.
const MMVQ_MAX_ROWS: usize = 8;
fn address<T>(slice: &CudaSlice<T>) -> u64 {
slice.device_ptr(slice.stream()).0
}
pub struct GgufDenseSource {
device: CudaDevice,
index: GgufIndex,
maps: Vec<Mmap>,
heads: Heads,
key_dim: usize,
}
impl GgufDenseSource {
pub fn open(first: &Path, device: &Device, heads: Heads, key_dim: usize) -> Result<Self> {
let device = device.as_cuda_device()?.clone();
let index = GgufIndex::open(first)?;
let mut maps = Vec::with_capacity(index.shards.len());
for path in &index.shards {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
// SAFETY: model files are not modified while serving.
let map = unsafe { Mmap::map(&file) }
.with_context(|| format!("map {}", path.display()))?;
map.advise(Advice::Sequential).context("advise dense map")?;
maps.push(map);
}
tracing::info!(
shards = maps.len(),
"dense projections from GGUF on native kernels"
);
Ok(Self {
device,
index,
maps,
heads,
key_dim,
})
}
}
impl LinearSource for GgufDenseSource {
fn linear(
&self,
name: &str,
in_dim: usize,
out_dim: usize,
) -> Result<Option<Arc<dyn ExternalLinear>>> {
let Some((gguf, mut how, needs_skip)) = gguf_name(name) else {
return Ok(None);
};
let Some(tensor) = self.index.tensors.get(&gguf) else {
return Ok(None);
};
let ty = tensor.ggml_type as i32;
// SAFETY: a pure function of its argument.
if unsafe { ffi::neuron_strata_mmvq_supported(ty) } == 0 {
tracing::info!(
name,
ggml_type = ty,
"no native kernel for this type; dense"
);
return Ok(None);
}
ensure!(
tensor.dims == [in_dim as u64, out_dim as u64],
"{gguf} is {:?}, the checkpoint's {name} is [{in_dim}, {out_dim}]",
tensor.dims
);
if needs_skip {
how = super::Reorder::Rows {
skip_rows: 2 * self.key_dim,
};
}
// SAFETY: pure functions of their integer arguments.
let (row_bytes, head_bytes) = unsafe {
(
ffi::neuron_strata_row_bytes(ty, in_dim as i64),
ffi::neuron_strata_row_bytes(ty, self.heads.head_dim as i64),
)
};
ensure!(row_bytes > 0, "{gguf}: no row size for type {ty}");
if how == super::Reorder::Cols && head_bytes * self.heads.value_heads != row_bytes {
bail!(
"{gguf}: type {ty} blocks do not divide a {}-wide head",
self.heads.head_dim
);
}
let start = tensor.offset as usize;
let bytes = out_dim * row_bytes;
let map = &self.maps[tensor.shard];
ensure!(start + bytes <= map.len(), "{gguf} runs past its shard");
let host = reorder(
&map[start..start + bytes],
out_dim,
row_bytes,
head_bytes,
how,
self.heads,
)
.with_context(|| format!("reorder {gguf}"))?;
// SAFETY: written in full by the copy below.
let mut weight = unsafe { self.device.alloc::<u8>(bytes) }?;
self.device.memcpy_htod(&host, &mut weight)?;
Ok(Some(Arc::new(QuantLinear {
device: self.device.clone(),
weight,
ty,
n_in: in_dim,
n_out: out_dim,
})))
}
}
struct QuantLinear {
device: CudaDevice,
weight: CudaSlice<u8>,
ty: i32,
n_in: usize,
n_out: usize,
}
impl QuantLinear {
fn stream(&self) -> *mut c_void {
self.device.cuda_stream().cu_stream() as *mut c_void
}
/// `(rows, n_in)` f32 activations to `(rows, n_out)` f32.
fn mmvq(&self, x: &Tensor, rows: usize) -> candle_core::Result<Tensor> {
let (storage, layout) = x.storage_and_layout();
let Storage::Cuda(storage) = &*storage else {
candle_core::bail!("native dense projections need activations on the GPU");
};
let x_slice = storage.as_cuda_slice::<f32>()?;
let x_ptr = (address(x_slice) as usize + layout.start_offset() * 4) as *const f32;
// SAFETY: both are written in full before they are read.
let q8 = unsafe {
self.device
.alloc::<u8>(rows * (self.n_in / 32) * Q8_1_BLOCK_BYTES)?
};
// SAFETY: as above.
let out = unsafe { self.device.alloc::<f32>(rows * self.n_out)? };
// SAFETY: every pointer is a live device allocation of the
// size the kernels read or write; the stream orders them.
unsafe {
ffi::neuron_strata_quantize_q8_1(
x_ptr,
rows as i64,
self.n_in as i64,
address(&q8) as *mut c_void,
self.stream(),
);
ffi::neuron_strata_mmvq(
self.ty,
address(&self.weight) as *const c_void,
address(&q8) as *const c_void,
address(&out) as *mut f32,
self.n_in as i32,
self.n_out as i32,
rows as i32,
self.stream(),
);
}
// `q8` is freed stream-ordered, after the kernel has read it.
drop(q8);
Ok(Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
(rows, self.n_out),
)))
}
/// The weight as a `(n_out, n_in)` tensor of `dtype`.
fn dense(&self, dtype: DType) -> candle_core::Result<Tensor> {
let n = self.n_in * self.n_out;
// SAFETY: written in full by the dequantize below.
let out = unsafe { self.device.alloc::<f32>(n)? };
// SAFETY: the weight holds `n` values of `ty`; `out` holds n.
unsafe {
ffi::neuron_strata_dequant_f32(
self.ty,
address(&self.weight) as *const c_void,
n as i64,
address(&out) as *mut f32,
self.stream(),
);
}
Tensor::from((
Storage::Cuda(CudaStorage::wrap_cuda_slice(out, self.device.clone())),
(self.n_out, self.n_in),
))
.to_dtype(dtype)
}
}
impl ExternalLinear for QuantLinear {
fn forward(&self, x: &Tensor) -> candle_core::Result<Tensor> {
let dims = x.dims().to_vec();
let Some((&n_in, lead)) = dims.split_last() else {
candle_core::bail!("a projection needs at least one dimension");
};
if n_in != self.n_in {
candle_core::bail!("input is {n_in} wide, the weight takes {}", self.n_in);
}
let rows: usize = lead.iter().product();
let x2 = x.reshape((rows, n_in))?;
let y = if rows <= MMVQ_MAX_ROWS {
let x32 = x2.to_dtype(DType::F32)?.contiguous()?;
self.mmvq(&x32, rows)?.to_dtype(x.dtype())?
} else {
let w = self.dense(x.dtype())?;
x2.contiguous()?.matmul(&w.t()?)?
};
let mut out_dims = lead.to_vec();
out_dims.push(self.n_out);
y.reshape(out_dims)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const HEADS: Heads = Heads {
key_heads: 2,
value_heads: 6,
head_dim: 1,
};
/// The mapping recovered from the shipped GGUF (16 key heads, 48
/// value heads): GGUF head `g * 16 + k` is checkpoint head `3k + g`.
#[test]
fn the_shipped_geometry_matches_the_measured_permutation() {
let heads = Heads {
key_heads: 16,
value_heads: 48,
head_dim: 128,
};
// Checkpoint heads 0, 1, 2 are GGUF 0, 16, 32; checkpoint 3 is 1.
assert_eq!(
(0..5).map(|h| heads.source(h)).collect::<Vec<_>>(),
[0, 16, 32, 1, 17]
);
// And measured directly: GGUF position 1 holds checkpoint head 3.
let gguf_holds: Vec<usize> = (0..48)
.map(|p| (0..48).find(|&h| heads.source(h) == p).unwrap())
.collect();
assert_eq!(&gguf_holds[..4], [0, 3, 6, 9]);
assert_eq!(gguf_holds[16], 1);
}
/// Rows after the skipped q/k move as whole heads; the skipped rows
/// keep their place.
#[test]
fn rows_move_by_head_after_the_skip() {
// Two skipped rows, then six value heads of one row each, two
// bytes per row. GGUF value position p holds head `gguf_holds[p]`.
let gguf_holds = [0u8, 3, 1, 4, 2, 5];
let mut src = vec![100, 101, 102, 103];
for h in gguf_holds {
src.extend_from_slice(&[h, h]);
}
let got = reorder(&src, 8, 2, 0, Reorder::Rows { skip_rows: 2 }, HEADS).unwrap();
assert_eq!(
got,
[100, 101, 102, 103, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
);
}
/// Columns move as whole head spans within every row.
#[test]
fn columns_move_by_head_within_each_row() {
let gguf_holds = [0u8, 3, 1, 4, 2, 5];
let mut src = Vec::new();
for row in 0..2u8 {
for h in gguf_holds {
src.extend_from_slice(&[10 * row + h, 10 * row + h]);
}
}
let got = reorder(&src, 2, 12, 2, Reorder::Cols, HEADS).unwrap();
let want: Vec<u8> = (0..2u8)
.flat_map(|row| (0..6u8).flat_map(move |h| [10 * row + h, 10 * row + h]))
.collect();
assert_eq!(got, want);
}
#[test]
fn names_map_to_their_gguf_tensors() {
assert_eq!(
gguf_name("model.language_model.layers.7.linear_attn.out_proj.weight"),
Some(("blk.7.ssm_out.weight".into(), Reorder::Cols, false))
);
assert_eq!(
gguf_name("model.language_model.layers.3.self_attn.q_proj.weight"),
Some(("blk.3.attn_q.weight".into(), Reorder::None, false))
);
assert_eq!(
gguf_name("model.language_model.layers.0.linear_attn.in_proj_qkv.weight"),
Some((
"blk.0.attn_qkv.weight".into(),
Reorder::Rows { skip_rows: 0 },
true
))
);
assert_eq!(
gguf_name("model.language_model.hyper_connection_mixer.input_mix_weight_up.weight"),
Some(("output_hc_up.weight".into(), Reorder::None, false))
);
// Unmapped names — the indexer, the MTP head — stay dense.
assert_eq!(
gguf_name("model.language_model.layers.3.self_attn.indexer.index_qk_proj.weight"),
None
);
assert_eq!(gguf_name("mtp.layers.0.self_attn.q_proj.weight"), None);
}
#[test]
fn a_tensor_of_the_wrong_size_is_refused() {
assert!(reorder(&[0; 5], 2, 2, 0, Reorder::None, HEADS).is_err());
assert!(reorder(&[0; 14], 7, 2, 0, Reorder::Rows { skip_rows: 2 }, HEADS).is_err());
}
}
@@ -1,354 +0,0 @@
//! Where each tensor of a split GGUF lies.
//!
//! A deliberately small reader: the native expert path needs names,
//! shapes, types and absolute offsets, and must accept quantisation
//! types candle's GGUF reader has no enum value for.
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail, ensure};
/// One tensor's location.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GgufTensor {
pub shard: usize,
pub offset: u64,
/// In GGUF order, innermost dimension first.
pub dims: Vec<u64>,
pub ggml_type: u32,
}
/// Every tensor of a model, across its shards.
#[derive(Debug)]
pub struct GgufIndex {
pub shards: Vec<PathBuf>,
pub tensors: HashMap<String, GgufTensor>,
}
fn read_u32(r: &mut impl Read) -> Result<u32> {
let mut b = [0; 4];
r.read_exact(&mut b)?;
Ok(u32::from_le_bytes(b))
}
fn read_u64(r: &mut impl Read) -> Result<u64> {
let mut b = [0; 8];
r.read_exact(&mut b)?;
Ok(u64::from_le_bytes(b))
}
fn read_string(r: &mut impl Read) -> Result<String> {
let len = read_u64(r)?;
ensure!(len <= 1 << 30, "implausible GGUF string length {len}");
let mut b = vec![0; len as usize];
r.read_exact(&mut b)?;
String::from_utf8(b).context("GGUF string is not UTF-8")
}
fn skip(r: &mut (impl Read + Seek), bytes: i64) -> Result<()> {
r.seek(SeekFrom::Current(bytes))?;
Ok(())
}
fn scalar_size(value_type: u32) -> Option<i64> {
match value_type {
0 | 1 | 7 => Some(1),
2 | 3 => Some(2),
4..=6 => Some(4),
10..=12 => Some(8),
_ => None,
}
}
/// Skips one value, returning it when it is an unsigned 32-bit integer
/// (the type `general.alignment` is stored as).
fn skip_value(r: &mut (impl Read + Seek), value_type: u32) -> Result<Option<u32>> {
if value_type == 4 {
return Ok(Some(read_u32(r)?));
}
if let Some(size) = scalar_size(value_type) {
skip(r, size)?;
return Ok(None);
}
match value_type {
8 => {
let len = read_u64(r)?;
skip(r, i64::try_from(len)?)?;
}
9 => {
let element = read_u32(r)?;
let count = read_u64(r)?;
if let Some(size) = scalar_size(element) {
skip(
r,
size.checked_mul(i64::try_from(count)?)
.context("GGUF array size")?,
)?;
} else if element == 8 {
for _ in 0..count {
let len = read_u64(r)?;
skip(r, i64::try_from(len)?)?;
}
} else {
bail!("unsupported GGUF array element type {element}");
}
}
other => bail!("unknown GGUF value type {other}"),
}
Ok(None)
}
fn read_shard(path: &Path, shard: usize, out: &mut HashMap<String, GgufTensor>) -> Result<()> {
let mut r =
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
let mut magic = [0; 4];
r.read_exact(&mut magic)?;
ensure!(&magic == b"GGUF", "{} is not a GGUF file", path.display());
let version = read_u32(&mut r)?;
ensure!(version == 3, "{}: GGUF version {version}", path.display());
let n_tensors = read_u64(&mut r)?;
let n_kv = read_u64(&mut r)?;
let mut alignment = 32_u64;
for _ in 0..n_kv {
let key = read_string(&mut r)?;
let value_type = read_u32(&mut r)?;
if let Some(v) = skip_value(&mut r, value_type)?
&& key == "general.alignment"
{
ensure!(v > 0 && v.is_power_of_two(), "bad GGUF alignment {v}");
alignment = u64::from(v);
}
}
let mut found = Vec::with_capacity(n_tensors as usize);
for _ in 0..n_tensors {
let name = read_string(&mut r)?;
let n_dims = read_u32(&mut r)?;
ensure!(n_dims <= 8, "{name}: {n_dims} dimensions");
let dims = (0..n_dims)
.map(|_| read_u64(&mut r))
.collect::<Result<Vec<_>>>()?;
let ggml_type = read_u32(&mut r)?;
let offset = read_u64(&mut r)?;
found.push((name, dims, ggml_type, offset));
}
let header_end = r.stream_position()?;
let data_start = header_end.div_ceil(alignment) * alignment;
for (name, dims, ggml_type, offset) in found {
out.insert(
name,
GgufTensor {
shard,
offset: data_start + offset,
dims,
ggml_type,
},
);
}
Ok(())
}
/// The sibling paths of a `name-00001-of-0000N.gguf` shard, or the file
/// itself when it is not split.
fn shard_paths(first: &Path) -> Result<Vec<PathBuf>> {
let name = first
.file_name()
.and_then(|n| n.to_str())
.context("GGUF path has no file name")?;
let Some(stem) = name.strip_suffix(".gguf") else {
bail!("{name} is not a .gguf file");
};
let parts: Vec<&str> = stem.rsplitn(4, '-').collect();
if parts.len() == 4
&& parts[1] == "of"
&& parts[0].len() == 5
&& parts[2].len() == 5
&& let Ok(total) = parts[0].parse::<usize>()
{
let dir = first.parent().unwrap_or_else(|| Path::new("."));
return Ok((1..=total)
.map(|i| dir.join(format!("{}-{i:05}-of-{total:05}.gguf", parts[3])))
.collect());
}
Ok(vec![first.to_path_buf()])
}
impl GgufIndex {
/// Reads every shard of the model whose first shard is `first`.
pub fn open(first: &Path) -> Result<Self> {
let shards = shard_paths(first)?;
let mut tensors = HashMap::new();
for (i, path) in shards.iter().enumerate() {
read_shard(path, i, &mut tensors)?;
}
Ok(Self { shards, tensors })
}
}
/// The `(layer, expert)` pairs of a Strata expert profile, hottest first.
pub fn read_expert_profile(path: &Path, layers: usize, experts: usize) -> Result<Vec<(u16, u16)>> {
let blob = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
parse_expert_profile(&blob, layers, experts)
.with_context(|| format!("parse {}", path.display()))
}
fn parse_expert_profile(blob: &[u8], layers: usize, experts: usize) -> Result<Vec<(u16, u16)>> {
const HEADER: usize = 24;
ensure!(
blob.len() >= HEADER && &blob[..4] == b"STRP",
"not an expert profile"
);
let field = |i: usize| {
u32::from_le_bytes(blob[4 + i * 4..8 + i * 4].try_into().expect("four bytes")) as usize
};
ensure!(field(0) == 1, "profile version {}", field(0));
ensure!(
(field(1), field(2)) == (layers, experts),
"profile is {}x{}, the model is {layers}x{experts}",
field(1),
field(2)
);
let count = field(4);
ensure!(count <= layers * experts, "profile ranks {count} pairs");
ensure!(blob.len() >= HEADER + count * 4, "profile is truncated");
blob[HEADER..HEADER + count * 4]
.as_chunks::<4>()
.0
.iter()
.map(|pair| {
let layer = u16::from_le_bytes([pair[0], pair[1]]);
let expert = u16::from_le_bytes([pair[2], pair[3]]);
ensure!(
(layer as usize) < layers && (expert as usize) < experts,
"pair ({layer}, {expert}) is out of range"
);
Ok((layer, expert))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn string(out: &mut Vec<u8>, s: &str) {
out.extend((s.len() as u64).to_le_bytes());
out.extend(s.as_bytes());
}
/// A GGUF with one of each key shape the skipper must cross.
fn shard(alignment: u32, tensors: &[(&str, &[u64], u32, u64)]) -> Vec<u8> {
let mut b = b"GGUF".to_vec();
b.extend(3_u32.to_le_bytes());
b.extend((tensors.len() as u64).to_le_bytes());
b.extend(4_u64.to_le_bytes());
string(&mut b, "a.string");
b.extend(8_u32.to_le_bytes());
string(&mut b, "value");
string(&mut b, "a.array");
b.extend(9_u32.to_le_bytes());
b.extend(8_u32.to_le_bytes());
b.extend(2_u64.to_le_bytes());
string(&mut b, "x");
string(&mut b, "yz");
string(&mut b, "a.numbers");
b.extend(9_u32.to_le_bytes());
b.extend(5_u32.to_le_bytes());
b.extend(3_u64.to_le_bytes());
b.extend([0_u8; 12]);
string(&mut b, "general.alignment");
b.extend(4_u32.to_le_bytes());
b.extend(alignment.to_le_bytes());
for (name, dims, ty, offset) in tensors {
string(&mut b, name);
b.extend((dims.len() as u32).to_le_bytes());
for d in *dims {
b.extend(d.to_le_bytes());
}
b.extend(ty.to_le_bytes());
b.extend(offset.to_le_bytes());
}
b
}
#[test]
fn offsets_are_absolute_and_follow_the_alignment() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("m.gguf");
let bytes = shard(64, &[("t", &[2560, 640, 512], 21, 128)]);
let data_start = (bytes.len() as u64).div_ceil(64) * 64;
File::create(&path).unwrap().write_all(&bytes).unwrap();
let index = GgufIndex::open(&path).unwrap();
assert_eq!(
index.tensors["t"],
GgufTensor {
shard: 0,
offset: data_start + 128,
dims: vec![2560, 640, 512],
ggml_type: 21,
}
);
}
#[test]
fn split_models_are_read_from_every_shard() {
let dir = tempfile::tempdir().unwrap();
for (i, name) in ["a", "b"].iter().enumerate() {
let path = dir.path().join(format!("m-Q-{:05}-of-00002.gguf", i + 1));
let bytes = shard(32, &[(name, &[1], 8, 0)]);
File::create(path).unwrap().write_all(&bytes).unwrap();
}
let index = GgufIndex::open(&dir.path().join("m-Q-00001-of-00002.gguf")).unwrap();
assert_eq!(index.shards.len(), 2);
assert_eq!((index.tensors["a"].shard, index.tensors["b"].shard), (0, 1));
}
fn profile(version: u32, layers: u32, experts: u32, pairs: &[(u16, u16)]) -> Vec<u8> {
let mut b = b"STRP".to_vec();
for v in [
version,
layers,
experts,
layers * experts,
pairs.len() as u32,
] {
b.extend(v.to_le_bytes());
}
for (l, e) in pairs {
b.extend(l.to_le_bytes());
b.extend(e.to_le_bytes());
}
b
}
#[test]
fn a_profile_keeps_its_rank_order() {
let blob = profile(1, 2, 4, &[(1, 3), (0, 2)]);
assert_eq!(
parse_expert_profile(&blob, 2, 4).unwrap(),
vec![(1, 3), (0, 2)]
);
}
#[test]
fn a_profile_for_another_shape_or_out_of_range_is_refused() {
assert!(parse_expert_profile(&profile(1, 2, 4, &[]), 3, 4).is_err());
assert!(parse_expert_profile(&profile(2, 2, 4, &[]), 2, 4).is_err());
assert!(parse_expert_profile(&profile(1, 2, 4, &[(2, 0)]), 2, 4).is_err());
let truncated = profile(1, 2, 4, &[(1, 1)]);
assert!(parse_expert_profile(&truncated[..truncated.len() - 1], 2, 4).is_err());
}
#[test]
fn a_file_that_is_not_gguf_is_refused() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("m.gguf");
File::create(&path).unwrap().write_all(b"NOPE0000").unwrap();
assert!(GgufIndex::open(&path).is_err());
}
}
@@ -40,7 +40,6 @@ use candle_core::{D, Module, Tensor};
use candle_nn::Linear;
use candle_nn::var_builder::ShardedVarBuilder;
use crate::harness::arch::qwen3_5::proj::{LinearSource, Proj, load_proj};
use crate::harness::arch::qwen3_5::rmsnorm::Qwen3_5RmsNorm;
/// What a hyper-connection hands its sublayer.
@@ -57,8 +56,8 @@ pub struct HyperSplit {
/// `Qwen4ExpTextGatedResidual`.
pub struct HyperConnection {
hc_norm: Qwen3_5RmsNorm,
mix_down: Proj,
mix_up: Proj,
mix_down: Linear,
mix_up: Linear,
/// Absent on the top-level `hyper_connection_mixer`, which collapses
/// the streams for the LM head instead of feeding a sublayer.
block_inject: Option<Linear>,
@@ -74,13 +73,12 @@ impl HyperConnection {
hc_lowrank: usize,
eps: f64,
use_combine: bool,
source: Option<&dyn LinearSource>,
) -> Result<Self> {
let wide = hidden_size * hc_count;
let hc_norm = Qwen3_5RmsNorm::load_grouped(&vb.pp("hc_norm"), wide, hidden_size, eps)
.with_context(|| format!("load '{}/hc_norm'", vb.prefix()))?;
let mix_down = load_proj(vb, "input_mix_weight_down", wide, hc_lowrank, source)?;
let mix_up = load_proj(vb, "input_mix_weight_up", hc_lowrank, wide, source)?;
let mix_down = linear(vb, "input_mix_weight_down", wide, hc_lowrank)?;
let mix_up = linear(vb, "input_mix_weight_up", hc_lowrank, wide)?;
let block_inject = if use_combine {
Some(linear(vb, "block_inject_weight", wide, hc_count)?)
} else {
@@ -125,8 +123,8 @@ impl HyperConnection {
1e-6,
Some(hidden_size),
),
mix_down: z(hc_lowrank, wide).into(),
mix_up: z(wide, hc_lowrank).into(),
mix_down: z(hc_lowrank, wide),
mix_up: z(wide, hc_lowrank),
block_inject: use_combine.then(|| z(hc_count, wide)),
hidden_size,
hc_count,
@@ -31,15 +31,10 @@ use crate::harness::arch::qwen3_5::linear_attn::{
};
use super::config::TextConfig;
use crate::harness::arch::qwen3_5::proj::LinearSource;
/// `vb` should be `.pp(...)`-ed to the layer's `linear_attn` prefix.
pub fn load(
cfg: &TextConfig,
vb: &ShardedVarBuilder,
source: Option<&dyn LinearSource>,
) -> Result<GatedDeltaNet> {
GatedDeltaNet::load_with_source(params(cfg)?, vb, source)
pub fn load(cfg: &TextConfig, vb: &ShardedVarBuilder) -> Result<GatedDeltaNet> {
GatedDeltaNet::load_with_params(params(cfg)?, vb)
}
/// The settings this architecture asks for, as opposed to the ones
@@ -36,20 +36,12 @@
pub mod config;
pub mod decoder;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod engine;
pub mod full_attn;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod gguf_dense;
#[cfg(any(test, feature = "strata-kernels"))]
pub mod gguf_index;
pub mod hyper;
pub mod linear_attn;
pub mod model;
pub mod moe;
pub mod mtp;
#[cfg(feature = "strata-kernels")]
pub mod native_experts;
pub mod ple;
pub mod qsa;
@@ -95,14 +87,4 @@ pub struct LoadOptions<'a> {
/// Reading them straight into host memory removes the transit
/// rather than managing it.
pub experts_vb: Option<&'a candle_nn::var_builder::ShardedVarBuilder<'a>>,
/// VRAM tier for host-resident experts (#318). `None` computes them
/// where they live.
pub expert_tier: Option<std::sync::Arc<super::qwen3_5::moe::DeviceExpertTier>>,
/// Routed experts served outside candle. When set, the checkpoint's
/// expert tensors are not read at all.
pub external_experts: Option<std::sync::Arc<dyn super::qwen3_5::moe::ExternalExpertSource>>,
/// Dense projections served outside candle (a GGUF's quantized
/// blocks). Each is asked for by checkpoint name; what it declines
/// is read from the checkpoint.
pub dense: Option<std::sync::Arc<dyn super::qwen3_5::proj::LinearSource>>,
}
@@ -35,11 +35,10 @@
use anyhow::{Context, Result, ensure};
use candle_core::{DType, Device, IndexOp, Module, Tensor};
use candle_nn::Embedding;
use candle_nn::var_builder::ShardedVarBuilder;
use candle_nn::{Embedding, Linear};
use std::sync::Arc;
use crate::harness::arch::qwen3_5::proj::{Proj, load_proj};
use crate::harness::arch::qwen3_5::rope::RotaryEmbedding;
use super::config::{Config, TextConfig};
@@ -117,7 +116,7 @@ pub struct Qwen4ExpForCausalLM {
/// `hyper_connection_mixer` — `use_combine = false`, so it collapses
/// rather than scatters, and there is no final norm beside it.
mixer: HyperConnection,
lm_head: Proj,
lm_head: Linear,
ngram: Option<NGramEmbedding>,
rotary: Arc<RotaryEmbedding>,
hc_count: usize,
@@ -192,24 +191,19 @@ impl Qwen4ExpForCausalLM {
// No block_inject_weight in the checkpoint: this one ends
// the streams rather than feeding a sublayer.
false,
opts.dense.as_deref(),
)
.context("load hyper_connection_mixer")?;
let lm_head = load_proj(
vb,
"lm_head",
text.hidden_size,
text.vocab_size,
opts.dense.as_deref(),
)
.context("load 'lm_head.weight'")?;
let lm_head_weight = vb
.pp("lm_head")
.get((text.vocab_size, text.hidden_size), "weight")
.context("load 'lm_head.weight'")?;
Ok(Self {
embed_tokens,
layers,
mixer,
lm_head,
lm_head: Linear::new(lm_head_weight, None),
ngram,
rotary,
hc_count: text.hc_count,
@@ -238,25 +232,6 @@ 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)
@@ -532,7 +507,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.
pub fn rotary_for(cfg: &TextConfig, dtype: DType, device: &Device) -> Result<RotaryEmbedding> {
fn rotary_for(cfg: &TextConfig, dtype: DType, device: &Device) -> Result<RotaryEmbedding> {
RotaryEmbedding::from_parts(
dtype,
cfg.head_dim,
@@ -874,9 +849,6 @@ mod tests {
isq_cache: None,
experts_onto: &Device::Cpu,
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.unwrap();
@@ -99,7 +99,7 @@ pub fn load(
// A hit skips reading the fused tensors at all, which is the point:
// the cost being avoided is the 5.03 GB read *and* the ~32 s of
// quantisation, not just the latter.
let cached = match (quant, isq_cache.filter(|_| opts.external_experts.is_none())) {
let cached = match (quant, isq_cache) {
(Some(_), Some(cache)) => cache.load(&cache_key, experts_onto).and_then(|entries| {
match Experts::from_cache_entries(entries, cfg.num_experts) {
Ok(e) => Some(e),
@@ -113,19 +113,7 @@ pub fn load(
_ => None,
};
let external = match &opts.external_experts {
Some(source) => {
let layer = layer_of(&vb.prefix())
.with_context(|| format!("no layer index in '{}'", vb.prefix()))?;
Some(Experts::External {
count: cfg.num_experts,
inner: source.block(layer)?,
})
}
None => None,
};
let experts = match external.or(cached) {
let experts = match cached {
Some(experts) => experts,
None => {
let gate_up = experts_vb
@@ -163,11 +151,10 @@ pub fn load(
};
let (shared_expert, shared_expert_gate) = if cfg.shared_expert_intermediate_size > 0 {
let shared = Qwen3_5MLP::load_with_source(
let shared = Qwen3_5MLP::load_with_dims(
&vb.pp("shared_expert"),
h,
cfg.shared_expert_intermediate_size,
opts.dense.as_deref(),
)
.context("load shared_expert")?;
let gate_w = vb
@@ -186,16 +173,7 @@ pub fn load(
shared_expert_gate,
cfg.num_experts_per_tok,
cfg.norm_topk_prob,
)
.with_tier(opts.expert_tier.clone()))
}
/// The layer index in a tensor prefix such as
/// `model.language_model.layers.7.mlp`.
fn layer_of(prefix: &str) -> Option<usize> {
let mut parts = prefix.split('.');
parts.find(|p| *p == "layers")?;
parts.next()?.parse().ok()
))
}
/// Validate the fused pair before it is banked.
@@ -230,12 +208,6 @@ mod tests {
/// The loader validates the fused pair up front. Without this the
/// first token to route to a bad expert fails mid-forward, which is
/// a worse place to learn the checkpoint disagrees with the config.
#[test]
fn the_layer_index_comes_from_the_tensor_prefix() {
assert_eq!(layer_of("model.language_model.layers.17.mlp"), Some(17));
assert_eq!(layer_of("mtp.mlp"), None);
}
#[test]
fn a_fused_pair_that_disagrees_with_the_config_is_rejected() {
let dev = Device::Cpu;
@@ -124,9 +124,6 @@ impl MtpHead {
isq_cache: None,
experts_onto: vb.device(),
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.context("load mtp.layers.0")?,
@@ -137,7 +134,6 @@ impl MtpHead {
cfg.hc_lowrank,
cfg.rms_norm_eps,
false,
None,
)
.context("load mtp.hyper_connection_mixer")?,
hidden_size: h,
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,47 @@
//! Z-Image text-to-image models.
//!
//! Vendored from candle-transformers' `z_image` (huggingface/candle at
//! 0.11.0, MIT OR Apache-2.0; original module by SpenserCai) together
//! with neuron's four changes to it, which used to live in the
//! `grenade/candle` fork (#426): an all-ones attention-mask elision so
//! flash-attn engages (offered upstream as huggingface/candle#3798), the
//! quantized transformer `QuantizedZImageTransformer2DModel`, reuse of
//! the transformer's `Config`, and an f32 -> bf16 cast around flash-attn
//! on the quantized path. Changes here beyond those: crate paths.
//! Keeping the module here lets neuron depend on stock candle.
//!
//! Z-Image is a text-to-image generation model from Alibaba using Flow Matching.
//!
//! - 🤗 [Hugging Face Model](https://huggingface.co/Tongyi-MAI/Z-Image-Turbo)
//! - [Official Website](https://z-image-turbo.org/)
//!
//! # Example
//!
//! ```bash
//! cargo run --features metal --example z_image --release -- \
//! --prompt "A beautiful landscape" --height 1024 --width 1024
//! ```
//!
//! # Architecture
//!
//! - Transformer: ~24B parameters, 30 main layers + 2 noise_refiner + 2 context_refiner
//! - Text Encoder: Qwen3 (hidden_size=2560, 36 layers)
//! - VAE: AutoencoderKL (diffusers format)
//! - Scheduler: FlowMatchEulerDiscreteScheduler (shift=3.0)
pub mod preprocess;
pub mod quantized_transformer;
pub mod sampling;
pub mod scheduler;
pub mod text_encoder;
pub mod transformer;
pub mod vae;
// Re-export main types
pub use preprocess::{PreparedInputs, prepare_inputs};
pub use quantized_transformer::QuantizedZImageTransformer2DModel;
pub use sampling::{get_noise, get_schedule, postprocess_image};
pub use scheduler::{FlowMatchEulerDiscreteScheduler, SchedulerConfig, calculate_shift};
pub use text_encoder::{TextEncoderConfig, ZImageTextEncoder};
pub use transformer::{Config, ZImageTransformer2DModel};
pub use vae::{AutoEncoderKL, VaeConfig};
@@ -0,0 +1,169 @@
//! Input preprocessing utilities for Z-Image
//!
//! Provides padding and mask construction to convert variable-length inputs
//! into fixed-shape batch tensors.
use candle_core::{DType, Device, Result, Tensor};
use super::transformer::SEQ_MULTI_OF;
/// Preprocessed inputs structure
#[derive(Debug, Clone)]
pub struct PreparedInputs {
/// Latent tensor (B, C, 1, H, W)
pub latents: Tensor,
/// Padded caption features (B, max_text_len, dim)
pub cap_feats: Tensor,
/// Caption attention mask (B, max_text_len), 1=valid, 0=padding
pub cap_mask: Tensor,
/// Original text lengths for each sample
pub text_lengths: Vec<usize>,
}
/// Compute padding length to align to SEQ_MULTI_OF
#[inline]
pub fn compute_padding_len(ori_len: usize) -> usize {
(SEQ_MULTI_OF - (ori_len % SEQ_MULTI_OF)) % SEQ_MULTI_OF
}
/// Pad variable-length text embeddings to uniform length
///
/// # Arguments
/// * `text_embeddings` - Variable-length text embeddings, each of shape (seq_len, dim)
/// * `pad_value` - Padding value (typically 0.0)
/// * `device` - Device
///
/// # Returns
/// * Padded tensor (B, max_len, dim)
/// * Attention mask (B, max_len), 1=valid, 0=padding
/// * Original lengths
pub fn pad_text_embeddings(
text_embeddings: &[Tensor],
pad_value: f32,
device: &Device,
) -> Result<(Tensor, Tensor, Vec<usize>)> {
if text_embeddings.is_empty() {
candle_core::bail!("text_embeddings cannot be empty");
}
let batch_size = text_embeddings.len();
let dim = text_embeddings[0].dim(1)?;
let dtype = text_embeddings[0].dtype();
// Compute max length and align to SEQ_MULTI_OF
let lengths: Vec<usize> = text_embeddings
.iter()
.map(|t| t.dim(0))
.collect::<Result<Vec<_>>>()?;
let max_len = *lengths.iter().max().unwrap();
let padded_len = max_len + compute_padding_len(max_len);
// Build padded tensor and mask
let mut padded_list = Vec::with_capacity(batch_size);
let mut mask_list = Vec::with_capacity(batch_size);
for (i, emb) in text_embeddings.iter().enumerate() {
let seq_len = lengths[i];
let pad_len = padded_len - seq_len;
// Pad embedding
let padded = if pad_len > 0 {
let padding = Tensor::full(pad_value, (pad_len, dim), device)?.to_dtype(dtype)?;
Tensor::cat(&[emb, &padding], 0)?
} else {
emb.clone()
};
padded_list.push(padded);
// Create mask: 1 for valid, 0 for padding
let valid = Tensor::ones((seq_len,), DType::U8, device)?;
let mask = if pad_len > 0 {
let invalid = Tensor::zeros((pad_len,), DType::U8, device)?;
Tensor::cat(&[&valid, &invalid], 0)?
} else {
valid
};
mask_list.push(mask);
}
// Stack into batch
let cap_feats = Tensor::stack(&padded_list, 0)?;
let cap_mask = Tensor::stack(&mask_list, 0)?;
Ok((cap_feats, cap_mask, lengths))
}
/// Prepare all inputs, converting variable-length inputs to fixed-shape batch tensors
///
/// # Arguments
/// * `latents` - Latent tensor (B, C, H, W)
/// * `text_embeddings` - Variable-length text embeddings, each of shape (seq_len, cap_feat_dim)
/// * `device` - Device
///
/// # Returns
/// PreparedInputs containing all preprocessed tensors
pub fn prepare_inputs(
latents: &Tensor,
text_embeddings: &[Tensor],
device: &Device,
) -> Result<PreparedInputs> {
// Latents: (B, C, H, W) -> (B, C, 1, H, W) add frame dimension
let latents = latents.unsqueeze(2)?;
// Pad text embeddings
let (cap_feats, cap_mask, text_lengths) = pad_text_embeddings(text_embeddings, 0.0, device)?;
Ok(PreparedInputs {
latents,
cap_feats,
cap_mask,
text_lengths,
})
}
/// Create attention mask for a single sample
/// Useful for testing or simplified scenarios
pub fn create_attention_mask(
valid_len: usize,
total_len: usize,
device: &Device,
) -> Result<Tensor> {
let valid = Tensor::ones((valid_len,), DType::U8, device)?;
if valid_len < total_len {
let invalid = Tensor::zeros((total_len - valid_len,), DType::U8, device)?;
Tensor::cat(&[&valid, &invalid], 0)
} else {
Ok(valid)
}
}
/// Create a batch of uniform text embeddings
///
/// # Arguments
/// * `text_embedding` - Single text embedding (seq_len, dim)
/// * `batch_size` - Number of copies to create
///
/// # Returns
/// Batched text embeddings (batch_size, seq_len, dim)
pub fn batch_text_embedding(text_embedding: &Tensor, batch_size: usize) -> Result<Tensor> {
let (seq_len, dim) = text_embedding.dims2()?;
text_embedding
.unsqueeze(0)?
.broadcast_as((batch_size, seq_len, dim))?
.contiguous()
}
/// Create a batch of uniform masks
///
/// # Arguments
/// * `mask` - Single mask (seq_len,)
/// * `batch_size` - Number of copies to create
///
/// # Returns
/// Batched masks (batch_size, seq_len)
pub fn batch_mask(mask: &Tensor, batch_size: usize) -> Result<Tensor> {
let seq_len = mask.dim(0)?;
mask.unsqueeze(0)?
.broadcast_as((batch_size, seq_len))?
.contiguous()
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,133 @@
//! Sampling utilities for Z-Image model.
use candle_core::{DType, Device, Result, Tensor};
/// Generate initial Gaussian noise
///
/// # Arguments
/// * `batch_size` - Batch size
/// * `channels` - Number of channels (typically 16, VAE latent channels)
/// * `height` - Height (latent space, i.e., image_height / 16)
/// * `width` - Width (latent space)
/// * `device` - Compute device
///
/// # Returns
/// Noise tensor of shape (batch_size, channels, height, width)
pub fn get_noise(
batch_size: usize,
channels: usize,
height: usize,
width: usize,
device: &Device,
) -> Result<Tensor> {
Tensor::randn(0f32, 1.0, (batch_size, channels, height, width), device)
}
/// Get linear time schedule with shift
///
/// # Arguments
/// * `num_steps` - Number of inference steps
/// * `mu` - Time shift parameter (from calculate_shift)
///
/// # Returns
/// Time points from 1.0 to 0.0 (num_steps+1 points)
pub fn get_schedule(num_steps: usize, mu: f64) -> Vec<f64> {
let timesteps: Vec<f64> = (0..=num_steps)
.map(|v| v as f64 / num_steps as f64)
.rev()
.collect();
// Apply time shift (for Flow Matching)
timesteps
.into_iter()
.map(|t| {
if t <= 0.0 || t >= 1.0 {
t // boundary case
} else {
let e = mu.exp();
e / (e + (1.0 / t - 1.0))
}
})
.collect()
}
/// Post-process image from VAE output
/// Converts from [-1, 1] to [0, 255] u8 image
pub fn postprocess_image(image: &Tensor) -> Result<Tensor> {
let image = image.clamp(-1.0, 1.0)?;
let image = ((image + 1.0)? * 127.5)?;
image.to_dtype(DType::U8)
}
/// CFG configuration
#[derive(Debug, Clone)]
pub struct CfgConfig {
/// Guidance scale (typically 5.0)
pub guidance_scale: f64,
/// CFG truncation threshold (1.0 = full CFG, 0.0 = no CFG)
pub cfg_truncation: f64,
/// Whether to normalize CFG output
pub cfg_normalization: bool,
}
impl Default for CfgConfig {
fn default() -> Self {
Self {
guidance_scale: 5.0,
cfg_truncation: 1.0,
cfg_normalization: false,
}
}
}
/// Apply Classifier-Free Guidance
///
/// # Arguments
/// * `pos_pred` - Positive (conditional) prediction
/// * `neg_pred` - Negative (unconditional) prediction
/// * `cfg` - CFG configuration
/// * `t_norm` - Normalized time [0, 1]
pub fn apply_cfg(
pos_pred: &Tensor,
neg_pred: &Tensor,
cfg: &CfgConfig,
t_norm: f64,
) -> Result<Tensor> {
// CFG truncation: disable CFG in late sampling
let current_scale = if t_norm > cfg.cfg_truncation {
0.0
} else {
cfg.guidance_scale
};
if current_scale <= 0.0 {
return Ok(pos_pred.clone());
}
// CFG formula: pred = pos + scale * (pos - neg)
let diff = (pos_pred - neg_pred)?;
let pred = (pos_pred + (diff * current_scale)?)?;
// Optional: CFG normalization (limit output norm)
if cfg.cfg_normalization {
let ori_norm = pos_pred.sqr()?.sum_all()?.sqrt()?;
let new_norm = pred.sqr()?.sum_all()?.sqrt()?;
let ori_norm_val = ori_norm.to_scalar::<f32>()?;
let new_norm_val = new_norm.to_scalar::<f32>()?;
if new_norm_val > ori_norm_val {
let scale = ori_norm_val / new_norm_val;
return pred * scale as f64;
}
}
Ok(pred)
}
/// Scale latents to initial noise level
///
/// For flow matching, the initial sample should be pure noise.
/// This function scales the noise by the initial sigma.
pub fn scale_noise(noise: &Tensor, sigma: f64) -> Result<Tensor> {
noise * sigma
}
@@ -0,0 +1,237 @@
//! FlowMatch Euler Discrete Scheduler for Z-Image
//!
//! Implements the flow matching scheduler used in Z-Image generation.
use candle_core::{Result, Tensor};
/// FlowMatchEulerDiscreteScheduler configuration
#[derive(Debug, Clone, serde::Deserialize)]
pub struct SchedulerConfig {
#[serde(default = "default_num_train_timesteps")]
pub num_train_timesteps: usize,
#[serde(default = "default_shift")]
pub shift: f64,
#[serde(default)]
pub use_dynamic_shifting: bool,
}
fn default_num_train_timesteps() -> usize {
1000
}
fn default_shift() -> f64 {
3.0
}
impl Default for SchedulerConfig {
fn default() -> Self {
Self {
num_train_timesteps: default_num_train_timesteps(),
shift: default_shift(),
use_dynamic_shifting: false,
}
}
}
impl SchedulerConfig {
/// Create configuration for Z-Image Turbo
pub fn z_image_turbo() -> Self {
Self {
num_train_timesteps: 1000,
shift: 3.0,
use_dynamic_shifting: false,
}
}
}
/// FlowMatch Euler Discrete Scheduler
#[derive(Debug, Clone)]
pub struct FlowMatchEulerDiscreteScheduler {
/// Configuration
pub config: SchedulerConfig,
/// Timesteps for inference
pub timesteps: Vec<f64>,
/// Sigma values
pub sigmas: Vec<f64>,
/// Minimum sigma
pub sigma_min: f64,
/// Maximum sigma
pub sigma_max: f64,
/// Current step index
step_index: usize,
}
impl FlowMatchEulerDiscreteScheduler {
pub fn new(config: SchedulerConfig) -> Self {
let num_train_timesteps = config.num_train_timesteps;
let shift = config.shift;
// Generate initial sigmas
let timesteps: Vec<f64> = (1..=num_train_timesteps).rev().map(|t| t as f64).collect();
let sigmas: Vec<f64> = timesteps
.iter()
.map(|&t| t / num_train_timesteps as f64)
.collect();
// Apply shift
let sigmas: Vec<f64> = if !config.use_dynamic_shifting {
sigmas
.iter()
.map(|&s| shift * s / (1.0 + (shift - 1.0) * s))
.collect()
} else {
sigmas
};
let timesteps: Vec<f64> = sigmas
.iter()
.map(|&s| s * num_train_timesteps as f64)
.collect();
let sigma_max = sigmas[0];
let sigma_min = *sigmas.last().unwrap_or(&0.0);
Self {
config,
timesteps,
sigmas,
sigma_min,
sigma_max,
step_index: 0,
}
}
/// Set timesteps for inference
///
/// # Arguments
/// * `num_inference_steps` - Number of denoising steps
/// * `mu` - Optional time shift parameter (from calculate_shift)
pub fn set_timesteps(&mut self, num_inference_steps: usize, mu: Option<f64>) {
let sigma_max = self.sigmas[0];
let sigma_min = *self.sigmas.last().unwrap_or(&0.0);
// Linear interpolation to generate timesteps
let timesteps: Vec<f64> = (0..num_inference_steps)
.map(|i| {
let t = i as f64 / num_inference_steps as f64;
sigma_max * (1.0 - t) + sigma_min * t
})
.map(|s| s * self.config.num_train_timesteps as f64)
.collect();
let mut sigmas: Vec<f64> = timesteps
.iter()
.map(|&t| t / self.config.num_train_timesteps as f64)
.collect();
// Apply shift
if let Some(mu) = mu {
if self.config.use_dynamic_shifting {
// time_shift: exp(mu) / (exp(mu) + (1/t - 1))
sigmas = sigmas
.iter()
.map(|&t| {
if t <= 0.0 {
0.0
} else {
let e_mu = mu.exp();
e_mu / (e_mu + (1.0 / t - 1.0))
}
})
.collect();
}
} else if !self.config.use_dynamic_shifting {
let shift = self.config.shift;
sigmas = sigmas
.iter()
.map(|&s| shift * s / (1.0 + (shift - 1.0) * s))
.collect();
}
// Add terminal sigma = 0
sigmas.push(0.0);
self.timesteps = timesteps;
self.sigmas = sigmas;
self.step_index = 0;
}
/// Get current sigma value
pub fn current_sigma(&self) -> f64 {
self.sigmas[self.step_index]
}
/// Get current timestep (for model input)
/// Converts scheduler timestep to model input format: (1000 - t) / 1000
pub fn current_timestep_normalized(&self) -> f64 {
let t = self.timesteps.get(self.step_index).copied().unwrap_or(0.0);
(1000.0 - t) / 1000.0
}
/// Euler step
///
/// # Arguments
/// * `model_output` - Model predicted velocity field
/// * `sample` - Current sample x_t
///
/// # Returns
/// Next sample x_{t-1}
pub fn step(&mut self, model_output: &Tensor, sample: &Tensor) -> Result<Tensor> {
let sigma = self.sigmas[self.step_index];
let sigma_next = self.sigmas[self.step_index + 1];
let dt = sigma_next - sigma;
// prev_sample = sample + dt * model_output
let prev_sample = (sample + (model_output * dt)?)?;
self.step_index += 1;
Ok(prev_sample)
}
/// Reset scheduler state
pub fn reset(&mut self) {
self.step_index = 0;
}
/// Get number of inference steps
pub fn num_inference_steps(&self) -> usize {
self.timesteps.len()
}
/// Get current step index
pub fn step_index(&self) -> usize {
self.step_index
}
/// Check if denoising is complete
pub fn is_complete(&self) -> bool {
self.step_index >= self.timesteps.len()
}
}
/// Calculate timestep shift parameter mu
///
/// # Arguments
/// * `image_seq_len` - Image sequence length (after patchify)
/// * `base_seq_len` - Base sequence length (typically 256)
/// * `max_seq_len` - Maximum sequence length (typically 4096)
/// * `base_shift` - Base shift value (typically 0.5)
/// * `max_shift` - Maximum shift value (typically 1.15)
pub fn calculate_shift(
image_seq_len: usize,
base_seq_len: usize,
max_seq_len: usize,
base_shift: f64,
max_shift: f64,
) -> f64 {
let m = (max_shift - base_shift) / (max_seq_len - base_seq_len) as f64;
let b = base_shift - m * base_seq_len as f64;
image_seq_len as f64 * m + b
}
/// Constants for shift calculation
pub const BASE_IMAGE_SEQ_LEN: usize = 256;
pub const MAX_IMAGE_SEQ_LEN: usize = 4096;
pub const BASE_SHIFT: f64 = 0.5;
pub const MAX_SHIFT: f64 = 1.15;
@@ -0,0 +1,453 @@
//! Z-Image Text Encoder (Qwen3 Adapter)
//!
//! This module provides a Qwen3-based text encoder for Z-Image.
//! Key difference from the standard Qwen3 model:
//! - Returns the **second-to-last layer** hidden states (hidden_states[-2])
//! - Does NOT apply the final RMSNorm
use candle_core::{DType, Device, Module, Result, Tensor};
use candle_nn::{Activation, VarBuilder};
use candle_transformers::models::with_tracing::{Linear, RmsNorm, linear_b};
use std::sync::Arc;
/// Text Encoder configuration (Qwen3-based)
#[derive(Debug, Clone, serde::Deserialize)]
pub struct TextEncoderConfig {
#[serde(default = "default_vocab_size")]
pub vocab_size: usize,
#[serde(default = "default_hidden_size")]
pub hidden_size: usize,
#[serde(default = "default_intermediate_size")]
pub intermediate_size: usize,
#[serde(default = "default_num_hidden_layers")]
pub num_hidden_layers: usize,
#[serde(default = "default_num_attention_heads")]
pub num_attention_heads: usize,
#[serde(default = "default_num_key_value_heads")]
pub num_key_value_heads: usize,
#[serde(default = "default_head_dim")]
pub head_dim: usize,
#[serde(default = "default_rms_norm_eps")]
pub rms_norm_eps: f64,
#[serde(default = "default_rope_theta")]
pub rope_theta: f64,
#[serde(default = "default_attention_bias")]
pub attention_bias: bool,
#[serde(default = "default_hidden_act")]
pub hidden_act: Activation,
#[serde(default = "default_max_position_embeddings")]
pub max_position_embeddings: usize,
}
fn default_vocab_size() -> usize {
151936
}
fn default_hidden_size() -> usize {
2560
}
fn default_intermediate_size() -> usize {
9728
}
fn default_num_hidden_layers() -> usize {
36
}
fn default_num_attention_heads() -> usize {
32
}
fn default_num_key_value_heads() -> usize {
8
}
fn default_head_dim() -> usize {
128
}
fn default_rms_norm_eps() -> f64 {
1e-6
}
fn default_rope_theta() -> f64 {
1_000_000.0
}
fn default_attention_bias() -> bool {
false
}
fn default_hidden_act() -> Activation {
Activation::Silu
}
fn default_max_position_embeddings() -> usize {
40960
}
impl Default for TextEncoderConfig {
fn default() -> Self {
Self::z_image()
}
}
impl TextEncoderConfig {
/// Create configuration for Z-Image Text Encoder
pub fn z_image() -> Self {
Self {
vocab_size: 151936,
hidden_size: 2560,
intermediate_size: 9728,
num_hidden_layers: 36,
num_attention_heads: 32,
num_key_value_heads: 8,
head_dim: 128,
rms_norm_eps: 1e-6,
rope_theta: 1_000_000.0,
attention_bias: false,
hidden_act: Activation::Silu,
max_position_embeddings: 40960,
}
}
}
// ==================== Rotary Embedding ====================
#[derive(Debug, Clone)]
struct RotaryEmbedding {
sin: Tensor,
cos: Tensor,
}
impl RotaryEmbedding {
fn new(dtype: DType, cfg: &TextEncoderConfig, dev: &Device) -> Result<Self> {
let dim = cfg.head_dim;
let max_seq_len = cfg.max_position_embeddings;
let inv_freq: Vec<_> = (0..dim)
.step_by(2)
.map(|i| 1f32 / cfg.rope_theta.powf(i as f64 / dim as f64) as f32)
.collect();
let inv_freq_len = inv_freq.len();
let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(DType::F32)?;
let t = Tensor::arange(0u32, max_seq_len as u32, dev)?
.to_dtype(DType::F32)?
.reshape((max_seq_len, 1))?;
let freqs = t.matmul(&inv_freq)?;
Ok(Self {
sin: freqs.sin()?.to_dtype(dtype)?,
cos: freqs.cos()?.to_dtype(dtype)?,
})
}
/// Apply RoPE (q, k shape: B x H x L x D)
fn apply(&self, q: &Tensor, k: &Tensor, offset: usize) -> Result<(Tensor, Tensor)> {
let (_, _, seq_len, _) = q.dims4()?;
let cos = self.cos.narrow(0, offset, seq_len)?;
let sin = self.sin.narrow(0, offset, seq_len)?;
let q_embed = candle_nn::rotary_emb::rope(&q.contiguous()?, &cos, &sin)?;
let k_embed = candle_nn::rotary_emb::rope(&k.contiguous()?, &cos, &sin)?;
Ok((q_embed, k_embed))
}
}
// ==================== MLP ====================
#[derive(Debug, Clone)]
struct Mlp {
gate_proj: candle_nn::Linear,
up_proj: candle_nn::Linear,
down_proj: candle_nn::Linear,
act_fn: Activation,
}
impl Mlp {
fn new(cfg: &TextEncoderConfig, vb: VarBuilder) -> Result<Self> {
Ok(Self {
gate_proj: candle_nn::linear_no_bias(
cfg.hidden_size,
cfg.intermediate_size,
vb.pp("gate_proj"),
)?,
up_proj: candle_nn::linear_no_bias(
cfg.hidden_size,
cfg.intermediate_size,
vb.pp("up_proj"),
)?,
down_proj: candle_nn::linear_no_bias(
cfg.intermediate_size,
cfg.hidden_size,
vb.pp("down_proj"),
)?,
act_fn: cfg.hidden_act,
})
}
}
impl Module for Mlp {
fn forward(&self, x: &Tensor) -> Result<Tensor> {
let lhs = x.apply(&self.gate_proj)?.apply(&self.act_fn)?;
let rhs = x.apply(&self.up_proj)?;
(lhs * rhs)?.apply(&self.down_proj)
}
}
// ==================== Attention ====================
fn repeat_kv(x: Tensor, n_rep: usize) -> Result<Tensor> {
if n_rep == 1 {
Ok(x)
} else {
let (b_sz, n_kv_head, seq_len, head_dim) = x.dims4()?;
x.unsqueeze(2)?
.broadcast_as((b_sz, n_kv_head, n_rep, seq_len, head_dim))?
.reshape((b_sz, n_kv_head * n_rep, seq_len, head_dim))
}
}
#[derive(Debug, Clone)]
struct Attention {
q_proj: Linear,
k_proj: Linear,
v_proj: Linear,
o_proj: Linear,
q_norm: RmsNorm,
k_norm: RmsNorm,
num_heads: usize,
num_kv_heads: usize,
num_kv_groups: usize,
head_dim: usize,
hidden_size: usize,
rotary_emb: Arc<RotaryEmbedding>,
}
impl Attention {
fn new(
cfg: &TextEncoderConfig,
rotary_emb: Arc<RotaryEmbedding>,
vb: VarBuilder,
) -> Result<Self> {
let head_dim = cfg.head_dim;
let num_heads = cfg.num_attention_heads;
let num_kv_heads = cfg.num_key_value_heads;
let num_kv_groups = num_heads / num_kv_heads;
let q_proj = linear_b(
cfg.hidden_size,
num_heads * head_dim,
cfg.attention_bias,
vb.pp("q_proj"),
)?;
let k_proj = linear_b(
cfg.hidden_size,
num_kv_heads * head_dim,
cfg.attention_bias,
vb.pp("k_proj"),
)?;
let v_proj = linear_b(
cfg.hidden_size,
num_kv_heads * head_dim,
cfg.attention_bias,
vb.pp("v_proj"),
)?;
let o_proj = linear_b(
num_heads * head_dim,
cfg.hidden_size,
cfg.attention_bias,
vb.pp("o_proj"),
)?;
let q_norm = RmsNorm::new(head_dim, cfg.rms_norm_eps, vb.pp("q_norm"))?;
let k_norm = RmsNorm::new(head_dim, cfg.rms_norm_eps, vb.pp("k_norm"))?;
let hidden_size = head_dim * cfg.num_attention_heads;
Ok(Self {
q_proj,
k_proj,
v_proj,
o_proj,
q_norm,
k_norm,
num_heads,
num_kv_heads,
num_kv_groups,
head_dim,
hidden_size,
rotary_emb,
})
}
fn forward(&self, x: &Tensor, attn_mask: Option<&Tensor>, offset: usize) -> Result<Tensor> {
let (b, l, _) = x.dims3()?;
// 1. Proj
let q = self.q_proj.forward(x)?;
let k = self.k_proj.forward(x)?;
let v = self.v_proj.forward(x)?;
// 2. Reshape: (B, L, H, D) -> (B, H, L, D)
let q = q
.reshape((b, l, self.num_heads, self.head_dim))?
.transpose(1, 2)?;
let k = k
.reshape((b, l, self.num_kv_heads, self.head_dim))?
.transpose(1, 2)?;
let v = v
.reshape((b, l, self.num_kv_heads, self.head_dim))?
.transpose(1, 2)?;
// 3. Per-head RMSNorm
let q_flat = q.flatten(0, 2)?;
let k_flat = k.flatten(0, 2)?;
let q_flat = self.q_norm.forward(&q_flat)?;
let k_flat = self.k_norm.forward(&k_flat)?;
let q = q_flat.reshape((b, self.num_heads, l, self.head_dim))?;
let k = k_flat.reshape((b, self.num_kv_heads, l, self.head_dim))?;
// 4. RoPE
let (q, k) = self.rotary_emb.apply(&q, &k, offset)?;
// 5. GQA repeat_kv
let k = repeat_kv(k, self.num_kv_groups)?.contiguous()?;
let v = repeat_kv(v, self.num_kv_groups)?.contiguous()?;
// 6. Attention score
let scale = 1.0 / (self.head_dim as f64).sqrt();
let mut scores = (q.matmul(&k.transpose(2, 3)?)? * scale)?;
if let Some(m) = attn_mask {
scores = scores.broadcast_add(m)?;
}
let probs = candle_nn::ops::softmax_last_dim(&scores)?;
let ctx = probs.matmul(&v)?; // (B, H, L, D)
// 7. Output proj
ctx.transpose(1, 2)?
.reshape((b, l, self.hidden_size))?
.apply(&self.o_proj)
}
}
// ==================== Decoder Layer ====================
#[derive(Debug, Clone)]
struct DecoderLayer {
self_attn: Attention,
mlp: Mlp,
ln1: RmsNorm,
ln2: RmsNorm,
}
impl DecoderLayer {
fn new(cfg: &TextEncoderConfig, rotary: Arc<RotaryEmbedding>, vb: VarBuilder) -> Result<Self> {
let self_attn = Attention::new(cfg, rotary, vb.pp("self_attn"))?;
let mlp = Mlp::new(cfg, vb.pp("mlp"))?;
let ln1 = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("input_layernorm"))?;
let ln2 = RmsNorm::new(
cfg.hidden_size,
cfg.rms_norm_eps,
vb.pp("post_attention_layernorm"),
)?;
Ok(Self {
self_attn,
mlp,
ln1,
ln2,
})
}
fn forward(&self, x: &Tensor, mask: Option<&Tensor>, offset: usize) -> Result<Tensor> {
let h = self.ln1.forward(x)?;
let h = self.self_attn.forward(&h, mask, offset)?;
let x = (x + h)?;
let h2 = self.ln2.forward(&x)?;
let h2 = h2.apply(&self.mlp)?;
x + h2
}
}
// ==================== ZImageTextEncoder ====================
/// Z-Image Text Encoder (Qwen3-based)
///
/// Returns the second-to-last layer hidden states (hidden_states[-2])
/// without applying the final RMSNorm.
#[derive(Debug, Clone)]
pub struct ZImageTextEncoder {
embed_tokens: candle_nn::Embedding,
layers: Vec<DecoderLayer>,
num_hidden_layers: usize,
device: Device,
dtype: DType,
}
impl ZImageTextEncoder {
pub fn new(cfg: &TextEncoderConfig, vb: VarBuilder) -> Result<Self> {
// Note: weights have "model." prefix
let vb_model = vb.pp("model");
let embed_tokens =
candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_model.pp("embed_tokens"))?;
let rotary = Arc::new(RotaryEmbedding::new(vb.dtype(), cfg, vb.device())?);
let mut layers = Vec::with_capacity(cfg.num_hidden_layers);
let vb_layers = vb_model.pp("layers");
for i in 0..cfg.num_hidden_layers {
layers.push(DecoderLayer::new(cfg, rotary.clone(), vb_layers.pp(i))?);
}
// NOTE: We do NOT load the final norm (model.norm.weight)
// because we return the second-to-last layer output without final norm
Ok(Self {
embed_tokens,
layers,
num_hidden_layers: cfg.num_hidden_layers,
device: vb.device().clone(),
dtype: vb.dtype(),
})
}
/// Create causal attention mask
fn causal_mask(&self, b: usize, tgt: usize, offset: usize) -> Result<Tensor> {
let minf = f32::NEG_INFINITY;
let mask: Vec<_> = (0..tgt)
.flat_map(|i| {
(0..(tgt + offset)).map(move |j| if j <= i + offset { 0.0 } else { minf })
})
.collect();
Tensor::from_slice(&mask, (b, 1, tgt, tgt + offset), &self.device)?.to_dtype(self.dtype)
}
/// Encode text, returning second-to-last layer hidden states
///
/// # Arguments
/// * `input_ids` - Token IDs (B, seq_len)
///
/// # Returns
/// Hidden states (B, seq_len, hidden_size) from layer[-2]
///
/// **Important**: Returns raw output from layer[-2] WITHOUT final RMSNorm
pub fn forward(&self, input_ids: &Tensor) -> Result<Tensor> {
let (b, l) = input_ids.dims2()?;
let mut hidden_states = self.embed_tokens.forward(input_ids)?;
let causal = if l == 1 {
None
} else {
Some(self.causal_mask(b, l, 0)?)
};
// num_hidden_layers = 36, second-to-last layer index = 34
let target_layer = self.num_hidden_layers - 2;
for (i, layer) in self.layers.iter().enumerate() {
hidden_states = layer.forward(&hidden_states, causal.as_ref(), 0)?;
// Return after second-to-last layer, do NOT apply final norm
if i == target_layer {
return Ok(hidden_states);
}
}
// Should not reach here
candle_core::bail!("Layer index out of bounds")
}
/// Get the output dimension (hidden_size)
pub fn hidden_size(&self) -> usize {
// This is derived from embed_tokens weight shape
self.embed_tokens.embeddings().dim(1).unwrap_or(2560)
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,684 @@
//! Z-Image VAE (AutoEncoderKL) - Diffusers Format
//!
//! This VAE implementation uses the diffusers weight naming format,
//! which is different from the Flux autoencoder original format.
//!
//! Key differences from Flux autoencoder:
//! 1. Weight paths: `encoder.down_blocks.{i}.resnets.{j}.*` vs `encoder.down.{i}.block.{j}.*`
//! 2. Attention naming: `to_q/to_k/to_v/to_out.0.*` vs `q/k/v/proj_out.*`
//! 3. Shortcut naming: `conv_shortcut.*` vs `nin_shortcut.*`
use candle_core::{D, Module, Result, Tensor};
use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, VarBuilder, conv2d, group_norm};
// ==================== Config ====================
/// VAE configuration
#[derive(Debug, Clone, serde::Deserialize)]
pub struct VaeConfig {
#[serde(default = "default_in_channels")]
pub in_channels: usize,
#[serde(default = "default_out_channels")]
pub out_channels: usize,
#[serde(default = "default_latent_channels")]
pub latent_channels: usize,
#[serde(default = "default_block_out_channels")]
pub block_out_channels: Vec<usize>,
#[serde(default = "default_layers_per_block")]
pub layers_per_block: usize,
#[serde(default = "default_scaling_factor")]
pub scaling_factor: f64,
#[serde(default = "default_shift_factor")]
pub shift_factor: f64,
#[serde(default = "default_norm_num_groups")]
pub norm_num_groups: usize,
}
fn default_in_channels() -> usize {
3
}
fn default_out_channels() -> usize {
3
}
fn default_latent_channels() -> usize {
16
}
fn default_block_out_channels() -> Vec<usize> {
vec![128, 256, 512, 512]
}
fn default_layers_per_block() -> usize {
2
}
fn default_scaling_factor() -> f64 {
0.3611
}
fn default_shift_factor() -> f64 {
0.1159
}
fn default_norm_num_groups() -> usize {
32
}
impl Default for VaeConfig {
fn default() -> Self {
Self::z_image()
}
}
impl VaeConfig {
/// Create configuration for Z-Image VAE
pub fn z_image() -> Self {
Self {
in_channels: 3,
out_channels: 3,
latent_channels: 16,
block_out_channels: vec![128, 256, 512, 512],
layers_per_block: 2,
scaling_factor: 0.3611,
shift_factor: 0.1159,
norm_num_groups: 32,
}
}
}
// ==================== Attention ====================
fn scaled_dot_product_attention(q: &Tensor, k: &Tensor, v: &Tensor) -> Result<Tensor> {
let dim = q.dim(D::Minus1)?;
let scale_factor = 1.0 / (dim as f64).sqrt();
let attn_weights = (q.matmul(&k.t()?)? * scale_factor)?;
candle_nn::ops::softmax_last_dim(&attn_weights)?.matmul(v)
}
/// VAE Attention block (diffusers format)
///
/// Note: VAE attention uses Linear with bias (2D weight shape)
/// Unlike Transformer attention which uses linear_no_bias
#[derive(Debug, Clone)]
struct Attention {
group_norm: GroupNorm,
to_q: candle_nn::Linear,
to_k: candle_nn::Linear,
to_v: candle_nn::Linear,
to_out: candle_nn::Linear,
}
impl Attention {
fn new(channels: usize, num_groups: usize, vb: VarBuilder) -> Result<Self> {
let group_norm = group_norm(num_groups, channels, 1e-6, vb.pp("group_norm"))?;
// VAE attention uses Linear with bias
let to_q = candle_nn::linear(channels, channels, vb.pp("to_q"))?;
let to_k = candle_nn::linear(channels, channels, vb.pp("to_k"))?;
let to_v = candle_nn::linear(channels, channels, vb.pp("to_v"))?;
let to_out = candle_nn::linear(channels, channels, vb.pp("to_out").pp("0"))?;
Ok(Self {
group_norm,
to_q,
to_k,
to_v,
to_out,
})
}
}
impl Module for Attention {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let residual = xs;
let (b, c, h, w) = xs.dims4()?;
// GroupNorm
let xs = xs.apply(&self.group_norm)?;
// (B, C, H, W) -> (B, H, W, C) -> (B*H*W, C)
let xs = xs.permute((0, 2, 3, 1))?.reshape((b * h * w, c))?;
// Linear projections
let q = xs.apply(&self.to_q)?; // (B*H*W, C)
let k = xs.apply(&self.to_k)?;
let v = xs.apply(&self.to_v)?;
// Reshape for attention: (B*H*W, C) -> (B, H*W, C) -> (B, 1, H*W, C)
let q = q.reshape((b, h * w, c))?.unsqueeze(1)?;
let k = k.reshape((b, h * w, c))?.unsqueeze(1)?;
let v = v.reshape((b, h * w, c))?.unsqueeze(1)?;
// Scaled dot-product attention
let xs = scaled_dot_product_attention(&q, &k, &v)?;
// (B, 1, H*W, C) -> (B*H*W, C)
let xs = xs.squeeze(1)?.reshape((b * h * w, c))?;
// Output projection
let xs = xs.apply(&self.to_out)?;
// (B*H*W, C) -> (B, H, W, C) -> (B, C, H, W)
let xs = xs.reshape((b, h, w, c))?.permute((0, 3, 1, 2))?;
// Residual connection
xs + residual
}
}
// ==================== ResnetBlock2D ====================
/// ResNet block (diffusers format)
#[derive(Debug, Clone)]
struct ResnetBlock2D {
norm1: GroupNorm,
conv1: Conv2d,
norm2: GroupNorm,
conv2: Conv2d,
conv_shortcut: Option<Conv2d>,
}
impl ResnetBlock2D {
fn new(
in_channels: usize,
out_channels: usize,
num_groups: usize,
vb: VarBuilder,
) -> Result<Self> {
let conv_cfg = Conv2dConfig {
padding: 1,
..Default::default()
};
let norm1 = group_norm(num_groups, in_channels, 1e-6, vb.pp("norm1"))?;
let conv1 = conv2d(in_channels, out_channels, 3, conv_cfg, vb.pp("conv1"))?;
let norm2 = group_norm(num_groups, out_channels, 1e-6, vb.pp("norm2"))?;
let conv2 = conv2d(out_channels, out_channels, 3, conv_cfg, vb.pp("conv2"))?;
let conv_shortcut = if in_channels != out_channels {
Some(conv2d(
in_channels,
out_channels,
1,
Default::default(),
vb.pp("conv_shortcut"),
)?)
} else {
None
};
Ok(Self {
norm1,
conv1,
norm2,
conv2,
conv_shortcut,
})
}
}
impl Module for ResnetBlock2D {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let h = xs
.apply(&self.norm1)?
.apply(&candle_nn::Activation::Swish)?
.apply(&self.conv1)?
.apply(&self.norm2)?
.apply(&candle_nn::Activation::Swish)?
.apply(&self.conv2)?;
match &self.conv_shortcut {
Some(conv) => xs.apply(conv)? + h,
None => xs + h,
}
}
}
// ==================== DownEncoderBlock2D ====================
#[derive(Debug, Clone)]
struct Downsample2D {
conv: Conv2d,
}
impl Downsample2D {
fn new(channels: usize, vb: VarBuilder) -> Result<Self> {
let conv_cfg = Conv2dConfig {
stride: 2,
padding: 0,
..Default::default()
};
let conv = conv2d(channels, channels, 3, conv_cfg, vb.pp("conv"))?;
Ok(Self { conv })
}
}
impl Module for Downsample2D {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
// Manual padding: (0, 1, 0, 1) for right=1, bottom=1
let xs = xs.pad_with_zeros(D::Minus1, 0, 1)?; // width: right
let xs = xs.pad_with_zeros(D::Minus2, 0, 1)?; // height: bottom
xs.apply(&self.conv)
}
}
#[derive(Debug, Clone)]
struct DownEncoderBlock2D {
resnets: Vec<ResnetBlock2D>,
downsampler: Option<Downsample2D>,
}
impl DownEncoderBlock2D {
fn new(
in_channels: usize,
out_channels: usize,
num_layers: usize,
num_groups: usize,
add_downsample: bool,
vb: VarBuilder,
) -> Result<Self> {
let mut resnets = Vec::with_capacity(num_layers);
let vb_resnets = vb.pp("resnets");
for i in 0..num_layers {
let in_c = if i == 0 { in_channels } else { out_channels };
resnets.push(ResnetBlock2D::new(
in_c,
out_channels,
num_groups,
vb_resnets.pp(i),
)?);
}
let downsampler = if add_downsample {
Some(Downsample2D::new(
out_channels,
vb.pp("downsamplers").pp("0"),
)?)
} else {
None
};
Ok(Self {
resnets,
downsampler,
})
}
}
impl Module for DownEncoderBlock2D {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let mut h = xs.clone();
for resnet in &self.resnets {
h = h.apply(resnet)?;
}
if let Some(ds) = &self.downsampler {
h = h.apply(ds)?;
}
Ok(h)
}
}
// ==================== UpDecoderBlock2D ====================
#[derive(Debug, Clone)]
struct Upsample2D {
conv: Conv2d,
}
impl Upsample2D {
fn new(channels: usize, vb: VarBuilder) -> Result<Self> {
let conv_cfg = Conv2dConfig {
padding: 1,
..Default::default()
};
let conv = conv2d(channels, channels, 3, conv_cfg, vb.pp("conv"))?;
Ok(Self { conv })
}
}
impl Module for Upsample2D {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let (_, _, h, w) = xs.dims4()?;
xs.upsample_nearest2d(h * 2, w * 2)?.apply(&self.conv)
}
}
#[derive(Debug, Clone)]
struct UpDecoderBlock2D {
resnets: Vec<ResnetBlock2D>,
upsampler: Option<Upsample2D>,
}
impl UpDecoderBlock2D {
fn new(
in_channels: usize,
out_channels: usize,
num_layers: usize, // decoder has num_layers + 1 resnets per block
num_groups: usize,
add_upsample: bool,
vb: VarBuilder,
) -> Result<Self> {
let mut resnets = Vec::with_capacity(num_layers + 1);
let vb_resnets = vb.pp("resnets");
for i in 0..=num_layers {
let in_c = if i == 0 { in_channels } else { out_channels };
resnets.push(ResnetBlock2D::new(
in_c,
out_channels,
num_groups,
vb_resnets.pp(i),
)?);
}
let upsampler = if add_upsample {
Some(Upsample2D::new(out_channels, vb.pp("upsamplers").pp("0"))?)
} else {
None
};
Ok(Self { resnets, upsampler })
}
}
impl Module for UpDecoderBlock2D {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let mut h = xs.clone();
for resnet in &self.resnets {
h = h.apply(resnet)?;
}
if let Some(us) = &self.upsampler {
h = h.apply(us)?;
}
Ok(h)
}
}
// ==================== UNetMidBlock2D ====================
#[derive(Debug, Clone)]
struct UNetMidBlock2D {
resnet_0: ResnetBlock2D,
attention: Attention,
resnet_1: ResnetBlock2D,
}
impl UNetMidBlock2D {
fn new(channels: usize, num_groups: usize, vb: VarBuilder) -> Result<Self> {
let resnet_0 =
ResnetBlock2D::new(channels, channels, num_groups, vb.pp("resnets").pp("0"))?;
let attention = Attention::new(channels, num_groups, vb.pp("attentions").pp("0"))?;
let resnet_1 =
ResnetBlock2D::new(channels, channels, num_groups, vb.pp("resnets").pp("1"))?;
Ok(Self {
resnet_0,
attention,
resnet_1,
})
}
}
impl Module for UNetMidBlock2D {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
xs.apply(&self.resnet_0)?
.apply(&self.attention)?
.apply(&self.resnet_1)
}
}
// ==================== Encoder ====================
/// VAE Encoder
#[derive(Debug, Clone)]
pub struct Encoder {
conv_in: Conv2d,
down_blocks: Vec<DownEncoderBlock2D>,
mid_block: UNetMidBlock2D,
conv_norm_out: GroupNorm,
conv_out: Conv2d,
}
impl Encoder {
pub fn new(cfg: &VaeConfig, vb: VarBuilder) -> Result<Self> {
let conv_cfg = Conv2dConfig {
padding: 1,
..Default::default()
};
let conv_in = conv2d(
cfg.in_channels,
cfg.block_out_channels[0],
3,
conv_cfg,
vb.pp("conv_in"),
)?;
let mut down_blocks = Vec::with_capacity(cfg.block_out_channels.len());
let vb_down = vb.pp("down_blocks");
for (i, &out_channels) in cfg.block_out_channels.iter().enumerate() {
let in_channels = if i == 0 {
cfg.block_out_channels[0]
} else {
cfg.block_out_channels[i - 1]
};
let add_downsample = i < cfg.block_out_channels.len() - 1;
down_blocks.push(DownEncoderBlock2D::new(
in_channels,
out_channels,
cfg.layers_per_block,
cfg.norm_num_groups,
add_downsample,
vb_down.pp(i),
)?);
}
let mid_channels = *cfg.block_out_channels.last().unwrap();
let mid_block = UNetMidBlock2D::new(mid_channels, cfg.norm_num_groups, vb.pp("mid_block"))?;
let conv_norm_out = group_norm(
cfg.norm_num_groups,
mid_channels,
1e-6,
vb.pp("conv_norm_out"),
)?;
let conv_out = conv2d(
mid_channels,
2 * cfg.latent_channels,
3,
conv_cfg,
vb.pp("conv_out"),
)?;
Ok(Self {
conv_in,
down_blocks,
mid_block,
conv_norm_out,
conv_out,
})
}
}
impl Module for Encoder {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let mut h = xs.apply(&self.conv_in)?;
for block in &self.down_blocks {
h = h.apply(block)?;
}
h.apply(&self.mid_block)?
.apply(&self.conv_norm_out)?
.apply(&candle_nn::Activation::Swish)?
.apply(&self.conv_out)
}
}
// ==================== Decoder ====================
/// VAE Decoder
#[derive(Debug, Clone)]
pub struct Decoder {
conv_in: Conv2d,
mid_block: UNetMidBlock2D,
up_blocks: Vec<UpDecoderBlock2D>,
conv_norm_out: GroupNorm,
conv_out: Conv2d,
}
impl Decoder {
pub fn new(cfg: &VaeConfig, vb: VarBuilder) -> Result<Self> {
let conv_cfg = Conv2dConfig {
padding: 1,
..Default::default()
};
let mid_channels = *cfg.block_out_channels.last().unwrap();
let conv_in = conv2d(
cfg.latent_channels,
mid_channels,
3,
conv_cfg,
vb.pp("conv_in"),
)?;
let mid_block = UNetMidBlock2D::new(mid_channels, cfg.norm_num_groups, vb.pp("mid_block"))?;
// Decoder up_blocks order is reversed from encoder down_blocks
let reversed_channels: Vec<usize> = cfg.block_out_channels.iter().rev().cloned().collect();
let mut up_blocks = Vec::with_capacity(reversed_channels.len());
let vb_up = vb.pp("up_blocks");
for (i, &out_channels) in reversed_channels.iter().enumerate() {
let in_channels = if i == 0 {
mid_channels
} else {
reversed_channels[i - 1]
};
let add_upsample = i < reversed_channels.len() - 1;
up_blocks.push(UpDecoderBlock2D::new(
in_channels,
out_channels,
cfg.layers_per_block,
cfg.norm_num_groups,
add_upsample,
vb_up.pp(i),
)?);
}
let final_channels = *reversed_channels.last().unwrap();
let conv_norm_out = group_norm(
cfg.norm_num_groups,
final_channels,
1e-6,
vb.pp("conv_norm_out"),
)?;
let conv_out = conv2d(
final_channels,
cfg.out_channels,
3,
conv_cfg,
vb.pp("conv_out"),
)?;
Ok(Self {
conv_in,
mid_block,
up_blocks,
conv_norm_out,
conv_out,
})
}
}
impl Module for Decoder {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let mut h = xs.apply(&self.conv_in)?.apply(&self.mid_block)?;
for block in &self.up_blocks {
h = h.apply(block)?;
}
h.apply(&self.conv_norm_out)?
.apply(&candle_nn::Activation::Swish)?
.apply(&self.conv_out)
}
}
// ==================== DiagonalGaussian ====================
/// Diagonal Gaussian distribution sampling (VAE reparameterization trick)
#[derive(Debug, Clone)]
pub struct DiagonalGaussian {
sample: bool,
}
impl DiagonalGaussian {
pub fn new(sample: bool) -> Self {
Self { sample }
}
}
impl Module for DiagonalGaussian {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let chunks = xs.chunk(2, 1)?; // Split along channel dimension
let mean = &chunks[0];
let logvar = &chunks[1];
if self.sample {
let std = (logvar * 0.5)?.exp()?;
mean + (std * mean.randn_like(0., 1.)?)?
} else {
Ok(mean.clone())
}
}
}
// ==================== AutoEncoderKL ====================
/// Z-Image VAE (AutoEncoderKL) - Diffusers Format
#[derive(Debug, Clone)]
pub struct AutoEncoderKL {
encoder: Encoder,
decoder: Decoder,
reg: DiagonalGaussian,
scale_factor: f64,
shift_factor: f64,
}
impl AutoEncoderKL {
pub fn new(cfg: &VaeConfig, vb: VarBuilder) -> Result<Self> {
let encoder = Encoder::new(cfg, vb.pp("encoder"))?;
let decoder = Decoder::new(cfg, vb.pp("decoder"))?;
let reg = DiagonalGaussian::new(true);
Ok(Self {
encoder,
decoder,
reg,
scale_factor: cfg.scaling_factor,
shift_factor: cfg.shift_factor,
})
}
/// Encode image to latent space
/// xs: (B, 3, H, W) RGB image, range [-1, 1]
/// Returns: (B, latent_channels, H/8, W/8)
pub fn encode(&self, xs: &Tensor) -> Result<Tensor> {
let z = xs.apply(&self.encoder)?.apply(&self.reg)?;
(z - self.shift_factor)? * self.scale_factor
}
/// Decode latent to image
/// xs: (B, latent_channels, H/8, W/8)
/// Returns: (B, 3, H, W) RGB image, range [-1, 1]
pub fn decode(&self, xs: &Tensor) -> Result<Tensor> {
let xs = ((xs / self.scale_factor)? + self.shift_factor)?;
xs.apply(&self.decoder)
}
/// Get scaling factor
pub fn scale_factor(&self) -> f64 {
self.scale_factor
}
/// Get shift factor
pub fn shift_factor(&self) -> f64 {
self.shift_factor
}
}
impl Module for AutoEncoderKL {
fn forward(&self, xs: &Tensor) -> Result<Tensor> {
self.decode(&self.encode(xs)?)
}
}
+1 -15
View File
@@ -3067,9 +3067,6 @@ impl CandleHarness {
// choice here.
experts_onto: &device_for_load,
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.context("build qwen4_exp model")?;
@@ -4492,18 +4489,8 @@ impl Harness for CandleHarness {
// Publish the KV budget while nothing is in flight (#257) —
// the only moment a free-VRAM reading is not already net of
// some running sequence's reservations.
// The expert tier fills after this reading, so what it may
// come to hold is not available to KV.
let tier_reserved_mb = if matches!(
spec.expert_residency,
Some(cortex_core::harness::ExpertResidency::Host)
) {
super::arch::qwen3_5::expert_tier::configured_budget_mb().unwrap_or(0)
} else {
0
};
let budget = kv_budget_mb(
free_mb.saturating_sub(tier_reserved_mb),
free_mb,
&self.context_limit_cfg,
prefix_cache_reserved_mb(&self.prefix_cache_cfg),
);
@@ -4511,7 +4498,6 @@ impl Harness for CandleHarness {
tracing::info!(
model = %spec.model_id,
free_at_load_mb = free_mb,
tier_reserved_mb,
kv_budget_mb = budget,
"admission: KV budget published"
);
@@ -319,10 +319,6 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
reply,
} => {
let result = forward_logits(&mut state, handle, &tokens, offset);
trace_device_pool(&state, "forward", tokens.len());
if crate::harness::arch::qwen3_5::moe::prompt_chunk_streams_experts(tokens.len()) {
trim_device_pool(&state);
}
let _ = reply.send(result);
}
Job::AssembleKvBatch {
@@ -896,14 +892,6 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
// semantics in mod.rs for the Phase 3+ refinement.
}
/// `NEURON_CUDA_EVENT_TRACKING=0` turns cudarc's cross-stream event
/// tracking off for the worker's context. On by default until measured
/// across the fleet's models.
#[cfg(feature = "cuda")]
fn cuda_event_tracking() -> bool {
std::env::var("NEURON_CUDA_EVENT_TRACKING").map_or(true, |v| v != "0")
}
fn init_state(device_index: u32) -> DeviceWorkerState {
#[cfg(feature = "cuda")]
{
@@ -913,23 +901,6 @@ fn init_state(device_index: u32) -> DeviceWorkerState {
// CudaContext::new and Device::new_cuda end up sharing state.
let (device, ctx) = match candle_core::Device::new_cuda(device_index as usize) {
Ok(device) => match CudaContext::new(device_index as usize) {
Ok(ctx) if !cuda_event_tracking() => {
// cudarc gives every allocation two events and waits
// on them when it is freed, which only matters when
// a buffer crosses streams. All of this worker's
// work runs on candle's one stream, and the events
// cost ~74k driver calls per qwen4_exp decode token.
if let Ok(cuda) = device.as_cuda_device() {
// SAFETY: nothing has been allocated yet, and
// this context's work is on a single stream.
unsafe { cuda.disable_event_tracking() };
tracing::info!(device_index, "CUDA event tracking off");
}
if let Err(e) = ctx.bind_to_thread() {
tracing::warn!(device_index, error = ?e, "device worker: bind_to_thread failed");
}
(device, Some(ctx))
}
Ok(ctx) => {
if let Err(e) = ctx.bind_to_thread() {
tracing::warn!(
@@ -1092,63 +1063,6 @@ fn trim_device_pool(state: &DeviceWorkerState) {
);
}
/// Logs the device pool after a job when `NEURON_VRAM_TRACE` is set:
/// bytes live now, the job's peak, and bytes the pool holds from the
/// driver. The peak counter is reset, so each line covers one job.
/// Memory the driver reports used beyond `reserved` was allocated
/// outside the pool (context, library workspaces, synchronous allocs).
#[cfg(feature = "cuda")]
fn trace_device_pool(state: &DeviceWorkerState, job: &str, tokens: usize) {
use candle_core::cuda::cudarc::driver::{
result::{device, mem_pool},
sys::CUmemPool_attribute,
};
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ENABLED.get_or_init(|| std::env::var_os("NEURON_VRAM_TRACE").is_some()) {
return;
}
let Some(ctx) = state.ctx.as_ref() else {
return;
};
let Ok(pool) = (unsafe { device::get_default_mem_pool(ctx.cu_device()) }) else {
return;
};
let read = |attr: CUmemPool_attribute| -> u64 {
let mut value = 0_u64;
// SAFETY: these attributes are all cuuint64_t.
match unsafe { mem_pool::get_attribute(pool, attr, (&raw mut value).cast()) } {
Ok(()) => value >> 20,
Err(_) => 0,
}
};
let used = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_CURRENT);
let peak = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_HIGH);
let reserved = read(CUmemPool_attribute::CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT);
let mut zero = 0_u64;
// SAFETY: writing zero resets the high-water mark.
let _ = unsafe {
mem_pool::set_attribute(
pool,
CUmemPool_attribute::CU_MEMPOOL_ATTR_USED_MEM_HIGH,
(&raw mut zero).cast(),
)
};
let (free, total) = query_vram(state).unwrap_or((0, 0));
tracing::info!(
device_index = state.device_index,
job,
tokens,
pool_used_mb = used,
pool_peak_mb = peak,
pool_reserved_mb = reserved,
device_used_mb = total.saturating_sub(free),
"vram trace"
);
}
#[cfg(not(feature = "cuda"))]
fn trace_device_pool(_state: &DeviceWorkerState, _job: &str, _tokens: usize) {}
#[cfg(not(feature = "cuda"))]
fn trim_device_pool(_state: &DeviceWorkerState) {}
@@ -1434,19 +1348,6 @@ fn load_dense_inner(
} else {
None
};
// A byte budget, because what else the card must hold (KV,
// activations) is the operator's trade to make.
let tier_budget = crate::harness::arch::qwen3_5::expert_tier::configured_budget_mb()
.filter(|_| experts_on_host);
let external_experts =
native_expert_source(&cfg, device, experts_on_host, tier_budget)?;
let dense = native_dense_source(&cfg, device, external_experts.is_some())?;
let expert_tier = tier_budget
.filter(|_| external_experts.is_none())
.map(|mb| {
tracing::info!(budget_mb = mb, "VRAM expert tier enabled (#318)");
crate::harness::arch::qwen3_5::moe::DeviceExpertTier::new(mb << 20)
});
let model = crate::harness::arch::qwen4_exp::model::Qwen4ExpForCausalLM::load(
&cfg,
dtype,
@@ -1457,9 +1358,6 @@ fn load_dense_inner(
safetensors_paths,
isq_cache,
experts_vb: host_vb.as_ref(),
expert_tier,
external_experts,
dense,
// Host residency (#318) is what makes a model whose
// experts exceed VRAM loadable; everything else in
// the model still lands on the device.
@@ -1481,83 +1379,6 @@ fn load_dense_inner(
}
}
/// Strata's kernels over the GGUF named by `NEURON_STRATA_EXPERT_GGUF`.
#[cfg(feature = "strata-kernels")]
fn native_expert_source(
cfg: &crate::harness::arch::qwen4_exp::config::Config,
device: &candle_core::Device,
experts_on_host: bool,
tier_budget_mb: Option<u64>,
) -> anyhow::Result<
Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::moe::ExternalExpertSource>>,
> {
use crate::harness::arch::qwen4_exp::native_experts::{GgufExpertSource, NativeExpertFactory};
let Some(path) = std::env::var_os("NEURON_STRATA_EXPERT_GGUF").filter(|_| experts_on_host)
else {
return Ok(None);
};
let text = &cfg.text_config;
let source = GgufExpertSource::open(
std::path::Path::new(&path),
device,
text.num_hidden_layers,
text.num_experts,
text.hidden_size,
text.moe_intermediate_size,
tier_budget_mb,
)?;
Ok(Some(std::sync::Arc::new(NativeExpertFactory(
std::sync::Arc::new(source),
))))
}
#[cfg(not(feature = "strata-kernels"))]
fn native_expert_source(
_cfg: &crate::harness::arch::qwen4_exp::config::Config,
_device: &candle_core::Device,
_experts_on_host: bool,
_tier_budget_mb: Option<u64>,
) -> anyhow::Result<
Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::moe::ExternalExpertSource>>,
> {
Ok(None)
}
/// The GGUF's quantized dense weights, when `NEURON_STRATA_DENSE=1`
/// and the experts already come from that GGUF.
#[cfg(feature = "strata-kernels")]
fn native_dense_source(
cfg: &crate::harness::arch::qwen4_exp::config::Config,
device: &candle_core::Device,
native_experts: bool,
) -> anyhow::Result<Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::proj::LinearSource>>> {
use crate::harness::arch::qwen4_exp::gguf_dense::{GgufDenseSource, Heads};
let text = &cfg.text_config;
let enabled = std::env::var("NEURON_STRATA_DENSE").is_ok_and(|v| v == "1");
let Some(path) =
std::env::var_os("NEURON_STRATA_EXPERT_GGUF").filter(|_| enabled && native_experts)
else {
return Ok(None);
};
let heads = Heads {
key_heads: text.linear_num_key_heads,
value_heads: text.linear_num_value_heads,
head_dim: text.linear_value_head_dim,
};
let key_dim = text.linear_num_key_heads * text.linear_key_head_dim;
let source = GgufDenseSource::open(std::path::Path::new(&path), device, heads, key_dim)?;
Ok(Some(std::sync::Arc::new(source)))
}
#[cfg(not(feature = "strata-kernels"))]
fn native_dense_source(
_cfg: &crate::harness::arch::qwen4_exp::config::Config,
_device: &candle_core::Device,
_native_experts: bool,
) -> anyhow::Result<Option<std::sync::Arc<dyn crate::harness::arch::qwen3_5::proj::LinearSource>>> {
Ok(None)
}
/// Load the leader's TP shard on the worker thread. Reads the Comm
/// directly from `state.nccl`; no cross-thread Arc<Comm> transfer.
#[cfg(feature = "cuda")]
+5 -5
View File
@@ -18,15 +18,15 @@
//! Everything in this module except [`ZImagePipeline::load`] and the
//! forward passes is pure CPU logic, unit-testable without weights.
use anyhow::{Context, Result};
use candle_core::quantized::GgmlDType;
use candle_core::{DType, Device, IndexOp, Tensor};
use candle_nn::VarBuilder;
use candle_transformers::models::z_image::{
use crate::harness::arch::z_image::{
AutoEncoderKL, Config as DitConfig, FlowMatchEulerDiscreteScheduler,
QuantizedZImageTransformer2DModel, SchedulerConfig, TextEncoderConfig, VaeConfig,
ZImageTextEncoder, ZImageTransformer2DModel, calculate_shift, get_noise, postprocess_image,
};
use anyhow::{Context, Result};
use candle_core::quantized::GgmlDType;
use candle_core::{DType, Device, IndexOp, Tensor};
use candle_nn::VarBuilder;
use std::path::PathBuf;
/// Scheduler shift constants from the reference pipeline. Identical to
@@ -423,9 +423,6 @@ fn qwen4_exp_case(name: &str, max_abs_bound: f32) {
isq_cache: None,
experts_onto: &device,
experts_vb: None,
expert_tier: None,
external_experts: None,
dense: None,
},
)
.expect("load the fixture through the production loader");
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 Niko1221 and the Strata contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-21
View File
@@ -1,21 +0,0 @@
# Vendored from Strata
These files are an unmodified subset of [Strata](https://github.com/Niko1221/Strata)
at commit `6a6db7ff58c283cf28d2b913404b5fa31a767eaa`, kept at their upstream paths so
their relative includes work and so they can be diffed against upstream.
- Strata is MIT licensed. See `LICENSE`.
- Its quantised-block layouts and dot products derive from llama.cpp / ggml, also MIT
licensed. See `engine/third_party/ggml/LICENSE` and `VERSION.txt`.
To update, copy the same paths from a newer upstream commit and change the commit above.
Do not edit these files in place; neuron's adapter is `crates/neuron/src/cuda/strata_adapter/strata_shim.cu`.
## Decode kernels for the native engine (#427)
Added from the same Strata revision for neuron's native qwen4_exp decode
engine, unmodified: `native_gdn`, `native_gdn_preprocess`, `fused_gdn`,
`native_gr_norm`, `native_gr_postops`, `gr`, `native_router`, `native_moe`,
`quantize_act`, `bf16_gemv` and `native_bf16` (`engine/src/kernels/cuda/`),
with the headers they include. neuron calls them through
`src/cuda/strata_adapter/engine_shim.cu`.
@@ -1,77 +0,0 @@
// include/strata/artifact/model_family.hpp - which model family a GGUF holds, from its general.architecture.
//
// Strata was written for one model (Qwen3.8-Flash-Next, `qwen4exp`). Qwen3.6-35B-A3B (`qwen35moe`) is a close
// cousin (same tokenizer, the same Gated-DeltaNet + gated-attention 3:1 layer pattern, the same head dims), so the
// reader, the geometry and the layout tables know both. The ENGINE runs only the families `model_family_runs`
// names; a recognised family it does not run yet is refused with `model_family_not_supported`, not mis-run.
//
// No dependencies: the GGUF reader (the architecture guard) and the core geometry both include this.
#pragma once
#include <string>
namespace strata {
enum class ModelFamily {
Unknown = 0,
Qwen4Exp, ///< Qwen3.8-Flash-Next and its fine-tunes / pruned variants (Swift 1.5, the Coder)
Qwen35Moe, ///< Qwen3.6-35B-A3B (Unsloth's MTP GGUFs): plain pre-norm residual, dense attention, nextn MTP block
Hy4Flash, ///< Tencent Hy4-Flash 220B-A12B (LatentMoE + Hybrid MLA/IndexPool + 4-Module Engram + 5L DFly2)
Inkling2Loop, ///< Thinking Machines Inkling 2 Mini 26.4B-A3.4B/5.4B (24->48 Looped MoE + SITU + AttnRes + ShortConv + DSpark)
};
inline ModelFamily model_family_from_arch(const std::string& arch) {
if (arch == "qwen4exp") return ModelFamily::Qwen4Exp;
if (arch == "qwen35moe") return ModelFamily::Qwen35Moe;
if (arch == "hy_v4_flash") return ModelFamily::Hy4Flash;
if (arch == "inkling2" || arch == "inkling2_loop" || arch == "inkling2_loop_text") return ModelFamily::Inkling2Loop;
return ModelFamily::Unknown;
}
/// The GGUF architecture string (also the metadata key prefix: "<arch>.block_count").
inline const char* model_family_arch(ModelFamily f) {
switch (f) {
case ModelFamily::Qwen4Exp:
return "qwen4exp";
case ModelFamily::Qwen35Moe:
return "qwen35moe";
case ModelFamily::Hy4Flash:
return "hy_v4_flash";
case ModelFamily::Inkling2Loop:
return "inkling2_loop";
default:
return "";
}
}
/// The model's name for messages.
inline const char* model_family_title(ModelFamily f) {
switch (f) {
case ModelFamily::Qwen4Exp:
return "Qwen3.8-Flash-Next";
case ModelFamily::Qwen35Moe:
return "Qwen3.6-35B-A3B";
case ModelFamily::Hy4Flash:
return "Tencent Hy4-Flash";
case ModelFamily::Inkling2Loop:
return "Thinking Machines Inkling 2 Mini";
default:
return "an unknown model";
}
}
/// Whether Flash-Next's engine path runs the family. Qwen3.6 has an engine path of its own (src/qwen35), which the
/// CUDA and HIP builds of `strata` switch to at the top of main(); the Intel Arc (SYCL) build has none yet, so there
/// (and on Flash-Next's path) the family is refused with `model_family_not_supported`.
inline bool model_family_runs(ModelFamily f) { return f == ModelFamily::Qwen4Exp; }
/// The refusal for a recognised family the engine does not run (empty when it runs it).
inline std::string model_family_not_supported(ModelFamily f) {
if (model_family_runs(f)) return {};
if (f == ModelFamily::Unknown) return "this is not a model family Strata knows";
return std::string(model_family_title(f)) + " (architecture '" + model_family_arch(f) +
"') runs on the NVIDIA (CUDA) and AMD (HIP) builds of Strata; this build does not run it yet (the Intel "
"Arc / SYCL port is in development). Use a CUDA or HIP build, or a Qwen3.8-Flash-Next model file";
}
} // namespace strata
@@ -1,21 +0,0 @@
// 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
@@ -1,41 +0,0 @@
// include/strata/core/defaults_026.hpp - STRATA_DEFAULTS=026: the master switch of the Qwen engine's 0.2.7 defaults.
//
// Every default the Qwen engine (`strata`) changed since v0.2.6 goes back to what v0.2.6 did when STRATA_DEFAULTS=026 is in the
// environment (the app's "off" for its speed switches sends it): the wide
// hyper-connection up read (STRATA_GR_UP_WIDE), the stream-split hyper-connection read (STRATA_GR_V3), the int8 prompt attention
// (STRATA_PROMPT_ATTN_IMMA), the four gfx12 decode switches of the arch table, the PLE residency policy (STRATA_PLE_AUTO_RAM), and the
// gfx12 decode miss split of 0.15 (back to 0.55). KVA is off by default in 0.2.7 and stays whatever STRATA_KVA says.
// The residency-biased routing (STRATA_ROUTE_PRIOR) was in this set in 0.2.7; it is off by default again (owner, 2026-10-29), so the master switch
// has nothing to take back there, and route_prior_default() answers 0 with the switch on or off.
// An explicit per-feature variable (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, STRATA_PLE_AUTO_RAM=1, ...) or flag (--pcie-frac, --ple-io)
// still wins over the master switch. Each rule is a pure function that takes the answer of qwen_defaults_026() as its `v026`
// argument, so a test can check both settings without touching the environment (src/core/arch_defaults_test.cpp,
// src/core/ple_residency_test.cpp).
#pragma once
#include <cstdlib>
#include <cstring>
namespace strata {
/// "026", "0.2.6" and "v0.2.6" name version 0.2.6; anything else (unset, "", "0", "027") does not.
inline bool is_026_token(const char* v) {
return v != nullptr && (std::strcmp(v, "026") == 0 || std::strcmp(v, "0.2.6") == 0 || std::strcmp(v, "v0.2.6") == 0);
}
/// STRATA_DEFAULTS=026 (read once).
inline bool qwen_defaults_026() {
static const bool on = is_026_token(std::getenv("STRATA_DEFAULTS"));
return on;
}
/// The decode miss split's start value (the share of a native pack's missing experts the CPU pool takes) when --pcie-frac is not given:
/// NVFP4 packs 0.25, other native packs 0.55 (the x16 share), and 0.15 on gfx12 (0.2.7) unless STRATA_PCIE_FRAC_DEFAULT=old or the master
/// switch is 026; a canonical pack 0.2.
inline double pcie_start_frac(bool nvfp4_pack, bool native_pack, bool gfx12_default, bool pf_old, bool v026 = false) {
if (nvfp4_pack) return 0.25;
if (!native_pack) return 0.2;
return gfx12_default && !pf_old && !v026 ? 0.15 : 0.55;
}
} // namespace strata
@@ -1,154 +0,0 @@
// strata/core/dispatch_stats.hpp - aggregate dispatch counters (BW-MEASURE, P0.2 of the Blackwell plan).
//
// Which kernel path a run really took: the dense projection kernel by type and shape, the grouped expert path, the hyper-connection
// format, the head, the all-resident or partial window graph, and why a fast path was declined. Counted where a path is CHOSEN:
// * inside a graph capture (Verifier::record_window): once per recorded window, binned by the window width T and the graph kind;
// a run's total calls = counts of that bin x how often that graph was launched (graph_launch(), one increment per launch);
// * outside a capture (the draft head, the prompt path): every call, bin "eager".
// Nothing is read back from the device and nothing runs inside a timed device region. A call costs one mutex and one hash lookup
// (tens of ns, against a kernel launch of microseconds); STRATA_DISPATCH_STATS=0 turns it off.
//
// The report is JSON, written at exit when STRATA_DISPATCH_REPORT=<path> is set (and by the CLI's --stats to stdout as "dispatch").
// Header only, standard C++17, no CUDA / HIP / SYCL / Metal types: every backend compiles it.
#pragma once
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace strata::dispatch {
struct Key {
uint16_t cat = 0, var = 0, scope = 0, t = 0, ncols = 0, pad = 0;
uint32_t n_in = 0, n_out = 0;
bool operator==(const Key& o) const { return std::memcmp(this, &o, sizeof(Key)) == 0; }
};
struct KeyHash {
size_t operator()(const Key& k) const {
uint64_t a, b;
std::memcpy(&a, reinterpret_cast<const char*>(&k), 8);
std::memcpy(&b, reinterpret_cast<const char*>(&k) + 8, 8);
uint64_t h = a * 0x9E3779B97F4A7C15ull ^ (b + 0x7F4A7C159E3779B9ull + (a << 6) + (a >> 2));
h ^= h >> 29;
return (size_t) h;
}
};
enum Cat : uint16_t { kStr = 0, kDense = 1, kExpert = 2, kHc = 3, kHead = 4, kWindow = 5 };
class Stats {
public:
// leaked on purpose: the atexit report must not run after the maps are destroyed
static Stats& get() { static Stats* s = new Stats(); return *s; }
bool on() const { return on_; }
// the current thread's bin: 0 = eager, else 1 + (T * 4 + kind) of the graph being captured
static uint16_t& scope() { thread_local uint16_t s = 0; return s; }
void count(const Key& k, uint64_t n = 1) {
if (!on_) return;
std::lock_guard<std::mutex> lk(m_);
map_[k] += n;
}
// a free-text path / reason; interned once per distinct text
void note(const char* text, uint64_t n = 1) {
if (!on_) return;
std::lock_guard<std::mutex> lk(m_);
auto it = intern_.find(text);
uint16_t id;
if (it == intern_.end()) { id = (uint16_t) names_.size(); names_.push_back(text); intern_.emplace(text, id); }
else id = it->second;
Key k; k.cat = kStr; k.var = id; k.scope = scope();
map_[k] += n;
}
void graph_launch(int T, int kind) { // kind: 0 all-resident graph, 1 doorbell (partial) graph, 2 other
if (!on_) return;
if (T < 0 || T > 63) return;
launches_[T][kind & 3].fetch_add(1, std::memory_order_relaxed);
}
void graph_capture(int T, int kind) { note_capture_(T, kind); }
std::string json() {
std::lock_guard<std::mutex> lk(m_);
std::string o = "{\n \"launches\": {";
bool first = true;
for (int t = 0; t < 64; ++t)
for (int k = 0; k < 4; ++k) {
const uint64_t n = launches_[t][k].load();
if (n == 0) continue;
char b[96];
std::snprintf(b, sizeof b, "%s\"T%d/k%d\": %llu", first ? "" : ", ", t, k, (unsigned long long) n);
o += b; first = false;
}
o += "},\n \"counts\": [\n";
first = true;
for (const auto& kv : map_) {
const Key& k = kv.first;
char b[512];
const int sc = k.scope == 0 ? -1 : (k.scope - 1) / 4, kd = k.scope == 0 ? -1 : (k.scope - 1) % 4;
if (k.cat == kStr)
std::snprintf(b, sizeof b, "%s {\"scope\": [%d, %d], \"cat\": \"str\", \"key\": \"%s\", \"n\": %llu}", first ? "" : ",\n",
sc, kd, k.var < names_.size() ? names_[k.var].c_str() : "?", (unsigned long long) kv.second);
else
std::snprintf(b, sizeof b,
"%s {\"scope\": [%d, %d], \"cat\": %u, \"var\": %u, \"type\": %u, \"ncols\": %u, \"n_in\": %u, \"n_out\": %u, \"n\": %llu}",
first ? "" : ",\n", sc, kd, k.cat, k.var, k.t, k.ncols, k.n_in, k.n_out, (unsigned long long) kv.second);
o += b; first = false;
}
o += "\n ]\n}\n";
return o;
}
void write_report() {
const char* p = std::getenv("STRATA_DISPATCH_REPORT");
if (!on_ || p == nullptr || p[0] == '\0') return;
const std::string j = json();
if (std::FILE* f = std::fopen(p, "wb")) { std::fwrite(j.data(), 1, j.size(), f); std::fclose(f); }
}
private:
Stats() {
const char* e = std::getenv("STRATA_DISPATCH_STATS");
on_ = e == nullptr || e[0] != '0';
for (auto& r : launches_) for (auto& c : r) c.store(0);
if (on_) std::atexit([] { Stats::get().write_report(); });
}
void note_capture_(int T, int kind) { note(("capture T" + std::to_string(T) + "/k" + std::to_string(kind)).c_str()); }
bool on_ = true;
std::mutex m_;
std::unordered_map<Key, uint64_t, KeyHash> map_;
std::unordered_map<std::string, uint16_t> intern_;
std::vector<std::string> names_;
std::atomic<uint64_t> launches_[64][4];
};
// RAII: while alive, this thread's counts go to the bin of a T-token graph of the given kind
struct Scope {
uint16_t prev;
Scope(int T, int kind) : prev(Stats::scope()) { Stats::scope() = (uint16_t) (1 + T * 4 + (kind & 3)); }
~Scope() { Stats::scope() = prev; }
};
// a kernel-level choice: a dense projection / expert / hc / head launch with its shape
inline void kernel(Cat cat, int variant, int type, int n_in, int n_out, int ncols) {
Stats& s = Stats::get();
if (!s.on()) return;
Key k; k.cat = cat; k.var = (uint16_t) variant; k.t = (uint16_t) type; k.ncols = (uint16_t) ncols;
k.n_in = (uint32_t) n_in; k.n_out = (uint32_t) n_out; k.scope = Stats::scope();
s.count(k);
}
inline void note(const char* text) { Stats::get().note(text); }
inline void notef(const char* fmt, long a = 0, long b = 0, long c = 0) {
Stats& s = Stats::get();
if (!s.on()) return;
char buf[200];
std::snprintf(buf, sizeof buf, fmt, a, b, c);
s.note(buf);
}
} // namespace strata::dispatch
@@ -1,94 +0,0 @@
// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only).
//
// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer
// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the
// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for:
// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that
// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's.
#pragma once
#include <cstdlib>
#if defined(__linux__) && !defined(__HIPCC__) && !defined(STRATA_GPU_METAL)
#include <dlfcn.h>
#include <string>
#endif
namespace strata {
/// nbald/volta-forever version string when running under the CUDA 13 Volta compatibility proxy (libcuda.so.1
/// exports volta_forever_version()), or "" when not loaded. Cached once per process.
inline const char* volta_forever_version() {
#if defined(__linux__) && !defined(__HIPCC__) && !defined(STRATA_GPU_METAL)
static const std::string ver = []() -> std::string {
using Fn = const char* (*)();
auto probe = [](void* handle) -> std::string {
if (!handle) return {};
void* sym = dlsym(handle, "volta_forever_version");
if (!sym) return {};
const char* s = reinterpret_cast<Fn>(sym)();
return s ? std::string(s) : std::string();
};
std::string out;
#ifdef RTLD_DEFAULT
out = probe(RTLD_DEFAULT);
if (!out.empty()) return out;
#endif
#ifdef RTLD_NOLOAD
if (void* h = dlopen("libcuda.so.1", RTLD_LAZY | RTLD_NOLOAD)) {
out = probe(h);
dlclose(h);
if (!out.empty()) return out;
}
#endif
if (void* h = dlopen("libcuda.so.1", RTLD_LAZY | RTLD_LOCAL)) {
out = probe(h);
dlclose(h);
if (!out.empty()) return out;
}
return {};
}();
return ver.c_str();
#else
return "";
#endif
}
inline bool volta_forever_active() { return volta_forever_version()[0] != '\0'; }
/// the emulated compute capability as 10 * major + minor, or 0 (off)
inline int emulated_cc() {
static const int cc = [] {
const char* e = std::getenv("STRATA_EMULATE_CC");
const int v = e ? std::atoi(e) : 0;
return v >= 75 && v < 120 ? v : 0;
}();
return cc;
}
/// Effective compute capability (10 * major + minor). STRATA_EMULATE_CC wins; otherwise under
/// nbald/volta-forever (which spoofs physical Volta 7.0 as 7.5 for CUDA 13 binaries), remap 7.5 -> 7.0.
inline int cc_of(int real_major, int real_minor, bool vf_active) {
if (const int e = emulated_cc()) return e;
if (vf_active && real_major == 7 && real_minor == 5) return 70;
return 10 * real_major + real_minor;
}
inline int cc_of(int real_major, int real_minor) {
return cc_of(real_major, real_minor, volta_forever_active());
}
inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; }
inline int cc_minor_of(int real_minor) {
if (const int e = emulated_cc()) return e % 10;
if (volta_forever_active() && real_minor == 5) return 0;
return real_minor;
}
/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100,
/// 99 KB on the other Ampere and Ada cards
inline int smem_optin_of(int real) {
switch (emulated_cc()) {
case 0: return real;
case 75: return 65536;
case 80: return 166912;
default: return real < 101376 ? real : 101376;
}
}
} // namespace strata
@@ -1,457 +0,0 @@
// include/strata/core/expert_nibble.hpp - STRATA_EXPERT_NIBBLE=1 (opt-in, default off): the gate/up experts of
// IQ2_S / IQ3_XXS / IQ3_S layers kept as 4-bit codes in their VRAM slots, for Pascal GP100 (sm_60).
//
// **WHY.** On a GP100 the decode window's gate/up expert kernels are not held by memory bandwidth: they use a small
// part of it and wait on each block's serial chain (the weights, the codebook lookups, the emulated dp4a, the
// reduction). Re-encoding each 32-weight item of these three formats as sixteen bytes of 4-bit codes (one aligned
// 16-byte load) and keeping the integer scale and the fp16 d as they are makes the slot 1.25-1.68x the GGUF bytes and
// the decode of four weights 1-4 integer instructions instead of two codebook lookups.
//
// **WHY IT IS LOSSLESS.** Their grids have only 3 (IQ2_S) or 8 (IQ3_XXS, IQ3_S) magnitudes, so each int8 weight the
// production `Split<TG>::load` decodes is one of at most 16 signed values. At every start the transcoder decodes every
// item of every converted slot with the production load, encodes it, decodes the written code again and compares; and
// the GGUF blocks are rebuilt from every slot and compared with the blob byte for byte (`check_gguf`). The decode
// kernels run the production integer chain and float tail in the production order: every gate / up value is the
// production kernel's, bit for bit. The prompt path's MMQ reads the GGUF blocks rebuilt from the slot (`gather_gguf`,
// in place of the copy it does today): the same bytes, so the same bits.
//
// **OFF IS TODAY.** Unset or 0: no layer is converted, `slot_bytes(l)` is `expert_layout().blob_bytes(l)`, nothing is
// transcoded, sealed or hashed, and none of the new branches is entered. Only a CUDA build with
// STRATA_EXPERIMENTAL_SM60 has the kernels (STRATA_EXPERT_NIBBLE_BUILT); every other build refuses the switch at start.
#pragma once
#include "strata/kernels/cpu/expert_layout.hpp"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \
!defined(STRATA_GPU_METAL)
#define STRATA_EXPERT_NIBBLE_BUILT 1
#else
#define STRATA_EXPERT_NIBBLE_BUILT 0
#endif
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_NIB_HD __host__ __device__
#else
#define STRATA_NIB_HD
#endif
namespace strata::core::nibble {
// ------------------------------------------------------------------------------------------------ the slot layout
//
// A converted layer's expert slot, in order (the host arena and the pack keep the GGUF blocks):
//
// codes kRows x kItems x 16 B row r, item k at (r * kItems + k) * 16; rows 0..kNFf-1 gate, kNFf..kRows-1 up
// scales kRows x kItems x 1 B row r, item k at kScOff + r * kItems + k (the production scale step's input)
// d kRows x kSuper x 2 B row r, superblock s at kDOff + (r * kSuper + s) * 2: the block's fp16 d, bit for bit
// ------ kGuBytes = 1,766,400 B (6900 x 256: the down part starts 256-aligned)
// down the GGUF down rows, copied verbatim from the raw blob's [down_off, bytes)
// ------ slot_bytes = round_up(kGuBytes + down bytes, kSlotAlign)
//
// One item = 32 weights of a row, one 16-byte code (four 32-bit words, see `encode_item`). Only the expert shape
// n_embd 2560, n_ff 640 is converted: every other layer keeps its GGUF blob and its kernels.
inline constexpr int64_t kNEmbd = 2560; ///< the gate/up rows' width (the activation)
inline constexpr int64_t kNFf = 640; ///< gate rows = up rows = n_ff
inline constexpr int64_t kRows = 2 * kNFf; ///< 1280: gate, then up
inline constexpr int64_t kItems = kNEmbd / 32; ///< 80 items of 32 weights per row
inline constexpr int64_t kSuper = kNEmbd / 256; ///< 10 superblocks (one fp16 d each) per row
inline constexpr uint64_t kItemBytes = 16; ///< one item's code: four words, one 16-byte load
inline constexpr uint64_t kCodesOff = 0;
inline constexpr uint64_t kUpCodesOff = (uint64_t) kNFf * kItems * kItemBytes; ///< 819,200: row kNFf
inline constexpr uint64_t kScOff = (uint64_t) kRows * kItems * kItemBytes; ///< 1,638,400
inline constexpr uint64_t kDOff = kScOff + (uint64_t) kRows * kItems; ///< 1,740,800
inline constexpr uint64_t kGuBytes = kDOff + (uint64_t) kRows * kSuper * 2; ///< 1,766,400
inline constexpr uint64_t kDownOff = kGuBytes; ///< the down rows
inline constexpr uint64_t kSlotAlign = 256; ///< every slot's size
static_assert(kGuBytes == 1766400, "the slot layout above");
static_assert(kGuBytes % kSlotAlign == 0, "the down part starts 256-aligned");
static_assert(kScOff % 16 == 0 && kDOff % 16 == 0, "each region starts 16-aligned");
/// Byte offset of row `row` (0..kRows-1; up rows are kNFf + r) item `k`'s code inside the slot.
STRATA_NIB_HD constexpr uint64_t code_off(int64_t row, int64_t k) {
return kCodesOff + ((uint64_t) row * kItems + (uint64_t) k) * kItemBytes;
}
/// Byte offset of row `row` item `k`'s scale byte.
STRATA_NIB_HD constexpr uint64_t scale_off(int64_t row, int64_t k) { return kScOff + (uint64_t) row * kItems + (uint64_t) k; }
/// Byte offset of row `row` superblock `s`'s fp16 d (s = k / 8 for item k).
STRATA_NIB_HD constexpr uint64_t d_off(int64_t row, int64_t s) { return kDOff + ((uint64_t) row * kSuper + (uint64_t) s) * 2; }
/// A converted slot's size for a raw blob whose down rows are `down_bytes` long.
STRATA_NIB_HD constexpr uint64_t slot_bytes_for(uint64_t down_bytes) {
return (kGuBytes + down_bytes + kSlotAlign - 1) / kSlotAlign * kSlotAlign;
}
// ------------------------------------------------------------------------------------------------ the formats
inline constexpr int kIQ3_XXS = 18;
inline constexpr int kIQ3_S = 21;
inline constexpr int kIQ2_S = 22;
/// Whether `gu_type` is converted (the three formats whose weights take at most 16 values).
STRATA_NIB_HD constexpr bool fmt_built(int gu_type) { return gu_type == kIQ2_S || gu_type == kIQ3_XXS || gu_type == kIQ3_S; }
/// The GGUF gate/up row bytes of `gu_type` at kNEmbd (a converted layer's raw blob must agree; 0 = not a format here).
STRATA_NIB_HD constexpr uint64_t raw_gu_row(int gu_type) {
return gu_type == kIQ2_S ? 820 : gu_type == kIQ3_XXS ? 980 : gu_type == kIQ3_S ? 1100 : 0;
}
inline const char* fmt_name(int gu_type) {
switch (gu_type) {
case kIQ3_XXS: return "IQ3_XXS";
case kIQ3_S: return "IQ3_S";
case kIQ2_S: return "IQ2_S";
default: return "?";
}
}
// ------------------------------------------------------------------------------------------------ the item code
//
// `g[32]` below is one item as the production `Split<TG>::load` leaves it: g[4 * j + b] is byte b of W.g[j]
// (j = 0..7, the dp4a order against the q8_1 block's qs words). Word m (0..3) of the 16-byte code holds W.g[2m]
// and W.g[2m + 1]:
//
// IQ2_S bits 4b..4b+3 = c(g[8m + b]), bits 16+4b.. = c(g[8m + 4 + b]), b = 0..3
// c = magnitude index of {8, 25, 43} | sign << 2: the PRMT selector into {8,25,43,0} {-8,-25,-43,0}
// IQ3_XXS same nibble positions; c = index of {4, 12, 20, 28, 36, 44, 52, 62} | sign << 3
// IQ3_S byte b = u(g[8m + b]) | u(g[8m + 4 + b]) << 4, u = (v + 15) / 2 (v odd, -15..15); v = 2u - 15
//
// The scale byte keeps the production integer scale step's input:
// IQ2_S the block's scales byte for the item: ls0 | ls1 << 4 (W.ls0, W.ls1)
// IQ3_XXS aux32 >> 28 (0..15, W.ls)
// IQ3_S 1 + 2 * nibble (1..31, W.ls)
/// Encodes one item; false when a weight is outside the format's code set (the conversion then refuses to start).
inline bool encode_item(int gu_type, const int8_t g[32], uint32_t q[4]) {
bool ok = true;
auto code = [&](int8_t v) -> uint32_t {
const int a = v < 0 ? -(int) v : (int) v;
if (gu_type == kIQ3_S) {
if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; }
return (uint32_t) (((int) v + 15) / 2);
}
if (gu_type == kIQ3_XXS) {
static constexpr int mag[8] = { 4, 12, 20, 28, 36, 44, 52, 62 };
for (uint32_t i = 0; i < 8; ++i)
if (a == mag[i]) return i | (v < 0 ? 8u : 0u);
ok = false;
return 0;
}
const uint32_t m = a == 8 ? 0u : a == 25 ? 1u : a == 43 ? 2u : 3u; // IQ2_S
if (m == 3u) { ok = false; return 0; }
return m | (v < 0 ? 4u : 0u);
};
for (int m = 0; m < 4; ++m) {
uint32_t w = 0;
for (int b = 0; b < 4; ++b) {
const uint32_t c0 = code(g[8 * m + b]), c1 = code(g[8 * m + 4 + b]);
if (gu_type == kIQ3_S) w |= (c0 | c1 << 4) << (8 * b);
else w |= c0 << (4 * b) | c1 << (16 + 4 * b);
}
q[m] = w;
}
return ok;
}
/// Decodes one item's code back to the production W.g bytes (the host reference the parity program compares with;
/// the device decoders give the same bytes). Codes outside the set decode as the PRMT does: IQ2_S index 3 -> 0.
inline void decode_item(int gu_type, const uint32_t q[4], int8_t g[32]) {
static constexpr int8_t iq2[8] = { 8, 25, 43, 0, -8, -25, -43, 0 };
static constexpr int8_t iq3[8] = { 4, 12, 20, 28, 36, 44, 52, 62 };
for (int m = 0; m < 4; ++m)
for (int b = 0; b < 4; ++b) {
uint32_t c0, c1;
if (gu_type == kIQ3_S) {
c0 = q[m] >> (8 * b) & 15u;
c1 = q[m] >> (8 * b + 4) & 15u;
} else {
c0 = q[m] >> (4 * b) & 15u;
c1 = q[m] >> (16 + 4 * b) & 15u;
}
auto val = [&](uint32_t c) -> int8_t {
if (gu_type == kIQ3_S) return (int8_t) (2 * (int) c - 15);
if (gu_type == kIQ3_XXS) return (int8_t) ((c & 8u) ? -iq3[c & 7u] : iq3[c & 7u]);
return iq2[c & 7u];
};
g[8 * m + b] = val(c0);
g[8 * m + 4 + b] = val(c1);
}
}
// ------------------------------------------------------------------------------------------------ the slot hash
//
// STRATA_EXPERT_NIBBLE_RECHECK's fingerprint of a slot: over the slot's first `hashed` bytes (kGuBytes plus the down
// rows; the alignment tail is not written and not hashed) as little-endian 32-bit words w_i, the last one
// zero-extended, H = sum_i (uint64) (w_i ^ i) * kHashMul mod 2^64. A sum, so the device's order of adding does not
// change it; the index term makes a moved word count.
inline constexpr uint64_t kHashMul = 0x9E3779B97F4A7C15ull;
/// The host reference of the slot hash (the device hash gives the same value for the same bytes).
inline uint64_t hash_host(const void* p, uint64_t bytes) {
const uint8_t* s = (const uint8_t*) p;
uint64_t h = 0;
const uint64_t n = (bytes + 3) / 4;
for (uint64_t i = 0; i < n; ++i) {
uint32_t w = 0;
const uint64_t at = 4 * i, take = bytes - at < 4 ? bytes - at : 4;
std::memcpy(&w, s + at, (size_t) take); // little-endian hosts only
h += (uint64_t) (w ^ (uint32_t) i) * kHashMul;
}
return h;
}
// ------------------------------------------------------------------------------------------------ the switches
struct Config {
bool on = false; ///< STRATA_EXPERT_NIBBLE=1
bool recheck = false; ///< STRATA_EXPERT_NIBBLE_RECHECK=1 (debug: every slot's hash per request)
std::vector<int> fmts{ kIQ2_S, kIQ3_XXS, kIQ3_S }; ///< STRATA_EXPERT_NIBBLE_FMTS (default 22,18,21)
std::vector<int64_t> skip; ///< STRATA_EXPERT_NIBBLE_SKIP: layers kept in their GGUF blocks
std::string error; ///< non-empty: a malformed value - the start is refused
};
namespace detail {
/// "a,b,c" -> integers; false on anything else (empty = an empty list).
inline bool parse_list(const char* s, std::vector<int64_t>& out) {
out.clear();
while (s != nullptr && *s != '\0') {
char* end = nullptr;
const long long v = std::strtoll(s, &end, 10);
if (end == s) return false;
out.push_back((int64_t) v);
s = end;
if (*s == ',') ++s;
else if (*s != '\0') return false;
}
return true;
}
} // namespace detail
/// The switches, read once (generate.cpp reads them before anything is allocated).
inline const Config& config() {
static const Config c = [] {
Config r;
const char* e = std::getenv("STRATA_EXPERT_NIBBLE");
if (e != nullptr && e[0] != '\0' && std::strcmp(e, "0") != 0) {
if (std::strcmp(e, "1") == 0) r.on = true;
else r.error = std::string("STRATA_EXPERT_NIBBLE=") + e + ": expected 0 or 1";
}
const char* rc = std::getenv("STRATA_EXPERT_NIBBLE_RECHECK");
r.recheck = rc != nullptr && std::strcmp(rc, "1") == 0;
std::vector<int64_t> v;
if (const char* f = std::getenv("STRATA_EXPERT_NIBBLE_FMTS"); f != nullptr && f[0] != '\0') {
if (!detail::parse_list(f, v)) {
if (r.error.empty()) r.error = std::string("STRATA_EXPERT_NIBBLE_FMTS=") + f + ": expected ggml types, e.g. 22,18,21";
} else {
r.fmts.clear();
for (const int64_t t : v) {
if (!fmt_built((int) t) && r.error.empty())
r.error = "STRATA_EXPERT_NIBBLE_FMTS: type " + std::to_string(t) +
" is not converted (22 IQ2_S, 18 IQ3_XXS, 21 IQ3_S)";
r.fmts.push_back((int) t);
}
}
}
if (const char* k = std::getenv("STRATA_EXPERT_NIBBLE_SKIP"); k != nullptr && k[0] != '\0') {
if (!detail::parse_list(k, r.skip) && r.error.empty())
r.error = std::string("STRATA_EXPERT_NIBBLE_SKIP=") + k + ": expected layer numbers, e.g. 40,44";
}
return r;
}();
return c;
}
/// With the switch on, the first environment setting it refuses, as a message (empty = none): the paths that would
/// read a converted slot as GGUF blocks, write GGUF bytes into one, or run other kernels for the converted layers
/// than the ones the 4-bit kernels are bit for bit. The command-line half (--peer-device, remote expert caches,
/// --kv-grow, --vram-elastic), the cc 6.0 check, full residency and no loan are generate.cpp's checks; the prompt
/// path's own (MMQ on every converted layer) is Prefill::nibble_prompt_check.
inline std::string env_conflicts() {
auto set = [](const char* n) -> const char* {
const char* v = std::getenv(n);
return v != nullptr && v[0] != '\0' ? v : nullptr;
};
const char* v = set("STRATA_MMQ_DIRECT");
if (v != nullptr && std::atoi(v) != 0)
return "STRATA_MMQ_DIRECT (the prompt MMQ would read a converted slot in place as GGUF blocks)";
v = set("STRATA_PREFILL_MMQ");
if (v != nullptr && std::atoi(v) == 0) return "STRATA_PREFILL_MMQ=0 (the FP16 prompt path reads GGUF blocks)";
v = set("STRATA_PF_FUSED");
if (v != nullptr && v[0] == '1') return "STRATA_PF_FUSED=1 (the fused prompt kernels read GGUF blocks)";
v = set("STRATA_FS_SLOTS");
if (v != nullptr && std::atoi(v) > 0) return "STRATA_FS_SLOTS (Foresight swaps GGUF blobs into slots)";
v = set("STRATA_EXPERT_V2");
if (v != nullptr && v[0] == '1') return "STRATA_EXPERT_V2=1 (the S26 kernels, not the CUDA layout, on IQ3_S)";
v = set("STRATA_KV_GROW");
if (v != nullptr && v[0] != '0') return "STRATA_KV_GROW (the elastic K/V moves slots at their GGUF size)";
v = set("STRATA_EXP_MODE");
if (v != nullptr && std::atoi(v) != 0 && std::atoi(v) != 8)
return "STRATA_EXP_MODE other than 0 or 8 (another layout's gate/up kernels)";
return {};
}
// ------------------------------------------------------------------------------------------------ the VRAM table
/// One layer's slots. `on` false: the GGUF blob, `slot_bytes == raw_bytes`, the production kernels.
struct LayerVram {
bool on = false;
int gu_type = -1, d_type = -1;
uint64_t down_off = 0; ///< in the slot: kDownOff when on, else the raw blob's down_off
uint64_t down_bytes = 0; ///< the down rows (raw_bytes - raw_down_off)
uint64_t hashed = 0; ///< bytes the slot hash covers: kGuBytes + down_bytes when on, else 0
uint64_t slot_bytes = 0; ///< what the expert cache allocates per slot (`open_sized`, every estimate)
// the raw blob as the arena and the pack hold it (expert_layout().fmt[l]); the transcoder reads these
uint64_t raw_bytes = 0, raw_gu_row = 0, raw_up_off = 0, raw_down_off = 0;
};
/// One layer's entry from its GGUF format and the switches (pure; `plan_layers` calls it per layer).
inline LayerVram plan_layer(int64_t l, const strata::kernels::cpu::NativeFmt& f, const Config& c) {
LayerVram v;
v.gu_type = f.gu_type;
v.d_type = f.d_type;
v.raw_bytes = f.bytes;
v.raw_gu_row = f.gu_row;
v.raw_up_off = f.up_off;
v.raw_down_off = f.down_off;
v.down_bytes = f.bytes - f.down_off;
v.down_off = f.down_off;
v.slot_bytes = f.bytes;
bool listed = false, skipped = false;
for (const int t : c.fmts) listed = listed || t == f.gu_type;
for (const int64_t s : c.skip) skipped = skipped || s == l;
// [gate | up | down] exactly, no NVFP4 tail, the down rows a whole number of 16-byte words (the gathers copy them so)
const bool shape = f.n_embd == kNEmbd && f.n_ff == kNFf && f.gu_row == raw_gu_row(f.gu_type) &&
f.up_off == (uint64_t) kNFf * f.gu_row && f.down_off == 2 * f.up_off && f.bytes > f.down_off &&
f.tail_off == 0 && (f.bytes - f.down_off) % 16 == 0;
if (c.on && c.error.empty() && listed && !skipped && fmt_built(f.gu_type) && shape) {
v.on = true;
v.down_off = kDownOff;
v.hashed = kGuBytes + v.down_bytes;
v.slot_bytes = slot_bytes_for(v.down_bytes);
}
return v;
}
/// Every layer's entry for this pack (all off for a Q2_0 pack or with the switch off). `err`: a SKIP layer out of
/// range, or the switch on with a Q2_0 pack.
inline std::vector<LayerVram> plan_layers(const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {
const Config& c = config();
std::vector<LayerVram> out((size_t) (lay.n_layers > 0 ? lay.n_layers : 0));
for (int64_t l = 0; l < (int64_t) out.size(); ++l) {
if (lay.native && (size_t) l < lay.fmt.size()) out[(size_t) l] = plan_layer(l, lay.fmt[(size_t) l], c);
else out[(size_t) l].slot_bytes = out[(size_t) l].raw_bytes = lay.blob_bytes(l);
}
if (c.on && !lay.native) err = "STRATA_EXPERT_NIBBLE needs a native pack (native_experts.txt)";
for (const int64_t s : c.skip)
if (c.on && (s < 0 || s >= lay.n_layers) && err.empty())
err = "STRATA_EXPERT_NIBBLE_SKIP: layer " + std::to_string(s) + " is not in the model";
return out;
}
namespace detail {
inline std::vector<LayerVram>& table() {
static std::vector<LayerVram> t;
return t;
}
} // namespace detail
/// generate.cpp only: the table, once, after `expert_layout_load` and BEFORE the first slot estimate (placement
/// search, can_start, the cache's auto size, every `open_sized`). Not thread-safe: set before any other thread.
inline void set_layers(std::vector<LayerVram> v) { detail::table() = std::move(v); }
/// Layer `l`'s entry (an off entry when the table is not set or `l` is outside it). Read-only after `set_layers`.
inline const LayerVram& layer(int64_t l) {
static const LayerVram off;
const auto& t = detail::table();
return l >= 0 && (size_t) l < t.size() ? t[(size_t) l] : off;
}
/// Whether any layer is converted (the switch on and the table set).
inline bool any_on() {
for (const LayerVram& v : detail::table())
if (v.on) return true;
return false;
}
/// Bytes of one of layer `l`'s VRAM slots: the converted size for a converted layer, else the layout's blob bytes
/// (exactly `expert_layout().blob_bytes(l)`: with the switch off every caller sizes what it sized before).
inline uint64_t slot_bytes(int64_t l) {
const auto& t = detail::table();
if (l >= 0 && (size_t) l < t.size()) return t[(size_t) l].slot_bytes;
return strata::kernels::cpu::expert_layout().blob_bytes(l);
}
// ------------------------------------------------------------------------------------------------ fatal paths
/// A converted layer reached a path that would compute or copy it as GGUF blocks: say where and stop. Never a
/// silent wrong answer.
[[noreturn]] inline void fatal(int64_t l, const char* where, const char* why) {
std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: layer %lld (%s, 4-bit slots) reached %s: %s - stopping\n",
(long long) l, fmt_name(layer(l).gu_type), where != nullptr ? where : "?", why != nullptr ? why : "");
std::fflush(stderr);
std::abort();
}
/// Before each raw slot copy that bypasses the ExpertCache API (the adaptive tier's copies, the elastic K/V's slot
/// moves): fatal when `l` is a converted layer. The startup refusals keep these paths off; this is the backstop
/// (with `ExpertCache::seal()` for the API's own fills).
inline void guard_raw(int64_t l, const char* where) {
if (layer(l).on) fatal(l, where, "a raw slot copy at the GGUF size");
}
// ------------------------------------------------------------------------------------------------ the decode kernels
//
// Two skeletons in the shape of native_gu_multi_kernel (16 lanes a row, a group's entries GRP_NC at a time), both bit
// for bit the production gate/up: S stages the entries' q8_1 blocks in shared memory and decodes each item where it
// is used (IQ3_S: v = 2u - 15 restored per byte, then the production apply); P loads the lane's codes, scales and d
// before staging the qs words as 16-byte rows (IQ3_S: sum = 2 dot(u, x) - 15 sum(x), the same int32). Per format the
// faster one on 4x GP100 at T = 1..6 (native_expert_bench --nibble): IQ2_S P, IQ3_XXS S, IQ3_S S.
inline constexpr int kSkelS = 0, kSkelP = 1;
STRATA_NIB_HD constexpr int gu_skeleton(int gu_type) { return gu_type == kIQ2_S ? kSkelP : kSkelS; }
// ------------------------------------------------------------------------------------------------ iq_kernels.cu
//
// Device addresses are `unsigned long long` (as native_expert_grouped's grp_ptr), streams `void*`; each returns the
// CUDA error code (0 = success) so the caller can name the layer. A build without STRATA_EXPERT_NIBBLE_BUILT
// returns cudaErrorInvalidValue (1) from each.
/// The reverse codebooks (grid magnitudes -> GGUF grid index) `check_gguf` and `gather_gguf` use, built on the CURRENT
/// device (once per device; call it at load, before any capture). Non-zero also when a grid entry is not unique.
int prepare(void* stream);
/// Converts `n` raw blobs of layer `L` (device `staging`, `L.raw_bytes` apart, as the host arena holds them) into
/// the converted slots at `slot_ptrs[0..n)` (a device array): codes, scales, d. The down rows are not touched (the
/// caller copies them to `slot + kDownOff`). Every item is decoded with the production `Split<TG>::load`, encoded,
/// decoded from the written code again and compared with W.g[0..7], the scale and d; each item that differs or holds
/// a weight outside the code set adds 1 to `*bad` (device). L.on must be true.
int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
unsigned long long* bad, void* stream);
/// The GGUF gate/up blocks rebuilt from each of the `n` (<= 64) converted slots at `slot_ptrs` and its down rows,
/// compared with the raw blobs in `staging` (`L.raw_bytes` apart) byte for byte: each 32-bit word that differs adds 1
/// to `*bad`. `prepare` first.
int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
unsigned long long* bad, void* stream);
/// The prompt path's gather of a converted layer's experts (prefill.cpp, MMQ): for q in [first, n) (n <= 16), the
/// GGUF [gate | up] blocks rebuilt from slot `slots[q]` (host array of device addresses) into gu_dst + q * gu_stride -
/// the bytes the raw blob holds, byte for byte - and its down rows copied to d_dst + q * d_stride; `zero_bytes` zeroed
/// after expert n - 1's gate/up and down (MMQ's tail). Every address, stride and size 16-byte aligned. `prepare`
/// on this device first.
int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride,
void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream);
/// The slot hash (`hash_host`'s value) of the `L.hashed` bytes at each `slot_ptrs[i]`, into device `out[0..n)`.
int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out,
void* stream);
} // namespace strata::core::nibble
@@ -1,11 +0,0 @@
// include/strata/core/geometries/flash_next.hpp - Qwen3.8-Flash-Next (qwen4exp), the shape the engine ships for.
// The values are ModelGeometry's member defaults (geometry.hpp); this header exists so that every shape is a header,
// and so that the default build is byte-for-byte the build it was before shapes were selectable.
#pragma once
namespace strata::core {
inline constexpr const char* kGeometryName = "flash_next";
inline constexpr ModelGeometry kCompiledGeometry{};
} // namespace strata::core
@@ -1,92 +0,0 @@
// include/strata/core/geometry.hpp - the model's geometry: one struct for the shape a model file declares and
// the shape the kernels are compiled for.
//
// A model file's geometry is read from its own metadata (`strata::read_geometry`, gguf_reader.hpp), and the
// engine passes that struct everywhere it needs a dimension. The CUDA/HIP kernels still fix most of these
// numbers at compile time (`constexpr int N = 2560` and the like); `kCompiledGeometry` is that shape, written
// once, and each kernel that pins a number `static_assert`s it against this struct. So a kernel and this file
// cannot drift apart without the build failing, and a model file of another shape is refused at load with the
// metadata key that differs (`strata::geometry_unsupported`) instead of mis-running.
//
// Dependency-free on purpose: the kernels include it.
#pragma once
#include "strata/artifact/model_family.hpp"
#include <cstdint>
namespace strata::core {
/// Every field is a number a kernel depends on, so a change to the compiled values is a change to a kernel
/// contract and not a tuning knob. The defaults are Qwen3.8-Flash-Next's (qwen4exp), the shape the kernels
/// are compiled for; the GGUF key each field is read from is named beside it.
struct ModelGeometry {
int64_t n_embd = 2560; ///< embedding_length
int64_t n_layers = 48; ///< block_count (the trunk; an in-file MTP block is counted in n_mtp_layers)
int64_t qsa_interval = 4; ///< full_attention_interval: every 4th layer is full attention, 3, 7, ... 47
int64_t n_vocab = 248320; ///< the length of tokenizer.ggml.tokens
double rms_eps = 1e-6; ///< attention.layer_norm_rms_epsilon
// GDN (36 layers)
int64_t ssm_state_size = 128; ///< ssm.state_size: the key head width, and the value head width
int64_t ssm_k_heads = 16; ///< ssm.group_count
int64_t ssm_v_heads = 48; ///< ssm.time_step_rank
int64_t ssm_d_conv = 4; ///< ssm.conv_kernel
int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48, derived
int64_t ssm_value_dim = 6144; ///< ssm.inner_size, 128 * 48
// QSA (12 layers)
int64_t n_head = 24; ///< attention.head_count
int64_t n_head_kv = 2; ///< attention.head_count_kv
int64_t head_dim = 256; ///< attention.key_length (= attention.value_length)
int64_t n_rot = 64; ///< rope.dimension_count: the rotated slice of head_dim and of idx_key_dim
int64_t idx_q_heads = 4; ///< attention.indexer.head_count
int64_t idx_key_dim = 128; ///< attention.indexer.key_length
int64_t idx_block = 4; ///< the non-zero attention.compress_ratios entry: one pooled key per 4 cells
int64_t idx_top_k = 2048; ///< attention.indexer.top_k: cells of selection budget
// gated residual, on every layer
int64_t hc = 4; ///< hyper_connection.count
int64_t hc_lr = 320; ///< hyper_connection.low_rank
// MoE, on every layer
int64_t n_expert = 512; ///< expert_count; pruned variants (GSQ-RCO Coder) ship fewer
int64_t n_expert_used = 10; ///< expert_used_count
int64_t n_ff = 640; ///< expert_feed_forward_length (= expert_shared_feed_forward_length)
// appended for the model families (Qwen3.6 = qwen35moe); the defaults keep Flash-Next's values
int64_t n_ff_shexp = 640; ///< the shared expert's FFN width (qwen4exp: equal to n_ff, read_geometry checks)
ModelFamily family = ModelFamily::Qwen4Exp;
int64_t n_mtp_layers = 0; ///< MTP blocks inside the model file, after the trunk (qwen35moe: blk.40)
constexpr bool has_indexer() const { return idx_q_heads > 0; } ///< false: dense attention only
constexpr bool has_hyper_connections() const { return hc > 0; } ///< false: plain pre-norm residual
constexpr int64_t hc_dim() const { return hc * n_embd; }
/// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list.
constexpr int64_t n_qsa_layers() const { return n_layers / qsa_interval; }
constexpr int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); }
};
} // namespace strata::core
// The shape the kernels are compiled for: `kCompiledGeometry`, defined by the geometry header chosen at configure
// time (`-DSTRATA_GEOMETRY=<name>` selects include/strata/core/geometries/<name>.hpp, `-DSTRATA_GEOMETRY_FILE=<path>`
// takes any header; cmake/strata_geometry.cmake writes geometry_selected.hpp into the build tree for either). With
// neither option the build uses Flash-Next's header and adds no compile flag. A kernel that fixes a dimension at
// compile time asserts it against `kCompiledGeometry`; geometry_checks.hpp holds the constraints every shape must meet.
#if __has_include("strata/core/geometry_selected.hpp")
#include "strata/core/geometry_selected.hpp"
#else
#include "strata/core/geometries/flash_next.hpp"
#endif
#include "strata/core/geometry_checks.hpp"
namespace strata::core {
/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval
/// = 4` and an explicit `attention.compress_ratios` array - and `read_geometry` checks that the two agree.
inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) {
return layer % g.qsa_interval == g.qsa_interval - 1;
}
} // namespace strata::core
@@ -1,52 +0,0 @@
// include/strata/core/geometry_checks.hpp - what every compiled shape must satisfy.
//
// The kernels are written for a family of shapes, not for one number each: some values are the same in every Qwen
// model of this layer design (the GDN state width, the attention head width, the conv width) and are held fixed
// here; the others have to be divisible or within a range the tiles, the shared-memory plans and the register
// arrays were written for. A geometry header that breaks one of these fails the build with the line below that
// names the field, instead of compiling a kernel that mis-runs. Included by geometry.hpp, after the header.
#pragma once
#include "strata/core/geometry.hpp"
namespace strata::core::geometry_checks {
inline constexpr const ModelGeometry& g = kCompiledGeometry;
// ---- held fixed: the same in every published Qwen3-Next / 3.5 / 3.6 config and in Flash-Next; the kernels unroll them
static_assert(g.ssm_state_size == 128, "geometry: ssm.state_size must be 128 (GDN kernels: 4 rows per lane, 128-thread blocks, 32x32 state tiles)");
static_assert(g.ssm_k_heads == 16, "geometry: ssm.group_count must be 16 (GDN key heads)");
static_assert(g.ssm_d_conv == 4, "geometry: ssm.conv_kernel must be 4 (3 history taps and 4 weights are unrolled)");
static_assert(g.head_dim == 256, "geometry: attention.key_length must be 256 (attention kernels: thread per dim, 4 warps x 64)");
static_assert(g.n_rot == 64, "geometry: rope.dimension_count must be 64");
static_assert(g.qsa_interval == 4, "geometry: full_attention_interval must be 4");
static_assert(g.hc == 4, "geometry: hyper_connection.count must be 4 (register and shared arrays hold 4 streams)");
static_assert(g.idx_q_heads == 4 && g.idx_key_dim == 128,
"geometry: the indexer must be 4 heads x 128 (one float4 per lane, one warp per head)");
static_assert(g.idx_block == 4, "geometry: the indexer pooling block must be 4 cells");
// ---- ranges and divisibility the tiles were written for
static_assert(g.n_embd % 256 == 0 && g.n_embd >= 1024 && g.n_embd <= 4096,
"geometry: embedding_length must be a multiple of 256 within 1024..4096 (K-quant rows, 8x512 partial sums, 4096-half shared staging)");
static_assert(g.n_ff % 64 == 0 && g.n_ff >= 256 && g.n_ff <= 1100,
"geometry: expert_feed_forward_length must be a multiple of 64 within 256..1100 (Q2 blobs, 64-wide act groups, 1024-byte act buffer)");
static_assert(g.n_ff_shexp == g.n_ff, "geometry: the shared expert must be as wide as the routed experts");
static_assert(g.hc_lr % 64 == 0 && g.hc_lr / 8 >= 32 && g.hc_lr / 8 <= 64 && g.hc_lr % 8 == 0,
"geometry: hyper_connection.low_rank must be a multiple of 64 with 32 <= low_rank/8 <= 64 (fused_gr lane rule)");
static_assert(g.n_head_kv >= 1 && g.n_head % g.n_head_kv == 0 && g.n_head / g.n_head_kv <= 16,
"geometry: attention.head_count / head_count_kv must be a whole number <= 16 (one M16 tile of query heads)");
static_assert(g.ssm_v_heads % g.ssm_k_heads == 0 && g.ssm_v_heads / g.ssm_k_heads >= 1 && g.ssm_v_heads / g.ssm_k_heads <= 4,
"geometry: ssm.time_step_rank must be 1..4 times ssm.group_count");
static_assert(g.n_expert % 32 == 0 && g.n_expert >= 32 && g.n_expert <= 512,
"geometry: expert_count must be a multiple of 32 up to 512 (router: one lane per 32 experts)");
static_assert(g.n_expert_used >= 1 && g.n_expert_used <= 16 && g.n_expert_used <= g.n_expert,
"geometry: expert_used_count must be 1..16");
static_assert(g.n_layers % g.qsa_interval == 0 && g.n_layers >= g.qsa_interval,
"geometry: block_count must be a multiple of full_attention_interval");
// ---- derived fields written out in the header must agree
static_assert(g.ssm_conv_channels == 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_state_size * g.ssm_v_heads,
"geometry: ssm_conv_channels must be 2*state*k_heads + state*v_heads");
static_assert(g.ssm_value_dim == g.ssm_state_size * g.ssm_v_heads, "geometry: ssm_value_dim must be state*v_heads");
} // namespace strata::core::geometry_checks
@@ -1,221 +0,0 @@
// strata/core/sm120_series.hpp - bitwise kernel switches that are ON by default on a compute capability 12.0 card
// (RTX 50 series / RTX PRO Blackwell workstation cards).
//
// 147-verify measured these exact switches on an RTX PRO 5000 Blackwell 72 GB (IQ3_S, every expert in VRAM): together
// a verify round of 4 tokens 13.70 -> 12.23 ms with the same text (notes-147-l620.md). Each one is bitwise equal to
// the kernels it replaces (their own parity tests and the identity gate), so only the speed changes:
// STRATA_SIDE_MIXER=2 the mixer's input-only work on branches of the verify graph
// STRATA_ATTN_DAILY=1 the Daily's decode attention (attn_chunk_kernel_pre75 + merge v2)
// STRATA_GR_UP75=1 the hyper-connection up projection with its rows' loads hoisted
// STRATA_GR_DOWN_TG=1 the hyper-connection down projection with one token a block row (T times the blocks); =2 (token
// pairs) on a 12.0 card with fewer than 80 SMs
// STRATA_GU_SWIGLU=1 gate/up, SwiGLU and the q8_1 blocks of the routed experts in one launch
// STRATA_GR_UP_WIDE=1 the hyper-connection up projection with one warp a row (1,280 blocks instead of 160; +1.9%
// story / +0.7% code decode on the RTX PRO 5000, 5 pairs, token ids identical; bitwise)
// and one that rounds differently (KL-checked, the AMD gfx12 rule): STRATA_PF_FUSED (the native packs' prompt experts on the
// fused int8 kernels, IQ2_S / IQ3_XXS / IQ3_S / IQ4_XS gate/up only, 12.0 cards with 80+ SMs only; =0 keeps MMQ, =1 takes every
// covered format on any card).
//
// STRATA_SM120_PERF=0 turns the whole set off on a 12.0 card (the defaults every other card has).
// Each switch's own variable still wins in both directions (=0 off, =1 / =2 on), on any card, as before.
// Nothing here changes a card that is not a 12.0, except the two switches the GB10 (sm_121) measured as well (kGb10AttnDaily, kGb10GrDownTg below;
// STRATA_SM121_PERF=0 or STRATA_DEFAULTS=026 give the GB10 its earlier defaults back); an sm_100 card keeps its defaults.
#pragma once
#include "strata/core/defaults_026.hpp"
#include "strata/core/emulate.hpp"
#include <cstdlib>
namespace strata {
/// STRATA_SM120_PERF (read once): unset or anything but "0" = on
inline bool sm120_series() {
static const bool on = [] {
const char* e = std::getenv("STRATA_SM120_PERF");
return e == nullptr || std::atoi(e) != 0;
}();
return on;
}
/// the device (raw cudaDevAttrComputeCapabilityMajor / Minor) is a 12.0 card, or emulates one (STRATA_EMULATE_CC=120)
inline bool is_sm120(int major, int minor) { return cc_major_of(major) == 12 && cc_minor_of(minor) == 0; }
/// STRATA_PLE_BATCH (the prompt path's batched PLE post-ops) when the user set nothing. ON everywhere except one toolchain: an engine built with CUDA 12.8
/// (CUDART_VERSION 12080..12089) running on a compute capability 12.0 card faults in the prompt path with it ("an illegal memory access", first error in the
/// native PLE postops launch; RTX PRO 6000, driver 580, srv118; issues #220, #224; CMake already warns for a CUDA < 13.0 sm_120 build). The same source built
/// with CUDA 13.0 (the released cuda13 package) and 13.2 runs it at every prompt length, and it is worth ~23% of the prompt speed there, so it stays on there.
/// `cudart_version`: CUDART_VERSION of the toolkit the engine was built with (0 in a HIP build); `hip`: a HIP build (a gfx12 card reports 12.0 as well).
inline bool ple_batch_default(int cudart_version, bool hip, int major, int minor) {
const bool cuda_12_8 = !hip && cudart_version >= 12080 && cudart_version < 12090;
return !(cuda_12_8 && is_sm120(major, minor));
}
/// The decision: STRATA_PLE_BATCH wins in both directions (text that reads as 0 is off, anything else on, as before); unset is ple_batch_default.
inline bool ple_batch_resolve(const char* env, int cudart_version, bool hip, int major, int minor) {
if (env != nullptr) return std::atoi(env) != 0;
return ple_batch_default(cudart_version, hip, major, minor);
}
/// the default of a bitwise switch of the set: on for a 12.0 card unless STRATA_SM120_PERF=0
inline bool sm120_default(int major, int minor) { return is_sm120(major, minor) && sm120_series(); }
/// the device is a GB10 (NVIDIA DGX Spark, compute capability 12.1, or emulates one)
inline bool is_sm121(int major, int minor) { return cc_major_of(major) == 12 && cc_minor_of(minor) == 1; }
/// STRATA_SM121_PERF (read once): unset or anything but "0" = on. The GB10 table of nv_defaults.cpp reads the same variable.
inline bool sm121_series() {
static const bool on = [] {
const char* e = std::getenv("STRATA_SM121_PERF");
return e == nullptr || std::atoi(e) != 0;
}();
return on;
}
/// The default of a bitwise switch of the 12.0 set that was ALSO measured on a GB10 (BW-7, phaseA-tests/bw/RESULTS-BW-B.md): on for a 12.0 card unless
/// STRATA_SM120_PERF=0, and on for a GB10 when `gb10_measured` (the caller's constant: the switch won there and passed its gate) unless
/// STRATA_SM121_PERF=0 or STRATA_DEFAULTS=026 (the same off switches as the GB10 table of nv_defaults.cpp). `v026`: qwen_defaults_026().
inline bool sm12x_default_v(int major, int minor, bool gb10_measured, bool v026) {
return sm120_default(major, minor) || (gb10_measured && is_sm121(major, minor) && sm121_series() && !v026);
}
inline bool sm12x_default(int major, int minor, bool gb10_measured) { return sm12x_default_v(major, minor, gb10_measured, qwen_defaults_026()); }
/// Which switches of the 12.0 set are on for a GB10 (compute capability 12.1, DGX Spark) as well. BW-7, 11-19, a rented GB10 (IQ3_S, all 24,576 experts resident,
/// DFlash2 Q4_0 drafter, --spec 6, fixed draft-cost table, fresh engine per start, arms interleaved, 4 requests x 300 tokens per kind a start, token ids identical to
/// the default's); numbers and gates in phaseA-tests/bw/RESULTS-BW-B.md. Each constant is one measured verdict, so a later measurement flips one line.
/// Decode against the GB10 default (3 paired rounds, median; chat / code / json / agent):
/// STRATA_ATTN_DAILY +0.3 / +0.9 / +0.7 / +1.2 % (json, agent 3 of 3 pairs) -> ON
/// STRATA_GR_DOWN_TG -0.1 / +0.7 / +1.1 / +0.9 % (json, agent 3 of 3 pairs; token pairs, the GB10 has 48 SMs) -> ON
/// STRATA_GU_SWIGLU -0.2 / -1.0 / 0.0 / +0.1 %, STRATA_GR_UP75 -0.7 / -0.2 / -0.4 / -0.6 %, STRATA_GR_UP_WIDE -0.4 / -0.3 / -0.1 / -0.2 %,
/// STRATA_SMALL_UNR +0.1 / -0.9 / +0.2 / 0.0 %, STRATA_DF_PDL +0.1 / -0.6 / 0.0 / +0.3 %: level or slower here (inside the 0.2-1 % scatter) -> stay off
/// STRATA_GR_V3 (another summation order, KL-gated; text changes) and STRATA_GR_V3_PF (E15, acts only with GR_V3): mixed, E15 itself level (v3 with / without PF
/// chat +1.0 %, code -0.9 %, json -0.4 %, agent -0.5 %) -> stay off
constexpr bool kGb10GuSwiglu = false; ///< STRATA_GU_SWIGLU
constexpr bool kGb10AttnDaily = true; ///< STRATA_ATTN_DAILY
constexpr bool kGb10GrUp75 = false; ///< STRATA_GR_UP75
constexpr bool kGb10GrDownTg = true; ///< STRATA_GR_DOWN_TG
constexpr bool kGb10GrUpWide = false; ///< STRATA_GR_UP_WIDE
constexpr bool kGb10SmallUnr = false; ///< STRATA_SMALL_UNR
constexpr bool kGb10DfPdl = false; ///< STRATA_DF_PDL
constexpr bool kGb10GrV3Pf = false; ///< STRATA_GR_V3_PF (E15: the v3 HC read's load ordering; bitwise, but it only acts when the v3 read runs)
constexpr bool kGb10GrV3 = false; ///< STRATA_GR_V3 (the stream-split HC read: another summation order, KL-gated)
// ---- 0.2.7 defaults of the CUDA speed work (pure rules; the engine reads the device and calls these; tests in arch_defaults_test)
// `hip`: a HIP build, where a gfx1200 / gfx1201 reports compute capability 12.0 as well and none of these is measured or wanted.
// `v026`: STRATA_DEFAULTS=026 (defaults_026.hpp qwen_defaults_026()): every one of these is then off, as in v0.2.6. An explicit variable
// (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, ...) is decided by the caller before it asks the rule, so it still wins.
// `total_bytes`: the card's memory (cudaDeviceProp::totalGlobalMem); `integrated`: a GPU that shares the PC's memory.
constexpr double kSmallCardGiB = 13.0; // "a 12 GB card": 12 GB cards report 11.6 - 12.0 GiB, 16 GB ones 15.6 - 16.0
/// The residency-bias bonus the user can ask for on a discrete CUDA card of 13 GiB or less (STRATA_ROUTE_PRIOR=1.5; the app's Expert-settings row
/// "Faster answers on 12 GB NVIDIA cards" writes it): THE one place the value lives. 1.5 since the owner decision of 2026-10-26 (2.0 had real defects in
/// the copy and code check on the RTX 3060 12 GB with IQ3_XXS; none in 19 tasks at 1.5 or 1.0). Speed against off: story +15%, code +37%.
/// It was the default on those cards in 0.2.7 only. Owner decision of 2026-10-29: OFF by default again (#4402: repetition loops and weaker results in long
/// agent sessions; our own 0.2.7 agent check passed 4.5 of 10 tasks with it on against 5.6 with it off). It stays an opt-in.
constexpr float kRoutePriorSmallCard = 1.5f;
/// STRATA_ROUTE_PRIOR when the user set nothing: 0 on every card (residency-biased routing changes which experts run, so it is only on when asked for:
/// STRATA_ROUTE_PRIOR=1.5, or the Expert-settings row). The same answer as v0.2.6 and as 0.2.7 with STRATA_ROUTE_PRIOR=0 or STRATA_DEFAULTS=026.
/// The arguments are kept so a caller and the table test (arch_defaults_test) still ask the same question per card; none of them changes the answer.
inline float route_prior_default(bool /*hip*/, bool /*integrated*/, double /*total_bytes*/, bool /*v026*/ = false) { return 0.0f; }
/// The lambda the engine uses given the text of STRATA_ROUTE_PRIOR (nullptr = unset): any set value is the user's own and wins on every card
/// (atof; "0" and text that reads as 0 are off; "1.5" is what the Expert-settings row writes), unset is route_prior_default (0).
inline float route_prior_resolve(const char* env, bool hip, bool integrated, double total_bytes, bool v026 = false) {
return env != nullptr ? (float) std::atof(env) : route_prior_default(hip, integrated, total_bytes, v026);
}
/// The window warm-up before READY (generate.cpp, lane DRAFT-COSTS): one dummy window per width on token id 1, whose misses page that token's experts into the GPU expert
/// cache. "Speed only" while routing ignores residency; with STRATA_ROUTE_PRIOR on, the first request is routed towards what is resident, so the dummy token's experts bend its
/// answer (#6171: P(<|im_end|>) summed over the 8 digits of a long passkey answer 4.8 - 7.4 % in the first request after a start against 1.4 - 1.7 % with the warm-up off or the prior off;
/// 8 starts per arm, RTX 3090, IQ4_XS). warm_env is STRATA_WINDOW_WARM (nullptr unset): "0" off, "1" on whatever the prior says; unset: on, except while the prior is on (prior > 0).
/// The cost of skipping it is the graph build of a width that the policy first picks inside a request (tens of ms, once).
inline bool window_warm_on(const char* warm_env, float prior) {
if (warm_env != nullptr && warm_env[0] == '0') return false;
if (warm_env != nullptr && warm_env[0] == '1') return true;
return !(prior > 0.0f);
}
/// STRATA_GR_V3 (the stream-split hyper-connection read, another summation order) when the user set nothing: ON for a discrete compute capability
/// 12.0 card (STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB, CUDA builds only. Measured: RTX PRO 5000 72 GB +1.2% decode clean,
/// -3.0% / -5.9% on 2x RTX A4000 (sm_86), +1.0% / -3.4% on an RTX 3060 (sm_86): so not those; a 12 GB sm_120 card is unmeasured.
inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, double total_bytes, bool v026 = false) {
return !v026 && !hip && ((!integrated && sm120_default(major, minor) && total_bytes / 1073741824.0 > kSmallCardGiB) || (kGb10GrV3 && is_sm121(major, minor) && sm121_series()));
}
/// STRATA_PROMPT_ATTN_IMMA (the prompt attention on int8 tensor cores, another summation order) when the user set nothing: ON for every CUDA card of
/// compute capability 8.0 or newer (the int8 m16n8k32 MMA), not Turing / Volta / Pascal, not HIP. `cc` = 10 * major + minor as the engine
/// resolves it (an emulated or forced Turing counts as 75). Measured on sm_120 (RTX PRO 5000) and sm_86 (2x RTX A4000): +1.1 .. +1.8% prompt.
inline bool prompt_attn_imma_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc >= 80; }
/// STRATA_MMVQ_IL_89 (#3453: the decode kernel row tables of an Ada card, the cells where an RTX 4070 and an RTX 4080 agreed; bitwise the same
/// output, only the rows-a-warp split differs) when the user set nothing: ON for compute capability 8.9 only (owner decision, 26 October: not yet
/// measured on an Ada card by us), off under STRATA_DEFAULTS=026 and in HIP builds. `cc` = 10 * major + minor as the engine resolves it.
inline bool mmvq_il_89_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc == 89; }
/// The two sm_80-only defaults of 0.2.7 (#3779: the wide dense dequant and the MMVQ-IL sm_80 tables, both bitwise the old output, measured on a
/// CMP 170HX only) given the text of their variable (nullptr = unset): "1" on and "0" off win, unset is on unless STRATA_DEFAULTS=026.
inline bool sm80_default_on(const char* env, bool v026 = false) {
if (env != nullptr && env[0] == '1') return true;
if (env != nullptr && env[0] == '0') return false;
return !v026;
}
/// The answer for STRATA_MMVQ_IL_89 given the variable's text (nullptr = unset): "1" on and "0" off win over everything, anything else (unset,
/// empty, other text) is the rule above.
inline bool mmvq_il_89_resolve(const char* env, bool hip, int cc, bool v026 = false) {
if (env != nullptr && env[0] == '1') return true;
if (env != nullptr && env[0] == '0') return false;
return mmvq_il_89_default(hip, cc, v026);
}
/// STRATA_GR_UP_WIDE (the hyper-connection up projection, one warp a row; bitwise the old kernel) when the user set nothing: ON for a compute
/// capability 12.0 card (STRATA_SM120_PERF=0 turns the set off), CUDA builds only.
inline bool gr_up_wide_default(bool hip, int major, int minor, bool v026 = false) { return !v026 && !hip && sm12x_default_v(major, minor, kGb10GrUpWide, v026); }
/// STRATA_PREFILL_LAYER_MAJOR (#3976: the layer-major prompt walk, which reads each layer's streamed experts once per super-chunk instead of once
/// per chunk; another summation order of the routed experts, so KL-checked, not bitwise) when the user set nothing: OFF everywhere (owner's yes 2026-11-02).
/// It was ON for a CUDA layer split (`stages` = the number of GPUs the prompt path runs on, 2 or more; measured 2026-10-24 on 2x RTX A4000 with IQ3_XXS and
/// streamed experts only), but on 2x RTX A6000 (IQ3_S, MTP, three residency levels) the chunk-major path reads a 32K prompt 37-55% sooner and is level at 8K
/// (DF2-MGPU, boston). The one place the walk wins by default is the single-card small-cache rule (small_card_prompt_path below), which sets
/// STRATA_PREFILL_LAYER_MAJOR=1 itself. STRATA_PREFILL_LAYER_MAJOR=1 still turns it on, "0" off, by hand, on any build that has it. The parameters stay so that
/// the callers and the resolve rule below keep their shape. The engine adds its own per-prompt declines (image prompts, KVA, a batch read that yields,
/// a peer GPU, no VRAM for a super-chunk): those read the chunk-major path as before.
inline bool prefill_layer_major_default(bool /*hip*/, int /*stages*/, bool /*v026*/ = false) { return false; }
/// The answer for STRATA_PREFILL_LAYER_MAJOR given the variable's text (nullptr = unset): any text that starts a number other than 0 is on, "0" (or any
/// text that reads as 0) is off, both win over everything; unset or empty is the rule above. An explicit "1" is honoured on one GPU too (the
/// opt-in of the first ports); a HIP build still declines at run time.
inline bool prefill_layer_major_resolve(const char* env, bool hip, int stages, bool v026 = false) {
if (env != nullptr && env[0] != '\0') return std::atoi(env) != 0;
return prefill_layer_major_default(hip, stages, v026);
}
/// The small-card prompt path (owner's yes 2026-11-02; DF2-MEM, phaseA-tests/blackwell/RESULTS-DF2MEM.md sections 5-10). On one CUDA card whose expert
/// cache is small, the default prompt path has to read prompts in chunks below 8,192 tokens and streams every expert again for every chunk; reading them
/// with the unfused experts (STRATA_PF_FUSED=0) and, from two chunks on, the layer-major walk (each layer's experts once per super-chunk) is faster:
/// IQ3_S on an RTX PRO 5000 with the cache held to ~1.3K / ~1.6K / ~1.9K engine slots (default chunks 2048 / 3840 / 5888): time to first token of a 20K / 32K
/// prompt -44% / -50%, -41% / -42%, -14% / -12% (and -26% on a real 12 GB RTX 5070 at 20K); from a default chunk of 8,192 on (2.3K slots and up) the default
/// path wins and the same change costs +1..+25%. Not bitwise (first-token KL against the FP16 prompt path 0.012-0.018 for every path including the default;
/// top-1 47 of 48), hence the owner's yes. `default_chunk` is the chunk the DEFAULT path got from the cache sizing (0: none, e.g. no borrowing or an explicit
/// --prefill). One GPU, CUDA, a native (IQ) pack only (what was measured), not under STRATA_DEFAULTS=026. The user's own variables win both ways:
/// `fused_env_set` (STRATA_PF_FUSED named, either value) leaves the expert path alone and with it the walk (a fused layout declines it anyway);
/// `lm_env_set` (STRATA_PREFILL_LAYER_MAJOR named) leaves the walk alone.
struct SmallCardPromptPath {
bool fused_off = false; ///< read the prompt with the unfused experts (STRATA_PF_FUSED=0 as far as the engine is concerned)
bool layer_major = false; ///< and take the layer-major walk for a prompt of two chunks or more (STRATA_PREFILL_LAYER_MAJOR=1)
bool any() const { return fused_off || layer_major; }
};
inline constexpr long long kSmallCardChunkBelow = 8192;
inline SmallCardPromptPath small_card_prompt_path(long long default_chunk, bool hip, int stages, bool native_pack, bool v026, bool fused_env_set,
bool lm_env_set) {
SmallCardPromptPath r;
if (hip || v026 || !native_pack || stages > 1 || default_chunk <= 0 || default_chunk >= kSmallCardChunkBelow) return r;
if (fused_env_set) return r;
r.fused_off = true;
r.layer_major = !lm_env_set;
return r;
}
} // namespace strata
@@ -1,46 +0,0 @@
// strata/core/sm75_series.hpp - the Turing (RTX 20, compute capability 7.5) kernel series: one opt-in switch.
//
// The Turing kernels of PRs #2069-#2072, #2081, #2091-#2093, #2145-#2146, #2220-#2223, #1821 were measured on one RTX
// 2080 Ti (and a CMP 50HX) and are bitwise equal to the kernels they replace. We have no sm_75 card to confirm them, so
// they are ON ONLY WHEN ASKED FOR:
//
// STRATA_SM75_PERF=1 turns on every bitwise Turing kernel of the series on a compute capability 7.5 card.
//
// Each kernel keeps the author's own switch, which wins over STRATA_SM75_PERF in both directions (=0 off, =1 on, on any
// card where the PR said so for tests). Nothing here changes a card that is not a 7.5: the check is the card's compute
// capability (STRATA_EMULATE_CC=75 counts, so a 75-virtual build on an sm_86 card runs the series for tests).
//
// The numerics-changing Turing options are NOT part of this switch and keep their own explicit opt-ins:
// STRATA_SELECT_SIMT=1|2 (FP32 tiled block scorer), STRATA_PA_V2T=1 (v2 prompt attention), STRATA_PF_FUSED_SM75=1
// (fused int8 prompt experts), STRATA_BF16_TC=1 (FP16 tensor-core projections).
#pragma once
#include "strata/core/emulate.hpp"
#include <cstdlib>
namespace strata {
/// STRATA_SM75_PERF=1 (read once)
inline bool sm75_series() {
static const bool on = [] {
const char* e = std::getenv("STRATA_SM75_PERF");
return e != nullptr && std::atoi(e) != 0;
}();
return on;
}
/// the device (raw cudaDevAttrComputeCapabilityMajor / Minor) is a Turing card, or emulates one (STRATA_EMULATE_CC=75)
inline bool is_sm75(int major, int minor) { return cc_of(major, minor) == 75; }
/// the default of a bitwise Turing kernel switch: on for a Turing card when STRATA_SM75_PERF=1
inline bool sm75_default(int major, int minor) { return is_sm75(major, minor) && sm75_series(); }
/// a Turing switch with its own variable: `name` set means 0 off / anything else on (Turing only); unset follows the series
inline bool sm75_switch(const char* name, int major, int minor) {
if (!is_sm75(major, minor)) return false;
const char* v = std::getenv(name);
return v != nullptr ? std::atoi(v) != 0 : sm75_series();
}
} // namespace strata
@@ -1,61 +0,0 @@
// 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
@@ -1,70 +0,0 @@
// 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
@@ -1,207 +0,0 @@
// include/strata/kernels/cpu/expert.hpp - P2.S3: the CPU expert path.
//
// This is the Q2_0 expert kernel promoted out of `bench/micro/cpu_s2.cpp`, which is the instrument that
// measured `c` (Memory/LEDGER.md L9/L10: 15.03 ms for one token's full routed set on 6 cores, DRAM-bound at
// 44.14 GB/s) and whose P0.T2 parity passes at 1.461e-06.
//
// IT IS THE SAME CODE, NOT A COPY. Keeping a second implementation next to a validated one is how a project
// ends up with two answers and no way to say which is right, so `cpu_s2.cpp` is expected to become a thin
// benchmark over these functions. (Until it is, the two exist side by side and this header says so.)
//
// WHAT MAKES IT FAST, and each of the three was paid for once:
//
// * `vpdpbusd` (AVX512-VNNI) does four int8 MACs per instruction. The scalar loop it replaces ran at
// 9.89 GB/s on one core; VNNI is the reason the 6-core figure is 42.55 GB/s.
// * `vpmultishiftqb` (AVX512-VBMI) unpacks the 2-bit codes eight at a time. Its ARGUMENT ORDER is
// (control, data) and was determined empirically - the Intel guide states the opposite, and following the
// guide produced 43 of 64 wrong codes.
// * The row accumulator stays a FLOAT VECTOR and is reduced ONCE at the end of the row. Reducing per
// 64-weight block cost more than the dot products themselves: it made the kernel compute-bound at
// 21 GB/s instead of DRAM-bound at 32.
//
// THE CONTRACT THAT MATTERS, because collapsing it is invisible and cannot match ggml's logits: one Q2_0
// WEIGHT block is QK=64 weights with one fp16 scale, while one ACTIVATION chunk is QKA=32 elements with
// its OWN scale. So a weight block spans TWO activation chunks with two different scales. Using one scale
// per weight block is the natural-looking mistake.
#pragma once
#include "strata/core/geometry.hpp"
#include <cstdint>
#include <cstddef>
namespace strata::kernels::cpu {
// ---- geometry, all of it fixed by the artifact (tools/verify_q2_0_geometry.py: 202/202 tensors at QK=64) ----
inline constexpr int H = strata::core::kCompiledGeometry.n_embd; // 2560 in Flash-Next
inline constexpr int FF = strata::core::kCompiledGeometry.n_ff; // expert intermediate width, 640
inline constexpr int NE = strata::core::kCompiledGeometry.n_expert; // routed experts per layer, 512
static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff,
"the CPU expert path is compiled for core/geometry.hpp");
inline constexpr int QK = 64; // QK2_0: weights per fp16 scale
inline constexpr int QKA = 32; // QK8_1/QK8_0: ACTIVATION elements per scale
inline constexpr int BB = 18; // bytes per 64-weight Q2_0 block: 2 fp16-scale + 16 codes
inline constexpr int MAXC = H / QKA; // 80 activation chunks across the widest reduction
inline constexpr int ROW_GU = H * 2 / 8; // 640 B of codes per gate/up row
inline constexpr int ROW_D = FF * 2 / 8; // 160 B of codes per down row
inline constexpr int SC_GU = H / QK; // 40 weight blocks per gate/up row
inline constexpr int SC_D = FF / QK; // 10 weight blocks per down row
inline constexpr size_t BLOB = 3ull * (H * FF * BB / QK); // 1,382,400
// ---- the blob's internal layout (one expert) ----
inline constexpr size_t O_GU_CODES = 0;
inline constexpr size_t O_D_CODES = 2ull * FF * ROW_GU;
inline constexpr size_t O_GU_SCALES = O_D_CODES + 1ull * H * ROW_D;
inline constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2;
/// One activation in Strata's planar storage: `QKA` elements per chunk.
/// The default legacy quantizer uses FP32 scales and half-away rounding. It is
/// not the pinned ggml CPU Q8_0 contract; expert_set_oracle_q8_0 selects that
/// experimental contract (FP16-rounded scales and x86 nearest-even codes).
///
/// The historical function name `act_quant_q8_1` does not describe a native
/// ggml block layout. One 64-weight block always spans two 32-element chunks.
///
/// `hx[k] = scale[k] * sum[k]` is the weight-independent correction the Q2_0 identity needs
/// (`sum (c-1) d_w xhat d_x = d_w (d_x*sum(c*xhat) - d_x*sum(xhat))`), precomputed once per layer rather than
/// once per row: 640 rows would otherwise recompute it 640 times.
struct ActQ {
alignas(64) int8_t q[H];
float scale[MAXC];
int32_t sum[MAXC];
float hx[MAXC];
int nchunks;
/// The AVX-2 "bit-plane" image of `q` (src/kernels/cpu/q2_avx2.cpp explains it), filled only by
/// `act_quant_q8_1_avx2` with STRATA_Q2_BITPLANE=1 and read only by `q2_0_gguf_rows_multi_avx2`. Per pair p of 64-value blocks:
/// `qp[128p + 32k + 16h + i] = q[128p + 64h + 4i + k]`, `psum[8p + 4h + m]` = the sum of q[128p + 64h + 16m ..
/// + 16), `pscale[8p + 2c + e] = scale[4p + c]`. `bp_pairs` is 0 when the image is absent (n % 128 != 0).
alignas(32) int8_t qp[H];
alignas(32) int32_t psum[H / 16];
alignas(32) float pscale[H / 16];
int bp_pairs = 0;
};
/// Per-worker scratch. Owned by the caller and passed in, so the token path performs NO allocations
/// (P2.T10) - the kernel itself allocates nothing.
struct ExpertScratch {
ActQ a1;
ActQ a2;
alignas(64) float ff[FF];
};
/// Runtime CPU feature check. The kernel uses AVX512-VNNI + AVX512-VBMI + AVX512VL, and code compiled with
/// `/arch:AVX512` can emit AVX-512 anywhere in its translation unit, so a machine without them must be
/// REFUSED rather than silently run. `s2_expert_scalar` is the fallback and exists for tests.
struct CpuFeatures {
bool avx512f = false;
bool avx512bw = false;
bool avx512vl = false;
bool avx512_vnni = false;
bool avx512_vbmi = false;
bool usable() const { return avx512f && avx512bw && avx512vl && avx512_vnni && avx512_vbmi; }
/// A one-line description of what is missing, or "ok".
const char* reason() const;
};
CpuFeatures cpu_features();
/// Exits with a clear message if the CPU cannot run `s2_expert_vnni`. Called once at startup, so a user on an
/// older CPU learns why at second zero instead of seeing an illegal instruction at token 4000.
void cpu_require_expert_support();
/// Select the pinned x86 Q8_0 activation contract at BOTH expert quantization
/// boundaries and the pinned generic CPU Q2_0 dot reduction in all projections.
/// Default false preserves the legacy quantizer and eight-lane FP32 reduction.
/// Configure before starting worker threads and do not change during a request.
/// GPU expert-cache parity is not established for this mode; the driver must
/// reject combining it with that cache. No allocation occurs in either mode.
void expert_set_oracle_q8_0(bool enabled);
/// `x` -> `a` in the configured contract. The function name is historical;
/// `n` must be a multiple of QKA and at most H. No allocation occurs.
void act_quant_q8_1(const float* x, int n, ActQ& a);
/// One expert: `out(H) = down( swiglu( gate(x), up(x) ) )`, all three projections Q2_0,
/// with the configured activation and dot contracts at both quantization boundaries.
///
/// `blob` is one 1,382,400-byte expert in the pack's layout; `x` is the H-wide input; `out` is H-wide.
void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws);
/// The same, with the activation ALREADY quantized in the configured contract.
/// Workers may share this read-only activation; each must own its scratch/output.
///
/// This split exists for the pool. A layer runs TEN experts against ONE activation, so quantizing inside
/// `s2_expert_vnni` would do the same 2560-element conversion ten times per layer per token - 480 redundant
/// conversions per token. P2.S3's work item is `(blob, x-hat quantized, block sums, weight, out)`, and this
/// is the entry point that matches it.
void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws);
/// Plan v0.3 P6: ONE expert applied to up to MAXT tokens that were all routed to it (a speculative verify
/// window routes ~1.5 tokens to each distinct expert). The 1.38 MB blob is read and its 2-bit codes unpacked
/// ONCE per block for all tokens; only the VNNI dot and the accumulation run per token. Every token's output
/// is bitwise equal to `s2_expert_vnni_q` on that token (same operation order per token). Legacy activation
/// contract only; with `expert_set_oracle_q8_0(true)` it falls back to one `s2_expert_vnni_q` per token.
inline constexpr int MAXT = 8;
/// Plan v0.3 P4: the expert in row ranges, so several threads can share one expert. `s2_expert_gu_rows` writes
/// ff[r] = silu(gate_r . x) * (up_r . x) for r in [r0, r1) (of FF); `s2_expert_down_rows` writes out[r] for r in
/// [r0, r1) (of H) from the intermediate's quantized image. Together with `act_quant_q8_1(ff, FF, a2)` in
/// between they are exactly `s2_expert_vnni_q`, row for row (same `row_dot`), so the result is bitwise the same.
bool expert_oracle_q8_0_enabled();
void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1);
void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1);
/// Plan v0.3 P6: the row-range kernels for up to MAXT tokens routed to the same expert (legacy contract only).
/// Each token's rows are bitwise the single-token `s2_expert_gu_rows` / `s2_expert_down_rows`.
void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0,
int r1);
void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0,
int r1);
struct ExpertScratchMulti {
ActQ a2[MAXT];
alignas(64) float ff[MAXT][FF];
ExpertScratch single; // the oracle-contract fallback
};
void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out,
ExpertScratchMulti& ws);
/// The scalar transcription of ggml's formula - NOT a second opinion, but the ORACLE the VNNI path is checked
/// against, and the only path available on a CPU without AVX-512.
///
/// `quant_acts` makes the oracle consume the SAME INT8 activation values the VNNI path uses, **at BOTH
/// stages**. With it OFF the oracle is exact-FP32-activation and the gap between them IS the activation
/// contract; with it ON the two differ only by FP32 evaluation order, so a small gap there proves the kernel
/// itself correct. That separation is the whole point of P0.T2 and it is why this parameter exists rather
/// than two functions.
///
/// CORRECTION TO THE ORIGINAL: `bench/micro/cpu_s2.cpp`'s comment says "at both stages" but its code
/// quantizes only the intermediate, leaving the gate/up projections on raw f32 `x`. That is invisible when
/// the caller passes an already-quantized input - which the engine does - and shows up as a ~1.2% gap when it
/// does not, which reads as a kernel bug and is not one. This version quantizes both.
/// Plan v0.3 P6: rows [r0, r1) of a Q2_0 matrix in the GGUF block layout (18 bytes per 64 weights, `row_bytes`
/// per row, `nblocks` blocks each) against `nt` activations: out[t][r].
void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
/// The same two for CPUs without AVX-512 (src/kernels/cpu/q2_avx2.cpp, compiled for AVX2 only).
void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
/// STRATA_Q2_BITPLANE=1 (read once): the AVX-2 Q2_0 kernel reads the bit-plane image instead of the legacy one.
bool q2_bitplane_enabled();
/// The pre-bit-plane AVX-2 kernel (the default), kept for A/B and parity.
void q2_0_gguf_rows_multi_avx2_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
/// The same rows with AVX-VNNI on or off, not as cpu_avxvnni_ok() says (tests and benches; on only where it holds).
void q2_0_gguf_rows_multi_avx2_v(bool vnni, const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a,
int nt, float* const* out, int r0, int r1);
void act_quant_q8_1_avx2(const float* x, int n, ActQ& a);
/// The same for CPUs with AVX but no AVX2 (src/kernels/cpu/q2_avx1.cpp, the third rung of q2_rows_any /
/// act_quant_any, issue #1699): same arithmetic, 128-bit integer lanes, mul+add instead of FMA (last bits),
/// software fp16 conversion. Called only behind cpu_avx1_ok() && !cpu_avx2_ok().
void q2_0_gguf_rows_multi_avx1(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
void q2_0_gguf_rows_multi_avx1_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
float* const* out, int r0, int r1);
void act_quant_q8_1_avx1(const float* x, int n, ActQ& a);
void s2_expert_scalar(const uint8_t* blob, const float* x, float* out, bool quant_acts);
} // namespace strata::kernels::cpu
@@ -1,115 +0,0 @@
// include/strata/kernels/cpu/expert_layout.hpp - plan v0.3 P6: where each routed expert lives in experts.bin.
//
// A Q2_0 pack (tools/strata_pack.py) has one blob size for every layer, `BLOB`, in the Strata expert form. A
// native pack (tools/iq_pack.py, the IQ2_XS / IQ3_XXS files) keeps each expert's raw GGUF slices, so the blob
// size and the formats change from layer to layer; `native_experts.txt` says how. Everything that touches an
// expert blob - the arena, the VRAM tier, the prompt path, the CPU pool, the GPU window - asks this table.
#pragma once
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/cpu/native_expert.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace strata::kernels::cpu {
struct ExpertLayout {
bool native = false;
int64_t n_layers = 0, n_expert = NE;
std::vector<NativeFmt> fmt; ///< per layer (native packs)
std::vector<uint64_t> offset, bytes; ///< per layer: where its 512 blobs start, bytes per blob
/// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in their GGUF files, so the
/// arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown).
std::vector<uint64_t> gguf_off;
/// Per layer PER ROLE (3 x n_layers, `3 * layer + role`, matching `gguf_off`), the GGUF file - a name beside
/// the --native shard - that holds that role's tensor. Empty = the --native shard itself. Per role because a
/// shard boundary can fall inside a layer: Unsloth's UD-Q4_K_XL has layer 11's down in shard 2 and its gate
/// and up in shard 3 (native_experts.txt v4, the `gate,up,down` shard column).
std::vector<std::string> gguf_file;
int version = 0; ///< native_experts.txt's header version (0 = none given)
uint64_t max_blob = BLOB;
uint64_t total = 0; ///< experts.bin size
uint64_t blob_bytes(int64_t layer) const { return native ? bytes[(size_t) layer] : (uint64_t) BLOB; }
uint64_t layer_offset(int64_t layer) const {
return native ? offset[(size_t) layer] : (uint64_t) layer * (uint64_t) n_expert * (uint64_t) BLOB;
}
uint64_t blob_offset(int64_t layer, int64_t expert) const {
return layer_offset(layer) + (uint64_t) expert * blob_bytes(layer);
}
};
/// Plan v0.3 P6: whether this CPU (and its OS) runs the AVX-512 kernels (F, BW, VL, VNNI, VBMI). Probed in a
/// file compiled without AVX-512, so asking is safe everywhere; STRATA_FORCE_AVX2=1 answers no (for tests).
bool cpu_avx512_ok();
/// The same probes with VBMI required only (the multishift unpack and other byte-permute shuffles): a CPU may run
/// every other feature the kernels use and miss it (Cascade Lake Xeon).
bool cpu_vbmi_ok();
/// AVX-512F + DQ + BW + VL + VNNI, VBMI NOT required: the dpbusd row dots, the q8 quantizer and the dq/bw arithmetic
/// need no byte-permute shuffles (the q2 unpack's op has a substitute in expert.cpp). A CPU this answers yes on
/// used to run every expert through the AVX-2 fallback. Without VBMI, STRATA_VNNI_TIER=1 opts in; unset keeps
/// the AVX-2 rows' rounding. STRATA_FORCE_AVX2 and STRATA_FORCE_ISA still cap this probe.
bool cpu_vnni_ok();
/// Scattered pieces: the copy above is a declaration only (defined in expert.cpp, the AVX-512 TU, because it reads
/// its STRATA_CPU_YMM switch): whether the 512-bit q2 row dot may run at all (VNNI and not the YMM env).
bool q2_rows_512_ok();
/// Whether this CPU runs AVX-512F + AVX-512BW + AVX-512VL + AVX-512DQ (e.g. Skylake-X i9-9920X) for iq_avx512.cpp.
bool cpu_avx512bw_ok();
/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel
/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it.
bool cpu_avx2_ok();
/// Whether this CPU (and its OS) runs AVX (Sandy Bridge and newer): the AVX1 router dot (kq_avx1.cpp) and ggml-cpu in
/// a STRATA_ISA_FLOOR=avx build. The other expert rows then run on ggml-cpu (experimental, slow).
bool cpu_avx1_ok();
/// SSE4.2 + POPCNT: ggml-cpu in a STRATA_ISA_FLOOR=none build.
bool cpu_sse42_ok();
/// STRATA_FORCE_ISA=avx2|avx|sse caps the probes above (3 = no cap, 2 = AVX2, 1 = AVX, 0 = SSE4.2), so the older-CPU
/// paths run on any PC: tests and the experimental builds' checks. ggml-cpu keeps what it was compiled for.
int cpu_isa_cap();
/// The experimental older-CPU build this engine is ("avx", "sse4.2"), or "" for the normal build (AVX2 floor).
const char* isa_floor_build();
/// STRATA_IQ256_GATHER, the AVX-2 i-quant kernels' gathered grid decode (iq_avx2.cpp): -1 unset (auto, see
/// cpu_gather_fast_here), 0 the scalar decode on every core, 1 the gathered one on every core.
int iq256_gather_setting();
/// Whether this CPU's performance cores gather the IQ grid entries faster than they assemble them from scalar loads:
/// an Intel CPU with AVX-VNNI, i.e. Alder Lake / Sapphire Rapids or newer, and not one of the E-core-only parts.
/// The older Intel cores gather slowly (Haswell, Broadwell) or under the Downfall (GDS) microcode (Skylake to Tiger
/// Lake), AMD Zen 2/3 gather slowly, and Zen 4/5 run the AVX-512 kernels. STRATA_FORCE_ISA answers no.
bool cpu_gather_fast();
/// cpu_gather_fast() and the CALLING THREAD runs on a performance core: CPUID 1Ah core type 40h on a hybrid CPU (its
/// E-cores, 20h, gather slower than they assemble). Probed once per thread: the pool pins each worker to one core.
bool cpu_gather_fast_here();
/// Whether the AVX-2 expert kernels take their AVX-VNNI forms (vpdpwssd / vpdpbusd: Alder Lake, Sapphire Rapids and
/// later, P- and E-cores alike; the same integer sums): cpu_avx2_ok() and CPUID 7.1:EAX[4], not capped by
/// STRATA_FORCE_ISA, and not an older-CPU build (STRATA_ISA_FLOOR, which stays on its floor and AVX2).
/// STRATA_NO_AVXVNNI=1 answers no.
bool cpu_avxvnni_ok();
/// Whether a native pack's layer of this ggml type runs on Strata's own Q2_0 kernels (AVX-512 / AVX2, and the AVX1
/// rung of q2_rows_any / act_quant_any on a CPU with AVX but no AVX2: Sandy / Ivy Bridge). Only a CPU without AVX
/// (STRATA_ISA_FLOOR=none) takes ggml-cpu's own Q2_0 vec_dot, which on an i7-3770 took 0.98 ms per expert at one
/// token against 0.52 ms for the AVX1 rows (0.42 with STRATA_Q2_BITPLANE=1; kq_cpu_bench --pairs q2_0/q2_0).
inline bool q2_native_kernels(int type) { return type == 42 && (cpu_avx2_ok() || cpu_avx1_ok()); }
/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none.
std::string cpu_name();
/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has.
void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
int r0, int r1);
void act_quant_any(const float* x, int n, ActQ& a);
/// The same dispatch, always the pre-bit-plane kernel (tests and A/B; the bit-plane switch off by construction).
void q2_rows_any_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
int r0, int r1);
/// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack).
const ExpertLayout& expert_layout();
/// Reads `<pack_dir>/native_experts.txt` when it exists (a native pack), else sets the canonical layout.
/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it).
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);
/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`,
/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte).
/// v5 = v4 plus `hadamard.txt` beside it: Hadamard-folded experts (hadamard.hpp), written only for such models,
/// so an engine that cannot rotate the activations refuses the pack instead of running it wrong.
inline constexpr int kExpertLayoutVersion = 5;
} // namespace strata::kernels::cpu
@@ -1,88 +0,0 @@
// include/strata/kernels/cpu/native_expert.hpp - plan v0.3 P6: one routed expert in its GGUF form on the CPU.
//
// The IQ2_XS / IQ3_XXS model files keep their experts in i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS,
// IQ3_S gate/up; Q2_0 or IQ4_NL down) whose values cannot be re-expressed in the Q2_0 pack form. A native expert
// blob is the three GGUF slices back to back, [gate rows | up rows | down rows]. Activations use the weight type's
// ggml `vec_dot_type`; dispatch selects a format-specific kernel or ggml's per-token dot. The arithmetic mode
// controls whether grouping tokens may change the selected row arithmetic.
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include "strata/core/geometry.hpp"
namespace strata::kernels::cpu {
/// Bytes of the quantized activation of a row of `n` values: the larger of Q8_K (292 bytes per 256) and a 32-block
/// format at 36 bytes per 32 (Q8_1 and friends).
constexpr size_t native_act_bytes_for(int64_t n) {
const size_t q8k = (size_t) (n / 256) * 292, q81 = (size_t) (n / 32) * 36;
return q8k > q81 ? q8k : q81;
}
/// Bytes of the largest quantized activation any native layer uses (2560 values as Q8_K: 10 x 292); never below the
/// 4096 of the Flash-Next engine, and it grows with the compiled hidden size (4096 values need 4672).
inline constexpr size_t kNativeActBytes =
native_act_bytes_for(strata::core::kCompiledGeometry.n_embd) > 4096 ? native_act_bytes_for(strata::core::kCompiledGeometry.n_embd) : 4096;
/// Bytes of the largest quantized down activation (640 values as Q8_0: 20 x 34, or Q8_K 3 x 292); never below 1024,
/// and it grows with the compiled expert width (1024 values as Q8_K need 1168).
inline constexpr size_t kNativeHBytes =
native_act_bytes_for(strata::core::kCompiledGeometry.n_ff) > 1024 ? native_act_bytes_for(strata::core::kCompiledGeometry.n_ff) : 1024;
/// Arithmetic fixed for one pool batch. WindowInvariant preserves the legacy singleton result at every width.
enum class NativeArithmetic { Default, WindowInvariant };
/// One layer's native expert geometry.
struct NativeFmt {
int gu_type = -1, d_type = -1; ///< ggml types of gate/up and of down
int gu_act = -1, d_act = -1; ///< their vec_dot_type (the activation formats)
int64_t n_embd = 0, n_ff = 0;
size_t gu_row = 0, d_row = 0; ///< bytes per weight row
size_t up_off = 0, down_off = 0; ///< inside the blob
size_t bytes = 0; ///< the whole blob
size_t act_bytes = 0, h_bytes = 0; ///< quantized activation sizes (n_embd of gu_act, n_ff of d_act)
/// NVFP4 (ggml type 40) only: the blob ends with {s_gate, s_up, s_down, 0} at this offset, the per-expert
/// weight_scale_2 the block format has no room for (tools/iq_pack.py). 0 = no tail. Each scale goes on its own
/// projection's FP32 output: gate * s_gate, up * s_up, down * s_down. Do not fold s_down into up: the hidden
/// drops to ~1e-5 and its q8 block scale becomes an FP16 subnormal (expert error 2-12% instead of 1.1%).
size_t tail_off = 0;
/// prism.hadamard (hadamard.hpp): the experts of this layer are stored in a rotated basis, and
/// native_quant_act / native_quant_h apply y = H_block (signs * x) before quantizing. had_block 0 = none.
int had_block = 0;
bool had_gu = false, had_d = false;
int layer = -1; ///< the layer this format belongs to (set by expert_layout_load; STRATA_ACT_DUMP only)
const float* gu_signs = nullptr; ///< n_embd signs for x (nullptr: identity)
const float* d_signs = nullptr; ///< n_ff signs for h (nullptr: identity)
};
constexpr int kNvfp4Type = 40;
constexpr size_t kNvfp4Tail = 16;
/// Whether this build has the ggml-cpu path.
bool native_experts_available() noexcept;
/// Fills `f` for a layer; false (with a reason) when ggml-cpu has no dot product for a type.
bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err);
/// x (n_embd floats) -> the gate/up activation (act_bytes), rotated first when the layer is Hadamard-folded.
void native_quant_act(const NativeFmt& f, const float* x, void* dst);
/// h (n_ff floats) -> the down activation (h_bytes), rotated first when the layer is Hadamard-folded.
void native_quant_h(const NativeFmt& f, const float* h, void* dst);
/// From how many tokens native_gu_rows gives this gate/up type to a multi-token kernel (#152; ggml-cpu's per-token dot
/// below that). 1: a token's rows are the same alone and in any group.
int native_gu_mt_min(int gu_type);
/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]) for rows r in [r0, r1), `nt` tokens.
void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff,
int r0, int r1);
/// out[t][r] = down_r . hq[t] for rows r in [r0, r1).
void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out,
int r0, int r1);
/// Same per-token result as the corresponding legacy nt=1 call on this build and CPU.
/// Kernels that already satisfy this contract retain their grouped execution.
void native_gu_rows_invariant(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt,
float* const* ff, int r0, int r1);
void native_down_rows_invariant(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt,
float* const* out, int r0, int r1);
} // namespace strata::kernels::cpu
@@ -1,55 +0,0 @@
// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have.
//
// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time
// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is
// missing exactly two things the i-quant kernels rely on:
//
// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). The reference for its
// fallback is llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), since the kernels in this directory are
// transcribed from llama.cpp's vecdotq.cuh and that wrapper's operands are the same sites: it reinterprets
// the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a` does for these calls. The
// fallback below computes exactly that with four PTX `vmad` byte-select instructions, so it is bit-exact
// rather than merely close (tools/sm60_dp4a_check.cu checks it against the byte-wise form).
// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that
// spins without it is correct, merely busier.
//
// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX
// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is
// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is
// HIP's own `__nanosleep`.
#pragma once
#include <cstdint>
#if defined(STRATA_HIP_GFX906)
#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)
#endif
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
// PTX vmad with byte selectors: compiles to four VMAD.S8.S8 (cuobjdump -sass), no byte extraction.
// Bit-exact with the byte-wise form it replaces: 1.07e9 cases (edge bytes, every per-lane byte pair, random),
// 0 mismatches, ~2.2x faster in isolation on a Tesla P100 (tools/sm60_dp4a_check.cu).
int r = c;
asm("vmad.s32.s32.s32 %0, %1.b0, %2.b0, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b1, %2.b1, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b2, %2.b2, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b3, %2.b3, %0;"
// The first instruction writes r before the remaining instructions
// have read a/b. Equal-valued operands must not share its register.
: "+&r"(r) : "r"(a), "r"(b));
return r;
}
#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c))
#else
#define STRATA_DP4A(a, b, c) __dp4a((a), (b), (c))
#endif
/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a
/// contract, and only pre-Volta CUDA has no `__nanosleep` at all.
__device__ __forceinline__ void strata_spin_pause() {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700
// sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed.
#else
__nanosleep(100);
#endif
}
@@ -1,104 +0,0 @@
// 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
@@ -1,41 +0,0 @@
// 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
@@ -1,97 +0,0 @@
// 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
@@ -1,44 +0,0 @@
// include/strata/kernels/gfx_arch.hpp - which AMD architecture names the gfx11 matrix-core code (and the gfx12 native
// prompt-expert kernels) was built for.
//
// The WMMA kernels select their intrinsic with `#if defined(__gfx1100__) || ... || defined(__gfx1151__)`: a gfx11 part
// outside that list (gfx1152, ...) gets an empty or trapping body. The runtime gates therefore match the SAME
// list, not the "gfx11" prefix, so such a part falls back to hipBLASLt / the portable kernels instead of launching code
// that is not there. Pure string matching (no HIP headers), usable from host code of any build.
#pragma once
#include <cstddef>
#include <cstring>
namespace strata::kernels {
/// `gcn` is hipDeviceProp_t::gcnArchName ("gfx1151", or "gfx1151:sramecc-:xnack-"): true when it is exactly `name`.
inline bool gfx_arch_is(const char* gcn, const char* name) {
if (gcn == nullptr) return false;
const std::size_t n = std::strlen(name);
return std::strncmp(gcn, name, n) == 0 && (gcn[n] == '\0' || gcn[n] == ':');
}
/// Discrete RDNA3 desktop / workstation GPUs (RX 7900 XTX / XT / GRE / W7900 = gfx1100,
/// RX 7800 XT / 7700 XT = gfx1101, RX 7600 / 7600 XT = gfx1102).
inline bool gfx_arch_is_discrete_rdna3(const char* gcn) {
return gfx_arch_is(gcn, "gfx1100") || gfx_arch_is(gcn, "gfx1101") || gfx_arch_is(gcn, "gfx1102");
}
/// The gfx11 targets the matrix-core kernels (prompt GEMM / attention / scorer / fused experts) are compiled for.
inline bool gfx_arch_is_gfx11_wmma(const char* gcn) {
return gfx_arch_is(gcn, "gfx1100") || gfx_arch_is(gcn, "gfx1101") || gfx_arch_is(gcn, "gfx1102") || gfx_arch_is(gcn, "gfx1103") ||
gfx_arch_is(gcn, "gfx1150") || gfx_arch_is(gcn, "gfx1151");
}
/// The gfx12 (RDNA4) targets the gfx12 matrix-core kernels are compiled for (`#if defined(__gfx1200__) ||
/// defined(__gfx1201__)`): the R9700 / 9070 (XT) are gfx1201, the 9060 (XT) gfx1200.
inline bool gfx_arch_is_gfx12_wmma(const char* gcn) { return gfx_arch_is(gcn, "gfx1200") || gfx_arch_is(gcn, "gfx1201"); }
/// Strix Halo (Ryzen AI Max, RDNA3.5): the part the gfx1151 defaults (docs/STRIX_HALO.md) are measured on.
inline bool gfx_arch_is_gfx1151(const char* gcn) { return gfx_arch_is(gcn, "gfx1151"); }
/// RDNA4 (Radeon AI PRO R9700 = gfx1201, RX 9070 / 9070 XT = gfx1201, RX 9060 = gfx1200).
inline bool gfx_arch_is_gfx12(const char* gcn) { return gfx_arch_is(gcn, "gfx1200") || gfx_arch_is(gcn, "gfx1201"); }
} // namespace strata::kernels
@@ -1,132 +0,0 @@
// 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
@@ -1,135 +0,0 @@
// include/strata/kernels/i8_expert_rule.hpp - when a prompt layer's expert groups take our own int8 dot-product kernels (native_expert_i8,
// src/kernels/cuda/i8_expert.cuh) in place of MMQ.
//
// STRATA_EXPERT_I8 = 1 asks for them on any card, 0 turns them off, unset (or empty) leaves the card class to decide: on the HIP cards gfx1030 / gfx1031 /
// gfx1032 (RDNA2: no matrix cores, the byte dot product `v_dot4_i32_i8` only) the covered formats take them by default. Measured on the RX 6700 XT
// (gfx1031, one MoE layer of Flash-Next's shape, tokens 2,048 / 8,192 / 20,000): 1.10 - 1.35 times MMQ for the IQ2_S / IQ2_XXS packs with a Q2_0 down and
// for the IQ3_S / IQ3_XXS packs with an IQ4_NL down (par/RESULTS-OWN-I8.md). gfx1034 / 1035 / 1036 were not compiled or timed: they stay on MMQ.
//
// Both kinds of call keep the size floor: a launch of experts averaging fewer than kI8MinGroupEntries entries stays on today's path (no timing below
// 2,048 tokens exists on this class; the P100 / V100 numbers say the grouped / MMQ kernels win at 300 tokens). Pure functions: no GPU and no
// environment read here (the caller passes the variable's text and the device's gcnArchName), so the rule is unit-tested without a card.
#pragma once
#include <cstddef>
#include <cstdint>
#include "strata/kernels/gfx_arch.hpp"
namespace strata::kernels {
/// Groups (a launch of up to 16 experts) averaging fewer entries than this keep today's path.
inline constexpr int64_t kI8MinGroupEntries = 256;
/// The RDNA2 parts that take the int8 kernels by default. `gcn` is hipDeviceProp_t::gcnArchName (a CUDA card has none: nullptr or "").
inline bool gfx_arch_is_gfx103x_i8(const char* gcn) {
return gfx_arch_is(gcn, "gfx1030") || gfx_arch_is(gcn, "gfx1031") || gfx_arch_is(gcn, "gfx1032");
}
/// STRATA_EXPERT_I8 read as a state: 1 = on (any non-empty text that does not start with '0'), 0 = off (starts with '0'), -1 = not set (null or empty).
inline int i8_switch_parse(const char* text) {
return text == nullptr || text[0] == '\0' ? -1 : (text[0] == '0' ? 0 : 1);
}
/// A build without llama.cpp's MMQ (-DSTRATA_MMQ=OFF, or HIP without STRATA_PREFILL_MMQ; prefill.cpp's STRATA_PF_OWN_ONLY): the int8 kernels are the default prompt-expert kernels on every
/// card that covers the layer's formats, because MMQ is what they replace; without them the layer runs each expert on the FP16 path (4 - 5 times slower on an RX 6700 XT). `state` is
/// i8_switch_parse's answer; a value the user set (0 or 1) is kept, an unset switch reads as 1 in such a build. "Default on" is not "forced": see i8_order_allows.
inline int i8_switch_effective(int state, bool mmq_free) { return state == -1 && mmq_free ? 1 : state; }
/// Does the build / card class alone (switch not set) take the int8 kernels: the RDNA2 class, or any card in a build without MMQ.
inline bool i8_expert_class_default(int state, const char* gcn, bool mmq_free = false) { return state == -1 && (mmq_free || gfx_arch_is_gfx103x_i8(gcn)); }
/// The order of the prompt-expert paths for one layer of one chunk: the fused kernels (a long chunk on a layer they cover) and the staged group entry (a short chunk, the fused kernels'
/// entry) come first, the int8 kernels take what is left, the FP16 path what even they do not cover. This holds for a value the user set too (STRATA_EXPERT_I8=1 asks for the int8 kernels
/// where nothing faster takes the layer: R9700, 2,048 tokens, fused 1,144.6 ms against int8 1,624.5); it is the order prefill.cpp's `i8_l` condition has.
inline bool i8_order_allows(bool fused_takes, bool staged_takes) { return !fused_takes && !staged_takes; }
inline bool i8_expert_takes(int state, const char* gcn, int64_t group_entries, bool supported); // (defined below)
/// The whole question for one layer of one chunk, as the pure rule (the engine asks the two halves where it has them: i8_order_allows in prefill.cpp, i8_expert_takes in iq_kernels.cu).
inline bool i8_layer_takes(int raw_state, bool mmq_free, const char* gcn, int64_t group_entries, bool supported, bool fused_takes, bool staged_takes) {
return i8_order_allows(fused_takes, staged_takes) && i8_expert_takes(i8_switch_effective(raw_state, mmq_free), gcn, group_entries, supported);
}
/// Do the expert groups of a layer take `native_expert_i8`? `state` = i8_switch_parse(getenv), `gcn` the device's gcnArchName, `group_entries` the entries
/// of one launch on average, `supported` = native_expert_i8_supported(layout) (formats, sizes, the device's shared memory).
inline bool i8_expert_takes(int state, const char* gcn, int64_t group_entries, bool supported) {
if (state == 0 || !supported || group_entries < kI8MinGroupEntries) return false;
return state == 1 || i8_expert_class_default(state, gcn);
}
// The few-rows route. A layer whose experts average fewer routed rows than a crossing runs on the grouped kernels (native_expert_grouped, no shared-memory
// staging: one launch pair per 16 experts like the int8 kernel's, the q8_1 image of the rows made by quantize_q8_1_rows); from the crossing up it runs on the
// int8 kernel. Measured on one MoE layer of Flash-Next's shape (average rows per expert where both take equal time), WITHOUT the 8-entry slices (N8): Tesla P100 (sm_60) 8.4, A4000 10.2 - 11.7,
// RX 6700 XT 10.2 - 10.8, R9700 11.7 (par/RESULTS-I8-RESEARCH.md); WITH them (STRATA_I8_N8, on by default in this range, see i8_n8_takes) P100 5.7 - 5.8, A4000 6.9 - 7.4, R9700 6.9 - 7.4 (par/RESULTS-I8-MMQOFF.md). The limits below are the crossings with N8; the int8 side never loses more than 5 %.
// Without the route the int8 kernel keeps the size floor above (256 entries per group of 16 experts = 16 rows per expert) and the layers under it stay on today's path.
inline constexpr int kI8FewRowsDefault = 7; ///< every card but the Tesla P100 (10 with STRATA_I8_N8=0)
inline constexpr int kI8FewRowsSm60 = 6; ///< compute capability 6.0 (the P100): its crossing is lower (8 with STRATA_I8_N8=0)
/// STRATA_I8_FEWROWS read as the limit: not set (or empty, or text that is no number) = the card class's own `class_default`, 0 = no route, N = a limit of N rows per expert.
inline int i8_fewrows_limit(const char* text, int class_default) {
if (text == nullptr || text[0] == '\0') return class_default;
if (text[0] < '0' || text[0] > '9') return class_default;
long v = 0;
for (const char* p = text; *p >= '0' && *p <= '9'; ++p) {
v = v * 10 + (*p - '0');
if (v > 100000) break;
}
return (int) v;
}
/// The class's default limit: the P100 (compute capability 6.0) 6, every other card 7.
inline int i8_fewrows_class_default(int cc_major, int cc_minor) { return cc_major == 6 && cc_minor == 0 ? kI8FewRowsSm60 : kI8FewRowsDefault; }
/// Does a layer with `rows` routed rows over `experts` experts (those with at least one row) take the grouped kernels? limit 0 = the route is off.
inline bool i8_fewrows_takes(int limit, int64_t rows, int64_t experts) { return limit > 0 && experts > 0 && rows < (int64_t) limit * experts; }
// The 8-entry slices of the tile-2..4 int8 kernel (N8: two weight rows and one entry of each 8-entry slice per thread; bit-identical output). Measured on the A4000, the P100 and
// the R9700 (par/RESULTS-I8-MMQOFF.md, I8 column of the expert-paths bench, Flash-Next's shape, IQ2_XXS / Q2_0 and IQ3_S / IQ4_NL): tile 2 (up to 39 entries per expert on average, about
// 1,950 tokens) 23 - 33 % faster at 100 - 300 tokens, 12 - 17 % at 1,000 and 6 - 13 % at 1,500 on all three; tile 3 (2,048 tokens) 3 - 6 % faster on the A4000 and the P100 but
// 1.6 - 2.9 % SLOWER on the R9700. So the default is tile 2 only; STRATA_I8_N8=1 asks for tiles 2 - 4, STRATA_I8_N8=0 for none.
/// STRATA_I8_N8 read as a state (1 / 0 / -1 not set), the tile code the call settled on (2, 3, 4 = rows of 16 entries per thread; 8 = the 128-entry kernel, which has no 8-entry form).
inline bool i8_n8_takes(int state, int tile) {
if (state == 0) return false;
return state == 1 ? tile >= 2 && tile <= 4 : tile == 2;
}
// Volta (compute capability 7.0: 96 KB of shared memory per multiprocessor, no int8 matrix cores, so every routed expert of a prompt runs on these kernels). The tile the
// other cards take from 96 entries a group on average (tile 8, 128 x 128, 54-62 KB) and tile 4 (51-59 KB) leave one block of 8 warps per multiprocessor there; tiles 2 and 3 of
// the IQ3 formats (43 / 48 KB) run two. Tesla V100-SXM2 32 GB, one layer of Flash-Next's shape, uniform routing, MMQ time / int8 time (above 1: ours faster), the call's
// own pick against tile 3 (phaseA-tests/tune0216, bench1-v100): IQ3_S / IQ4_NL 0.745 -> 0.949 at 8,192 tokens and 0.795 -> 0.820 at 26,000, IQ3_XXS / IQ4_NL 0.721 -> 0.955 and
// 0.795 -> 0.831; output bits equal at every tile (the tile only groups entries). The big-grid formats (IQ2_S's 8 KB grid table) read their grid from global memory there
// (I8Smem GG: the same words, the same bits), so their tile 3 fits two blocks too. So on Volta the call's pick is lowered to the largest tile that still gives two blocks per
// multiprocessor (tile 8 counts as 4 first); a tile set by STRATA_I8_TM is kept as given.
/// `tm` the pick (2, 3, 4 or 8), `bytes2/3/4` the dynamic shared memory of tiles 2-4 for the layer's formats, `smem_sm` the multiprocessor's shared memory, `reserved` the
/// driver's reservation per block (cudaDevAttrReservedSharedMemoryPerBlock).
inline int i8_tile_two_blocks(int tm, std::size_t bytes2, std::size_t bytes3, std::size_t bytes4, std::size_t smem_sm, std::size_t reserved) {
int t = tm >= 4 ? 4 : tm <= 2 ? 2 : 3;
auto fits = [&](int k) { const std::size_t b = (k == 2 ? bytes2 : k == 3 ? bytes3 : bytes4) + reserved; return 2 * b <= smem_sm; };
while (t > 2 && !fits(t)) --t;
return t;
}
/// Volta's tensor-core form of the kernels (tile code 5, src/kernels/cuda/i8h_volta.cuh: the same products on the FP16 tensor cores, bit-identical output) from this many
/// entries a launch's expert has on average. Tesla V100, one layer of Flash-Next's shape, uniform routing, MMQ time / time (phaseA-tests/tune0216 bench5), tile 3 -> tile 5:
/// at 40 entries (2,048 tokens) 1.38 -> 1.22 (slower), at 160 (8,192) 0.95 -> 0.96 (IQ3_S), 0.95 -> 0.94 (IQ3_XXS), 0.90 -> 0.94 (IQ2_S), at 508 (26,000) 0.82 -> 0.86,
/// 0.83 -> 0.84, 0.82 -> 0.89; output hashes equal at every size.
inline constexpr int64_t kI8hMinAvg = 160;
/// The Volta pick: tile 5 from kI8hMinAvg entries on average when the formats have it (`h_ok`), else the two-block tile of i8_tile_two_blocks.
inline int i8_tile_volta(int two_block_tile, int64_t avg, bool h_ok) { return h_ok && avg >= kI8hMinAvg ? 5 : two_block_tile; }
/// STRATA_I8_SM70 read as a state (1 / 0 / -1 not set): the Volta tile rule above and the global grid are on unless it is 0.
inline bool i8_volta_rule_on(int state) { return state != 0; }
// The Tesla P100 (compute capability 6.0) in a build without MMQ. There the build WITH MMQ takes the FP16 prompt path by default (prefill.cpp gp100_fp16_default: GP100 has no
// dp4a), so the unset-switch int8 default of a build without MMQ (i8_switch_effective) must not replace it where the int8 kernel loses to it. Measured on the P100 (OUT build,
// prompt read ms int8 / FP16, par/RESULTS-P100-GATE.md): 300 0.874, 600 0.865, 1,000 0.844, then 1,200 1.196, 1,500 1.142, 2,048 1.085, 8,192 1.081: the step sits at the chunk size from
// which every expert streams (stream_all_min, 1,024 tokens, prefill.cpp), so the limit is that floor and no constant of its own: the int8 default applies to chunks BELOW it
// (the staged per-layer path), the FP16 path from it up, as the build with MMQ does. A value the user set wins at every size (STRATA_EXPERT_I8=1 keeps the int8 kernels, =0 turns
// them off); every other card class has no such limit.
/// May the int8 default (switch NOT set, build without MMQ) take a chunk of `chunk_tokens` tokens on this device? `raw_state` = i8_switch_parse(getenv): a set value (0 or 1) is
/// not this rule's to decide (true); a build with MMQ, or a card that is not the P100 (`sm60`), has no limit (true); otherwise the chunk must be under `limit`.
inline bool i8_chunk_default_allows(int raw_state, bool mmq_free, bool sm60, int64_t chunk_tokens, int64_t limit) {
if (raw_state != -1 || !mmq_free || !sm60) return true;
return chunk_tokens < limit;
}
} // namespace strata::kernels
@@ -1,197 +0,0 @@
// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S,
// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's
// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding).
//
// The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh,
// ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it
// means in llama.cpp. Activations are q8_1 (32 values, fp16 scale and fp16 sum), the llama.cpp CUDA contract.
#pragma once
#include <cstddef>
#include <cstdint>
namespace strata::kernels {
/// ggml type ids handled here.
bool iq_supported(int ggml_type) noexcept;
/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30).
bool embed_type_supported(int ggml_type) noexcept;
/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block).
size_t iq_row_bytes(int ggml_type, int64_t n) noexcept;
/// q8_1 blocks for `n_rows` rows of `n_cols` floats (n_cols a multiple of 32): y is n_rows * n_cols/32 blocks.
void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);
/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column).
void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream);
/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32; fp16 times `*scale` when given (device:
/// an NVFP4 expert's s_down, read by the kernel itself so the source may be released right after it).
void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale = nullptr);
void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream);
/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped
/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256).
void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,
int64_t n_embd, float* out, void* stream);
/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path
/// uses: row 2r = gate row r, row 2r+1 = up row r. `tail` (device, NVFP4 only): the blob's {s_gate, s_up,
/// s_down, 0}; gate rows are scaled by s_gate and up rows by s_up (s_down goes on the down matrix: folded into up,
/// the up weights would sit near 1e-8, deep in FP16's subnormals).
void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst,
void* stream, const float* tail = nullptr);
/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks.
struct NativeExpertLayout {
int gu_type = -1, d_type = -1;
int64_t n_embd = 0, n_ff = 0;
size_t gu_row = 0, d_row = 0; // bytes per row
size_t up_off = 0, down_off = 0; // byte offsets inside the blob
size_t bytes = 0; // the whole blob
size_t tail_off = 0; // NVFP4: {s_gate, s_up, s_down, 0} at the blob's end; 0 = none
// APR (prism.hadamard): the down weights are Hadamard-folded, so native_expert_grouped rotates h before
// quantizing it (hadamard_rows). had_block 0 = none; d_signs is a DEVICE vector of n_ff signs or nullptr.
int had_block = 0;
bool gu_nib = false; // STRATA_EXPERT_NIBBLE: gate/up as 4-bit codes (strata/core/expert_nibble.hpp's
// slot); set only by native_expert_layout_nib
const float* d_signs = nullptr;
};
NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
/// STRATA_EXPERT_NIBBLE: a converted VRAM slot - gate/up as 4-bit codes, scales and d (expert_nibble.hpp's layout:
/// up_off = the up rows' codes, down_off = kGuBytes, bytes = the slot), the GGUF down rows after them. IQ2_S /
/// IQ3_XXS / IQ3_S at n_embd 2560, n_ff 640 only, and only in a build with the kernels (`native_expert_nib_supported`).
NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;
/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the
/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated).
bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;
/// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries.
size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff);
/// A770 port (STRATA_PF_XMX=2): up to kXmxGroupMax experts' products in one XMX launch, the weights decoded from the
/// quantized rows into local memory. Expert i: Y_i[cnt[i]][N] = X_i . W_i^T (X FP16, Y FP32, rows back to back).
/// gate/up: b != nullptr (a = gate, b = up rows of n_embd = K; the output's virtual rows interleave gate/up);
/// down: b == nullptr, a = the [N][K] rows. N a multiple of 128, K of 32 (and a whole number of rows per 256 block).
constexpr int kXmxGroupMax = 16;
void iq_xmx_grouped(int ty, const uint8_t* const* a, const uint8_t* const* b, const int32_t* cnt, int n,
const uint16_t* X, float* Y, int N, int K, void* stream);
/// Grouped experts in the native format: group g's blob at device address grp_ptr[g]; its entries
/// [grp_start[g], grp_start[g+1]) read token ent_tok[e]'s q8_1 activation (n_embd/32 blocks per token in x_q8_1)
/// and write row ent_dst[e] of `out` (n_embd floats). Counts are read on the device.
/// `grid_groups` (1 .. cap_groups; 0 = cap_groups) groups run side by side, a block row each striding over the rest:
/// a call that usually has few groups or none (the verify window's PCIe share) launches less for the ones it does
/// not have. The results do not depend on it.
void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,
const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,
int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,
int64_t grid_groups = 0);
/// OWN-I8 (research, off by default): the same call as `native_expert_grouped` on our own int8 dot-product kernels - a tile of
/// 64 weight rows x 32..64 entries per block, each weight sub-block decoded once per tile into int8 in shared memory, `dp4a`
/// products, SwiGLU and the q8_1 quantization of H in the gate/up epilogue (gate/up never go to memory). For cards with no
/// matrix cores the fused prompt kernels can use. `scratch` as for native_expert_grouped (native_expert_scratch_bytes).
/// Covered: gate/up IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S / IQ2_S with a down of IQ4_NL / Q2_0 (`native_expert_i8_supported`);
/// no NVFP4 tail, no APR Hadamard, no 4-bit slots. STRATA_EXPERT_I8=1 makes `native_expert_grouped` itself take it for a call of
/// 256 entries or more (the prompt chunk of a Qwen3.6 engine without MMQ); STRATA_I8_TM = 2 | 3 | 4 forces the tile.
bool native_expert_i8_supported(const NativeExpertLayout& L) noexcept;
/// OWN-I8, the prompt path's question (once per layer, src/prefill/prefill.cpp): do the expert groups of this layer take `native_expert_i8`
/// on this device, for groups of about `group_entries` entries (rows of one launch)? STRATA_EXPERT_I8=1 asks for it on any card, =0 never; unset:
/// the HIP cards gfx1030 / gfx1031 / gfx1032 take it, every other card keeps MMQ (include/strata/kernels/i8_expert_rule.hpp). The formats and the
/// device's shared memory still have to allow it (`native_expert_i8_supported`); groups under 256 entries keep the other path.
/// Shared prompt code, no device work: a Metal build answers false.
bool native_expert_i8_prompt(const NativeExpertLayout& L, int64_t group_entries) noexcept;
/// OWN-I8: true when the answer above is "yes" because of the card class or the build (STRATA_EXPERT_I8 not set), not because the variable names it; the engine's
/// start line differs. A Metal build answers false.
bool native_expert_i8_by_default() noexcept;
/// OWN-I8: called once, before main, by a build without llama.cpp's MMQ (prefill.cpp, STRATA_PF_OWN_ONLY): an unset STRATA_EXPERT_I8 then reads as 1 (i8_expert_rule.hpp,
/// i8_switch_effective); a build with MMQ never calls it. A Metal build ignores it.
void native_expert_i8_set_mmq_free() noexcept;
/// OWN-I8, the few-rows route (include/strata/kernels/i8_expert_rule.hpp): the average routed rows per expert under which a prompt layer that takes the int8 kernels
/// runs on the grouped kernels instead; 0 = no route (STRATA_I8_FEWROWS=0, or the int8 kernels are off). The class default: 6 on a Tesla P100, 7 elsewhere.
/// Shared prompt code, no device work for a build that has none: a Metal build answers 0.
int native_expert_i8_few_rows_limit() noexcept;
/// OWN-I8 (tests, logs; CUDA / HIP builds only, no Metal definition: nothing shared calls these three): the dynamic shared memory per block the current device
/// lets `native_expert_i8` use, in bytes (the device's opt-in attribute, 48 KB where it reports less; STRATA_I8_SMEM_LIMIT can lower it).
size_t native_expert_i8_smem_limit() noexcept;
/// What the last `native_expert_i8` call asked its two launches for: the tile code, the dynamic shared memory passed as each launch's third argument, and each
/// launch's own status (cudaPeekAtLastError right after it, 0 = accepted).
struct NativeExpertI8Launch {
int tile;
size_t gu_bytes, down_bytes;
int gu_err, down_err;
};
NativeExpertI8Launch native_expert_i8_last_launch() noexcept;
/// Does a launch of an empty kernel with this much dynamic shared memory run on the current device? 1 yes, 0 refused, -1 not available (a HIP build). A
/// diagnostic for native_i8_parity; the attribute call is tried and its refusal ignored, the launch decides; the context is left clean.
int native_expert_i8_probe_launch(size_t bytes) noexcept;
/// Bytes of scratch `native_expert_i8` needs (it is smaller than native_expert_scratch_bytes: H goes out as q8_1 blocks only): `cap_entries`
/// entries, at most `cap_groups` groups, `n_ff` features.
size_t native_expert_i8_scratch_bytes(int64_t cap_entries, int64_t cap_groups, int64_t n_ff);
/// The activation image `native_expert_i8` reads (its `x_q8_1` argument): `n_rows` x `n_cols` floats as blocks of 32 values {float d; int8 q[32]} (36 bytes), MMQ's numbers
/// (d_inv = 127 / amax, q = round(x * d_inv), d = 1 / d_inv, the scale in FP32). NOT the q8_1 block of the other kernels (half2 ds); `n_cols` a multiple of 32.
void native_expert_i8_quantize(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);
/// A launch record of at most kI8PutRecordMax bytes (a multiple of 4) written to `dst` (device) on `stream` by a one-block kernel that takes the bytes as its argument:
/// no host-to-device copy, so the write does not queue behind other copies in the copy engine (the prompt path's streamed experts). False: too many bytes, or the launch failed.
constexpr size_t kI8PutRecordMax = 512;
bool native_expert_i8_put_record(void* dst, const void* src, size_t bytes, void* stream);
void native_expert_i8(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, const void* x_q8_1,
void* scratch, float* out, void* stream);
/// true: `native_expert_grouped`'s launches before the group stride (STRATA_GROUPED_V1=1 at startup) - a block row
/// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results
/// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs.
void native_grouped_set_v1(bool v1);
/// The bench / parity only: the 4-bit gate/up kernel of every format (-1 = expert_nibble.hpp's gu_skeleton, the
/// default; 0 = the S skeleton; 1 = the P skeleton). Bitwise the same results; set before graph capture.
void native_expert_nib_set_variant(int v);
/// gu-proto (nib_gu_proto.cuh): variant v's registers, local bytes and resident 256-thread blocks per SM for gu_type;
/// false when v is not a gu-proto id (>= 10) or the type has none.
bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm);
/// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase
/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down, 3 gate/up only).
void native_expert_set_mode(int mode, int phase);
/// APR (prism.hadamard): y = H_block (signs * x) per block of `block` values of each of `rows` rows of `width`
/// (x == y allowed). `signs`: a device vector of `width` signs, or nullptr (identity). The same floats as the CPU's
/// hadamard_rotate. The f16 form rotates in place, computing in float.
void hadamard_rows(const float* x, float* y, int64_t rows, int64_t width, int block, const float* signs, void* stream);
void hadamard_rows_f16(uint16_t* x, int64_t rows, int64_t width, int block, const float* signs, void* stream);
/// A device copy (on the current device) of the host sign vector `host` of `width` signs, made on first use and
/// kept for the process. Call it at setup, not inside a CUDA graph capture. nullptr for a nullptr `host`.
const float* hadamard_device_signs(const float* host, int width);
/// EXPDEC (STRATA_EXPDEC, docs/EXPERTDEC.md): `native_expert_grouped` stages the group's q8_1 activations in shared
/// memory and computes several rows per lane, the same sums per (row, entry) as the default kernels (bitwise), for
/// gate/up IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S / IQ2_S at n_embd 2560 and down IQ4_NL / Q2_0 at n_ff 640; other layouts
/// keep the default kernels. Enabled by default on gfx12 (STRATA_EXPDEC=0 disables it) and opt-in elsewhere
/// (STRATA_EXPDEC=1). Set before graph capture; captured graphs keep the kernels they captured.
void native_expert_set_expdec(int on);
int native_expert_expdec();
/// Its knobs, read from the environment at startup (STRATA_EXPDEC_R 1 | 2, _DR 1 | 2 | 4, _MINB 2 | 4, _D20 0 | 1,
/// _RB, _DRB, _MINBLK): gate/up and down rows per lane, the gate/up kernel's __launch_bounds__ minimum blocks per SM
/// (2 = up to 128 registers, 4 = up to 64), EXPDEC for the IQ4_NL down too, gate/up and down rows per block (0 = auto
/// from the launch's groups), the auto rule's minimum blocks. In the setter a field <= 0 (< 0 for the two rows per
/// block and down_iq4_nl) keeps the current value.
/// `down` (STRATA_EXPDEC_DOWN, default 1 on gfx12 for Q2_0 down and 0 elsewhere; STRATA_EXPDEC_DOWN=0/1 overrides):
/// EXPDEC for the down too; `down_iq4_nl` (STRATA_EXPDEC_D20, default 0) remains opt-in everywhere.
struct NativeExpertExpdecParams {
int gu_rows_per_lane = 0, down_rows_per_lane = 0, gu_min_blocks_per_sm = 0, down_iq4_nl = -1, down = -1;
int gu_rows_per_block = -1, down_rows_per_block = -1, min_blocks = 0;
};
void native_expert_set_expdec_params(const NativeExpertExpdecParams& p);
NativeExpertExpdecParams native_expert_expdec_params();
/// Whether EXPDEC has kernels for this layout's gate/up and down (the bench's check).
bool native_expert_expdec_takes(const NativeExpertLayout& L, bool& gu, bool& down);
/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry;
/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give
/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured.
/// Volta prompt experts (STRATA_PF_WMMA): Y[rows of expert e] = X[rows] . W_e^T for a group of experts, W_e at
/// W + e * expert_bytes (n_out rows of K values of type ty, GGUF blocks), X FP16 (ldx), rows bounds[e]..bounds[e+1],
/// Y FP32 (ldy). FP16 tensor cores, FP32 sums. false: not launched (shape or type not covered). CUDA only.
bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx,
const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream);
void iq_set_old_kernels(bool old);
bool iq_old_kernels();
} // namespace strata::kernels
@@ -1,64 +0,0 @@
// 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
@@ -1,22 +0,0 @@
#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
@@ -1,37 +0,0 @@
#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
@@ -1,21 +0,0 @@
#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
@@ -1,39 +0,0 @@
#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
@@ -1,37 +0,0 @@
#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);
}
@@ -1,31 +0,0 @@
#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);
}
@@ -1,27 +0,0 @@
#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);
}
@@ -1,28 +0,0 @@
// include/strata/kernels/nvfp4_decode_sm120.hpp - Clean-room MIT Blackwell sm_120a hardware NVFP4 grouped decode/verify.
//
// MIT License
// Copyright (c) 2026 Niko1221 and the Strata contributors
#pragma once
#include "strata/kernels/iq_kernels.hpp"
#include <cstdint>
namespace strata::kernels {
/// True when compiled with sm_120a/sm_121a hardware FP4 decode support and running on a Blackwell sm_120/sm_121 GPU
/// (STRATA_NVFP4_DEC_SM120=0 disables at runtime).
bool nvfp4_decode_sm120_available() noexcept;
/// Test/benchmark override: -1 = follow STRATA_NVFP4_DEC_SM120 env (default), 0 = disable, 1 = enable.
void nvfp4_decode_sm120_set_override(int mode) noexcept;
/// Hardware Blackwell sm_120a grouped NVFP4 (type 40) MoE decode/verify (fused gate+up+SwiGLU+Q8_1 -> down).
/// Uses native PTX cvt.rn.f16x2.e2m1x2 + K-chunked split-half FP16 shared-memory activation caching across up to
/// 8 tokens per expert group, reading weights once per group. Returns false if unsupported shape/device.
bool nvfp4_decode_sm120_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr,
const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst,
const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries,
const void* x_q8_1, void* hq_scratch, float* out, void* stream);
} // namespace strata::kernels
@@ -1,105 +0,0 @@
// 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
@@ -1,50 +0,0 @@
// include/strata/kernels/q8_1_finite.hpp - #606: the q8_1 activation block's scale and sum, kept finite.
//
// A q8_1 block stores its scale d = amax / 127 and the sum of its 32 raw activations as fp16. A sum past 65504 (one
// massive-activation dimension among 32 values is enough) rounds to inf, and d does past amax = 8.3M; the dot
// products then read inf * 0 = NaN, and a NaN in the residual ends as one token repeated (ggml-org/llama.cpp#23606
// is the same defect). Clamped to the largest finite half, such a block gives an approximate product instead of NaN,
// and the values are held to the int8 range they then exceed. Every block that was finite before is stored bit for
// bit as before: values in (65504, 65520) round to 65504 anyway, and a finite block's |x / d| is at most 127. A NaN
// stays NaN (the comparisons are false for it), so STRATA_DBG_NAN still sees one.
#pragma once
#include <cuda_fp16.h>
namespace strata::kernels {
constexpr float kHalfMax = 65504.0f;
__device__ __forceinline__ float q8_1_finite(const float v) {
return fabsf(v) > kHalfMax ? copysignf(kHalfMax, v) : v;
}
/// #3948: native_mmvq.cu (native_quantize_q8_1, the separate quantiser every consumer of a q8_1 image was written for)
/// is compiled with --use_fast_math, which makes `a / b` the fast full-range division (div.full.f32, up to 2 ulp off). The
/// fused producers (fused_gr.cu's hyper-connection read, verify_kernels.cu's GDN output norm: STRATA_QFUSE) are not, so
/// their IEEE division gave a different code at the rare element whose x / d lies next to a rounding boundary (found by
/// gr_parity: one code in about 10^6, off by one). A translation unit that defines STRATA_Q81_FASTMATH_DIV before including
/// this header divides the way the fast-math one does; every other one, and every HIP build, keeps `a / b` (so nothing
/// that compiled before this changes).
__device__ __forceinline__ float q81_div(const float a, const float b) {
#if defined(STRATA_Q81_FASTMATH_DIV) && defined(__CUDA_ARCH__) && !defined(__HIPCC__)
float r;
asm("div.full.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b));
return r;
#else
return a / b;
#endif
}
/// The block's quantized value of `xi` for the (finite) scale `d`; `amax` = 0 is an all-zero block.
__device__ __forceinline__ int8_t q8_1_quant(const float xi, const float d, const float amax) {
if (amax == 0.0f) return 0;
const float q = roundf(q81_div(xi, d));
return (int8_t) (q > 127.0f ? 127.0f : q < -127.0f ? -127.0f : q);
}
__device__ __forceinline__ half2 q8_1_ds(const float d, const float sum) {
return make_half2(__float2half(q8_1_finite(d)), __float2half(q8_1_finite(sum)));
}
} // namespace strata::kernels
@@ -1,90 +0,0 @@
// 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
@@ -1,113 +0,0 @@
// 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
@@ -1,193 +0,0 @@
// 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
@@ -1,42 +0,0 @@
// 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
@@ -1,258 +0,0 @@
// 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
@@ -1,27 +0,0 @@
// 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
File diff suppressed because it is too large Load Diff
@@ -1,189 +0,0 @@
// 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
@@ -1,186 +0,0 @@
// 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
@@ -1,552 +0,0 @@
// 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
File diff suppressed because it is too large Load Diff
@@ -1,268 +0,0 @@
// src/kernels/cuda/i8h_volta.cuh - the Volta form of the int8 expert kernels (TUNE-0216): the same products as i8_kernel, on the tensor cores.
// Included by i8_expert.cuh (inside iq_kernels.cu's anonymous namespace) after the tile kernels; it uses their decode (i8_load / i8_pack / i8_convert), their
// activation image and their tile tables. CUDA only; the device code is Volta's (__CUDA_ARCH__ 700): every other architecture compiles a trap.
//
// Why. On a Tesla V100 (no int8 matrix cores) the dp4a tile kernels read prompts of 8,192+ tokens at 0.75-0.95 of MMQ's speed per layer, and with every expert
// resident (#6053's 6x V100) a 26K prompt's expert products took 1.30 times MMQ's time. Volta's FP16 tensor cores do 512 FMA a clock per SM against dp4a's 256.
//
// Exact, by construction. The weights' int8 codes (the decoded sub-blocks i8_convert writes) and the activations' int8 codes become FP16 values (integers of
// -128..127: exact), mma.m8n8k4 multiplies them exactly and adds them in FP32; every partial sum is an integer below 2^24 (32 products of at most 127 x 127), so it is
// exact in any order. A fresh accumulator collects each 32-value sub-block (each 16-value half for the two-scale formats), and the epilogue then does what the dp4a
// kernels do with their integer sums, in the same order: t = s1 m1 + s0 m0 (or s m, or s), acc = fmaf(t, base * d_x, acc), sub-block after sub-block. The products
// t are integers below 2^24 as well (the dp4a kernels' own bound), so t is the same number whether made in int or float: the output is bit-identical to i8_kernel's.
//
// Shape. A block of 256 threads (8 warps) owns 64 weight rows (gate/up: 32 gate + the same 32 up features, as i8_kernel) x 64 entries of one expert, K in stages of
// 128 values (4 sub-blocks). Warp w: rows 16 (w % 4) .. +16, entries 32 (w / 4) .. +32. Per k-step of 4 values each of the warp's four quad pairs computes one 8 x 8
// tile; two mma per k-step cover the warp's 16 x 32. FP16 operands in shared memory (one buffer, the next stage's raw bytes held in registers meanwhile): 44 KB, two
// blocks per SM.
//
// The m8n8k4 fragments (PTX ISA, mma.m8n8k4 .row.col, f16 inputs, f32 accumulators; checked on the V100 by phaseA-tests/tune0216/probe_m884.cu): quad pair
// q = (lane % 16) / 4 holds lanes 4q..4q+3 and 4q+16..4q+19, local index t = lane % 4 + 4 (lane / 16); thread t supplies row t of A (k 0..3) and column t of B
// (k 0..3); accumulator element i of thread (g = lane % 4, h = lane / 16) is row (g & 1) + (i & 2) + 4 h, column (i & 4) + (g & 2) + (i & 1).
#pragma once
constexpr int I8H_BM = 64; // entries of a tile
constexpr int I8H_LDH = 136; // halves per shared row: 128 + 8 (bank spread)
constexpr int I8H_RS = 16; // words per row of the scale records: 4 sub-blocks x {m0, m1, base, 0}
// formats of the Volta form: the decodes with no per-32 minimum (the minimum formats Q4_K / Q5_K / Q5_1 keep the dp4a kernels)
__host__ __device__ constexpr bool i8h_type(int t) { return !i8_min_type(t) && (i8_gu_type(t) || i8_d_type(t)); }
template <int T>
struct I8HSmem {
static constexpr int GW = i8_gg_type(T) ? 0 : (i8_grid_words(T) + 3) / 4 * 4; // a big grid is read from global memory (as I8Smem's GG)
static constexpr int SG = i8_sign_type(T) ? 512 : 0;
static constexpr int SZ_W = 64 * I8H_LDH / 2, SZ_A = I8H_BM * I8H_LDH / 2; // words
static constexpr int SZ_R = 64 * I8H_RS, SZ_D = I8H_BM * 4;
static constexpr int o_sg = GW, o_w = o_sg + SG, o_a = o_w + SZ_W, o_r = o_a + SZ_A, o_d = o_r + SZ_R, o_src = o_d + SZ_D,
total = (o_src + I8H_BM + 3) / 4 * 4;
static constexpr size_t bytes = (size_t) total * 4;
};
// four int8 (bytes of w) as four FP16 values, exactly: x + 128 is the mantissa of 1024 + x + 128, minus 1152
__device__ __forceinline__ uint2 i8h_cvt4(uint32_t w) {
const uint32_t c = w ^ 0x80808080u;
const uint32_t lo = __byte_perm(c, 0x64646464u, 0x5140), hi = __byte_perm(c, 0x64646464u, 0x7362);
const __half2 m = __floats2half2_rn(1152.0f, 1152.0f);
const __half2 l = __hsub2(*(const __half2*) &lo, m), h = __hsub2(*(const __half2*) &hi, m);
return make_uint2(*(const uint32_t*) &l, *(const uint32_t*) &h);
}
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 700
__device__ __forceinline__ void i8h_mma(float (&d)[8], uint2 a, uint2 b) {
asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, {%0,%1,%2,%3,%4,%5,%6,%7};\n"
: "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]), "+f"(d[4]), "+f"(d[5]), "+f"(d[6]), "+f"(d[7])
: "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y));
}
#endif
template <int T, bool GU>
__global__ void __launch_bounds__(I8_NT, 2)
i8h_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups,
const int32_t* __restrict__ tile_off, const int32_t* __restrict__ ent_idx, const block_q8_1* __restrict__ A,
block_q8_1* __restrict__ hq, float* __restrict__ out, NativeExpertLayout L) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 700
using SM = I8HSmem<T>;
extern __shared__ uint4 i8_dyn[];
uint32_t* const smem = (uint32_t*) i8_dyn;
uint32_t* const s_grid = smem;
uint32_t* const s_sg = smem + SM::o_sg;
__half* const s_w = (__half*) (smem + SM::o_w);
__half* const s_a = (__half*) (smem + SM::o_a);
uint32_t* const s_r = smem + SM::o_r;
float* const s_ad = (float*) (smem + SM::o_d);
int* const s_src = (int*) (smem + SM::o_src);
const uint32_t* const grid_rd = i8_gg_type(T) ? i8_grid_src<T>() : s_grid;
const int ng = *n_groups;
const int ti = blockIdx.x;
if (ti >= tile_off[ng]) return;
int lo = 0, hi = ng - 1;
while (lo < hi) {
const int mid = (lo + hi + 1) >> 1;
if (tile_off[mid] <= ti) lo = mid; else hi = mid - 1;
}
const int g = lo;
const int e_lo = grp_start[g] + (ti - tile_off[g]) * I8H_BM;
const int e_hi = min(grp_start[g + 1], e_lo + I8H_BM);
const int nv = e_hi - e_lo;
I8P blob = i8_uniform(I8_GPTR(grp_ptr[g]));
const int tid = threadIdx.x;
const int K = GU ? (int) L.n_embd : (int) L.n_ff;
const int ns = K / I8_KS;
const size_t wrb = GU ? L.gu_row : L.d_row;
if constexpr (i8_grid_words(T) > 4 && !i8_gg_type(T)) {
const uint32_t* src = i8_grid_src<T>();
for (int i = tid; i < i8_grid_words(T); i += I8_NT) s_grid[i] = src[i];
}
if constexpr (i8_sign_type(T)) { // as i8_kernel's table
const uint32_t b = (uint32_t) tid;
uint32_t sb = b;
if constexpr (T != 21 && T != 22) sb = (b & 127u) | (((uint32_t) __popc(b & 127u) & 1u) << 7);
uint32_t mlo = 0, mhi = 0;
#pragma unroll
for (int k = 0; k < 4; ++k) {
mlo |= ((sb >> k) & 1u) ? (0xFFu << (8 * k)) : 0u;
mhi |= ((sb >> (4 + k)) & 1u) ? (0xFFu << (8 * k)) : 0u;
}
*(uint2*) (s_sg + 2 * b) = make_uint2(mlo, mhi);
}
uint32_t kv[4] = {0, 0, 0, 0};
if constexpr (T == 20 || T == 23) {
const uint32_t* t = (const uint32_t*) kvalues_iq4nl;
#pragma unroll
for (int i = 0; i < 4; ++i) kv[i] = t[i];
}
if (tid < I8H_BM) s_src[tid] = (e_lo + tid < e_hi) ? (GU ? ent_idx[e_lo + tid] : e_lo + tid) : -1;
__syncthreads();
// decode thread: row wr of the tile, sub-block wp of the stage (as i8_kernel); activation thread: q8_1 block (tid & 3) of entry (tid >> 2)
const int wr = tid >> 2, wp = tid & 3;
uint32_t row_off;
if constexpr (GU) row_off = (uint32_t) ((wr >= 32 ? L.up_off : (size_t) 0) + (size_t) (blockIdx.y * 32 + (wr & 31)) * wrb);
else row_off = (uint32_t) (L.down_off + (size_t) (blockIdx.y * 64 + wr) * wrb);
const I8Off woff = i8_offs<T>(row_off, wp);
I8P const abase = I8_GPTR(A);
uint32_t a_vo;
{
const int src = s_src[tid >> 2];
a_vo = (uint32_t) ((size_t) (src >= 0 ? src : 0) * (size_t) ((K / 32) * 36) + (size_t) (tid & 3) * 36);
}
auto store_w = [&](int st, const uint32_t (&r)[I8NR<T>]) {
uint32_t q[8], w[I8NW<T>];
int m0, m1;
float base, minv = 0.0f;
const int ibs = (st * 4 + wp) & 7;
i8_pack<T>(r, ibs, w);
i8_convert<T>(w, grid_rd, (const uint2*) s_sg, kv, q, m0, m1, base, ibs, &minv);
uint2* dst = (uint2*) (s_w + wr * I8H_LDH + wp * 32);
#pragma unroll
for (int k = 0; k < 8; ++k) dst[k] = i8h_cvt4(q[k]);
*(uint4*) (s_r + wr * I8H_RS + wp * 4) = make_uint4((uint32_t) m0, (uint32_t) m1, __float_as_uint(base), 0u);
};
auto store_a = [&](const uint32_t (&ar)[9]) {
uint2* d = (uint2*) (s_a + (tid >> 2) * I8H_LDH + (tid & 3) * 32);
#pragma unroll
for (int k = 0; k < 8; ++k) d[k] = i8h_cvt4(ar[1 + k]);
s_ad[tid] = __uint_as_float(ar[0]);
};
const int lane = tid & 31, warp = tid >> 5;
const int qp = (lane & 15) >> 2, tl = (lane & 3) + 4 * (lane >> 4);
const int gg = lane & 3, hh = lane >> 4;
const int r0 = 16 * (warp & 3) + 8 * (qp & 1); // the quad pair's 8 rows
const int c0 = 32 * (warp >> 2) + 8 * (qp >> 1); // its 8 entries of the first 16-entry half (the second: + 16)
const __half* const a_row = s_w + (r0 + tl) * I8H_LDH; // A: row tl of the quad pair's rows
const __half* const b_col0 = s_a + (c0 + tl) * I8H_LDH; // B: column tl (an entry) of the first half
const __half* const b_col1 = b_col0 + 16 * I8H_LDH; // ... of the second half
float acc[2][8];
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) acc[j][i] = 0.0f;
uint32_t wraw[I8NR<T>], ar[9];
i8_load<T>(blob, woff, 0, wraw);
{
I8P p = abase + a_vo;
#pragma unroll
for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
}
store_w(0, wraw);
store_a(ar);
__syncthreads();
for (int st = 0; st < ns; ++st) {
if (st + 1 < ns) { // the next stage's raw bytes into registers while this one computes
i8_load<T>(blob, woff, st + 1, wraw);
I8P p = abase + (size_t) (st + 1) * 144 + a_vo;
#pragma unroll
for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
}
#pragma unroll 1
for (int blk = 0; blk < 4; ++blk) {
float p0[2][8], p1[2][8]; // the sub-block's sums: values 0-15 (p0) and 16-31 (p1), or all 32 in p0 for the one-scale formats
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) { p0[j][i] = 0.0f; p1[j][i] = 0.0f; }
#pragma unroll
for (int kk = 0; kk < 8; ++kk) {
const int k = 32 * blk + 4 * kk;
const uint2 a = *(const uint2*) (a_row + k);
const uint2 b0 = *(const uint2*) (b_col0 + k), b1 = *(const uint2*) (b_col1 + k);
if (i8_two_scales(T) && kk >= 4) { i8h_mma(p1[0], a, b0); i8h_mma(p1[1], a, b1); }
else { i8h_mma(p0[0], a, b0); i8h_mma(p0[1], a, b1); }
}
// epilogue of the sub-block: the dp4a kernels' arithmetic on the same integers, in the same order
float axv[2][4]; // the activation scales of the thread's eight entries for this sub-block
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int cc = 0; cc < 4; ++cc) axv[j][cc] = s_ad[(c0 + 16 * j + ((cc & 2) << 1) + (gg & 2) + (cc & 1)) * 4 + blk];
#pragma unroll
for (int rr = 0; rr < 2; ++rr) { // the thread's two rows: (g & 1) + 2 rr + 4 h
const int row = r0 + (gg & 1) + 2 * rr + 4 * hh;
const uint4 rc = *(const uint4*) (s_r + row * I8H_RS + blk * 4);
const float base = __uint_as_float(rc.z);
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int cc = 0; cc < 4; ++cc) { // the thread's four entries: (cc & 2) * 2 + (g & 2) + (cc & 1)
const int i = (cc & 1) | (rr << 1) | ((cc & 2) << 1); // element index: col bit 0 = i & 1, row bit 1 = i & 2, col bit 2 = i & 4
const float ax = axv[j][cc];
float t;
if constexpr (i8_two_scales(T)) t = p1[j][i] * (float) (int) rc.y + p0[j][i] * (float) (int) rc.x;
else if constexpr (i8_unit_scale(T)) t = p0[j][i];
else t = p0[j][i] * (float) (int) rc.x;
acc[j][i] = fmaf(t, base * ax, acc[j][i]);
}
}
}
if (st + 1 < ns) {
__syncthreads();
store_w(st + 1, wraw);
store_a(ar);
}
__syncthreads();
}
// epilogues
if constexpr (GU) {
// the 64 rows x 64 entries of sums through shared memory (the weight and activation buffers are free now): F[row][entry]
float* const F = (float*) s_w; // 64 x 65 floats (16.6 KB) inside the two buffers (34.8 KB)
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int row = r0 + (gg & 1) + (i & 2) + 4 * hh, col = c0 + 16 * j + (i & 4) + (gg & 2) + (i & 1);
F[row * 65 + col] = acc[j][i];
}
__syncthreads();
const int nb = (int) (L.n_ff / 32);
for (int e8 = 0; e8 < 8; ++e8) { // warp w: entries 8 w .. 8 w + 7; lane: feature (gate row lane, up row 32 + lane)
const int el = 8 * warp + e8;
if (el >= nv) break; // uniform per warp
const float gv = F[lane * 65 + el], uv = F[(32 + lane) * 65 + el];
const float h = (gv / (1.0f + __expf(-gv))) * uv;
float amax = fabsf(h);
#pragma unroll
for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
const float d_inv = 127.0f / amax;
block_q8_1* hb = hq + (size_t) (e_lo + el) * nb + blockIdx.y;
hb->qs[lane] = i8_code(h, d_inv, amax);
if (lane == 0) i8_put_scale(hb, amax, d_inv);
}
} else {
#pragma unroll
for (int j = 0; j < 2; ++j)
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int row = r0 + (gg & 1) + (i & 2) + 4 * hh, col = c0 + 16 * j + (i & 4) + (gg & 2) + (i & 1);
if (col < nv) out[(size_t) ent_idx[e_lo + col] * L.n_embd + (size_t) blockIdx.y * 64 + row] = acc[j][i];
}
}
#else
(void) grp_ptr; (void) grp_start; (void) n_groups; (void) tile_off; (void) ent_idx; (void) A; (void) hq; (void) out; (void) L;
__trap();
#endif
}
File diff suppressed because it is too large Load Diff
@@ -1,521 +0,0 @@
#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

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