Merge f-nvfp4 into f-144-rel

This commit is contained in:
Niko1221 committed 2026-10-13 09:21:19 +02:00
commit 66db34dc40
36 files changed
+3374 -158

No files matched your search

+45 -3
View File
@@ -1293,12 +1293,15 @@ if(STRATA_NATIVE_EXPERTS)
# one-pass static linking has no cycle to resolve)
target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp
src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp
src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp)
src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp
src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp)
target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml)
if(MSVC)
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp
PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
# the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops
set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
# the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): 128-bit integer lanes,
@@ -1307,10 +1310,11 @@ if(STRATA_NATIVE_EXPERTS)
# the older CPUs' i-quant expert rows (iq_avx1.hpp): 128-bit SSSE3/SSE2 integer, SSE2 float, no FMA/F16C
set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
else()
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")
set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx")
# the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): SSE4.2 + AVX with
# AVX2/FMA/F16C explicitly off, so a -march=native build host cannot leak AVX2 code into the file that
@@ -1391,6 +1395,7 @@ if(STRATA_NATIVE_EXPERTS)
# #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA
# only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable)
add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu
src/prefill/mmq_nvfp4_w4a8.cu
src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu)
# q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and
# STRATA_MMQ_KQUANTS q4_k q5_k q5_1 q6_k, the experts of Unsloth's UD-Q4/Q5/Q6_K_XL (docs/QUANTS.md; the dispatch
@@ -1409,6 +1414,22 @@ if(STRATA_NATIVE_EXPERTS)
foreach(_t IN LISTS _strata_mmq_cuda_types)
target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu)
endforeach()
# NVFP4: W4A8 (default) in mmq_nvfp4_w4a8.cu with the plain architectures; the opt-in W4A4 needs RTX 50's FP4 MMA,
# which exists only in the arch-specific target, so its one unit alone is built with 12x -> 12xa (the default
# binary is unchanged and runs on sm_121; a card without that image falls back to W4A8 at run time)
set(_strata_w4a4_archs ${CMAKE_CUDA_ARCHITECTURES})
# (two steps: CMake before 3.29 rejects a \2 whose optional group did not match, "120" alone)
list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])$" "\\1a")
list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])-(real|virtual)$" "\\1a-\\2")
add_library(strata_mmq_w4a4 STATIC src/prefill/mmq_nvfp4_w4a4.cu)
set_target_properties(strata_mmq_w4a4 PROPERTIES CUDA_ARCHITECTURES "${_strata_w4a4_archs}")
target_include_directories(strata_mmq_w4a4 PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq})
target_compile_options(strata_mmq_w4a4 PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda -use_fast_math>)
if(MSVC)
target_compile_options(strata_mmq_w4a4 PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=/bigobj>)
endif()
target_link_libraries(strata_mmq_w4a4 PUBLIC ggml-base ${_strata_gpu_runtime_target})
target_link_libraries(strata_mmq PRIVATE strata_mmq_w4a4)
target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_compile_options(strata_mmq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda -use_fast_math>)
@@ -1477,6 +1498,15 @@ if(STRATA_NATIVE_EXPERTS)
# the K-quant MMQ is opt-in at run time (STRATA_MMQ_KQ=1), and on CUDA it is strata_kq next to the test
set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120 ENVIRONMENT STRATA_MMQ_KQ=1)
endif()
# the NVFP4 expert products (w4a8 / w4a4, STRATA_PREFILL_NVFP4) against a double-precision reference
add_executable(mmq_nvfp4_parity src/prefill/mmq_nvfp4_parity.cpp)
target_link_libraries(mmq_nvfp4_parity PRIVATE strata_mmq ggml-base CUDA::cudart)
if(NOT MSVC) # its FP16 rounding helper uses the F16C intrinsics (GCC/Clang need the target flag)
target_compile_options(mmq_nvfp4_parity PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-mf16c>)
endif()
# the routed-expert products (MMQ) timed at the prompt path's shapes (16 experts a launch)
add_executable(mmq_expert_bench src/prefill/mmq_expert_bench.cpp)
target_link_libraries(mmq_expert_bench PRIVATE strata_mmq ggml-base CUDA::cudart)
elseif(STRATA_PREFILL_MMQ)
# Compile only the pinned GGML MMQ and activation-quantizer sources used by prefill. This uses
# common.cuh's native HIP path without enabling a second GGML HIP backend.
@@ -1549,6 +1579,18 @@ if(STRATA_NATIVE_EXPERTS)
add_executable(hip_ple_iq4 tests/hip/ple_iq4.cpp)
target_link_libraries(hip_ple_iq4 PRIVATE strata_kernels strata_hip_runtime ggml-base)
endif()
# the NVFP4 AVX-512 and AVX2 rows vs ggml-cpu's vec_dot, and their speed (CPU only; optional arg: a pack's experts.bin)
add_executable(nvfp4_avx512_parity src/kernels/cpu/nvfp4_avx512_parity.cpp)
target_link_libraries(nvfp4_avx512_parity PRIVATE strata_kernels_cpu)
add_test(NAME nvfp4_cpu_parity COMMAND nvfp4_avx512_parity) # random blocks; the AVX2 rows bit-equal to ggml's
set_tests_properties(nvfp4_cpu_parity PROPERTIES TIMEOUT 120)
if(STRATA_ENABLE_CUDA) # the NVFP4 decode kernels vs ggml's reference
add_executable(nvfp4_expert_gpu_parity src/kernels/nvfp4_expert_gpu_parity.cpp)
target_link_libraries(nvfp4_expert_gpu_parity PRIVATE strata_kernels ggml-base CUDA::cudart)
# the decode experts' weight bandwidth on random blobs of a format pair, and an output hash (bit-for-bit checks)
add_executable(nvfp4_decode_bench src/kernels/nvfp4_decode_bench.cpp)
target_link_libraries(nvfp4_decode_bench PRIVATE strata_kernels CUDA::cudart)
endif()
if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_executable(native_expert_parity src/kernels/native_expert_parity.cpp)
target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories})
+197
View File
@@ -0,0 +1,197 @@
# NVFP4 routed experts
The engine can serve a Qwen3.8-Flash-Next whose routed experts are NVFP4, as NVIDIA's ModelOpt stores them: 64-value
blocks of E2M1 codes with four UE4M3 sub-block scales, plus one FP32 `weight_scale_2` per expert and projection.
Everything else (attention, GDN, shared experts, routers, the head) stays in the formats the native path already
reads. Measured on Windows 11, RTX 5090 (32 GB), Ryzen 9 9950X3D, 128 GB DDR5-5600.
## Getting a model
```
python tools/nvfp4_convert.py --model <ModelOpt NVFP4 checkpoint dir> --outfile <model>.gguf
python tools/iq_pack.py --gguf <model>.gguf --out <pack dir>
```
- `nvfp4_convert.py` runs llama.cpp's own converter (`third_party/llama.cpp`, the commit setup pins) with the type
policy the engine needs. The experts are repacked without loss: `tools/nvfp4_verify.py` compares them with the
checkpoint bit for bit, and `tools/nvfp4_verify_gguf.py` checks the GGUF.
- The small projections the BF16 kernels read (routers, SSM gates, indexer, PLE and hyper-connection projections)
are written as BF16.
- Everything served natively goes to Q8_0: attention, `ssm_out`, the shared experts, the output head, and the
token embedding.
- The 51.2e9-value PLE table is left out.
- `iq_pack.py` writes `experts.bin` for an NVFP4 GGUF by itself. Each blob is `[gate | up | down]` plus a 16-byte
tail `{s_gate, s_up, s_down, 0}`. The GGUF has no room for these scales, so the engine reads NVFP4 experts from
`experts.bin` only.
Run it like an IQ pack, with the GGUF as its own dense-weight source and the PLE table from an IQ GGUF's PLE shard:
```
strata --pack <pack dir> --native <model>.gguf --native-dense-gguf <model>.gguf \
--ple-gguf <an IQ model's shard with per_layer_token_embd> --mtp <mtp/rt> \
--expert-profile data/expert-profile.bin --expert-cache auto --prefill auto --spec 4 ...
```
The NVFP4 checkpoints change only the routed experts. The PLE table, the MTP layer and the expert profile of the
original model therefore work as they are.
Tested end to end with `jpezzulli/OrcaRouter-Qwen3.8-Flash-Next-Uncensored-ModelOpt-NVFP4`. By its
`hf_quant_config.json`, NVIDIA's `nvidia/Qwen3.8-Flash-Next-NVFP4` quantizes the routed experts the same way
(NVFP4, group 16; the other layers BF16, the PLE table FP8, the MTP experts FP8), so it takes the same path. It has
not been run here.
## Measured
RTX 5090, 64K context, int8 K/V, `--vram-reserve-mib 1500`:
| | NVFP4 pack | IQ2_XS, same engine |
| --- | ---: | ---: |
| experts in RAM | 63.3 GiB | 33.0 GiB |
| expert cache slots | ~8,350 | ~17,300 |
| decode, 400-token answer | 114-116 tokens/s | 132-139 tokens/s |
| a 32K prompt | 3,900 tokens/s | 5,600 tokens/s |
An NVFP4 expert blob is 2.76 MB, against 1.51 MB for IQ2_XS: the cache holds half as many, and a miss costs twice
the bytes over PCIe. The PCIe share of the missed experts is therefore 0.25 for an NVFP4 pack, not the usual 0.55.
At 0.55 the copy kernel was 40% of all GPU kernel time (nsys, 300-token decode). A sweep at 262K context gave the
following decode rates:
| PCIe share | short prompt | 32K prompt |
| --- | ---: | ---: |
| 0.55 | 103 tokens/s | 105 |
| 0.40 | 110 | 117 |
| 0.25 | 117 | 124 |
| 0.10 | 112 | 118 |
## Measured in Strata (2026-10-13)
The numbers above are the fork author's, on his RTX 5090 and 128 GB. These were measured here, on the ready-made GPTQ
pack (`--family nvfp4 --model NVFP4`).
Quality, the quant yardstick (`tools/quant_quality.py`, 4,995 teacher-forced positions of code, docs, English, other
languages and an agent transcript, against Unsloth's Q8_0; RTX 3060 box):
| | same top token as Q8_0 | mean KL | KL p99 |
| --- | ---: | ---: | ---: |
| NVFP4 GPTQ, experts on the CPU | 92.09% | 0.070 | 1.12 |
| NVFP4 GPTQ, 1,500 experts on the GPU | 91.79% | 0.069 | 1.07 |
| the same with `STRATA_ROUTE_TAIL_SKIP=7` | 88.59% | 0.118 | 1.76 |
| NVFP4 GPTQ with the GSQ-RCO IQ4_NL n-gram table instead of the FP8 one | 92.15% | 0.069 | 1.07 |
| for comparison, the same tool: Unsloth UD-Q5_K_XL | 94.55% | 0.038 | 0.64 |
| Unsloth UD-Q4_K_XL | 93.09% | 0.056 | - |
| Unsloth UD-IQ4_XS | 88.91% | 0.101 | 1.60 |
| GSQ-RCO IQ3_S | 87.69% | 0.144 | 1.98 |
The route tail skip moves the answers by more than the quantization itself, so it is off by default for NVFP4
experts. `STRATA_ROUTE_TAIL_SKIP=7` turns it on: +7-25% decode on the RTX 3060, +47-55% on the RTX 5070 (64 GB).
Decode experts (`nvfp4_decode_bench`, 64 distinct experts per call, the share of the card's DRAM bandwidth):
| tokens per expert | RTX 5070 | RTX 3060 | Tesla P100 |
| --- | ---: | ---: | ---: |
| 1 | 0.294 ms (89%) | 0.554 ms (89%) | 0.910 ms |
| 2 | 0.298 ms (88%) | 0.596 ms | 1.247 ms |
| 4 | 0.335 ms (79%) | 0.766 ms | 1.954 ms |
Each weight is decoded once for all the tokens of a verify window (before the port's kernel work: 2.26 ms on the 3060
at 4 tokens), bit for bit the same results.
Prompt experts on the RTX 5070 (`mmq_expert_bench`, one launch of 16 experts with 625 rows each, gate/up + down): w4a8
1.52 ms, w4a4x2 (`STRATA_PREFILL_NVFP4=w4a4x2`) 1.13 ms, w4a4x2 with down too (`STRATA_PREFILL_X2_MIN_K=640`)
0.995 ms, UD-IQ4_XS's experts 1.20 ms. First-token KL against the exact FP16 path (24 prompts, 1.5-8K tokens): w4a8
0.0068, w4a4x2 0.0056, w4a4x2 with down 0.0044. On a 64 GB PC the prompt waits for the experts read from the SSD,
so the modes give the same prompt speed there; w4a8 stays the default until a 96 GB+ RTX 50 PC measures the others.
On RTX 20-40 the NVFP4 prompt products are 1.35-1.6x slower than IQ3_S / IQ4_NL ones at 32K: NVFP4's 16-value scales
are applied in FP32 after every int8 step, which only Blackwell's FP4 tensor cores avoid.
Below its RAM need (68 GB of experts plus room) setup runs the pack in the RAM-budget mode (`--resident-budget-gib`,
the RAM less 24 GB), as for Unsloth's files. Mapped experts (`--mmap-experts`) on a 64 GB Windows PC filled the RAM.
Images: the packs keep Qwen's vision tower unquantized, so the original's image encoder reads pictures for them
(`--vision`; strata-vision opens the dense GGUF for the vocabulary). Checked on an RTX 5070 and an RTX 3060 against
IQ3_XXS's answers on the same picture (a number in the picture read, two shapes with their colours and sides). The
encoder on the GPU takes ~1.1 GiB of VRAM: on the 3060 at 8K context the cache held 1,293 experts with images against
1,734 without.
## Where the global scales go
Each scale multiplies its own projection's FP32 output, as llama.cpp applies `.scale`:
`h = silu(s_gate * (G x)) * (s_up * (U x))`, `y = s_down * (D h)`.
The scales are ~1e-4 each. Folding `s_down` into up is algebraically the same, but it leaves the hidden near 1e-5.
The hidden is then rounded to Q8_0 (CPU) or q8_1 (GPU) blocks with an FP16 scale, and `amax / 127` lands deep in
FP16's subnormals: one expert's output was off by 2-12% instead of 1.1% (`nvfp4_avx512_parity --expert`). The FP16
prompt path had the same problem in its dequantized up weights (~1e-8). Any future fold must be checked against
FP16's range.
## Prompt path precision
`STRATA_PREFILL_NVFP4` picks how the batched prompt path multiplies the experts:
| mode | kernel | activations | one product vs FP64 (`mmq_nvfp4_parity`) |
|---|---|---|---|
| `w4a8` (default) | llama.cpp MMQ, int8 tensor cores | q8_1, float block scales | 0.53% |
| `w4a4` | llama.cpp MMQ, Blackwell FP4 MMA (sm_120a only) | NVFP4 | 8.6% |
| `fp16` | dequantize + cuBLAS FP16 GEMM | FP16 | reference |
`src/prefill/mmq_nvfp4_w4a8.cu` compiles mmq.cuh's int8 NVFP4 path with Blackwell's FP4 MMA hidden from both the
device code and the host's tile config, so it is the same on every architecture; decode already multiplies at this
precision. The FP4 MMA exists only in the arch-specific target, so `src/prefill/mmq_nvfp4_w4a4.cu` (the FP4 x FP4
kernel and its FP4 activation quantizer) is the one unit CMake builds with `12x` -> `12xa` (`strata_mmq_w4a4`);
the rest of the engine keeps the architectures as given and runs on sm_121 too. A card without that unit's image
(another architecture, or sm_121 against a 120a build) falls back to `w4a8` with a note.
First-token KL divergence against `fp16`, 8 prompts (code and prose, 1K-8K tokens). The noise floor is the same
`fp16` path cut into 4096-token chunks instead of 8192: another summation order, same arithmetic.
| mode | KL mean | KL median | KL max | top-1 agreement | prefill, 4-8K prompts |
|---|---|---|---|---|---|
| noise floor | 0.00023 | 0.00003 | 0.0016 | 8/8 | - |
| `w4a8` | 0.0018 | 0.0010 | 0.0096 | 8/8 | 2,503 tok/s |
| `w4a4` | 0.0080 | 0.0027 | 0.040 | 7/8 | 2,904 tok/s |
| `fp16` | reference | | | | 1,905 tok/s |
`w4a8` is the default. It is 4.5x closer to the reference than `w4a4`, at 86% of its speed, and it is the precision
every generated token already runs at. `fp16` is the choice when the prompt must be read exactly.
`STRATA_DUMP_MOE_INPUT` + `mmq_nvfp4_parity --real` test one product on a real prompt's rows: layer 20, its 12
busiest experts, max|x|/rms 4 median and 9 at most. The errors:
| mode | gate/up | down (heavier SwiGLU tails) |
| --- | ---: | ---: |
| `w4a8` | 0.46% | 0.90% |
| `w4a4` | 7.2% | 8.4% |
| `fp16` | 0.017% | 0.021% |
## CPU experts
`src/kernels/cpu/nvfp4_avx512.cpp` computes the CPU pool's NVFP4 rows in 512-bit lanes. Each 64-value block is
decoded once for every token of a verify window: `vpdpbusd` on |E2M1| codes, with the sign moved onto the
activation. The arithmetic is ggml-cpu's `ggml_vec_dot_nvfp4_q8_0`, with the float additions ordered differently
(worst 4.5e-7 relative, `nvfp4_avx512_parity`). `STRATA_NO_NVFP4_512=1` falls back to ggml-cpu, which is also the
path of CPUs without AVX-512.
| tokens | ggml-cpu | AVX-512 | speedup |
|---|---|---|---|
| 1 | 0.102 ms | 0.058 ms | 1.76x |
| 4 | 0.410 ms | 0.125 ms | 3.29x |
| 7 | 0.719 ms | 0.196 ms | 3.66x |
These are one expert's gate+up (1280 rows of 2560, cache-resident). The pool itself is bound by DRAM.
## Other GPUs
Only the optional `w4a4` needs Blackwell. The default `w4a8` is ggml's int8 MMQ (sm_75 and up), and decode uses the
engine's own q8_1 kernels, which decode UE4M3/E2M1 in software. The engine was built for sm_75/86/89 as PTX and run
on the RTX 5090 with the host answering as that generation. On those builds `mmq_nvfp4_parity` and
`nvfp4_expert_gpu_parity` gave results identical to sm_120.
HIP: the decode kernels use no CUDA-only intrinsics. The NVFP4 MMQ instance and the W4A8 unit are CUDA-only and
guarded (`GGML_USE_HIP`). Neither was built for HIP here.
## Tests
- `nvfp4_expert_gpu_parity`: the decode kernels against ggml's reference.
- `nvfp4_avx512_parity`: the CPU rows against ggml-cpu (with `--expert`: one whole expert).
- `mmq_nvfp4_parity`: the prompt path's products against FP64 (with `--real`: rows dumped by `STRATA_DUMP_MOE_INPUT`).
- `tools/nvfp4_verify.py` and `tools/nvfp4_verify_gguf.py`: the conversion, bit for bit.
+4
View File
@@ -212,6 +212,10 @@ inline bool block_geometry(uint32_t t, int& elems, int& bytes) {
elems = 1;
bytes = 1;
return true;
case 40: // NVFP4: 64 values = 4 UE4M3 sub-block scales + 32 bytes of E2M1 codes
elems = 64;
bytes = 36;
return true;
case 42:
elems = 64;
bytes = 18;
@@ -27,7 +27,14 @@ struct NativeFmt {
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;
};
constexpr int kNvfp4Type = 40;
constexpr size_t kNvfp4Tail = 16;
/// Whether this build has the ggml-cpu path.
bool native_experts_available() noexcept;
+26
View File
@@ -0,0 +1,26 @@
// include/strata/kernels/cpu/nvfp4_avx2.hpp - NVFP4 expert rows in 256-bit lanes, several tokens at once, for CPUs
// without AVX-512 (Zen 2/3, Intel 12th-14th gen).
//
// ggml-cpu's NVFP4 dot product (ggml_vec_dot_nvfp4_q8_0) re-decodes a row's blocks for every token of a window;
// these decode a 64-value block once and apply it to each token. Each token's arithmetic is that dot product's AVX2
// path step for step (the same integer sums, the same FMA order, the same horizontal sum), so a row equals
// ggml-cpu's bit for bit - what an AVX2 CPU computed before these existed. Activations are Q8_0.
#pragma once
#include <cstddef>
#include <cstdint>
namespace strata::kernels::cpu {
/// Whether rows of `n` values fit the kernels (whole 64-value blocks, at most 64 of them).
bool nvfp4_256_fits(int n);
/// Gate/up rows [r0, r1) for `nt` tokens: ff[t][r] = silu(s_gate * g) * (s_up * u), as nvfp4_512_gu_rows.
void nvfp4_256_gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
float* const* ff, int r0, int r1, float s_gate, float s_up);
/// Plain rows [r0, r1) against `nt` Q8_0 activations of `n` values, times `scale`, as nvfp4_512_rows.
void nvfp4_256_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
int r0, int r1, float scale = 1.f);
} // namespace strata::kernels::cpu
@@ -0,0 +1,28 @@
// include/strata/kernels/cpu/nvfp4_avx512.hpp - NVFP4 expert rows in 512-bit lanes, several tokens at once.
//
// ggml-cpu's NVFP4 dot product (ggml_vec_dot_nvfp4_q8_0) is AVX2 and single-token: every token of a verify window
// re-decodes the same weights. These decode a 64-value block once and apply it to every token. The arithmetic is
// ggml's: an exact integer sum per 16-value sub-block, times the sub-block's UE4M3 scale and the Q8_0 block's scale;
// only the order of the float additions differs. Activations are Q8_0, NVFP4's vec_dot_type in ggml-cpu.
#pragma once
#include <cstddef>
#include <cstdint>
namespace strata::kernels::cpu {
/// Whether rows of `n` values fit the kernels (whole 64-value blocks, at most 64 of them).
bool nvfp4_512_fits(int n);
/// Gate/up rows [r0, r1) of an NVFP4 expert blob for `nt` tokens: ff[t][r] = silu(s_gate * g) * (s_up * u), where g
/// and u are the raw NVFP4 dot products of gate row r and up row r (at `up_off`) with activation t (Q8_0, `n` values).
/// `s_gate` / `s_up` are the expert's global scales from its blob tail.
void nvfp4_512_gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
float* const* ff, int r0, int r1, float s_gate, float s_up);
/// Plain rows [r0, r1) of an NVFP4 matrix (`row_bytes` apart) against `nt` Q8_0 activations of `n` values, times
/// `scale` (the down matrix's s_down).
void nvfp4_512_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
int r0, int r1, float scale = 1.f);
} // namespace strata::kernels::cpu
+8 -4
View File
@@ -25,17 +25,20 @@ void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y,
/// 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.
void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, 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.
/// 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);
void* stream, const float* tail = nullptr);
/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks.
struct NativeExpertLayout {
@@ -44,6 +47,7 @@ struct NativeExpertLayout {
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
};
NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the
+1 -1
View File
@@ -87,7 +87,7 @@ void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream);
void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream);
/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_k w[t, k] * D[slot[t, k], :]
void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
int64_t T, void* stream);
int64_t T, void* stream, const float* row_sd = nullptr);
/// --peer-device's prompt share as sums: bo[t, :] = (sum over the k with slot[t, k] < rows_local of w[t, k] *
/// D[slot[t, k], :], in k order) + peer[t, :] + shared[t, :] * sigmoid(sg[t]). `peer` (the peer's per-token sums)
/// may be mapped host memory.
+35 -6
View File
@@ -12,14 +12,19 @@ namespace strata::prefill::mmq {
/// This build has the MMQ path (the ggml sources were available to the build).
bool built();
/// MMQ covers this ggml type (the i-quants and Q2_0 the packs use, Q8_0, and with STRATA_MMQ_KQUANTS the
/// K-quants Q4_K / Q5_K / Q5_1 / Q6_K: Unsloth's UD-Q4_K_XL experts (CUDA), and the dense GGUF projections of
/// the mixed-quant packs through Gemm::native's STRATA_DENSE_MMQ path (HIP); IQ1_M is not covered).
/// MMQ covers this ggml type (the i-quants and Q2_0 the packs use, Q8_0, NVFP4 unless fp16, and with
/// STRATA_MMQ_KQUANTS the K-quants Q4_K / Q5_K / Q5_1 / Q6_K: Unsloth's UD-Q4_K_XL experts (CUDA), and the dense GGUF
/// projections of the mixed-quant packs through Gemm::native's STRATA_DENSE_MMQ path (HIP); IQ1_M is not covered).
bool supported(int ggml_type);
/// #420: `supported`, and on every visible GPU llama.cpp's MMQ has a tile for this type and a weight matrix of
/// `w_rows` rows that fits the card's shared memory - the same test its tile choice makes, which aborts the process
/// ("J_best=0") when nothing fits. false (said once per type) keeps that product on the non-MMQ path.
bool fits(int ggml_type, int64_t w_rows);
/// NVFP4 prompt precision, STRATA_PREFILL_NVFP4: w4a8 (default) - int8 tensor cores, Q8_1 activations, what decode
/// runs at; w4a4 - Blackwell's FP4 x FP4 MMA, activations rounded to NVFP4 (faster, first-token KL up to 0.03 vs
/// fp16); fp16 - the dequantize + FP16 GEMM path (the reference).
enum class Nvfp4Mode { W4A8, W4A4, FP16 };
Nvfp4Mode nvfp4_mode();
/// Bytes of one expert's gate+up ([2*n_ff, n_embd]) or down ([n_embd, n_ff]) weights in `ggml_type`.
size_t matrix_bytes(int ggml_type, int64_t rows, int64_t cols);
/// Bytes of `rows` activation rows of `cols` values quantized for MMQ (the row padded to 512 values).
@@ -28,7 +33,19 @@ size_t q8_bytes(int64_t rows, int64_t cols);
/// q8_1 activations for MMQ against weights of `ggml_type`: row i of the output is row ids[i] of x (or row i when
/// ids is null); `x` has `ld` floats per row.
void quantize(const float* x, const int32_t* ids, void* xq, int ggml_type, int64_t cols, int64_t ld, int64_t rows,
void* stream);
void* stream, float* yscale = nullptr);
/// NVFP4 on Blackwell in w4a4 mode: the MMQ kernel multiplies FP4 x FP4, so its activations are NVFP4 too, with
/// one float scale per row that `quantize` writes to `yscale` and the product reads as Product::y_scale. Decided
/// by the mode and a device probe of the same compile.
bool fp4_activations(int ggml_type);
/// NVFP4 expert tails: GU rows [row0, row0 + nrows) of a group of `n` experts (absolute `bounds`, n + 1 of them,
/// on the device) scaled by their expert's {s_gate, s_up, s_down, 0} (`tails`, 4 floats each, on the device): the
/// gate half by s_gate, the up half by s_up.
void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, int n, const float* tails,
int64_t row0, int64_t nrows, void* stream);
/// The down product's rows [0, nrows) (`ld` floats each, relative `bounds`) times their expert's s_down - on the FP32
/// output, not folded into up, where the hidden would sit near 1e-5 (FP16-subnormal block scales in q8 formats).
void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream);
/// One launch over n experts whose weights lie `expert_bytes` apart from `w`: for expert e, the activation rows
/// [bounds[e], bounds[e+1]) of `xq` (bounds on the device, n+1 entries) times its [w_rows, w_cols] matrix into
@@ -46,6 +63,7 @@ struct Product {
int64_t total_rows = 0, max_rows = 0;
float* dst = nullptr;
int64_t ld_dst = 0;
const float* y_scale = nullptr; ///< NVFP4 w4a4: the per-row activation scales (fp4_activations)
};
/// The launch context (llama.cpp's MMQ keeps a small scratch pool for its stream-k fixup). One per prompt path.
@@ -63,18 +81,24 @@ private:
/// A GGUF-native expert (gate at `gate`, up at `up`, down at `down`, each its GGUF rows) into a group buffer's
/// slot: gate rows then up rows at `gu_dst`, down at `d_dst`.
/// `tail` (16 bytes, may be null) goes to `tail_dst`; `zero_bytes` zeroed right after gu_dst's and d_dst's copies
/// (the MMQ tail after a group's last expert).
void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes,
void* gu_dst, void* d_dst, void* stream);
void* gu_dst, void* d_dst, void* stream, const void* tail = nullptr, void* tail_dst = nullptr,
size_t zero_bytes = 0);
/// gather_native for an MMQ group's experts [first, n) in ONE launch: expert q's blob (`blob[q]`; gate at +0, up at
/// +up_off, down at +down_off) to gu_dst + q * gu_stride and d_dst + q * d_stride - the same bytes as one gather_native
/// each. Every pointer, offset and size 16-byte aligned (false otherwise: nothing launched, gather one at a time).
/// NVFP4: `tail_off` (0 = none) is each blob's 16-byte tail, copied to tail_dst + 16 q; `zero_bytes` are zeroed after
/// the last expert's gu and d slots (the MMQ tail).
constexpr int kGatherGroupMax = 16;
struct GatherGroup {
const uint8_t* blob[kGatherGroupMax] = {};
int first = 0, n = 0;
};
bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_bytes, size_t down_off, size_t d_bytes,
void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream);
void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream,
size_t tail_off = 0, void* tail_dst = nullptr, size_t zero_bytes = 0);
/// A Strata-pack Q2_0 expert blob (codes and fp16 scales in separate planes, gate/up rows interleaved) into GGUF
/// Q2_0 blocks: gate/up [1280, 2560] at `gu_dst` (rows stay interleaved), down [2560, 640] at `d_dst`. Same values.
void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream);
@@ -82,6 +106,11 @@ void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stre
/// h[r, k] = silu(gate) * up of GU rows [2 n_ff wide]: interleaved (gate 2k, up 2k+1: the Strata pack) or split
/// (gate k, up n_ff + k: GGUF). FP32 out (the down product's quantizer reads floats).
void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream);
/// swiglu of an NVFP4 group's gate/up rows (split halves) with scale_gu_rows' scales applied as they are read.
void swiglu_scaled(const float* gu, float* h, int64_t rows, int64_t n_ff, const int32_t* bounds, int n,
const float* tails, int64_t row0, void* stream);
/// sd[r] = the s_down of row r's expert (group-local bounds): the combine applies it as it reads the row.
void down_row_scales(float* sd, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream);
/// dst[i] = i for i < n (the identity row map MMQ's MoE mode writes through).
void iota(int32_t* dst, int64_t n, void* stream);
+207 -25
View File
@@ -198,6 +198,47 @@ KV_CELL_BYTES = {"q4_0": 576, "k8v4": 816}
PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"]
REQUIREMENTS = ROOT / "requirements.txt" # the same packages and their dependencies, pinned (#214)
# NVFP4 experts (MODEL-UPDATE Phase 4; the engine path is ported from sergqwer/strata-nvfp4, MIT). Ready-made Strata
# packs on Hugging Face by the fork's author: nothing is converted here. Every file is pinned by its upload's commit,
# size and SHA-256 (the fork's setup.py NVFP4_REPOS, checked against the Hub's LFS pointers 2026-10-12). The FP8 n-gram
# table and the BF16 token embedding are the same files in both repositories (a second install links them). The
# MTP draft layer is setup's own, as for every other model, so the repositories' mtp/ folder is not downloaded.
# role: pack = the experts pack folder (index.txt, experts.bin, ...), dense = the dense GGUF (--native and
# --native-dense-gguf), ple = the FP8 n-gram table (--ple-gguf), embd = the BF16 token embedding (--embd-gguf)
NVFP4_GPTQ_REPO = "Maximilian228/Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata" # Qwen's BF16 experts by GPTQ (the fork)
NVFP4_NVIDIA_REPO = "Maximilian228/Qwen3.8-Flash-Next-NVIDIA-NVFP4-Strata" # nvidia/Qwen3.8-Flash-Next-NVFP4, converted
_NVFP4_TOKENIZER = {
"pack/tokenizer/chat_template.jinja": ("pack", 8952, "c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041"),
"pack/tokenizer/merges.txt": ("pack", 3600844, "080cf95432173729d160346b7882bd2a644b07f7a3813a3eb73f4e66787bfde9"),
"pack/tokenizer/token_type.json": ("pack", 744960, "5088c8c298fc06af8382ddb3b76c888703ac2634e82263b97eedcc2ad202738b"),
"pack/tokenizer/tokenizer.json": ("pack", 554, "87be2ac47d8bc7393b7435df6ccd276740019a393941a2585d5edce59f450c54"),
"pack/tokenizer/vocab.json": ("pack", 5737005, "4ba64f0332abcfb0b600b7df1537d1e836e68009d5fb7cdb77339738dc6365c4"),
}
_NVFP4_SHARED = {
"ple-fp8.gguf": ("ple", 51200246176, "37f89b8ce5a3425932763257c40229ec02723ad2ab14b4bbfc26a486f4725c9c"),
"token-embd-bf16.gguf": ("embd", 1271398656, "386203af9070c7b43acb24ded8922876721d97bbad1a709b25cb49d694a7f51d"),
}
NVFP4_REPOS = {
NVFP4_GPTQ_REPO: {"revision": "640a1db97446ddd5e89d2b70ecd0297987192c93", "files": {
"pack/dense.bin": ("pack", 1538035200, "974df6dcefcae85e3fd2c19fcc12eeaacaadde8261ab732d5af5af6ce2e25a7a"),
"pack/experts.bin": ("pack", 67948118016, "325e5e0d85c262a8d8278daf73b20696ec877d9a3ff584e57391fa69ad10bc64"),
"pack/index.txt": ("pack", 93663, "f62dc71e1c74a72794db54d3917bc71131cc6eae6f3dcdc3fdada48ff70f93ab"),
"pack/native_experts.txt": ("pack", 1599, "615f655fb28bf60b243664860b135710bf4177b111c6be89073e780a35de1018"),
**_NVFP4_TOKENIZER,
"qwen-nvfp4-gptq-dense.gguf": ("dense", 5991569472, "abdf74336b53d8f7ca3d99947f1eac8f19b8a544966750127cb61e561b127e3b"),
**_NVFP4_SHARED}},
NVFP4_NVIDIA_REPO: {"revision": "cca8f7fee5ce0af932097340a75e06df25c4e57d", "files": {
"pack/dense.bin": ("pack", 1538625024, "1f1c2422069de292673ae6cee7d69f7090732dec69f3f125612a0de456279714"),
"pack/experts.bin": ("pack", 67948118016, "bb42080bb7585505b64d091d5a734c05376bbd6171406fa9688a46fbc261b957"),
"pack/index.txt": ("pack", 117490, "17793d1c5b187a73d3c1dc1677af4d4c9b23845394dd7e88bfa53396b41b77e3"),
"pack/native_experts.txt": ("pack", 1590, "d7f8b4372bb122f3d711030e5d522bff1c8746ac7d133a59a2cc7277283e59b6"),
**_NVFP4_TOKENIZER,
"qwen-nvidia-nvfp4-dense.gguf": ("dense", 5992176896, "0f795ca0cbb908e0cf2b894b30103e21455b5a05346a7ef79da208540cfd2be3"),
**_NVFP4_SHARED}},
}
# the first release engine with NVFP4 experts (a source build of this checkout has them whatever its number says)
NVFP4_ENGINE = (0, 1, 47)
MODELS = {
# the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which
# the pack tool (tools/iq_pack.py) cannot prepare yet (#171)
@@ -247,6 +288,23 @@ MODELS = {
"download_gb": 188.2, "ram_gb": 136, "arena_gb": 128.3, "families": ("unsloth",), "budget": True,
"shards": 6, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf", "engine": (0, 1, 38),
"vision": True},
# MODEL-UPDATE Phase 4: NVFP4 experts, ready-made packs (NVFP4_REPOS). 63.3 GiB (68.0 GB) of experts in the
# pack's experts.bin; the low-RAM mode reads them from there on a PC whose RAM does not hold them. NVIDIA only
# (the HIP and SYCL engines have no NVFP4 kernels). Images: both packs keep Qwen's vision tower unquantized, so the
# original's image encoder (ISTA's mmproj, the same file as for every Flash-Next model) reads pictures for them;
# checked end to end on an RTX 5070 and an RTX 3060 against IQ3_XXS's answers on the same picture.
"NVFP4": {"about": "4-bit NVFP4 experts, GPTQ (sergqwer's strata-nvfp4 pack); RTX 50 has FP4 tensor cores, other "
"NVIDIA cards run it at 8-bit precision", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0,
"families": ("nvfp4",), "nvidia_only": True, "vision": True, "repo": NVFP4_GPTQ_REPO,
"engine": NVFP4_ENGINE,
"license": "Qwen Community License 1.0 (Qwen3.8-Flash-Next's): https://huggingface.co/Qwen/Qwen3.8-Flash-Next"},
"NVFP4-NVIDIA": {"about": "NVIDIA's own NVFP4 checkpoint (plain rounding), converted by sergqwer; the same size "
"and speed as NVFP4", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0,
"families": ("nvfp4",), "nvidia_only": True, "vision": True, "repo": NVFP4_NVIDIA_REPO,
"engine": NVFP4_ENGINE,
"license": "NVIDIA Open Model License (Licensed by NVIDIA Corporation under the NVIDIA Open Model "
"License) with Qwen3.8-Flash-Next's Qwen Community License 1.0: "
"https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4"},
}
# The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the
# download (setup trusts no other model file by name and size alone either: check_shards reads their directories).
@@ -355,6 +413,13 @@ FAMILIES = {
"mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth",
"vision": False, "pack_args": ["--compat-bf16"],
"sha256": {**UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS, **UNSLOTH_BIG_SHARDS}},
# MODEL-UPDATE Phase 4: the original model with NVFP4 experts, as ready-made packs (NVFP4_REPOS): the files come
# as the engine reads them (no GGUF to pack), each size has its own repository ("repo" in MODELS)
"nvfp4": {"title": "Qwen3.8-Flash-Next (NVFP4)", "by": "NVFP4 packs by sergqwer (strata-nvfp4)",
"about": "4-bit NVFP4 experts, NVIDIA cards; a 128 GB download, ~80 GB of RAM to keep every expert in RAM",
"tag": "nvfp4-", "name": "qwen3.8-flash-next-nvfp4", "ready": True,
"mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf",
"mmproj_sha256": (907543008, "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0")},
}
MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf"
# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README
@@ -1652,6 +1717,8 @@ def gguf_choice(name: str) -> tuple | None:
"""#444: (--family, --model) whose published first shard this file is, or None (the Coder's IQ1_M is named like
the original's sizes: the size tells them apart)."""
for f, d in FAMILIES.items():
if d.get("ready"): # ready-made packs (NVFP4): no GGUF shards to match
continue
for m in MODELS:
if f in MODELS[m].get("families", ("qwen", "swift")) and name == model_file(d, m, 1):
return f, m
@@ -1708,6 +1775,64 @@ def verify_sha256(s: Path, size: int, sha: str) -> None:
mark(s, f"sha256 {sha}")
def ready_files(model: str) -> list:
"""A ready-made pack's files (NVFP4_REPOS): (role, repo, revision, path, bytes, sha256) each."""
repo = MODELS[model]["repo"]
t = NVFP4_REPOS[repo]
return [(role, repo, t["revision"], path, size, sha) for path, (role, size, sha) in t["files"].items()]
def ready_where(models_dir: Path, f) -> Path:
"""Where one of them goes: <models>/<owner>--<repo>/<its path in the repository> (the repository's layout, so the
pack folder is whole as the engine reads it)."""
return Path(models_dir) / f[1].replace("/", "--") / f[3]
def ready_paths(model: str, models_dir: Path) -> dict:
"""What the engine is given: the pack folder and the dense, PLE and embedding GGUFs."""
out = {}
for f in ready_files(model):
p = ready_where(models_dir, f)
if f[0] == "pack" and p.name == "index.txt":
out["pack"] = p.parent
elif f[0] in ("dense", "ple", "embd"):
out[f[0]] = p
return out
def ready_verified(p: Path, sha: str) -> bool:
"""Downloaded whole and checked: its finish mark holds the pinned SHA-256 (verify_sha256)."""
m = p.with_name(p.name + ".done")
try:
return p.is_file() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace")
except OSError:
return False
def ready_fetch(model: str, models_dir: Path) -> None:
"""Every file of a ready-made pack: already here and checked; the same file (by SHA-256) checked for another
ready-made pack, linked instead of downloaded (the PLE table and the embedding); or downloaded from its pinned
revision and checked against its size and SHA-256 (a wrong file is deleted and setup stops)."""
others = [(ready_where(models_dir, g), g[5]) for m in MODELS if MODELS[m].get("repo") for g in ready_files(m)]
for f in ready_files(model):
dst, size, sha = ready_where(models_dir, f), f[4], f[5]
if ready_verified(dst, sha):
ok(f"{f[3]} already downloaded")
continue
src = next((p for p, s in others if s == sha and p != dst and ready_verified(p, s)), None)
if src is not None and not dst.exists():
try:
dst.parent.mkdir(parents=True, exist_ok=True)
os.link(src, dst)
mark(dst, f"sha256 {sha}")
ok(f"{f[3]}: the same file as {src} (linked, not downloaded again)")
continue
except OSError:
pass # another drive: downloaded
download(f"{hf_endpoint()}/{f[1]}/resolve/{f[2]}/{f[3]}", dst, f"{f[1].split('/')[-1]}: {f[3]}")
verify_sha256(dst, size, sha)
def resident_budget_gib(model, ram, kv_ram_gb=0.0) -> int:
"""UD-Q4_K_XL: the GiB of experts the engine keeps in RAM (--resident-budget-gib): the RAM (GiB, ram_gb()) less
24 for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to
@@ -5341,7 +5466,10 @@ def main() -> int:
else "the rest is read from the SSD as needed)"))
if d.get("budget") and hip and d.get("nvidia_only"): # #429: not run on AMD yet
verdict += " - NVIDIA only so far, untested on AMD"
any_fits = any_fits or not verdict.startswith("does not fit")
if hip and d.get("repo"): # the ready-made NVFP4 packs: no AMD kernels at all
verdict = "NVIDIA only (the AMD engine has no NVFP4 kernels)"
else:
any_fits = any_fits or not verdict.startswith("does not fit")
say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}")
if not any_fits:
# #977: every size says "does not fit", so the verdict says so too (and the exit code, for scripts). It only
@@ -5366,6 +5494,13 @@ def main() -> int:
family = fams[int(ask("Which model?", [str(i) for i in range(1, len(fams) + 1)],
str(fams.index(rec_fam) + 1), a.yes)) - 1]
fam = FAMILIES[family]
if fam.get("ready") and hip:
# not a risk the user could take: the HIP engine has no NVFP4 expert kernels at all, so it would not start
fail(f"{fam['title']} runs on NVIDIA cards only: the AMD engine has no NVFP4 kernels",
"UD-IQ4_XS is about the same size and runs on AMD: --family unsloth --model UD-IQ4_XS")
if fam.get("ready") and a.gguf_dir:
warn(f"--gguf-dir does not apply to {fam['title']}: its files are ready-made packs, not GGUF shards")
a.gguf_dir = None
ok(f"model: {fam['title']}")
if fam.get("license"):
say(f" Its license: {fam['license']}")
@@ -5455,6 +5590,8 @@ def main() -> int:
if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4:
confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model))
ok(f"size: {model}")
if MODELS[model].get("license"): # the ready-made packs: each size has its own license
say(f" Its license: {MODELS[model]['license']}")
tag = fam["tag"] + model # names of the pack, config and start script
small = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context
rec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072
@@ -5543,7 +5680,7 @@ def main() -> int:
# with a warning when they do not fit the RAM it finds free). mmap: they are read through the OS file cache.
# The GPU's share: its VRAM less the dense weights and buffers, this context's KV cache and the image encoder's room.
resident = False
if low_ram:
if low_ram and not fam.get("ready"): # NVFP4's packs: the RAM-budget mode instead (step 7)
arena = MODELS[model]["arena_gb"]
vram = low_ram_vram(gpu) - (VISION[vision]["reserve_mib"] / 1024 if vision != "none" else 0)
share = low_ram_gpu_share(model, vram, ctx, kv)
@@ -5596,26 +5733,37 @@ def main() -> int:
elif esp_choice.lower() not in ("", "off", "no", "n", "0"):
warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off"
if family == "swift" else f"the experimental speed projection is not tested with {model}: left off")
models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag
shards = gguf_dir_shards(models_dir, fam, model) if a.gguf_dir else \
[models_dir / model_file(fam, model, i) for i in range(1, model_shards(fam, model) + 1)]
ready = bool(fam.get("ready")) # NVFP4: ready-made packs (NVFP4_REPOS), no GGUF shards
if ready:
models_dir = Path(a.models_dir)
for r in elsewhere: # already downloaded and checked in a Strata folder elsewhere
if all(ready_verified(ready_where(r / "models", f), f[5]) for f in ready_files(model)):
models_dir = r / "models"
ok(f"model files found in {models_dir}")
break
shards = [ready_where(models_dir, f) for f in ready_files(model)]
else:
models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag
shards = gguf_dir_shards(models_dir, fam, model) if a.gguf_dir else \
[models_dir / model_file(fam, model, i) for i in range(1, model_shards(fam, model) + 1)]
problem = gguf_dir_problem(models_dir, shards[0], fam, model) if a.gguf_dir else None
if problem: # #444: files Strata cannot run, or another choice's files
fail(*problem)
if not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards):
if not ready and not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards):
for r in elsewhere: # already downloaded in a Strata folder on another drive
cand = [r / "models" / tag / sh.name for sh in shards]
if all(c.exists() and done(c) for c in cand):
models_dir, shards = cand[0].parent, cand
ok(f"model files found in {models_dir}")
break
for s in shards: # #173: a whole file copied in by hand has no finish mark
for s in ([] if ready else shards): # #173: a whole file copied in by hand has no finish mark
if s.exists() and not done(s) and whole_shard(s):
try:
mark(s, "whole (checked against its own tensor directory)")
except OSError as e: # a read-only folder (--gguf-dir on a share): the file is still whole
warn(f"{s.name} is whole but its finish mark cannot be written ({e})")
have_model = all(s.exists() and (done(s) or a.gguf_dir) for s in shards)
have_model = all(ready_verified(ready_where(models_dir, f), f[5]) for f in ready_files(model)) if ready else \
all(s.exists() and (done(s) or a.gguf_dir) for s in shards)
# #425 (jctaborda): a download that resumes needs room only for what is still missing - the finished shards and
# the .part files already on the disk count
on_disk = sum(f.stat().st_size for s in shards for f in (s, s.with_name(s.name + ".part")) if f.is_file()) / 1e9
@@ -5623,7 +5771,7 @@ def main() -> int:
# count only what step 6 will still write: a pack whose experts.bin is already there (the AVX-512 Q2_0
# conversion, or the low-RAM mode's copy) and an existing MTP draft layer need no new room
pack_now = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower()
pack_bin = (pack_now / "experts.bin").exists() and (pack_now / "index.txt").exists()
pack_bin = ready or ((pack_now / "experts.bin").exists() and (pack_now / "index.txt").exists()) # ready: in the download
mtp_have = find_in(roots, "mtp/rt/experts.bin") is not None
q2_avx = model == "Q2_0" and avx512 and family == "qwen"
need = to_fetch + (2 if mtp_have else 8) + \
@@ -5664,6 +5812,12 @@ def main() -> int:
if eng is None:
eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk)
meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8"))
if ready and meta.get("source") != "local" and \
tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) < MODELS[model]["engine"]:
# a ready-made engine from before NVFP4 cannot read these experts: one compiled from this source can
warn(f"the ready-made engine {meta.get('version')} has no NVFP4 experts yet: compiling the engine from this source")
eng = build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk)
meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8"))
if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH
lib_dirs = [str(d) for d in hip_lib_dirs(eng)]
else:
@@ -5678,7 +5832,12 @@ def main() -> int:
# ---- 5. the model files
step(5, f"downloading {fam['title']} {model}")
if not a.gguf_dir:
if ready: # pinned files of the pack's repository, each SHA-256-checked
say(f" The model files go in {models_dir / MODELS[model]['repo'].replace('/', '--')}")
if model_source() == "modelscope":
warn("these packs are on Hugging Face only: downloading them from " + hf_endpoint())
ready_fetch(model, models_dir)
elif not a.gguf_dir:
missing = [s.name for s in shards if not (s.exists() and done(s))]
if missing: # #495: files downloaded by hand go here, or --gguf-dir
say(f" The model files go in {models_dir}")
@@ -5706,19 +5865,22 @@ def main() -> int:
except OSError:
pass
download(fam["hf"].format(q=model) + s.name, s)
check_shards(shards)
for s in shards: # the Unsloth files: pinned sizes and SHA-256
if not ready:
check_shards(shards)
for s in ([] if ready else shards): # the Unsloth files: pinned sizes and SHA-256
if s.name in fam.get("sha256", {}):
verify_sha256(s, *fam["sha256"][s.name])
ok("model files present")
mmproj = Path(a.models_dir) / fam["mmproj"]
if not mmproj.exists():
mmproj = Path(a.models_dir) / fam.get("mmproj", MMPROJ)
if not mmproj.exists(): # an earlier install's copy (the same file for every family)
mmproj = find_in(roots, f"models/{fam['mmproj']}") or mmproj
if vision != "none":
if not mmproj.exists() and a.gguf_dir and (Path(a.gguf_dir) / fam["mmproj"]).exists():
mmproj = Path(a.gguf_dir) / fam["mmproj"]
else:
download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder")
if fam.get("mmproj_sha256"): # the NVFP4 family pins it by size and SHA-256 too
verify_sha256(mmproj, *fam["mmproj_sha256"])
ok(f"vision encoder: {mmproj}")
if vision == "cpu" and "BF16" in mmproj.name: # a tip only (recommend, never force; #625)
say(" tip: on the CPU a Q8_0 copy of this encoder is a third smaller and about as exact (embedding "
@@ -5728,7 +5890,9 @@ def main() -> int:
step(6, "preparing the model for Strata")
pack = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower()
env = dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py"))
if model == "Q2_0" and avx512 and family == "qwen":
if ready: # the downloaded pack folder is the pack, experts.bin included
pack = ready_paths(model, models_dir)["pack"]
elif model == "Q2_0" and avx512 and family == "qwen":
# the Q2_0 experts repacked for the AVX-512 kernel (the measured speed): a one-time ~40 GB conversion
if not (pack / "index.txt").exists() or not (pack / "experts.bin").exists(): # index.txt is written last
say(" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...")
@@ -5743,7 +5907,7 @@ def main() -> int:
# (UD-Q4_K_XL: --compat-bf16 - its Q8_0 hyper-connection projections become BF16, the form the engine reads)
run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack),
*fam.get("pack_args", [])], env=env)
if low_ram and not (pack / "experts.bin").exists():
if low_ram and not ready and not (pack / "experts.bin").exists():
say(f" Writing the experts into one file for the low-RAM mode (one time, {MODELS[model]['arena_gb']:.0f} GB) ...")
run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack),
"--experts-bin"], env=env)
@@ -5774,11 +5938,19 @@ def main() -> int:
step(7, "writing the start script")
sys.path.insert(0, str(ROOT / "tools"))
from gguf_reader import GGUFFile # the PLE table's shard: shard 2 (original) or 1 (Swift)
ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None)
if ple is None:
fail("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)")
# (a 4-shard file: the engine finds the PLE table's shard itself from shard 1, the measured setup)
args = ["--pack", str(pack), "--native", str(shards[0]), *(["--ple-gguf", str(ple)] if len(shards) <= 2 else []),
if ready: # the dense GGUF as --native and --native-dense-gguf (--native alone would look for a second shard),
rp = ready_paths(model, models_dir) # the FP8 n-gram table, the BF16 token embedding
ple = rp["ple"]
model_args = ["--pack", str(pack), "--native", str(rp["dense"]), "--native-dense-gguf", str(rp["dense"]),
"--ple-gguf", str(ple), "--embd-gguf", str(rp["embd"])]
else:
ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None)
if ple is None:
fail("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)")
# (a 4-shard file: the engine finds the PLE table's shard itself from shard 1, the measured setup)
model_args = ["--pack", str(pack), "--native", str(shards[0]),
*(["--ple-gguf", str(ple)] if len(shards) <= 2 else [])]
args = [*model_args,
"--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto",
"--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt),
"--max-context", str(ctx)]
@@ -5790,12 +5962,21 @@ def main() -> int:
resident = False # an engine from before --resident-experts would refuse it
ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through "
"the OS file cache (run setup again after the next engine update)")
if low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped
if low_ram and ready:
# NVFP4 (68 GB of experts) on a PC whose RAM does not hold them: the RAM-budget mode, as Unsloth's files - the
# most-used experts outside VRAM pinned within RAM less 24 GB, the rest read from experts.bin. Mapped
# (--mmap-experts) on a 64 GB Windows PC, the experts it read stayed in the engine's working set: free RAM
# fell to 0.6 GB on the RTX 5070 PC (2026-10-13), where the budget mode kept 22 GB free
rb = resident_budget_gib(model, ram)
args += ["--resident-budget-gib", str(rb)]
ok(f"low-RAM mode: {rb} GiB of {model}'s experts kept in RAM (the most used), the rest read from the pack's "
"experts.bin on the SSD as needed")
elif low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped
args += ["--resident-experts" if resident else "--mmap-experts"]
disk = None if is_wsl() else rotational_disk(ple) # #605 (WSL's virtual disk says rotational)
if disk:
tensor = next((t for t in GGUFFile(ple).tensors if t.name == "per_layer_token_embd.weight"), None)
size = getattr(tensor, "expected_bytes", lambda: None)()
tensor = None if ready else next((t for t in GGUFFile(ple).tensors if t.name == "per_layer_token_embd.weight"), None)
size = ple.stat().st_size if ready else getattr(tensor, "expected_bytes", lambda: None)()
table_gb = size / 1e9 if size else 28.8
if ram >= MODELS[model]["ram_gb"] + table_gb + 4:
args += ["--ple-io", "ram"]
@@ -5954,7 +6135,8 @@ def main() -> int:
if vision != "none":
old_cfg = ROOT / f"strata-{tag.lower()}.json"
vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted)
cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]),
cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), # the text model, opened vocab-only:
"model": str(ready_paths(model, models_dir)["dense"] if ready else shards[0]),
"gpu": vision == "gpu", "max_tokens": vt}
if vision == "cpu":
cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2)
+49 -3
View File
@@ -7,6 +7,8 @@
#include "strata/kernels/cpu/iq_avx2.hpp"
#include "strata/kernels/cpu/iq_avx1.hpp"
#include "strata/kernels/cpu/kq_avx2.hpp"
#include "strata/kernels/cpu/nvfp4_avx2.hpp"
#include "strata/kernels/cpu/nvfp4_avx512.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "ggml.h"
@@ -14,6 +16,7 @@
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <mutex>
namespace strata::kernels::cpu {
@@ -74,6 +77,12 @@ bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt
f.up_off = f.gu_row * (size_t) n_ff;
f.down_off = 2 * f.up_off;
f.bytes = f.down_off + f.d_row * (size_t) n_embd;
// NVFP4 in any projection: one scale tail per blob; a mixed expert (e.g. NVFP4 gate/up + Q8_0 down) has 1.0 for
// the other projection's scale (tools/iq_pack.py), so every path below multiplies by the tail unconditionally
if (gu_type == kNvfp4Type || d_type == kNvfp4Type) {
f.tail_off = f.bytes;
f.bytes += kNvfp4Tail;
}
f.act_bytes = ggml_row_size(tg->vec_dot_type, n_embd);
f.h_bytes = ggml_row_size(td->vec_dot_type, n_ff);
if (f.act_bytes > kNativeActBytes || f.h_bytes > kNativeHBytes) {
@@ -182,8 +191,31 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
iq128_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1);
return;
}
const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot;
const int n = (int) f.n_embd;
// NVFP4: the per-expert global scales from the blob's tail (1 and 1 otherwise). s_down goes on the down output:
// folded into up it left the hidden near 1e-5, whose Q8_0 block scale is an FP16 subnormal (expert error 2-12%)
float sg = 1.f, su = 1.f;
if (f.tail_off) {
float tail[4];
std::memcpy(tail, blob + f.tail_off, sizeof tail);
sg = tail[0];
su = tail[1];
}
// NVFP4 in 512-bit lanes: ggml's arithmetic, blocks decoded once per window; 1.8x at one token, 3.7x at seven
// (nvfp4_avx512_parity). STRATA_NO_NVFP4_512 falls back to ggml-cpu.
static const bool nvfp4_512 = cpu_avx512_ok() && std::getenv("STRATA_NO_NVFP4_512") == nullptr;
if (f.gu_type == kNvfp4Type && nvfp4_512 && nvfp4_512_fits(n)) {
nvfp4_512_gu_rows(blob, f.gu_row, f.up_off, n, act, nt, ff, r0, r1, sg, su);
return;
}
// Without AVX-512: the same rows in 256-bit lanes, bit-equal to ggml-cpu's AVX2 dot below; 2.0-2.4x it at 4-8
// tokens, 2x under DRAM load with 6 threads (nvfp4_avx512_parity). STRATA_NO_NVFP4_256 falls back to ggml-cpu.
static const bool nvfp4_256 = cpu_avx2_ok() && std::getenv("STRATA_NO_NVFP4_256") == nullptr;
if (f.gu_type == kNvfp4Type && nvfp4_256 && nvfp4_256_fits(n)) {
nvfp4_256_gu_rows(blob, f.gu_row, f.up_off, n, act, nt, ff, r0, r1, sg, su);
return;
}
const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot;
for (int r = r0; r < r1; ++r) {
const uint8_t* gr = blob + (size_t) r * f.gu_row;
const uint8_t* ur = blob + f.up_off + (size_t) r * f.gu_row;
@@ -191,6 +223,8 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
float g = 0.f, u = 0.f;
dot(n, &g, 0, gr, 0, act[t], 0, 1);
dot(n, &u, 0, ur, 0, act[t], 0, 1);
g *= sg;
u *= su;
ff[t][r] = (g / (1.f + std::exp(-g))) * u;
}
}
@@ -220,14 +254,26 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const
iq128_down_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1);
return;
}
const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot;
const int n = (int) f.n_ff;
float sd = 1.f; // NVFP4: the expert's s_down (see native_gu_rows)
if (f.tail_off) std::memcpy(&sd, blob + f.tail_off + 2 * sizeof(float), sizeof sd);
static const bool nvfp4_512 = cpu_avx512_ok() && std::getenv("STRATA_NO_NVFP4_512") == nullptr;
if (f.d_type == kNvfp4Type && nvfp4_512 && nvfp4_512_fits(n)) {
nvfp4_512_rows(blob + f.down_off, f.d_row, n, hq, nt, out, r0, r1, sd);
return;
}
static const bool nvfp4_256 = cpu_avx2_ok() && std::getenv("STRATA_NO_NVFP4_256") == nullptr; // see above
if (f.d_type == kNvfp4Type && nvfp4_256 && nvfp4_256_fits(n)) {
nvfp4_256_rows(blob + f.down_off, f.d_row, n, hq, nt, out, r0, r1, sd);
return;
}
const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot;
for (int r = r0; r < r1; ++r) {
const uint8_t* dr = blob + f.down_off + (size_t) r * f.d_row;
for (int t = 0; t < nt; ++t) {
float s = 0.f;
dot(n, &s, 0, dr, 0, hq[t], 0, 1);
out[t][r] = s;
out[t][r] = s * sd;
}
}
}
+185
View File
@@ -0,0 +1,185 @@
// src/kernels/cpu/nvfp4_avx2.cpp - see include/strata/kernels/cpu/nvfp4_avx2.hpp.
//
// Per 64-value block, once: its E2M1 values in element order as two 32-byte registers (ggml's reordering: sub-block
// s keeps value j in the low nibble of qs[8 s + j] and value j + 8 in the high one), their magnitudes, and the four
// sub-block scales. Per token, as ggml_vec_dot_nvfp4_q8_0's AVX2 path: vpsignb moves the sign onto the activation,
// vpmaddubsw + vpmaddwd give 8 int32 lanes (four per 16-value sub-block), one FMA per 32 values applies
// ue4m3(d[s]) * d_q8, and hsum_float_8's order sums the lanes.
//
// Needs AVX2, FMA and F16C - what cpu_avx2_ok() checks before anything here is called.
#include "strata/kernels/cpu/nvfp4_avx2.hpp"
#define GGML_COMMON_DECL_CPP
#define GGML_COMMON_IMPL_CPP
#include "ggml-common.h"
#include <immintrin.h>
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace strata::kernels::cpu {
namespace {
struct Ue4m3Table { // ggml_ue4m3_to_fp32 (ggml-impl.h): halved for the doubled kvalues_fp4, 0x7F read as 0
float v[256];
Ue4m3Table() {
for (int x = 0; x < 256; ++x) {
if (x == 0 || x == 0x7F) { v[x] = 0.0f; continue; }
const int e = (x >> 3) & 0xF, m = x & 0x7;
const float raw = e == 0 ? std::ldexp((float) m, -9) : std::ldexp(1.0f + (float) m / 8.0f, e - 7);
v[x] = raw * 0.5f;
}
}
};
const Ue4m3Table kUe4m3;
// software prefetch distance in bytes (STRATA_NVFP4_PREFETCH, 0 = off), as the AVX-512 rows
const int prefetch_ahead = [] {
const char* v = std::getenv("STRATA_NVFP4_PREFETCH");
return v ? std::atoi(v) : 2048;
}();
inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); }
// sub-blocks 2 h and 2 h + 1 (16 bytes of qs) as their 32 signed doubled E2M1 values, in element order
inline __m256i values32(const uint8_t* qs, const __m128i kv) {
const __m128i q = _mm_loadu_si128((const __m128i*) qs);
const __m128i m4 = _mm_set1_epi8(0x0F);
const __m128i lo = _mm_shuffle_epi8(kv, _mm_and_si128(q, m4));
const __m128i hi = _mm_shuffle_epi8(kv, _mm_and_si128(_mm_srli_epi16(q, 4), m4));
return _mm256_set_m128i(_mm_unpackhi_epi64(lo, hi), _mm_unpacklo_epi64(lo, hi));
}
inline float hsum8(const __m256 x) { // ggml's hsum_float_8
__m128 res = _mm256_extractf128_ps(x, 1);
res = _mm_add_ps(res, _mm256_castps256_ps128(x));
res = _mm_add_ps(res, _mm_movehl_ps(res, res));
res = _mm_add_ss(res, _mm_movehdup_ps(res));
return _mm_cvtss_f32(res);
}
constexpr int kMaxBlocks = 64; // rows of up to 4096 values (n_embd 2560)
// tokens per pass: the pool's MAXT, so a window is one pass. Spilled accumulators cost less than another pass over
// the weights: one expert's gate+up, 8 tokens, 0.415 ms in passes of 4 + 4, 0.352 in one of 8 (5 6 7 alike)
constexpr int kMaxW = 8;
struct Acts { // per token and block, the two Q8_0 blocks' scales; built once per call, reused by every row
int nt = 0, nb = 0;
const block_q8_0* y[kMaxW] = {};
float dy[kMaxW * kMaxBlocks * 2];
Acts(const void* const* act, int nt_, int nb_) : nt(nt_), nb(nb_) {
for (int t = 0; t < nt; ++t) {
y[t] = (const block_q8_0*) act[t];
for (int ib = 0; ib < 2 * nb; ++ib) dy[(size_t) t * 2 * nb + ib] = h2f(y[t][ib].d);
}
}
};
template <int NT>
inline void row_dot(const uint8_t* row, const Acts& a, float* res) {
const __m128i kv = _mm_loadu_si128((const __m128i*) kvalues_fp4);
const __m256i ones = _mm256_set1_epi16(1);
__m256 acc[NT];
for (int t = 0; t < NT; ++t) acc[t] = _mm256_setzero_ps();
const block_nvfp4* x = (const block_nvfp4*) row;
for (int ib = 0; ib < a.nb; ++ib) {
if (prefetch_ahead > 0) _mm_prefetch((const char*) (x + ib) + prefetch_ahead, _MM_HINT_T0);
const __m256i v01 = values32(x[ib].qs, kv), v23 = values32(x[ib].qs + 16, kv);
const __m256i a01 = _mm256_sign_epi8(v01, v01), a23 = _mm256_sign_epi8(v23, v23);
// lanes 0-3 ue4m3(d[0]), 4-7 d[1] (and d[2], d[3]): times a broadcast d_q8, each lane is ggml's scalar
// ue4m3(d[s]) * d_q8, rounded the same
const __m256 u01 = _mm256_set_m128(_mm_set1_ps(kUe4m3.v[x[ib].d[1]]), _mm_set1_ps(kUe4m3.v[x[ib].d[0]]));
const __m256 u23 = _mm256_set_m128(_mm_set1_ps(kUe4m3.v[x[ib].d[3]]), _mm_set1_ps(kUe4m3.v[x[ib].d[2]]));
for (int t = 0; t < NT; ++t) {
const block_q8_0* yb = a.y[t] + 2 * ib;
const __m256i q01 = _mm256_loadu_si256((const __m256i*) yb[0].qs);
const __m256i q23 = _mm256_loadu_si256((const __m256i*) yb[1].qs);
const __m256i p1 = _mm256_madd_epi16(_mm256_maddubs_epi16(a01, _mm256_sign_epi8(q01, v01)), ones);
const __m256i p2 = _mm256_madd_epi16(_mm256_maddubs_epi16(a23, _mm256_sign_epi8(q23, v23)), ones);
const float* dy = a.dy + (size_t) t * 2 * a.nb + 2 * ib;
const __m256 s01 = _mm256_mul_ps(u01, _mm256_broadcast_ss(dy));
const __m256 s23 = _mm256_mul_ps(u23, _mm256_broadcast_ss(dy + 1));
acc[t] = _mm256_fmadd_ps(s01, _mm256_cvtepi32_ps(p1), acc[t]);
acc[t] = _mm256_fmadd_ps(s23, _mm256_cvtepi32_ps(p2), acc[t]);
}
}
for (int t = 0; t < NT; ++t) res[t] = hsum8(acc[t]);
}
template <int NT>
void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, const Acts& a, float* const* ff, int r0, int r1,
float sg, float su) {
float g[NT], u[NT];
for (int r = r0; r < r1; ++r) {
row_dot<NT>(blob + (size_t) r * gu_row, a, g);
row_dot<NT>(blob + up_off + (size_t) r * gu_row, a, u);
for (int t = 0; t < NT; ++t) { // native_gu_rows' ggml path, operation for operation
const float gs = g[t] * sg, us = u[t] * su;
ff[t][r] = (gs / (1.f + std::exp(-gs))) * us;
}
}
}
template <int NT>
void dot_rows(const uint8_t* w, size_t row_bytes, const Acts& a, float* const* out, int r0, int r1, float scale) {
float res[NT];
for (int r = r0; r < r1; ++r) {
row_dot<NT>(w + (size_t) r * row_bytes, a, res);
for (int t = 0; t < NT; ++t) out[t][r] = res[t] * scale;
}
}
// windows wider than kMaxW (not from the pool) run in balanced slices of at most kMaxW
template <typename F>
inline void slices(int nt, F&& run) {
const int k = (nt + kMaxW - 1) / kMaxW;
for (int i = 0, t0 = 0; i < k; ++i) {
const int w = nt / k + (i < nt % k ? 1 : 0);
run(t0, w);
t0 += w;
}
}
} // namespace
bool nvfp4_256_fits(int n) { return n % QK_NVFP4 == 0 && n / QK_NVFP4 <= kMaxBlocks; }
void nvfp4_256_gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
float* const* ff, int r0, int r1, float s_gate, float s_up) {
slices(nt, [&](int t0, int w) {
const Acts a(act + t0, w, n / QK_NVFP4);
float* const* f = ff + t0;
switch (w) {
case 1: gu_rows<1>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 2: gu_rows<2>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 3: gu_rows<3>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 4: gu_rows<4>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 5: gu_rows<5>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 6: gu_rows<6>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 7: gu_rows<7>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
default: gu_rows<8>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
}
});
}
void nvfp4_256_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
int r0, int r1, float scale) {
slices(nt, [&](int t0, int k) {
const Acts a(act + t0, k, n / QK_NVFP4);
float* const* o = out + t0;
switch (k) {
case 1: dot_rows<1>(w, row_bytes, a, o, r0, r1, scale); break;
case 2: dot_rows<2>(w, row_bytes, a, o, r0, r1, scale); break;
case 3: dot_rows<3>(w, row_bytes, a, o, r0, r1, scale); break;
case 4: dot_rows<4>(w, row_bytes, a, o, r0, r1, scale); break;
case 5: dot_rows<5>(w, row_bytes, a, o, r0, r1, scale); break;
case 6: dot_rows<6>(w, row_bytes, a, o, r0, r1, scale); break;
case 7: dot_rows<7>(w, row_bytes, a, o, r0, r1, scale); break;
default: dot_rows<8>(w, row_bytes, a, o, r0, r1, scale); break;
}
});
}
} // namespace strata::kernels::cpu
+186
View File
@@ -0,0 +1,186 @@
// src/kernels/cpu/nvfp4_avx512.cpp - see include/strata/kernels/cpu/nvfp4_avx512.hpp.
//
// Per 64-value block, once: the 64 E2M1 codes in element order, their magnitudes from |kvalues_fp4| (0..12, the
// doubled E2M1 values), a sign mask (code bit 3), and the four sub-block scales. Per token: the sign moves onto the
// activation (a masked subtract - Q8_0 is quantized to [-127, 127], so negation never overflows), one vpdpbusd gives
// 16 int32 lanes = four per 16-value sub-block, and one FMA applies ue4m3(d[s]) * d_q8. The UE4M3 decode is ggml's
// CPU one (ggml-impl.h ggml_ue4m3_to_fp32): halved for the doubled table, 0x7F read as 0.
//
// Needs AVX512F/BW/VL and VNNI - what cpu_avx512_ok() checks before anything here is called.
#include "strata/kernels/cpu/nvfp4_avx512.hpp"
#define GGML_COMMON_DECL_CPP
#define GGML_COMMON_IMPL_CPP
#include "ggml-common.h"
#include <immintrin.h>
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace strata::kernels::cpu {
namespace {
struct Ue4m3Table {
float v[256];
Ue4m3Table() {
for (int x = 0; x < 256; ++x) {
if (x == 0 || x == 0x7F) { v[x] = 0.0f; continue; }
const int e = (x >> 3) & 0xF, m = x & 0x7;
const float raw = e == 0 ? std::ldexp((float) m, -9) : std::ldexp(1.0f + (float) m / 8.0f, e - 7);
v[x] = raw * 0.5f;
}
}
};
const Ue4m3Table kUe4m3;
// software prefetch distance in bytes (STRATA_NVFP4_PREFETCH, 0 = off): the rows stream from DRAM through 4 KB
// pages, where the hardware prefetchers stop at every page boundary; the IQ kernel's E-2 knob, same default
const int prefetch_ahead = [] {
const char* v = std::getenv("STRATA_NVFP4_PREFETCH");
return v ? std::atoi(v) : 2048;
}();
inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); }
// The block's 64 codes in element order. Sub-block s keeps its codes in qs[8 s .. 8 s + 7]: byte j holds value j
// in its low nibble and value j + 8 in its high one, so a sub-block is [low nibbles, high nibbles] of its 8 bytes.
inline __m512i codes64(const uint8_t* qs) {
const __m256i q = _mm256_loadu_si256((const __m256i*) qs);
const __m256i m4 = _mm256_set1_epi8(0x0F);
const __m256i lo = _mm256_and_si256(q, m4);
const __m256i hi = _mm256_and_si256(_mm256_srli_epi16(q, 4), m4);
const __m256i ul = _mm256_unpacklo_epi64(lo, hi); // [lo 0-7, hi 0-7 | lo 16-23, hi 16-23]
const __m256i uh = _mm256_unpackhi_epi64(lo, hi); // [lo 8-15, hi 8-15 | lo 24-31, hi 24-31]
const __m256i s01 = _mm256_permute2x128_si256(ul, uh, 0x20); // sub-blocks 0, 1
const __m256i s23 = _mm256_permute2x128_si256(ul, uh, 0x31); // sub-blocks 2, 3
return _mm512_inserti64x4(_mm512_castsi256_si512(s01), s23, 1);
}
// lanes 4 s .. 4 s + 3 = ue4m3(d[s])
inline __m512 sub_scales(const uint8_t* d) {
const __m128 s4 = _mm_setr_ps(kUe4m3.v[d[0]], kUe4m3.v[d[1]], kUe4m3.v[d[2]], kUe4m3.v[d[3]]);
const __m512i idx = _mm512_setr_epi32(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3);
return _mm512_permutexvar_ps(idx, _mm512_castps128_ps512(s4));
}
// Per token and block, the activation's scales as lanes: 0-7 -> the first Q8_0 block's d (sub-blocks 0, 1),
// 8-15 -> the second's (sub-blocks 2, 3). Built once per call, reused by every row.
constexpr int kMaxBlocks = 64; // rows of up to 4096 values (n_embd 2560)
struct Acts {
int nt = 0, nb = 0;
const block_q8_0* y[7] = {};
__m512 dy[7 * kMaxBlocks]; // [t * nb + ib]; on the stack, no allocation
Acts(const void* const* act, int nt_, int nb_) : nt(nt_), nb(nb_) {
for (int t = 0; t < nt; ++t) {
y[t] = (const block_q8_0*) act[t];
for (int ib = 0; ib < nb; ++ib) {
const block_q8_0* yb = y[t] + 2 * ib;
dy[(size_t) t * nb + ib] = _mm512_mask_blend_ps((__mmask16) 0xFF00, _mm512_set1_ps(h2f(yb[0].d)),
_mm512_set1_ps(h2f(yb[1].d)));
}
}
}
};
template <int NT>
inline void row_dot(const uint8_t* row, const Acts& a, float* res) {
const __m512i mag = _mm512_broadcast_i32x4(_mm_setr_epi8(0, 1, 2, 3, 4, 6, 8, 12, 0, 1, 2, 3, 4, 6, 8, 12));
const __m512i eight = _mm512_set1_epi8(8);
const __m512i zero = _mm512_setzero_si512();
__m512 acc[NT];
for (int t = 0; t < NT; ++t) acc[t] = _mm512_setzero_ps();
const block_nvfp4* x = (const block_nvfp4*) row;
for (int ib = 0; ib < a.nb; ++ib) {
if (prefetch_ahead > 0) _mm_prefetch((const char*) (x + ib) + prefetch_ahead, _MM_HINT_T0);
const __m512i codes = codes64(x[ib].qs);
const __m512i g = _mm512_shuffle_epi8(mag, codes);
const __mmask64 neg = _mm512_test_epi8_mask(codes, eight);
const __m512 sw = sub_scales(x[ib].d);
for (int t = 0; t < NT; ++t) {
const block_q8_0* yb = a.y[t] + 2 * ib;
const __m512i yv = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_loadu_si256((const __m256i*) yb[0].qs)),
_mm256_loadu_si256((const __m256i*) yb[1].qs), 1);
const __m512i ys = _mm512_mask_sub_epi8(yv, neg, zero, yv);
const __m512i p = _mm512_dpbusd_epi32(zero, g, ys);
acc[t] = _mm512_fmadd_ps(_mm512_mul_ps(sw, a.dy[(size_t) t * a.nb + ib]), _mm512_cvtepi32_ps(p), acc[t]);
}
}
for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]);
}
template <int NT>
void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, const Acts& a, float* const* ff, int r0, int r1,
float sg, float su) {
float g[NT], u[NT];
for (int r = r0; r < r1; ++r) {
row_dot<NT>(blob + (size_t) r * gu_row, a, g);
row_dot<NT>(blob + up_off + (size_t) r * gu_row, a, u);
for (int t = 0; t < NT; ++t) {
const float gs = g[t] * sg;
ff[t][r] = (gs / (1.f + std::exp(-gs))) * (u[t] * su);
}
}
}
template <int NT>
void dot_rows(const uint8_t* w, size_t row_bytes, const Acts& a, float* const* out, int r0, int r1, float scale) {
float res[NT];
for (int r = r0; r < r1; ++r) {
row_dot<NT>(w + (size_t) r * row_bytes, a, res);
for (int t = 0; t < NT; ++t) out[t][r] = res[t] * scale;
}
}
} // namespace
bool nvfp4_512_fits(int n) { return n % QK_NVFP4 == 0 && n / QK_NVFP4 <= kMaxBlocks; }
// Windows wider than 7 run in balanced slices of at most 7: at 8 the accumulators no longer fit beside the loads and
// MSVC spills (measured 0.32 ms for 8 tokens against 2 x 0.13 for 4 + 4).
template <typename F>
inline void slices(int nt, F&& run) {
const int k = (nt + 6) / 7;
for (int i = 0, t0 = 0; i < k; ++i) {
const int w = nt / k + (i < nt % k ? 1 : 0);
run(t0, w);
t0 += w;
}
}
void nvfp4_512_gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
float* const* ff, int r0, int r1, float s_gate, float s_up) {
slices(nt, [&](int t0, int w) {
const Acts a(act + t0, w, n / QK_NVFP4);
float* const* f = ff + t0;
switch (w) {
case 1: gu_rows<1>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 2: gu_rows<2>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 3: gu_rows<3>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 4: gu_rows<4>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 5: gu_rows<5>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
case 6: gu_rows<6>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
default: gu_rows<7>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
}
});
}
void nvfp4_512_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
int r0, int r1, float scale) {
slices(nt, [&](int t0, int k) {
const Acts a(act + t0, k, n / QK_NVFP4);
float* const* o = out + t0;
switch (k) {
case 1: dot_rows<1>(w, row_bytes, a, o, r0, r1, scale); break;
case 2: dot_rows<2>(w, row_bytes, a, o, r0, r1, scale); break;
case 3: dot_rows<3>(w, row_bytes, a, o, r0, r1, scale); break;
case 4: dot_rows<4>(w, row_bytes, a, o, r0, r1, scale); break;
case 5: dot_rows<5>(w, row_bytes, a, o, r0, r1, scale); break;
case 6: dot_rows<6>(w, row_bytes, a, o, r0, r1, scale); break;
default: dot_rows<7>(w, row_bytes, a, o, r0, r1, scale); break;
}
});
}
} // namespace strata::kernels::cpu
+357
View File
@@ -0,0 +1,357 @@
// src/kernels/cpu/nvfp4_avx512_parity.cpp - the AVX-512 and AVX2 NVFP4 rows against ggml-cpu's own dot product.
//
// nvfp4_avx512_parity [pack/experts.bin]
//
// Parity: every row x every token of the multi-token kernel against ggml_vec_dot_nvfp4_q8_0 on the same Q8_0
// activation. Both sum each 16-value sub-block exactly in integers; only the float additions are ordered differently,
// so the check is a relative tolerance, not equality. Random blocks cover every code and a wide scale range; a real
// expert (layer 0, expert 0 of a pack's experts.bin) covers the checkpoint's own distribution.
// Also the down rows (n 640) and gate/up through silu with the blob tail's scales, 1..9 tokens (past one slice).
// The AVX2 rows follow ggml's AVX2 path step for step, so for them every row must also be bit-equal (ggml-cpu built
// with AVX2: STRATA_PORTABLE, or a native build). Each kernel is checked when this CPU runs it.
// Speed: gate+up rows of one expert for 1..8 tokens, each way, as the CPU pool runs them.
//
// nvfp4_avx512_parity --bw THREADS TOKENS [ggml|avx2]
// nvfp4_avx512_parity --expert pack/experts.bin [layer expert]
//
// --expert: one whole expert as decode runs it (Q8_0 input, gate/up + silu, Q8_0 of the hidden, down) against a
// double-precision reference with the checkpoint's global scales, with s_down folded into up (the hidden becomes
// ~1e-5 and its Q8_0 scale an FP16 subnormal) and with s_down applied to the output instead.
//
// DRAM rate: THREADS threads each run whole experts (gate/up through silu, then down) out of 4.2 GB of blobs -
// 40x the L3 - for TOKENS tokens; GB/s of weights read. STRATA_NVFP4_PREFETCH sets the kernel's prefetch distance.
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/cpu/nvfp4_avx2.hpp"
#include "strata/kernels/cpu/nvfp4_avx512.hpp"
#include "ggml.h"
#include "ggml-cpu.h"
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <random>
#include <thread>
#include <string>
#include <vector>
namespace {
struct Kern {
const char* name;
void (*gu)(const uint8_t*, size_t, size_t, int, const void* const*, int, float* const*, int, int, float, float);
void (*rows)(const uint8_t*, size_t, int, const void* const*, int, float* const*, int, int, float);
bool exact; // bit-equal to ggml's AVX2 dot
};
const Kern k512{"avx512", strata::kernels::cpu::nvfp4_512_gu_rows, strata::kernels::cpu::nvfp4_512_rows, false};
const Kern k256{"avx2", strata::kernels::cpu::nvfp4_256_gu_rows, strata::kernels::cpu::nvfp4_256_rows, true};
constexpr int N = 2560, ROWS = 1280, BLK = 36; // an expert's gate+up: 1280 rows of 2560 values
constexpr int FF = 640; // its down: 2560 rows of 640
constexpr size_t ROW_BYTES = (size_t) N / 64 * BLK, D_ROW = (size_t) FF / 64 * BLK;
constexpr size_t BLOB = (size_t) ROWS * ROW_BYTES + (size_t) N * D_ROW + 16;
double now_ms() {
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
struct Acts {
std::vector<std::vector<uint8_t>> q;
std::vector<const void*> p;
Acts(int n, int nt, std::mt19937& rng) : q(nt), p(nt) {
const ggml_type_traits_cpu* ta = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> x(n);
for (int t = 0; t < nt; ++t) {
for (float& v : x) v = nd(rng) * (t + 1); // several magnitudes
q[t].resize(ggml_row_size(GGML_TYPE_Q8_0, n));
ta->from_float(x.data(), q[t].data(), n);
p[t] = q[t].data();
}
}
};
float ref_dot(const uint8_t* row, int n, const void* a) {
float s = 0.f;
ggml_get_type_traits_cpu(GGML_TYPE_NVFP4)->vec_dot(n, &s, 0, row, 0, a, 0, 1);
return s;
}
int report(const std::vector<std::vector<float>>& mine, const std::vector<std::vector<float>>& ref,
int nt, int rows, double& worst, int& differ) {
int bad = 0;
for (int t = 0; t < nt; ++t) {
double scale = 0;
for (int r = 0; r < rows; ++r) scale = std::fmax(scale, std::fabs(ref[t][r]));
for (int r = 0; r < rows; ++r) {
const double e = std::fabs((double) mine[t][r] - ref[t][r]) / (scale > 0 ? scale : 1);
worst = std::fmax(worst, e);
if (!(e <= 1e-5)) ++bad;
differ += std::memcmp(&mine[t][r], &ref[t][r], sizeof(float)) != 0;
}
}
return bad;
}
// a kernel that claims bit equality fails on any differing row
int verdict(const Kern& k, const char* what, double worst, int rows, int nt, int bad, int differ) {
std::printf("%-7s %-36s worst |mine - ggml| / max|ggml| = %.2e over %d rows x 1..%d tokens, %d beyond 1e-5, "
"%d not bit-equal\n", k.name, what, worst, rows, nt, bad, differ);
return bad + (k.exact ? differ : 0);
}
// plain rows: `rows` rows of `n` values, `row_bytes` apart
int check_rows(const Kern& k, const uint8_t* w, int n, size_t row_bytes, int rows, const char* what,
std::mt19937& rng) {
constexpr int NT = 9; // past one slice: 9 = 5 + 4
Acts a(n, NT, rng);
std::vector<std::vector<float>> mine(NT, std::vector<float>(rows)), ref(NT, std::vector<float>(rows));
std::vector<float*> op(NT);
for (int t = 0; t < NT; ++t) op[t] = mine[t].data();
int bad = 0, differ = 0;
double worst = 0;
for (int nt = 1; nt <= NT; ++nt) {
k.rows(w, row_bytes, n, a.p.data(), nt, op.data(), 0, rows, 1.f);
for (int t = 0; t < nt; ++t)
for (int r = 0; r < rows; ++r) ref[t][r] = ref_dot(w + (size_t) r * row_bytes, n, a.p[t]);
bad += report(mine, ref, nt, rows, worst, differ);
}
return verdict(k, what, worst, rows, NT, bad, differ);
}
// gate/up with the blob tail's scales: silu(s_gate g) * (s_up u), as native_gu_rows' ggml path computes it
int check_gu(const Kern& k, const uint8_t* blob, std::mt19937& rng) {
constexpr int NT = 9, F = ROWS / 2;
float tail[4];
std::memcpy(tail, blob + BLOB - 16, sizeof tail);
const float sg = tail[0], su = tail[1];
const size_t up_off = (size_t) F * ROW_BYTES;
Acts a(N, NT, rng);
std::vector<std::vector<float>> mine(NT, std::vector<float>(F)), ref(NT, std::vector<float>(F));
std::vector<float*> op(NT);
for (int t = 0; t < NT; ++t) op[t] = mine[t].data();
int bad = 0, differ = 0;
double worst = 0;
for (int nt = 1; nt <= NT; ++nt) {
k.gu(blob, ROW_BYTES, up_off, N, a.p.data(), nt, op.data(), 0, F, sg, su);
for (int t = 0; t < nt; ++t)
for (int r = 0; r < F; ++r) {
const float g = ref_dot(blob + (size_t) r * ROW_BYTES, N, a.p[t]) * sg;
const float u = ref_dot(blob + up_off + (size_t) r * ROW_BYTES, N, a.p[t]) * su;
ref[t][r] = (g / (1.f + std::exp(-g))) * u;
}
bad += report(mine, ref, nt, F, worst, differ);
}
char what[96];
std::snprintf(what, sizeof what, "expert 0: silu(gate) * up (s %.2g/%.2g)", sg, su);
return verdict(k, what, worst, F, NT, bad, differ);
}
void speed(const std::vector<uint8_t>& w, std::mt19937& rng, bool has512, bool has256) {
const ggml_type_traits_cpu* tw = ggml_get_type_traits_cpu(GGML_TYPE_NVFP4);
const ggml_type_traits_cpu* ta = ggml_get_type_traits_cpu(tw->vec_dot_type);
const size_t act_bytes = ggml_row_size(tw->vec_dot_type, N);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<std::vector<uint8_t>> act(8, std::vector<uint8_t>(act_bytes));
std::vector<float> x(N), sink(8 * ROWS);
const void* ap[8];
float* op[8];
for (int t = 0; t < 8; ++t) {
for (float& v : x) v = nd(rng);
ta->from_float(x.data(), act[t].data(), N);
ap[t] = act[t].data();
op[t] = sink.data() + (size_t) t * ROWS;
}
std::printf("\n%-6s %10s %10s %8s %10s %8s (one expert's gate+up, %d rows; best of 20)\n", "tokens",
"ggml ms", "avx512 ms", "speedup", "avx2 ms", "speedup", ROWS);
for (int nt = 1; nt <= 8; ++nt) {
double tg = 1e30, tm = 1e30, t2 = 1e30;
for (int rep = 0; rep < 20; ++rep) {
double t0 = now_ms();
for (int t = 0; t < nt; ++t)
for (int r = 0; r < ROWS; ++r) tw->vec_dot(N, &op[t][r], 0, w.data() + (size_t) r * ROW_BYTES, 0, ap[t], 0, 1);
tg = std::fmin(tg, now_ms() - t0);
if (has512) {
t0 = now_ms();
k512.rows(w.data(), ROW_BYTES, N, ap, nt, op, 0, ROWS, 1.f);
tm = std::fmin(tm, now_ms() - t0);
}
if (has256) {
t0 = now_ms();
k256.rows(w.data(), ROW_BYTES, N, ap, nt, op, 0, ROWS, 1.f);
t2 = std::fmin(t2, now_ms() - t0);
}
}
std::printf("%-6d %10.3f %10.3f %7.2fx %10.3f %7.2fx\n", nt, tg, has512 ? tm : 0.0, has512 ? tg / tm : 0.0,
has256 ? t2 : 0.0, has256 ? tg / t2 : 0.0);
}
}
int bandwidth(int threads, int nt, bool use_ggml, const Kern& k) {
constexpr int E = 1536;
std::vector<uint8_t> blobs((size_t) E * BLOB);
{
std::vector<std::thread> fill;
for (int t = 0; t < 16; ++t)
fill.emplace_back([&, t] {
uint64_t x = 0x9E3779B97F4A7C15ull * (t + 1);
const size_t n8 = blobs.size() / 8, a = n8 * t / 16, b = n8 * (t + 1) / 16;
for (size_t i = a; i < b; ++i) {
x ^= x << 13; x ^= x >> 7; x ^= x << 17;
uint64_t v = x & 0x3F3F3F3F3F3F3F3Full; // scale bytes stay finite; codes are any nibble
std::memcpy(blobs.data() + 8 * i, &v, 8);
}
});
for (auto& f : fill) f.join();
}
std::mt19937 rng(7);
Acts ax(N, nt, rng), ah(FF, nt, rng);
const ggml_type_traits_cpu* tw = ggml_get_type_traits_cpu(GGML_TYPE_NVFP4);
double best = 1e30;
for (int pass = 0; pass < 3; ++pass) {
const double t0 = now_ms();
std::vector<std::thread> pool;
for (int w = 0; w < threads; ++w)
pool.emplace_back([&, w] {
std::vector<float> ff((size_t) nt * (ROWS / 2)), out((size_t) nt * N);
std::vector<float*> fp(nt), op(nt);
for (int t = 0; t < nt; ++t) { fp[t] = ff.data() + (size_t) t * (ROWS / 2); op[t] = out.data() + (size_t) t * N; }
for (int e = w; e < E; e += threads) {
const uint8_t* b = blobs.data() + (size_t) e * BLOB;
const size_t up_off = (size_t) (ROWS / 2) * ROW_BYTES, d_off = (size_t) ROWS * ROW_BYTES;
if (!use_ggml) {
k.gu(b, ROW_BYTES, up_off, N, ax.p.data(), nt, fp.data(), 0, ROWS / 2, 1.f, 1.f);
k.rows(b + d_off, D_ROW, FF, ah.p.data(), nt, op.data(), 0, N, 1.f);
} else {
for (int r = 0; r < ROWS / 2; ++r)
for (int t = 0; t < nt; ++t) {
float g = 0.f, u = 0.f;
tw->vec_dot(N, &g, 0, b + (size_t) r * ROW_BYTES, 0, ax.p[t], 0, 1);
tw->vec_dot(N, &u, 0, b + up_off + (size_t) r * ROW_BYTES, 0, ax.p[t], 0, 1);
fp[t][r] = (g / (1.f + std::exp(-g))) * u;
}
for (int r = 0; r < N; ++r)
for (int t = 0; t < nt; ++t) tw->vec_dot(FF, &op[t][r], 0, b + d_off + (size_t) r * D_ROW, 0, ah.p[t], 0, 1);
}
}
});
for (auto& p : pool) p.join();
best = std::fmin(best, now_ms() - t0);
}
const char* pf = std::getenv("STRATA_NVFP4_PREFETCH");
std::printf("%s threads %d tokens %d prefetch %s: %.1f ms for %d experts -> %.1f GB/s, %.1f us/expert/thread\n",
use_ggml ? "ggml " : k.name, threads, nt, use_ggml ? "-" : (pf ? pf : "2048"), best, E,
(double) E * BLOB / best / 1e6, best * 1000.0 * threads / E);
return 0;
}
int expert_e2e(const char* path, int layer, int e) {
constexpr size_t STRIDE = 2764816, LAYER = 512 * STRIDE;
std::vector<uint8_t> b(BLOB);
std::ifstream f(path, std::ios::binary);
f.seekg((std::streamoff) (layer * LAYER + (size_t) e * STRIDE));
if (!f.read((char*) b.data(), (std::streamsize) b.size())) { std::fprintf(stderr, "cannot read %s\n", path); return 2; }
float tail[4];
std::memcpy(tail, b.data() + BLOB - 16, sizeof tail);
const float sg = tail[0], s_up = tail[1], s_down = tail[2];
const int F = ROWS / 2;
const size_t up_off = (size_t) F * ROW_BYTES, d_off = (size_t) ROWS * ROW_BYTES;
const ggml_type_traits* tt = ggml_get_type_traits(GGML_TYPE_NVFP4);
std::vector<float> wg((size_t) F * N), wu((size_t) F * N), wd((size_t) N * FF);
tt->to_float(b.data(), wg.data(), (int64_t) F * N);
tt->to_float(b.data() + up_off, wu.data(), (int64_t) F * N);
tt->to_float(b.data() + d_off, wd.data(), (int64_t) N * FF);
const ggml_type_traits_cpu* q8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
std::mt19937 rng(9);
std::normal_distribution<float> nd(0.f, 1.f);
double e_fold = 0, e_out = 0, den = 0, hmax_fold = 0;
for (int trial = 0; trial < 8; ++trial) {
std::vector<float> x(N);
for (float& v : x) v = nd(rng);
std::vector<double> h(F), y(N, 0.0);
for (int r = 0; r < F; ++r) {
double g = 0, u = 0;
for (int k = 0; k < N; ++k) { g += (double) wg[(size_t) r * N + k] * x[k]; u += (double) wu[(size_t) r * N + k] * x[k]; }
g *= sg; u *= s_up;
h[r] = g / (1 + std::exp(-g)) * u;
}
for (int r = 0; r < N; ++r) {
double s = 0;
for (int k = 0; k < F; ++k) s += (double) wd[(size_t) r * FF + k] * h[k];
y[r] = s * s_down;
}
std::vector<uint8_t> xq(ggml_row_size(GGML_TYPE_Q8_0, N)), hq(ggml_row_size(GGML_TYPE_Q8_0, FF));
q8->from_float(x.data(), xq.data(), N);
const void* ap[1] = {xq.data()};
std::vector<float> ff(F), out(N);
float* fp[1] = {ff.data()};
float* op[1] = {out.data()};
for (int mode = 0; mode < 2; ++mode) { // 0: s_down folded into up; 1: s_down on the output
const Kern& k = strata::kernels::cpu::cpu_avx512_ok() ? k512 : k256;
k.gu(b.data(), ROW_BYTES, up_off, N, ap, 1, fp, 0, F, sg, mode == 0 ? s_up * s_down : s_up);
if (mode == 0) for (float v : ff) hmax_fold = std::fmax(hmax_fold, std::fabs(v));
q8->from_float(ff.data(), hq.data(), FF);
const void* hp[1] = {hq.data()};
k.rows(b.data() + d_off, D_ROW, FF, hp, 1, op, 0, N, 1.f);
double err = 0;
for (int r = 0; r < N; ++r) {
const double got = mode == 0 ? out[r] : (double) out[r] * s_down;
err += (got - y[r]) * (got - y[r]);
}
(mode == 0 ? e_fold : e_out) += err;
}
for (int r = 0; r < N; ++r) den += y[r] * y[r];
}
std::printf("layer %d expert %d: s_gate %.3g s_up %.3g s_down %.3g; folded hidden max |h| %.3g (Q8_0 d %.3g, FP16 "
"normal from 6.1e-05)\n", layer, e, sg, s_up, s_down, hmax_fold, hmax_fold / 127);
std::printf(" s_down folded into up : expert output rel. error %.3f%%\n", 100 * std::sqrt(e_fold / den));
std::printf(" s_down on the output : expert output rel. error %.3f%%\n", 100 * std::sqrt(e_out / den));
return 0;
}
} // namespace
int main(int argc, char** argv) {
ggml_cpu_init();
if (argc >= 3 && std::string(argv[1]) == "--expert")
return expert_e2e(argv[2], argc >= 4 ? std::atoi(argv[3]) : 0, argc >= 5 ? std::atoi(argv[4]) : 0);
const bool has512 = strata::kernels::cpu::cpu_avx512_ok(), has256 = strata::kernels::cpu::cpu_avx2_ok();
if (argc >= 4 && std::string(argv[1]) == "--bw") {
const std::string how = argc >= 5 ? argv[4] : "";
return bandwidth(std::atoi(argv[2]), std::atoi(argv[3]), how == "ggml", how == "avx2" || !has512 ? k256 : k512);
}
std::vector<const Kern*> ks;
if (has512) ks.push_back(&k512);
if (has256) ks.push_back(&k256);
std::mt19937 rng(20260929);
std::vector<uint8_t> w(BLOB);
// random blocks: every code, scales 0x20..0x5f (sign bit clear, never 0x7F), as ModelOpt writes them
std::uniform_int_distribution<int> byte(0, 255), sc(0x20, 0x5f);
for (size_t b = 0; b + BLK <= BLOB - 16; b += BLK) {
for (int s = 0; s < 4; ++s) w[b + s] = (uint8_t) sc(rng);
for (int q = 4; q < BLK; ++q) w[b + q] = (uint8_t) byte(rng);
}
int bad = 0;
for (const Kern* k : ks) {
bad += check_rows(*k, w.data(), N, ROW_BYTES, ROWS, "random blocks, n 2560", rng);
bad += check_rows(*k, w.data(), FF, D_ROW, N, "random blocks, n 640", rng);
}
if (argc >= 2) { // layer 0, expert 0 of the pack
std::ifstream f(argv[1], std::ios::binary);
if (!f.read((char*) w.data(), (std::streamsize) w.size())) {
std::fprintf(stderr, "cannot read %zu bytes of %s\n", w.size(), argv[1]);
return 2;
}
for (const Kern* k : ks) {
bad += check_rows(*k, w.data(), N, ROW_BYTES, ROWS, "expert 0: gate+up rows", rng);
bad += check_rows(*k, w.data() + (size_t) ROWS * ROW_BYTES, FF, D_ROW, N, "expert 0: down rows", rng);
bad += check_gu(*k, w.data(), rng);
}
}
speed(w, rng, has512, has256);
std::printf("\nRESULT: %s\n", bad ? "MISMATCH" : "parity OK");
return bad ? 1 : 0;
}
+224 -45
View File
@@ -567,6 +567,38 @@ __device__ __forceinline__ float vec_dot_q8_0_q8_1(const void* __restrict__ vbq,
const float d8_0 = __half2float(bq8_0->d), d8_1 = __low2float(bq8_1->ds);
return d8_0 * d8_1 * ((float) sumi);
}
// NVFP4 (ModelOpt): 64 values = 4 sub-blocks of 16, one UE4M3 scale each, E2M1 codes split-half like Q4_0.
// kvalues_fp4 holds the E2M1 values doubled (0, 1, 2, 3, 4, 6, 8, 12), so the scale is halved here - exactly
// ggml's ggml_cuda_ue4m3_to_fp32, decoded in software so the GPU and ggml-cpu agree bit for bit (NaN -> 0).
__device__ __forceinline__ float ue4m3_to_f32_half(uint8_t x) {
// The same value as ldexpf(1 + man/8, exp - 7) * 0.5 (ldexpf(man, -9) * 0.5 for exp 0), built from its bits: every
// such value is exact in FP32, so this is equal for all 256 inputs - without the ldexpf and the branches it cost
// in the decode experts' inner loop. Normal: 2^(exp-8) * (1 + man/8) = exponent field exp + 119, mantissa man<<20.
if (x == 0 || x == 0x7F) return 0.0f;
const uint32_t exp = (x >> 3) & 0xF, man = x & 0x7;
return exp == 0 ? (float) man * 0.0009765625f : __uint_as_float(((exp + 119u) << 23) | (man << 20));
}
// One call = two sub-blocks (32 values); `bq8_1` is the block's first q8_1 block (two per 64 values).
__device__ __forceinline__ float vec_dot_nvfp4_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
const int& kbx, const int& iqs) {
const block_nvfp4* bq4 = (const block_nvfp4*) vbq + kbx;
float sum = 0.0f;
#pragma unroll
for (int i = 0; i < 2; i++) {
const int iqs0 = iqs + 2 * i, iqs1 = iqs0 + 1, is = iqs0 >> 1;
const int2 v0 = get_int_from_table_16(get_int_b4(bq4->qs, iqs0), kvalues_fp4);
const int2 v1 = get_int_from_table_16(get_int_b4(bq4->qs, iqs1), kvalues_fp4);
const block_q8_1* bq8 = bq8_1 + (is >> 1);
const int i8 = (is & 1) << 2;
int sumi = ggml_cuda_dp4a(v0.x, get_int_b4(bq8->qs, i8 + 0), 0);
sumi = ggml_cuda_dp4a(v0.y, get_int_b4(bq8->qs, i8 + 2), sumi);
sumi = ggml_cuda_dp4a(v1.x, get_int_b4(bq8->qs, i8 + 1), sumi);
sumi = ggml_cuda_dp4a(v1.y, get_int_b4(bq8->qs, i8 + 3), sumi);
sum += ue4m3_to_f32_half(bq4->d[is]) * __low2float(bq8->ds) * (float) sumi;
}
return sum;
}
// ---------------------------------------------------------------- the formats
// qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls.
@@ -609,12 +641,14 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0,
// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every
// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
#ifdef STRATA_Q6K_EXPERTS // opt-in build (-DSTRATA_Q6K_EXPERTS=ON): one more instance per kernel, loaded at start
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8)
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(40)
#else
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8)
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40)
#endif
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8)
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8)
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(40)
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40)
template<> struct Fmt<40> { static constexpr int qk = 64, ipb = 2, step = 4; // NVFP4: 2 calls of 32 values
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_nvfp4_q8_1(v, y, kbx, iqs); } };
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
@@ -964,6 +998,38 @@ template<> struct Split<42> { // Q2_0
return r.d2 * d8 * sumi;
}
};
template<> inline constexpr bool kSplit<40> = true;
template<> struct Split<40> { // NVFP4: vec_dot_nvfp4_q8_1's two 16-value sub-blocks, weights decoded once per call
struct W { int2 v0[2], v1[2]; float sc[2]; };
template<bool STAGE_GRID = false>
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
const block_nvfp4* bq4 = (const block_nvfp4*) vbq + kbx;
W r;
#pragma unroll
for (int i = 0; i < 2; i++) {
const int iqs0 = iqs + 2 * i, iqs1 = iqs0 + 1, is = iqs0 >> 1;
r.v0[i] = get_int_from_table_16(get_int_b4(bq4->qs, iqs0), kvalues_fp4);
r.v1[i] = get_int_from_table_16(get_int_b4(bq4->qs, iqs1), kvalues_fp4);
r.sc[i] = ue4m3_to_f32_half(bq4->d[is]);
}
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
float sum = 0.0f; // the same operations, in the same order, as the dot
#pragma unroll
for (int i = 0; i < 2; i++) {
const int is = (iqs + 2 * i) >> 1;
const block_q8_1* bq8 = bq8_1 + (is >> 1);
const int i8 = (is & 1) << 2;
int sumi = ggml_cuda_dp4a(r.v0[i].x, get_int_b4(bq8->qs, i8 + 0), 0);
sumi = ggml_cuda_dp4a(r.v0[i].y, get_int_b4(bq8->qs, i8 + 2), sumi);
sumi = ggml_cuda_dp4a(r.v1[i].x, get_int_b4(bq8->qs, i8 + 1), sumi);
sumi = ggml_cuda_dp4a(r.v1[i].y, get_int_b4(bq8->qs, i8 + 3), sumi);
sum += r.sc[i] * __low2float(bq8->ds) * (float) sumi;
}
return sum;
}
};
// One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to
// spare registers), the whole warp. Per activation this is row_dot: the same calls k, lane-strided the same way,
@@ -1046,7 +1112,54 @@ __device__ __forceinline__ void row_dot_40_sub8(const uint8_t* row, const block_
}
}
// 16-lane sub-warp row dot for K = nb * ipb == 20 (TD == 42, Q2_0 with n_ff == 640):
// 8-lane sub-warp row dot for K = nb * ipb == 20 (TD == 40, NVFP4 with n_ff == 640): 4 rows per warp (32 rows per
// 256-thread block). Bitwise row_dot_multi's tree: warp_sum adds lane i + 16 (terms k and k + 16; lanes 20-31 hold
// +0) then i + 8, then 4, 2, 1 - so lane t here takes k = t (+ k = t + 16 for t < 4, else + 0) and k = t + 8 (+ 0).
template<int TY, int NC, bool EXACT_N = false>
__device__ __forceinline__ void row_dot_20_sub8(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
int t, float (&s)[NC]) {
using F = Fmt<TY>;
using S = Split<TY>;
#pragma unroll
for (int c = 0; c < NC; ++c) s[c] = 0.0f;
{
const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
const typename S::W w = S::load(row, kbx, iqs);
#pragma unroll
for (int c = 0; c < NC; ++c)
if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
}
float s16[NC];
#pragma unroll
for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
if (t < 4) {
const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
const typename S::W w = S::load(row, kbx, iqs);
#pragma unroll
for (int c = 0; c < NC; ++c)
if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
}
float s8[NC];
#pragma unroll
for (int c = 0; c < NC; ++c) s8[c] = 0.0f;
{
const int k = t + 8, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
const typename S::W w = S::load(row, kbx, iqs);
#pragma unroll
for (int c = 0; c < NC; ++c)
if (EXACT_N || c < n) s8[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
}
#pragma unroll
for (int c = 0; c < NC; ++c) {
if (EXACT_N || c < n) {
s[c] = __fadd_rn(__fadd_rn(s[c], s16[c]), __fadd_rn(s8[c], 0.0f));
#pragma unroll
for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
}
}
}
// 16-lane sub-warp row dot for K = nb * ipb == 20 (TD == 42, Q2_0, and TD == 40, NVFP4, with n_ff == 640):
// 2 rows per warp (16 rows per 256-thread block), bitwise identical addition tree to row_dot_multi.
template<int TY, int NC, bool EXACT_N = false>
__device__ __forceinline__ void row_dot_20_sub16(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
@@ -1225,11 +1338,19 @@ __global__ void __launch_bounds__(256) native_gu_kernel(const unsigned long long
const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
const int ng = *n_groups;
for (int g = blockIdx.y; g < ng; g += gridDim.y) {
const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
const uint8_t* wr = blob + off;
// NVFP4: the expert's global scales from the blob's tail; s_down goes on the down output (native_down_kernel):
// folded into up it left the hidden near 1e-5, whose q8_1 block scale is an FP16 subnormal
float scale = 1.0f;
if (L.tail_off) {
const float* tail = (const float*) (blob + L.tail_off);
scale = is_up ? tail[1] : tail[0];
}
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; ++e) {
const float s = row_dot<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);
if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s;
if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s * scale;
}
}
}
@@ -1262,6 +1383,8 @@ __global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned lon
float* dst = is_up ? up : gate;
for (int g = blockIdx.y; g < ng; g += gridDim.y) {
const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
// NVFP4: the expert's s_gate / s_up on the FP32 output, as native_gu_kernel (1 otherwise: exact)
const float sc = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[is_up ? 1 : 0] : 1.0f;
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; e += GRP_NC) {
const int n = min(GRP_NC, e1 - e);
@@ -1269,22 +1392,22 @@ __global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned lon
const int off1[1] = { ent_tok[e] * 80 };
float s1[1];
row_dot_80_sub16<TG, 1, true, STAGE_GRID>(wr, xq, off1, 1, t, s1, s_grid);
if (t == 0) dst[(size_t) e * L.n_ff + r] = s1[0];
if (t == 0) dst[(size_t) e * L.n_ff + r] = s1[0] * sc;
} else if (n == 2) {
const int off2[2] = { ent_tok[e] * 80, ent_tok[e + 1] * 80 };
float s2[2];
row_dot_80_sub16<TG, 2, true, STAGE_GRID>(wr, xq, off2, 2, t, s2, s_grid);
if (t < 2) dst[(size_t) (e + t) * L.n_ff + r] = s2[t];
if (t < 2) dst[(size_t) (e + t) * L.n_ff + r] = s2[t] * sc;
} else if (n == 3) {
const int off3[3] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80 };
float s3[3];
row_dot_80_sub16<TG, 3, true, STAGE_GRID>(wr, xq, off3, 3, t, s3, s_grid);
if (t < 3) dst[(size_t) (e + t) * L.n_ff + r] = s3[t];
if (t < 3) dst[(size_t) (e + t) * L.n_ff + r] = s3[t] * sc;
} else {
const int off4[4] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80, ent_tok[e + 3] * 80 };
float s4[4];
row_dot_80_sub16<TG, 4, true, STAGE_GRID>(wr, xq, off4, 4, t, s4, s_grid);
if (t < 4) dst[(size_t) (e + t) * L.n_ff + r] = s4[t];
if (t < 4) dst[(size_t) (e + t) * L.n_ff + r] = s4[t] * sc;
}
}
}
@@ -1300,6 +1423,8 @@ __global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned lon
float* dst = is_up ? up : gate;
for (int g = blockIdx.y; g < ng; g += gridDim.y) { // the group stride, as native_gu_kernel
const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
// NVFP4: the expert's s_gate / s_up on the FP32 output, as native_gu_kernel (1 otherwise: exact)
const float sc = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[is_up ? 1 : 0] : 1.0f;
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; e += GRP_NC) {
const int n = min(GRP_NC, e1 - e);
@@ -1307,22 +1432,22 @@ __global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned lon
const int off1[1] = { ent_tok[e] * xb };
float s1[1];
row_dot_multi<TG, 1, true, STAGE_GRID>(wr, xq, off1, 1, nb, lane, s1, s_grid);
if (lane == 0) dst[(size_t) e * L.n_ff + r] = s1[0];
if (lane == 0) dst[(size_t) e * L.n_ff + r] = s1[0] * sc;
} else if (n == 2) {
const int off2[2] = { ent_tok[e] * xb, ent_tok[e + 1] * xb };
float s2[2];
row_dot_multi<TG, 2, true, STAGE_GRID>(wr, xq, off2, 2, nb, lane, s2, s_grid);
if (lane < 2) dst[(size_t) (e + lane) * L.n_ff + r] = s2[lane];
if (lane < 2) dst[(size_t) (e + lane) * L.n_ff + r] = s2[lane] * sc;
} else if (n == 3) {
const int off3[3] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb };
float s3[3];
row_dot_multi<TG, 3, true, STAGE_GRID>(wr, xq, off3, 3, nb, lane, s3, s_grid);
if (lane < 3) dst[(size_t) (e + lane) * L.n_ff + r] = s3[lane];
if (lane < 3) dst[(size_t) (e + lane) * L.n_ff + r] = s3[lane] * sc;
} else {
const int off4[4] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb, ent_tok[e + 3] * xb };
float s4[4];
row_dot_multi<TG, 4, true, STAGE_GRID>(wr, xq, off4, 4, nb, lane, s4, s_grid);
if (lane < 4) dst[(size_t) (e + lane) * L.n_ff + r] = s4[lane];
if (lane < 4) dst[(size_t) (e + lane) * L.n_ff + r] = s4[lane] * sc;
}
}
}
@@ -1350,15 +1475,25 @@ __global__ void __launch_bounds__(256) native_down_kernel(const unsigned long lo
const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
const int ng = *n_groups;
for (int g = blockIdx.y; g < ng; g += gridDim.y) { // as native_gu_kernel
const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
const uint8_t* wr = blob + off;
const float sd = L.tail_off ? ((const float*) (blob + L.tail_off))[2] : 1.0f; // NVFP4: s_down
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; ++e) {
const float s = row_dot<TD>(wr, hq + (size_t) e * hb, nb, lane);
if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s;
if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s * sd;
}
}
}
// the 8-lane down rows: IQ4_NL's K = 40, NVFP4's K = 20
template<int TD, int NC, bool EXACT_N = false>
__device__ __forceinline__ void row_dot_sub8(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n, int t,
float (&s)[NC]) {
if constexpr (TD == 40) row_dot_20_sub8<TD, NC, EXACT_N>(row, x, off, n, t, s);
else row_dot_40_sub8<TD, NC, EXACT_N>(row, x, off, n, t, s);
}
// native_down_kernel with the entries taken GRP_NC at a time
template<int TD, bool SUB_DOWN = true>
__global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned long long* __restrict__ grp_ptr,
@@ -1371,7 +1506,7 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
if (blockIdx.y >= ng) return;
__shared__ uint32_t s_hq_buf[GRP_NC * 20 * 9];
const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
if constexpr (SUB_DOWN && TD == 20) {
if constexpr (SUB_DOWN && (TD == 20 || TD == 40)) { // IQ4_NL (K 40) and NVFP4 (K 20): 8-lane rows
if (hb == 20) {
const int r = blockIdx.x * 32 + (threadIdx.x >> 3);
const int t = threadIdx.x & 7;
@@ -1380,6 +1515,7 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
for (int g = blockIdx.y; g < ng; g += gridDim.y) {
const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
const float sd = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[2] : 1.0f; // NVFP4: s_down
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; e += GRP_NC) {
const int n = min(GRP_NC, e1 - e);
@@ -1392,23 +1528,23 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
if (n == 1) {
const int off1[1] = { 0 };
float s1[1];
row_dot_40_sub8<TD, 1, true>(wr, s_hq, off1, 1, t, s1);
if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];
row_dot_sub8<TD, 1, true>(wr, s_hq, off1, 1, t, s1);
if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0] * sd;
} else if (n == 2) {
const int off2[2] = { 0, 20 };
float s2[2];
row_dot_40_sub8<TD, 2, true>(wr, s_hq, off2, 2, t, s2);
if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t];
row_dot_sub8<TD, 2, true>(wr, s_hq, off2, 2, t, s2);
if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t] * sd;
} else if (n == 3) {
const int off3[3] = { 0, 20, 40 };
float s3[3];
row_dot_40_sub8<TD, 3, true>(wr, s_hq, off3, 3, t, s3);
if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t];
row_dot_sub8<TD, 3, true>(wr, s_hq, off3, 3, t, s3);
if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t] * sd;
} else {
const int off4[4] = { 0, 20, 40, 60 };
float s4[4];
row_dot_40_sub8<TD, 4, true>(wr, s_hq, off4, 4, t, s4);
if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t];
row_dot_sub8<TD, 4, true>(wr, s_hq, off4, 4, t, s4);
if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t] * sd;
}
}
}
@@ -1424,6 +1560,7 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
for (int g = blockIdx.y; g < ng; g += gridDim.y) {
const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
const float sd = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[2] : 1.0f; // NVFP4: s_down
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; e += GRP_NC) {
const int n = min(GRP_NC, e1 - e);
@@ -1437,22 +1574,22 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
const int off1[1] = { 0 };
float s1[1];
row_dot_20_sub16<TD, 1, true>(wr, s_hq, off1, 1, t, s1);
if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];
if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0] * sd;
} else if (n == 2) {
const int off2[2] = { 0, 20 };
float s2[2];
row_dot_20_sub16<TD, 2, true>(wr, s_hq, off2, 2, t, s2);
if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t];
if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t] * sd;
} else if (n == 3) {
const int off3[3] = { 0, 20, 40 };
float s3[3];
row_dot_20_sub16<TD, 3, true>(wr, s_hq, off3, 3, t, s3);
if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t];
if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t] * sd;
} else {
const int off4[4] = { 0, 20, 40, 60 };
float s4[4];
row_dot_20_sub16<TD, 4, true>(wr, s_hq, off4, 4, t, s4);
if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t];
if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t] * sd;
}
}
}
@@ -1466,6 +1603,7 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;
for (int g = blockIdx.y; g < ng; g += gridDim.y) { // the group stride, as native_gu_kernel
const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
const float sd = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[2] : 1.0f; // NVFP4: s_down
const int e0 = grp_start[g], e1 = grp_start[g + 1];
if (hb == 20) {
const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
@@ -1481,12 +1619,12 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
const int off1[1] = { 0 };
float s1[1];
row_dot_multi<TD, 1, true>(wr, s_hq, off1, 1, nb, lane, s1);
if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];
if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0] * sd;
} else if (n == 2) {
const int off2[2] = { 0, 20 };
float s2[2];
row_dot_multi<TD, 2, true>(wr, s_hq, off2, 2, nb, lane, s2);
if (lane < 2) out[(size_t) ent_dst[e + lane] * L.n_embd + r] = s2[lane];
if (lane < 2) out[(size_t) ent_dst[e + lane] * L.n_embd + r] = s2[lane] * sd;
} else {
int off[GRP_NC];
#pragma unroll
@@ -1495,7 +1633,7 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
row_dot_multi<TD, GRP_NC>(wr, s_hq, off, n, nb, lane, s);
#pragma unroll
for (int c = 0; c < GRP_NC; ++c)
if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];
if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c] * sd;
}
}
}
@@ -1509,7 +1647,7 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l
row_dot_multi<TD, GRP_NC>(wr, hq, off, n, nb, lane, s);
#pragma unroll
for (int c = 0; c < GRP_NC; ++c)
if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];
if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c] * sd;
}
}
}
@@ -1869,6 +2007,20 @@ __device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) {
for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt<dst_t>(__uint_as_float((uint32_t) x[j] << 16));
}
// NVFP4: one "superblock" = 256 values = 4 blocks of 64; thread tid writes 8 values of block tid / 8.
// Sub-block s (16 values) keeps its codes in qs[8 s .. 8 s + 7]: byte j = value j (low nibble) and j + 8 (high).
template<typename dst_t>
__device__ void dq_nvfp4(const void* vx, int64_t ibs, dst_t* yy, int tid) {
const block_nvfp4* x = (const block_nvfp4*) vx + ibs * 4;
const int b = tid / 8, part = tid % 8;
for (int j = 0; j < 8; ++j) {
const int i = part * 8 + j, s = i / 16, k = i % 16;
const uint8_t byte = x[b].qs[s * 8 + (k & 7)];
const int code = k < 8 ? (byte & 0x0F) : (byte >> 4);
yy[b * 64 + i] = cvt<dst_t>((float) kvalues_fp4[code] * ue4m3_to_f32_half(x[b].d[s]));
}
}
// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others,
// so the default is unreachable.
template<typename dst_t>
@@ -1893,6 +2045,7 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs,
case 6: dq_q5_0(vx, ibs, y, tid); break;
case 2: dq_q4_0(vx, ibs, y, tid); break;
case 3: dq_q4_1(vx, ibs, y, tid); break;
case 40: dq_nvfp4(vx, ibs, y, tid); break;
case 8: dq_q8_0(vx, ibs, y, tid); break;
case 30: dq_bf16(vx, ibs, y, tid); break;
default: break;
@@ -1901,26 +2054,44 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs,
// flat: superblock i -> y + 256 i
template<typename dst_t>
__global__ void dequant_flat_kernel(int ty, const void* __restrict__ vx, dst_t* __restrict__ y) {
__global__ void dequant_flat_kernel(int ty, const void* __restrict__ vx, dst_t* __restrict__ y,
const float* __restrict__ scale) {
const int64_t i = blockIdx.x;
dq_dispatch<dst_t>(ty, vx, i, y + i * QK_K, threadIdx.x);
if (scale != nullptr) { // NVFP4 down: s_down (the weights stay in FP16's normal range)
__syncwarp();
const float sc = *scale;
for (int k = 0; k < 8; ++k) {
const int j = threadIdx.x * 8 + k;
y[i * QK_K + j] = cvt<dst_t>((float) y[i * QK_K + j] * sc);
}
}
}
// gate/up: superblock i of a role matrix (n_embd/256 per row) -> interleaved row 2r + parity
__global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const void* __restrict__ up, int64_t per_row,
__half* __restrict__ y) {
__half* __restrict__ y, const float* __restrict__ tail) {
const int64_t i = blockIdx.x;
const int parity = blockIdx.y;
const int64_t r = i / per_row, c = i % per_row;
dq_dispatch<__half>(ty, parity ? up : gate, i, y + ((2 * r + parity) * per_row + c) * QK_K, threadIdx.x);
__half* dst = y + ((2 * r + parity) * per_row + c) * QK_K;
dq_dispatch<__half>(ty, parity ? up : gate, i, dst, threadIdx.x);
if (tail != nullptr) { // NVFP4: gate * s_gate, up * s_up (s_down on the down output: FP16 would underflow)
__syncwarp();
const float sc = parity ? tail[1] : tail[0];
for (int k = 0; k < 8; ++k) {
const int j = threadIdx.x * 8 + k;
dst[j] = __float2half(__half2float(dst[j]) * sc);
}
}
}
// the types dq_dispatch dequantizes
bool is_iq(int t) {
return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
#ifdef STRATA_Q6K_EXPERTS
t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;
t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40;
#else
t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;
t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40;
#endif
}
// values per block of the types the grouped expert kernels take (0 = none)
@@ -2721,6 +2892,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {
case 6: return (size_t) (n / 32) * sizeof(block_q5_0);
case 2: return (size_t) (n / 32) * sizeof(block_q4_0);
case 3: return (size_t) (n / 32) * sizeof(block_q4_1);
case 40: return (size_t) (n / 64) * sizeof(block_nvfp4);
case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)
default: return 0;
@@ -2748,9 +2920,9 @@ void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n
check("iq_mmvq");
}
void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream) {
void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale) {
if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); }
dequant_flat_kernel<__half><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, (__half*) dst);
dequant_flat_kernel<__half><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, (__half*) dst, scale);
check("iq_dequant_f16");
}
@@ -2775,16 +2947,17 @@ void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* to
void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) {
if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }
dequant_flat_kernel<float><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst);
dequant_flat_kernel<float><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst, nullptr);
check("iq_dequant_f32");
}
void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) {
void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream,
const float* tail) {
// checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error
if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); }
const int64_t per_row = n_embd / 256;
dequant_gu_kernel<<<dim3((unsigned) (n_ff * per_row), 2), 32, 0, (cudaStream_t) stream>>>(t, gate, up, per_row,
(__half*) dst);
(__half*) dst, tail);
check("iq_dequant_gu_f16");
}
@@ -2805,6 +2978,12 @@ NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd,
L.up_off = (size_t) n_ff * L.gu_row;
L.down_off = 2 * L.up_off;
L.bytes = L.down_off + (size_t) n_embd * L.d_row;
// NVFP4: {s_gate, s_up, s_down, 0} after down (tools/iq_pack.py) whenever any projection is NVFP4; a mixed
// expert's other projection has 1.0 there, so the kernels below multiply by it unconditionally
if (gu_type == 40 || d_type == 40) {
L.tail_off = L.bytes;
L.bytes += 16;
}
return L;
}
@@ -3602,7 +3781,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
check("native_expert_grouped/swiglu");
}
if (g_exp_phase == 1) return;
const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8;
const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 || L.d_type == 40 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8;
const dim3 gd((unsigned) ((L.n_embd + d_rows - 1) / d_rows), (unsigned) gy);
#if STRATA_EXP_LAYOUTS
if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) {
+12
View File
@@ -61,6 +61,13 @@ int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int se
tg->to_float(blob.data() + f.up_off + r * f.gu_row, U.data() + r * H, H);
}
for (int64_t r = 0; r < H; ++r) td->to_float(blob.data() + f.down_off + r * f.d_row, D.data() + r * FF, FF);
if (f.tail_off) { // the blob's scales, as the engine applies them (gate and up as read, down on its output)
float tail[4];
std::memcpy(tail, blob.data() + f.tail_off, sizeof tail);
for (auto& v : G) v *= tail[0];
for (auto& v : U) v *= tail[1];
for (auto& v : D) v *= tail[2];
}
std::mt19937 rng(11 + seed);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> x((size_t) NT * H);
@@ -404,6 +411,11 @@ std::vector<uint8_t> synthetic_blob(const cpu::NativeFmt& f, int seed) {
quant(f.gu_type, FF, H, blob.data());
quant(f.gu_type, FF, H, blob.data() + f.up_off);
quant(f.d_type, H, FF, blob.data() + f.down_off);
if (f.tail_off) { // NVFP4's {s_gate, s_up, s_down, 0}: non-unit for an NVFP4 projection, 1.0 for another format
const bool g4 = f.gu_type == 40, d4 = f.d_type == 40;
const float tail[4] = {g4 ? 0.75f : 1.f, g4 ? 1.25f : 1.f, d4 ? 0.5f : 1.f, 0.f};
std::memcpy(blob.data() + f.tail_off, tail, sizeof tail);
}
return blob;
}
+156
View File
@@ -0,0 +1,156 @@
// src/kernels/nvfp4_decode_bench.cpp - the decode path's grouped GPU experts (native_expert_grouped) timed on random
// blobs of a format pair, as weight bytes per second against the card's DRAM bandwidth, plus a hash of the output so
// a kernel change can be checked bit for bit.
//
// nvfp4_decode_bench [gu_type d_type] [groups] [tokens per group] [iters]
//
// Defaults: 40 40 (NVFP4), 64 groups (distinct ~2.7 MB blobs: far past L2), 2 tokens each, 50 iterations. UD-IQ4_XS's
// experts: 21 20 (IQ3_S gate/up, IQ4_NL down). Random bytes: the values are meaningless, the timing is not (the
// kernels have no data-dependent branches but the NVFP4 scale decode), and the hash is stable for a given build.
#include "strata/kernels/iq_kernels.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
namespace k = strata::kernels;
namespace {
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
}
} // namespace
int main(int argc, char** argv) {
{ // the UE4M3 decode built from bits (iq_kernels.cu) against the ldexpf form it replaced, all 256 bytes
int bad = 0;
for (int x = 0; x < 256; ++x) {
const int e = (x >> 3) & 0xF, m = x & 7;
const float old = (x == 0 || x == 0x7F) ? 0.0f
: (e == 0 ? std::ldexp((float) m, -9) : std::ldexp(1.0f + (float) m / 8.0f, e - 7)) * 0.5f;
uint32_t bits = ((uint32_t) (e + 119) << 23) | ((uint32_t) m << 20);
float nw;
std::memcpy(&nw, &bits, 4);
if (x == 0 || x == 0x7F) nw = 0.0f;
else if (e == 0) nw = (float) m * 0.0009765625f;
bad += std::memcmp(&old, &nw, 4) != 0;
}
std::printf("ue4m3 decode: %d of 256 bytes differ from the ldexpf form\n", bad);
if (bad) return 1;
}
const int gu = argc > 2 ? std::atoi(argv[1]) : 40, dt = argc > 2 ? std::atoi(argv[2]) : 40;
const int G = argc > 3 ? std::atoi(argv[3]) : 64, TPG = argc > 4 ? std::atoi(argv[4]) : 2;
const int IT = argc > 5 ? std::atoi(argv[5]) : 50;
constexpr int64_t N = 2560, FF = 640;
if (!k::native_expert_supported(gu, dt, N, FF)) { std::fprintf(stderr, "types %d/%d not supported\n", gu, dt); return 2; }
const k::NativeExpertLayout L = k::native_expert_layout(gu, dt, N, FF);
const int E = G * TPG, T = 8; // entries; tokens of the window (activations)
std::mt19937 rng(20261012);
std::vector<uint8_t> blobs((size_t) G * L.bytes);
for (auto& b : blobs) b = (uint8_t) (rng() & 0xFF);
if (gu == 40 || dt == 40) { // NVFP4: UE4M3 scales in the checkpoint's range, sane tails
for (int g = 0; g < G; ++g) {
uint8_t* b = blobs.data() + (size_t) g * L.bytes;
auto fix = [&](size_t off, size_t bytes) {
for (size_t o = off; o + 36 <= off + bytes; o += 36)
for (int s = 0; s < 4; ++s) b[o + s] = (uint8_t) (0x20 + rng() % 0x40);
};
if (gu == 40) fix(0, L.down_off);
if (dt == 40) fix(L.down_off, (size_t) N * L.d_row);
if (L.tail_off) {
const float t[4] = {8e-5f, 8e-5f, 1e-4f, 0.f};
std::memcpy(b + L.tail_off, t, sizeof t);
}
}
} else { // the other formats: fp16 block scales kept finite (|d| < 2)
for (size_t i = 1; i < blobs.size(); i += 2) blobs[i] &= 0x3B;
}
// NVFP4_BENCH_FILE=<experts.bin or its head>: the blobs are read from it (the first G whole blobs, cycled when it
// holds fewer), real GPTQ / ModelOpt weights instead of random ones
if (const char* fp = std::getenv("NVFP4_BENCH_FILE")) {
FILE* f = std::fopen(fp, "rb");
if (!f) { std::fprintf(stderr, "cannot open %s\n", fp); return 2; }
int have = 0;
while (have < G && std::fread(blobs.data() + (size_t) have * L.bytes, 1, L.bytes, f) == L.bytes) ++have;
std::fclose(f);
if (have == 0) { std::fprintf(stderr, "%s holds no whole blob\n", fp); return 2; }
for (int g = have; g < G; ++g)
std::memcpy(blobs.data() + (size_t) g * L.bytes, blobs.data() + (size_t) (g % have) * L.bytes, L.bytes);
std::printf("blobs: %d real from %s (cycled to %d)\n", have, fp, G);
}
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> x((size_t) T * N);
for (float& v : x) v = nd(rng);
std::vector<unsigned long long> ptr(G);
std::vector<int32_t> start(G + 1), dst(E), tok(E);
uint8_t* db;
ck(cudaMalloc(&db, blobs.size()), "blobs");
ck(cudaMemcpy(db, blobs.data(), blobs.size(), cudaMemcpyHostToDevice), "blobs");
for (int g = 0; g < G; ++g) {
ptr[g] = (unsigned long long) (db + (size_t) g * L.bytes);
start[g] = g * TPG;
for (int j = 0; j < TPG; ++j) { dst[g * TPG + j] = (g * TPG + j) % T + T * ((g * TPG + j) / T); tok[g * TPG + j] = (g + j) % T; }
}
start[G] = E;
for (int e = 0; e < E; ++e) dst[e] = e; // one output row per entry (no summation races in the hash)
float *dx, *dout; void *dxq, *scr; unsigned long long* dptr; int32_t *dstart, *dng, *ddst, *dtok;
ck(cudaMalloc(&dx, x.size() * 4), "x");
ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
ck(cudaMalloc(&dxq, (size_t) T * N / 32 * 36), "xq");
ck(cudaMalloc(&dout, (size_t) E * N * 4), "out");
ck(cudaMalloc(&scr, k::native_expert_scratch_bytes(E, FF)), "scratch");
ck(cudaMalloc(&dptr, 8 * G), "p");
ck(cudaMemcpy(dptr, ptr.data(), 8 * G, cudaMemcpyHostToDevice), "p");
ck(cudaMalloc(&dstart, 4 * (G + 1)), "s");
ck(cudaMemcpy(dstart, start.data(), 4 * (G + 1), cudaMemcpyHostToDevice), "s");
ck(cudaMalloc(&dng, 4), "n");
ck(cudaMemcpy(dng, &G, 4, cudaMemcpyHostToDevice), "n");
ck(cudaMalloc(&ddst, 4 * E), "d");
ck(cudaMemcpy(ddst, dst.data(), 4 * E, cudaMemcpyHostToDevice), "d");
ck(cudaMalloc(&dtok, 4 * E), "t");
ck(cudaMemcpy(dtok, tok.data(), 4 * E, cudaMemcpyHostToDevice), "t");
k::quantize_q8_1_rows(dx, T, N, dxq, nullptr);
// NVFP4_BENCH_PHASE=1: gate/up + SwiGLU + quantize only, 2: down only (native_expert_set_mode), 0/unset: all
if (const char* ph = std::getenv("NVFP4_BENCH_PHASE")) k::native_expert_set_mode(-1, std::atoi(ph));
auto run = [&] { k::native_expert_grouped(L, dptr, dstart, dng, ddst, dtok, G, E, dxq, scr, dout, nullptr); };
run();
ck(cudaDeviceSynchronize(), "warm");
std::vector<float> out((size_t) E * N);
ck(cudaMemcpy(out.data(), dout, out.size() * 4, cudaMemcpyDeviceToHost), "out");
uint64_t h = 1469598103934665603ull; // FNV-1a over the output bytes
for (const float& v : out) {
const auto* p = reinterpret_cast<const uint8_t*>(&v);
for (int i = 0; i < 4; ++i) h = (h ^ p[i]) * 1099511628211ull;
}
cudaEvent_t a, b;
cudaEventCreate(&a);
cudaEventCreate(&b);
float best = 1e30f, sum = 0.f;
for (int i = 0; i < IT; ++i) {
cudaEventRecord(a);
run();
cudaEventRecord(b);
cudaEventSynchronize(b);
float ms = 0.f;
cudaEventElapsedTime(&ms, a, b);
best = ms < best ? ms : best;
sum += ms;
}
ck(cudaGetLastError(), "run");
int dev = 0, bus = 0, clk = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&bus, cudaDevAttrGlobalMemoryBusWidth, dev);
cudaDeviceGetAttribute(&clk, cudaDevAttrMemoryClockRate, dev); // kHz
const double peak = 2.0 * clk * 1e3 * (bus / 8) / 1e9; // GB/s, DDR
const double bytes = (double) G * (double) L.bytes;
std::printf("types %d/%d blob %zu B groups %d x %d tokens: best %.3f ms mean %.3f ms -> %.1f GB/s of weights "
"(%.0f%% of the %.0f GB/s DRAM peak) out hash %016llx\n", gu, dt, L.bytes, G, TPG, best, sum / IT,
bytes / (best * 1e6), 100.0 * bytes / (best * 1e6) / peak, peak, (unsigned long long) h);
return 0;
}
+107
View File
@@ -0,0 +1,107 @@
// src/kernels/nvfp4_expert_gpu_parity.cpp - the decode path's GPU experts (native_expert_grouped) on real NVFP4
// blobs with their global scales, against a double-precision expert.
//
// nvfp4_expert_gpu_parity pack/experts.bin [layer expert ...]
//
// Eight tokens of N(0,1) activations through one expert: q8_1 input, gate/up with s_gate / s_up, SwiGLU, q8_1 of the
// hidden, down with s_down on its output. Only the two activation roundings separate it from the reference (~1%).
#include "strata/kernels/iq_kernels.hpp"
#include "ggml.h"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <random>
#include <vector>
namespace k = strata::kernels;
namespace {
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: nvfp4_expert_gpu_parity pack/experts.bin [layer expert ...]\n"); return 2; }
constexpr int64_t N = 2560, FF = 640;
constexpr int T = 8;
const k::NativeExpertLayout L = k::native_expert_layout(40, 40, N, FF);
const size_t layer_bytes = 512 * L.bytes; // L.bytes counts the 16-byte tail
std::vector<int> picks;
for (int i = 2; i + 1 < argc; i += 2) { picks.push_back(std::atoi(argv[i])); picks.push_back(std::atoi(argv[i + 1])); }
if (picks.empty()) picks = {0, 0, 0, 7, 12, 100, 24, 300, 40, 5, 47, 511};
std::ifstream f(argv[1], std::ios::binary);
std::mt19937 rng(9);
std::normal_distribution<float> nd(0.f, 1.f);
const ggml_type_traits* tt = ggml_get_type_traits(GGML_TYPE_NVFP4);
double worst = 0;
for (size_t pi = 0; pi < picks.size(); pi += 2) {
const int layer = picks[pi], e = picks[pi + 1];
std::vector<uint8_t> blob(L.bytes);
f.seekg((std::streamoff) (layer * layer_bytes + (size_t) e * L.bytes));
if (!f.read((char*) blob.data(), (std::streamsize) blob.size())) { std::fprintf(stderr, "cannot read\n"); return 2; }
float tail[4];
std::memcpy(tail, blob.data() + L.tail_off, sizeof tail);
std::vector<float> wg((size_t) FF * N), wu((size_t) FF * N), wd((size_t) N * FF), x((size_t) T * N);
tt->to_float(blob.data(), wg.data(), FF * N);
tt->to_float(blob.data() + L.up_off, wu.data(), FF * N);
tt->to_float(blob.data() + L.down_off, wd.data(), N * FF);
for (float& v : x) v = nd(rng);
std::vector<double> ref((size_t) T * N);
for (int t = 0; t < T; ++t) {
std::vector<double> h(FF);
for (int64_t r = 0; r < FF; ++r) {
double g = 0, u = 0;
for (int64_t c = 0; c < N; ++c) {
g += (double) wg[(size_t) r * N + c] * x[(size_t) t * N + c];
u += (double) wu[(size_t) r * N + c] * x[(size_t) t * N + c];
}
g *= tail[0];
u *= tail[1];
h[r] = g / (1 + std::exp(-g)) * u;
}
for (int64_t r = 0; r < N; ++r) {
double s = 0;
for (int64_t c = 0; c < FF; ++c) s += (double) wd[(size_t) r * FF + c] * h[c];
ref[(size_t) t * N + r] = s * tail[2];
}
}
uint8_t* db; float *dx, *dout; void *dxq, *scr; unsigned long long* dptr; int32_t *dstart, *dng, *ddst, *dtok;
ck(cudaMalloc(&db, blob.size()), "blob");
ck(cudaMemcpy(db, blob.data(), blob.size(), cudaMemcpyHostToDevice), "blob");
ck(cudaMalloc(&dx, x.size() * 4), "x");
ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
ck(cudaMalloc(&dxq, (size_t) T * N / 32 * 36), "xq");
ck(cudaMalloc(&dout, (size_t) T * N * 4), "out");
ck(cudaMalloc(&scr, k::native_expert_scratch_bytes(T, FF)), "scratch");
const unsigned long long ptr = (unsigned long long) db;
const int32_t start[2] = {0, T}, ng = 1, ids[T] = {0, 1, 2, 3, 4, 5, 6, 7};
ck(cudaMalloc(&dptr, 8), "p"); ck(cudaMemcpy(dptr, &ptr, 8, cudaMemcpyHostToDevice), "p");
ck(cudaMalloc(&dstart, 8), "s"); ck(cudaMemcpy(dstart, start, 8, cudaMemcpyHostToDevice), "s");
ck(cudaMalloc(&dng, 4), "n"); ck(cudaMemcpy(dng, &ng, 4, cudaMemcpyHostToDevice), "n");
ck(cudaMalloc(&ddst, 4 * T), "d"); ck(cudaMemcpy(ddst, ids, 4 * T, cudaMemcpyHostToDevice), "d");
ck(cudaMalloc(&dtok, 4 * T), "t"); ck(cudaMemcpy(dtok, ids, 4 * T, cudaMemcpyHostToDevice), "t");
k::quantize_q8_1_rows(dx, T, N, dxq, nullptr);
k::native_expert_grouped(L, dptr, dstart, dng, ddst, dtok, 1, T, dxq, scr, dout, nullptr);
ck(cudaDeviceSynchronize(), "run");
std::vector<float> got((size_t) T * N);
ck(cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost), "out");
for (void* p : {(void*) db, (void*) dx, dxq, (void*) dout, scr, (void*) dptr, (void*) dstart, (void*) dng,
(void*) ddst, (void*) dtok})
cudaFree(p);
double num = 0, den = 0;
for (size_t i = 0; i < got.size(); ++i) { num += (got[i] - ref[i]) * (got[i] - ref[i]); den += ref[i] * ref[i]; }
const double rel = std::sqrt(num / den);
worst = std::fmax(worst, rel);
std::printf("layer %2d expert %3d: s_gate %.3g s_up %.3g s_down %.3g -> expert output rel. error %.3f%%\n", layer,
e, tail[0], tail[1], tail[2], 100 * rel);
}
std::printf("RESULT: %s (worst %.3f%%)\n", worst < 0.03 ? "ok" : "TOO FAR", 100 * worst);
return worst < 0.03 ? 0 : 1;
}
+18 -7
View File
@@ -1576,13 +1576,18 @@ __global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32
}
__global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
const float* __restrict__ w, const float* __restrict__ shared,
const float* __restrict__ sg, float* __restrict__ bo, int64_t T) {
const float* __restrict__ sg, float* __restrict__ bo, int64_t T,
const float* __restrict__ row_sd) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * N) return;
const int64_t t = i / N, d = i % N;
float s = 0.0f;
#pragma unroll
for (int k = 0; k < 10; ++k) s = fmaf(w[t * 10 + k], Dm[(int64_t) slot[t * 10 + k] * N + d], s);
for (int k = 0; k < 10; ++k) {
const int64_t r = slot[t * 10 + k];
const float v = row_sd ? Dm[r * N + d] * row_sd[r] : Dm[r * N + d]; // the product scale_down_rows stored
s = fmaf(w[t * 10 + k], v, s);
}
bo[i] = s + shared[i] * sigm(sg[t]);
}
@@ -1590,7 +1595,8 @@ __global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t*
// (bitwise equal to moe_combine_kernel). Needs 16-byte aligned Dm / shared / bo (N * 4 bytes per row is a multiple of 16).
__global__ void moe_combine4_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
const float* __restrict__ w, const float4* __restrict__ shared,
const float* __restrict__ sg, float4* __restrict__ bo, int64_t T) {
const float* __restrict__ sg, float4* __restrict__ bo, int64_t T,
const float* __restrict__ row_sd) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // float4 index
if (i >= T * (N / 4)) return;
const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4;
@@ -1600,7 +1606,12 @@ __global__ void moe_combine4_kernel(const float* __restrict__ Dm, const int32_t*
#pragma unroll
for (int k = 0; k < 10; ++k) {
ww[k] = w[t * 10 + k];
v[k] = *reinterpret_cast<const float4*>(Dm + (int64_t) slot[t * 10 + k] * N + d);
const int64_t r = slot[t * 10 + k];
v[k] = *reinterpret_cast<const float4*>(Dm + r * N + d);
if (row_sd) { // NVFP4 in MMQ: the row's s_down, as moe_combine_kernel applies it
const float sd = row_sd[r];
v[k] = make_float4(v[k].x * sd, v[k].y * sd, v[k].z * sd, v[k].w * sd);
}
}
#pragma unroll
for (int k = 0; k < 10; ++k) {
@@ -2163,16 +2174,16 @@ void peer_scatter_add(float* sum, const float* rows, const float* wk, const int3
check("peer_scatter_add");
}
void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
int64_t T, void* stream) {
int64_t T, void* stream, const float* row_sd) {
#ifndef STRATA_W_NO_COMB
if (((reinterpret_cast<uintptr_t>(Dm) | reinterpret_cast<uintptr_t>(shared) | reinterpret_cast<uintptr_t>(bo)) & 15) == 0) {
moe_combine4_kernel<<<blocks_for(T * (N / 4)), 256, 0, (cudaStream_t) stream>>>(
Dm, slot, w, reinterpret_cast<const float4*>(shared), sg, reinterpret_cast<float4*>(bo), T);
Dm, slot, w, reinterpret_cast<const float4*>(shared), sg, reinterpret_cast<float4*>(bo), T, row_sd);
check("moe_combine");
return;
}
#endif
moe_combine_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T);
moe_combine_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T, row_sd);
check("moe_combine");
}
void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) {
+128
View File
@@ -0,0 +1,128 @@
// src/prefill/mmq_expert_bench.cpp - the prompt path's routed-expert products (MMQ) timed at the engine's shapes.
//
// [STRATA_PREFILL_NVFP4=w4a8|w4a4] mmq_expert_bench [rows per expert ...]
//
// One MMQ group as the prompt path launches it: 16 experts, R rows each, in one activation array in expert order.
// gate/up [1280 x 2560] and down [2560 x 640] in NVFP4, down in Q8_0 (the GPTQ + Q8_0-down pack's 27 layers), and
// UD-IQ4_XS's IQ3_S gate/up and IQ4_NL down for comparison.
// Synthetic weights of the right format (valid scales), random activations of row-varying magnitude. Per product:
// the median of 25 runs, and the rate in int8-equivalent TOPS (2 x rows x out x in). Default R: 12 (a 600-token
// chunk: 600 x 10 / 512), 160 (8K), 626 (32K).
#include "strata/prefill/moe_mmq.hpp"
#include "ggml.h"
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
namespace mmq = strata::prefill::mmq;
namespace {
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
}
// valid synthetic weights: NVFP4 blocks are {e4m3 scales, e2m1 codes}; Q8_0 {f16 d, int8 q[32]}. Random bytes with
// the scale fields overwritten by small positive values (an e4m3 / f16 in the model's range).
std::vector<uint8_t> weights(ggml_type t, int64_t rows, int64_t cols, int experts, std::mt19937& rng) {
const size_t per = mmq::matrix_bytes(t, rows, cols);
std::vector<uint8_t> w((size_t) experts * per + 4096);
std::uniform_int_distribution<int> byte(0, 255);
for (auto& b : w) b = (uint8_t) byte(rng);
const size_t bs = ggml_type_size(t), nblk = (size_t) experts * per / bs;
for (size_t i = 0; i < nblk; ++i) {
uint8_t* blk = w.data() + i * bs;
if (t != GGML_TYPE_NVFP4) { // Q8_0, IQ3_S, IQ4_NL: an f16 d leads the block
const uint16_t d = 0x2000 + (uint16_t) byte(rng); // f16 ~ 0.0078..0.016
std::memcpy(blk, &d, 2);
} else { // NVFP4: the scales lead the block
const int nsc = (int) (bs - (size_t) ggml_blck_size(t) / 2);
for (int s = 0; s < nsc; ++s) blk[s] = (uint8_t) (0x30 + byte(rng) % 16); // e4m3 ~ 0.5..1
}
}
return w;
}
struct Case {
const char* name;
ggml_type t;
int64_t rows, cols;
};
double run_case(const Case& c, int R, std::mt19937& rng, float* ms_out) {
constexpr int E = 16;
const int T = E * R;
const size_t per = mmq::matrix_bytes(c.t, c.rows, c.cols);
std::vector<uint8_t> w = weights(c.t, c.rows, c.cols, E, rng);
std::vector<float> x((size_t) T * c.cols);
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_real_distribution<float> mag(0.1f, 10.f);
for (int t = 0; t < T; ++t) { const float m = mag(rng); for (int64_t k = 0; k < c.cols; ++k) x[(size_t) t * c.cols + k] = nd(rng) * m; }
std::vector<int32_t> bounds(E + 1);
for (int e = 0; e <= E; ++e) bounds[e] = e * R;
uint8_t* dw; float *dx, *dd, *dys; void* dq; int32_t *dids, *db;
ck(cudaMalloc(&dw, w.size()), "w"); ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
ck(cudaMalloc(&dx, x.size() * 4), "x"); ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
ck(cudaMalloc(&dq, mmq::q8_bytes(T, c.cols)), "xq");
ck(cudaMalloc(&dys, (size_t) T * 4), "ys");
ck(cudaMalloc(&dd, (size_t) T * c.rows * 4), "dst");
ck(cudaMalloc(&dids, (size_t) T * 4), "ids");
ck(cudaMalloc(&db, (E + 1) * 4), "bounds");
ck(cudaMemcpy(db, bounds.data(), (E + 1) * 4, cudaMemcpyHostToDevice), "bounds");
mmq::iota(dids, T, nullptr);
mmq::quantize(dx, nullptr, dq, c.t, c.cols, c.cols, T, nullptr, dys);
mmq::Context ctx;
mmq::Product p;
p.w = dw; p.type = c.t; p.w_rows = c.rows; p.w_cols = c.cols; p.expert_bytes = per; p.n = E;
p.xq = dq; p.bounds = db; p.ids = dids; p.total_rows = T; p.max_rows = R; p.dst = dd; p.ld_dst = c.rows;
p.y_scale = mmq::fp4_activations(c.t) ? dys : nullptr;
cudaEvent_t e0, e1;
cudaEventCreate(&e0); cudaEventCreate(&e1);
std::vector<float> ts;
for (int i = 0; i < 28; ++i) {
cudaEventRecord(e0);
ctx.run(p, nullptr);
cudaEventRecord(e1);
ck(cudaEventSynchronize(e1), "run");
float ms; cudaEventElapsedTime(&ms, e0, e1);
if (i >= 3) ts.push_back(ms);
}
std::sort(ts.begin(), ts.end());
const float ms = ts[ts.size() / 2];
if (ms_out) *ms_out = ms;
cudaFree(dw); cudaFree(dx); cudaFree(dq); cudaFree(dys); cudaFree(dd); cudaFree(dids); cudaFree(db);
cudaEventDestroy(e0); cudaEventDestroy(e1);
return 2.0 * T * (double) c.rows * c.cols / (ms * 1e9);
}
} // namespace
int main(int argc, char** argv) {
std::vector<int> Rs;
for (int i = 1; i < argc; ++i) Rs.push_back(std::atoi(argv[i]));
if (Rs.empty()) Rs = {12, 160, 626};
const char* mode = std::getenv("STRATA_PREFILL_NVFP4");
std::printf("mmq_expert_bench: mode %s (FP4 activations: %s), 16 experts a launch, medians of 25\n",
mode ? mode : "w4a8", mmq::fp4_activations(GGML_TYPE_NVFP4) ? "yes" : "no");
const Case cases[] = {{"nvfp4 gate/up", GGML_TYPE_NVFP4, 1280, 2560},
{"nvfp4 down", GGML_TYPE_NVFP4, 2560, 640},
{"q8_0 down", GGML_TYPE_Q8_0, 2560, 640},
{"iq3_s gate/up", GGML_TYPE_IQ3_S, 1280, 2560},
{"iq4_nl down", GGML_TYPE_IQ4_NL, 2560, 640}};
std::mt19937 rng(7);
for (int R : Rs)
for (const Case& c : cases) {
float ms = 0;
const double tops = run_case(c, R, rng, &ms);
std::printf(" R %4d %-14s %8.3f ms %7.1f TOPS\n", R, c.name, ms, tops);
}
return 0;
}
+350
View File
@@ -0,0 +1,350 @@
// src/prefill/mmq_nvfp4_parity.cpp - the prompt path's NVFP4 expert products (MMQ) against an exact reference.
//
// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin [rows ...]
// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin --group
// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin --layers [expert]
// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin --real moe_input.bin layer
//
// --group: the prompt path's launch shape - 20 experts of layer 0 with 0..60 rows each, one activation array in
// expert order, gate/up in two launches (experts 0-15, then 16-19 through the same absolute bounds, 16 in), and the
// second group's down from its own rows through relative bounds.
// --layers: one expert (default 7) of every one of the 48 layers, 64 rows - scales differ by layer.
// --real: a layer's MoE input from a prompt (STRATA_DUMP_MOE_INPUT) through its 12 most-routed experts, gate/up on
// the real rows and down on the hidden they produce; also an FP16-activation product (the fp16 path) and the rows'
// outlier ratio (max |x| / rms x).
//
// One real expert (layer 0, expert 0): gate/up [1280, 2560] and down [2560, 640], as the prompt path gathers them.
// Activations are random rows; the reference dequantizes the weights with ggml's own NVFP4 decode and sums in double.
// Reported per product: relative Frobenius error and the worst element relative to the row's largest output.
// 8-bit activations land near 0.5%; FP4 activations near 10% - the difference between the two modes.
#include "strata/prefill/moe_mmq.hpp"
#include "ggml.h"
#include <cuda_runtime.h>
#include <immintrin.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include <random>
#include <vector>
namespace mmq = strata::prefill::mmq;
namespace {
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
}
// one product: x [T, cols] times w [rows, cols]^T
float half_round(float v) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtps_ph(_mm_set_ss(v), 0))); }
int product(const uint8_t* w_host, int64_t rows, int64_t cols, int T, const char* what, std::mt19937& rng,
const std::vector<float>* given = nullptr, double* rel_out = nullptr, double* rel16_out = nullptr,
std::vector<double>* ref_out = nullptr) {
const size_t wbytes = mmq::matrix_bytes(GGML_TYPE_NVFP4, rows, cols);
std::vector<float> wf((size_t) rows * cols);
ggml_get_type_traits(GGML_TYPE_NVFP4)->to_float(w_host, wf.data(), rows * cols);
std::vector<float> x((size_t) T * cols);
if (given) {
x = *given;
} else {
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_real_distribution<float> mag(0.1f, 10.f);
for (int t = 0; t < T; ++t) {
const float m = mag(rng); // rows of different magnitude, like a residual
for (int64_t k = 0; k < cols; ++k) x[(size_t) t * cols + k] = nd(rng) * m;
}
}
std::vector<double> ref((size_t) T * rows);
for (int t = 0; t < T; ++t)
for (int64_t r = 0; r < rows; ++r) {
double s = 0;
const float* a = x.data() + (size_t) t * cols;
const float* b = wf.data() + (size_t) r * cols;
for (int64_t k = 0; k < cols; ++k) s += (double) a[k] * b[k];
ref[(size_t) t * rows + r] = s;
}
uint8_t* dw = nullptr; float* dx = nullptr; void* dq = nullptr; float* dys = nullptr; float* dd = nullptr;
int32_t* dids = nullptr; int32_t* dbounds = nullptr;
ck(cudaMalloc(&dw, wbytes + 4096), "w");
ck(cudaMemset(dw, 0, wbytes + 4096), "w");
ck(cudaMemcpy(dw, w_host, wbytes, cudaMemcpyHostToDevice), "w");
ck(cudaMalloc(&dx, x.size() * sizeof(float)), "x");
ck(cudaMemcpy(dx, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "x");
ck(cudaMalloc(&dq, mmq::q8_bytes(T, cols)), "xq");
ck(cudaMalloc(&dys, T * sizeof(float)), "yscale");
ck(cudaMalloc(&dd, (size_t) T * rows * sizeof(float)), "dst");
ck(cudaMalloc(&dids, T * sizeof(int32_t)), "ids");
ck(cudaMalloc(&dbounds, 2 * sizeof(int32_t)), "bounds");
const int32_t bounds[2] = {0, T};
ck(cudaMemcpy(dbounds, bounds, sizeof bounds, cudaMemcpyHostToDevice), "bounds");
mmq::iota(dids, T, nullptr);
mmq::quantize(dx, nullptr, dq, GGML_TYPE_NVFP4, cols, cols, T, nullptr, dys);
mmq::Context ctx;
mmq::Product p;
p.w = dw; p.type = GGML_TYPE_NVFP4; p.w_rows = rows; p.w_cols = cols; p.expert_bytes = wbytes; p.n = 1;
p.xq = dq; p.bounds = dbounds; p.ids = dids; p.total_rows = T; p.max_rows = T; p.dst = dd; p.ld_dst = rows;
p.y_scale = mmq::fp4_activations(GGML_TYPE_NVFP4) ? dys : nullptr;
ctx.run(p, nullptr);
ck(cudaDeviceSynchronize(), "run");
std::vector<float> got((size_t) T * rows);
ck(cudaMemcpy(got.data(), dd, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "dst");
cudaFree(dw); cudaFree(dx); cudaFree(dq); cudaFree(dys); cudaFree(dd); cudaFree(dids); cudaFree(dbounds);
double num = 0, den = 0, worst = 0;
for (int t = 0; t < T; ++t) {
double rmax = 0;
for (int64_t r = 0; r < rows; ++r) rmax = std::fmax(rmax, std::fabs(ref[(size_t) t * rows + r]));
for (int64_t r = 0; r < rows; ++r) {
const double e = (double) got[(size_t) t * rows + r] - ref[(size_t) t * rows + r];
num += e * e;
den += ref[(size_t) t * rows + r] * ref[(size_t) t * rows + r];
worst = std::fmax(worst, std::fabs(e) / (rmax > 0 ? rmax : 1));
}
}
const double rel = std::sqrt(num / den);
if (rel_out) *rel_out = rel;
if (ref_out) *ref_out = ref;
if (rel16_out) { // the fp16 path: activations rounded to FP16
double n16 = 0;
for (int t = 0; t < T; ++t) {
std::vector<float> xh(cols);
for (int64_t k = 0; k < cols; ++k) xh[k] = half_round(x[(size_t) t * cols + k]);
for (int64_t r = 0; r < rows; ++r) {
double s = 0;
for (int64_t k = 0; k < cols; ++k) s += (double) xh[k] * wf[(size_t) r * cols + k];
const double e = s - ref[(size_t) t * rows + r];
n16 += e * e;
}
}
*rel16_out = std::sqrt(n16 / den);
return rel > 0.2 ? 1 : 0;
}
std::printf("%-8s T %4d [%lld x %lld] rel. error %.4f%% worst %.4f%% of the row max%s\n", what, T,
(long long) rows, (long long) cols, 100 * rel, 100 * worst, rel > 0.05 ? " <-- FP4-level or wrong" : "");
return rel > 0.2 ? 1 : 0;
}
double dot_ref(const float* a, const float* b, int64_t n) {
double s = 0;
for (int64_t k = 0; k < n; ++k) s += (double) a[k] * b[k];
return s;
}
struct Err {
double num = 0, den = 0;
void add(double got, double ref) { num += (got - ref) * (got - ref); den += ref * ref; }
double rel() const { return den > 0 ? std::sqrt(num / den) : 0; }
};
int group(const char* path) {
constexpr int64_t N = 2560, FF = 640;
constexpr int E = 20;
constexpr size_t STRIDE = 2764816; // one layer-0 blob in experts.bin
const size_t gub = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N), db = mmq::matrix_bytes(GGML_TYPE_NVFP4, N, FF);
std::vector<uint8_t> all((size_t) E * STRIDE);
std::ifstream f(path, std::ios::binary);
if (!f.read((char*) all.data(), (std::streamsize) all.size())) { std::fprintf(stderr, "cannot read %s\n", path); return 2; }
std::vector<uint8_t> G((size_t) E * gub + 4096, 0), D((size_t) E * db + 4096, 0);
for (int e = 0; e < E; ++e) {
std::memcpy(G.data() + e * gub, all.data() + e * STRIDE, gub);
std::memcpy(D.data() + e * db, all.data() + e * STRIDE + gub, db);
}
std::mt19937 rng(5);
std::uniform_int_distribution<int> cntd(0, 60);
std::vector<int32_t> bounds(E + 1, 0);
int maxA = 0, maxB = 0;
for (int e = 0; e < E; ++e) {
const int c = (e % 7 == 3) ? 0 : cntd(rng);
bounds[e + 1] = bounds[e] + c;
if (e < 16) maxA = std::max(maxA, c); else maxB = std::max(maxB, c);
}
const int T = bounds[E];
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_real_distribution<float> mag(0.1f, 10.f);
std::vector<float> x((size_t) T * N);
for (int t = 0; t < T; ++t) { const float m = mag(rng); for (int64_t k = 0; k < N; ++k) x[(size_t) t * N + k] = nd(rng) * m; }
// group B's down input: its own rows of FF values
const int rB = bounds[16], nB = T - rB;
std::vector<float> h((size_t) std::max(nB, 1) * FF);
for (auto& v : h) v = nd(rng);
std::vector<int32_t> relB(5);
for (int i = 0; i <= 4; ++i) relB[i] = bounds[16 + i] - rB;
uint8_t *dG, *dD; float *dx, *dh, *dgu, *ddn, *dys, *dhs; void *dxq, *dhq; int32_t *dids, *dbounds, *drel;
ck(cudaMalloc(&dG, G.size()), "G"); ck(cudaMemcpy(dG, G.data(), G.size(), cudaMemcpyHostToDevice), "G");
ck(cudaMalloc(&dD, D.size()), "D"); ck(cudaMemcpy(dD, D.data(), D.size(), cudaMemcpyHostToDevice), "D");
ck(cudaMalloc(&dx, x.size() * 4), "x"); ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
ck(cudaMalloc(&dh, h.size() * 4), "h"); ck(cudaMemcpy(dh, h.data(), h.size() * 4, cudaMemcpyHostToDevice), "h");
ck(cudaMalloc(&dgu, (size_t) T * 2 * FF * 4), "gu"); ck(cudaMemset(dgu, 0, (size_t) T * 2 * FF * 4), "gu");
ck(cudaMalloc(&ddn, (size_t) std::max(nB, 1) * N * 4), "dn");
ck(cudaMalloc(&dxq, mmq::q8_bytes(T, N)), "xq"); ck(cudaMalloc(&dhq, mmq::q8_bytes(std::max(nB, 1), FF)), "hq");
ck(cudaMalloc(&dys, T * 4), "ys"); ck(cudaMalloc(&dhs, std::max(nB, 1) * 4), "hs");
ck(cudaMalloc(&dids, T * 4), "ids"); ck(cudaMalloc(&dbounds, (E + 1) * 4), "b"); ck(cudaMalloc(&drel, 5 * 4), "rel");
ck(cudaMemcpy(dbounds, bounds.data(), (E + 1) * 4, cudaMemcpyHostToDevice), "b");
ck(cudaMemcpy(drel, relB.data(), 5 * 4, cudaMemcpyHostToDevice), "rel");
mmq::iota(dids, T, nullptr);
const bool fp4 = mmq::fp4_activations(GGML_TYPE_NVFP4);
mmq::quantize(dx, nullptr, dxq, GGML_TYPE_NVFP4, N, N, T, nullptr, dys);
mmq::Context ctx;
for (int grp = 0; grp < 2; ++grp) {
mmq::Product p;
p.w = dG + (grp ? 16 * gub : 0); p.type = GGML_TYPE_NVFP4; p.w_rows = 2 * FF; p.w_cols = N; p.expert_bytes = gub;
p.n = grp ? 4 : 16; p.xq = dxq; p.bounds = dbounds + (grp ? 16 : 0); p.ids = dids; p.total_rows = T;
p.max_rows = grp ? maxB : maxA; p.dst = dgu; p.ld_dst = 2 * FF; p.y_scale = fp4 ? dys : nullptr;
ctx.run(p, nullptr);
}
mmq::quantize(dh, nullptr, dhq, GGML_TYPE_NVFP4, FF, FF, nB, nullptr, dhs);
{
mmq::Product p;
p.w = dD + 16 * db; p.type = GGML_TYPE_NVFP4; p.w_rows = N; p.w_cols = FF; p.expert_bytes = db; p.n = 4;
p.xq = dhq; p.bounds = drel; p.ids = dids; p.total_rows = nB; p.max_rows = maxB; p.dst = ddn; p.ld_dst = N;
p.y_scale = fp4 ? dhs : nullptr;
ctx.run(p, nullptr);
}
ck(cudaDeviceSynchronize(), "run");
std::vector<float> gu((size_t) T * 2 * FF), dn((size_t) std::max(nB, 1) * N);
ck(cudaMemcpy(gu.data(), dgu, gu.size() * 4, cudaMemcpyDeviceToHost), "gu");
ck(cudaMemcpy(dn.data(), ddn, dn.size() * 4, cudaMemcpyDeviceToHost), "dn");
cudaFree(dG); cudaFree(dD); cudaFree(dx); cudaFree(dh); cudaFree(dgu); cudaFree(ddn); cudaFree(dxq); cudaFree(dhq);
cudaFree(dys); cudaFree(dhs); cudaFree(dids); cudaFree(dbounds); cudaFree(drel);
Err ea, eb, ed;
std::vector<float> wf((size_t) 2 * FF * N), wd((size_t) N * FF);
for (int e = 0; e < E; ++e) {
ggml_get_type_traits(GGML_TYPE_NVFP4)->to_float(G.data() + e * gub, wf.data(), 2 * FF * N);
for (int t = bounds[e]; t < bounds[e + 1]; ++t)
for (int64_t r = 0; r < 2 * FF; ++r)
(e < 16 ? ea : eb).add(gu[(size_t) t * 2 * FF + r], dot_ref(x.data() + (size_t) t * N, wf.data() + r * N, N));
if (e >= 16) {
ggml_get_type_traits(GGML_TYPE_NVFP4)->to_float(D.data() + e * db, wd.data(), N * FF);
for (int t = bounds[e]; t < bounds[e + 1]; ++t)
for (int64_t r = 0; r < N; ++r)
ed.add(dn[(size_t) (t - rB) * N + r], dot_ref(h.data() + (size_t) (t - rB) * FF, wd.data() + r * FF, FF));
}
}
std::printf("group: %d rows over %d experts (max %d / %d per expert)\n", T, E, maxA, maxB);
std::printf(" gate/up, experts 0-15 (bounds from 0) rel. error %.4f%%\n", 100 * ea.rel());
std::printf(" gate/up, experts 16-19 (bounds from 16) rel. error %.4f%%\n", 100 * eb.rel());
std::printf(" down, experts 16-19 (relative bounds) rel. error %.4f%%\n", 100 * ed.rel());
const double worst = std::max(ea.rel(), std::max(eb.rel(), ed.rel()));
std::printf("RESULT: %s\n", worst > 0.2 ? "WRONG (error beyond 20%)" : "ok");
return worst > 0.2 ? 1 : 0;
}
int layers(const char* path, int e) {
constexpr int64_t N = 2560, FF = 640;
constexpr size_t STRIDE = 2764816, LAYER = 512 * STRIDE;
const size_t gub = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N), db = mmq::matrix_bytes(GGML_TYPE_NVFP4, N, FF);
std::vector<uint8_t> blob(gub + db);
std::ifstream f(path, std::ios::binary);
std::mt19937 rng(3);
int bad = 0;
for (int l = 0; l < 48; ++l) {
f.seekg((std::streamoff) (l * LAYER + (size_t) e * STRIDE));
if (!f.read((char*) blob.data(), (std::streamsize) blob.size())) { std::fprintf(stderr, "cannot read layer %d\n", l); return 2; }
char name[32];
std::snprintf(name, sizeof name, "L%02d gu", l);
bad += product(blob.data(), 2 * FF, N, 64, name, rng);
std::snprintf(name, sizeof name, "L%02d dn", l);
bad += product(blob.data() + gub, N, FF, 64, name, rng);
}
std::printf("RESULT: %s\n", bad ? "WRONG (error beyond 20%)" : "ok");
return bad ? 1 : 0;
}
int real(const char* experts_bin, const char* dump, int layer) {
std::ifstream d(dump, std::ios::binary);
int64_t hdr[3];
if (!d.read((char*) hdr, sizeof hdr)) { std::fprintf(stderr, "cannot read %s\n", dump); return 2; }
const int64_t T = hdr[0], N = hdr[1], K = hdr[2], FF = 640;
std::vector<float> x((size_t) (T * N));
std::vector<int32_t> ids((size_t) (T * K));
d.read((char*) x.data(), (std::streamsize) (x.size() * 4));
d.read((char*) ids.data(), (std::streamsize) (ids.size() * 4));
// the rows' outlier ratio
std::vector<double> ratio;
for (int64_t t = 0; t < T; ++t) {
double mx = 0, ss = 0;
for (int64_t k = 0; k < N; ++k) { const double v = x[(size_t) (t * N + k)]; mx = std::fmax(mx, std::fabs(v)); ss += v * v; }
ratio.push_back(mx / std::sqrt(ss / N + 1e-30));
}
std::sort(ratio.begin(), ratio.end());
std::printf("layer %d: %lld tokens, max|x| / rms: median %.1f, p99 %.1f, max %.1f\n", layer, (long long) T,
ratio[ratio.size() / 2], ratio[ratio.size() * 99 / 100], ratio.back());
std::vector<int> cnt(512, 0);
for (int32_t e : ids) if (e >= 0 && e < 512) ++cnt[e];
std::vector<int> order(512);
for (int i = 0; i < 512; ++i) order[i] = i;
std::sort(order.begin(), order.end(), [&](int a, int b) { return cnt[a] > cnt[b]; });
constexpr size_t STRIDE = 2764816, LAYER = 512 * STRIDE;
const size_t gub = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N);
std::ifstream f(experts_bin, std::ios::binary);
std::vector<uint8_t> blob(STRIDE);
std::mt19937 rng(1);
double s_gu = 0, s_gu16 = 0, s_dn = 0, s_dn16 = 0;
int n = 0;
std::printf("%6s %5s %10s %10s %10s %10s\n", "expert", "rows", "gu mmq", "gu fp16", "down mmq", "down fp16");
for (int i = 0; i < 12; ++i) {
const int e = order[i];
f.seekg((std::streamoff) (layer * LAYER + (size_t) e * STRIDE));
f.read((char*) blob.data(), (std::streamsize) blob.size());
float tail[4];
std::memcpy(tail, blob.data() + STRIDE - 16, sizeof tail);
std::vector<float> xe;
for (int64_t t = 0; t < T; ++t)
for (int64_t k = 0; k < K; ++k)
if (ids[(size_t) (t * K + k)] == e) xe.insert(xe.end(), x.begin() + t * N, x.begin() + (t + 1) * N);
const int Te = (int) (xe.size() / N);
double gu = 0, gu16 = 0, dn = 0, dn16 = 0;
std::vector<double> ref;
product(blob.data(), 2 * FF, N, Te, "gu", rng, &xe, &gu, &gu16, &ref);
std::vector<float> h((size_t) Te * FF); // the hidden the exact gate/up gives
for (int t = 0; t < Te; ++t)
for (int64_t r = 0; r < FF; ++r) {
const double g = ref[(size_t) t * 2 * FF + r] * tail[0], u = ref[(size_t) t * 2 * FF + FF + r] * tail[1];
h[(size_t) t * FF + r] = (float) (g / (1 + std::exp(-g)) * u);
}
product(blob.data() + gub, N, FF, Te, "down", rng, &h, &dn, &dn16);
std::printf("%6d %5d %9.3f%% %9.3f%% %9.3f%% %9.3f%%\n", e, Te, 100 * gu, 100 * gu16, 100 * dn, 100 * dn16);
s_gu += gu; s_gu16 += gu16; s_dn += dn; s_dn16 += dn16; ++n;
}
std::printf("%6s %5s %9.3f%% %9.3f%% %9.3f%% %9.3f%%\n", "mean", "", 100 * s_gu / n, 100 * s_gu16 / n,
100 * s_dn / n, 100 * s_dn16 / n);
return 0;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: mmq_nvfp4_parity pack/experts.bin [rows ...]\n"); return 2; }
constexpr int64_t N = 2560, FF = 640;
const size_t gu_bytes = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N), d_bytes = mmq::matrix_bytes(GGML_TYPE_NVFP4, N, FF);
std::vector<uint8_t> blob(gu_bytes + d_bytes);
std::ifstream f(argv[1], std::ios::binary);
if (!f.read((char*) blob.data(), (std::streamsize) blob.size())) { std::fprintf(stderr, "cannot read %s\n", argv[1]); return 2; }
if (argc >= 3 && std::string(argv[2]) == "--group") return group(argv[1]);
if (argc >= 5 && std::string(argv[2]) == "--real") return real(argv[1], argv[3], std::atoi(argv[4]));
if (argc >= 3 && std::string(argv[2]) == "--layers") return layers(argv[1], argc >= 4 ? std::atoi(argv[3]) : 7);
const char* mode = std::getenv("STRATA_PREFILL_NVFP4");
std::printf("mode %s, FP4 activations: %s\n", mode ? mode : "default", mmq::fp4_activations(GGML_TYPE_NVFP4) ? "yes" : "no");
std::vector<int> Ts;
for (int i = 2; i < argc; ++i) Ts.push_back(std::atoi(argv[i]));
if (Ts.empty()) Ts = {1, 7, 37, 128, 300};
std::mt19937 rng(11);
int bad = 0;
for (int T : Ts) {
bad += product(blob.data(), 2 * FF, N, T, "gate/up", rng);
bad += product(blob.data() + gu_bytes, N, FF, T, "down", rng);
}
std::printf("RESULT: %s\n", bad ? "WRONG (error beyond 20%)" : "ok");
return bad ? 1 : 0;
}
+53
View File
@@ -0,0 +1,53 @@
// src/prefill/mmq_nvfp4_w4a4.cu - NVFP4 MMQ with FP4 activations on Blackwell (W4A4, opt-in: STRATA_PREFILL_NVFP4=w4a4).
//
// RTX 50's FP4 MMA exists only in the arch-specific target (sm_120a), so this is the one translation unit CMake
// builds with 12x -> 12xa (strata_mmq_w4a4); everything else, the default NVFP4 path included, keeps the plain
// architectures and runs on every Blackwell card (sm_121 too). Here mmq.cuh's NVFP4 tile loader and quantize.cu's
// FP4 activation quantizer see BLACKWELL_MMA_AVAILABLE together - they must agree on the activations' layout.
// Their non-static symbols are renamed so they cannot fold with strata_mmq's plain-arch copies.
#include "common.cuh"
#define mul_mat_q_switch_J strata_w4a4_mul_mat_q_switch_J
#define mul_mat_q_case strata_w4a4_mul_mat_q_case
#define quantize_row_q8_1_cuda strata_w4a4_quantize_row_q8_1_cuda
#define quantize_mmq_q8_1_cuda strata_w4a4_quantize_mmq_q8_1_cuda
#define quantize_scatter_mmq_q8_1_cuda strata_w4a4_quantize_scatter_mmq_q8_1_cuda
#define quantize_scatter_mmq_fp4_cuda strata_w4a4_quantize_scatter_mmq_fp4_cuda
#define quantize_mmq_fp4_cuda strata_w4a4_quantize_mmq_fp4_cuda
#include "mmq.cuh"
#include "quantize.cu"
DECL_MMQ_CASE(GGML_TYPE_NVFP4);
namespace {
// 1 when this unit's device code has the FP4 MMA (built for the running card's 12xa); a card without an image
// here (an architecture not in the list, or sm_121 against a 120a build) fails the launch: W4A4 is then off
__global__ void w4a4_probe_kernel(int* out) {
#if defined(BLACKWELL_MMA_AVAILABLE)
*out = 1;
#else
*out = 0;
#endif
}
} // namespace
namespace strata::prefill::mmq {
bool w4a4_available() {
int* d = nullptr;
int h = 0;
if (cudaMalloc(&d, sizeof(int)) != cudaSuccess) { (void) cudaGetLastError(); return false; }
w4a4_probe_kernel<<<1, 1>>>(d);
const bool ran = cudaGetLastError() == cudaSuccess && cudaMemcpy(&h, d, sizeof(int), cudaMemcpyDeviceToHost) == cudaSuccess;
(void) cudaGetLastError();
cudaFree(d);
return ran && h == 1;
}
void run_nvfp4_w4a4(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s) {
strata_w4a4_mul_mat_q_case<GGML_TYPE_NVFP4>(ctx, a, s);
}
void quantize_nvfp4_w4a4(const float* x, const int32_t* ids, void* xq, float* yscale, bool aligned, int64_t cols,
int64_t ld, int64_t rows, int64_t padded, cudaStream_t s) {
strata_w4a4_quantize_mmq_fp4_cuda(x, ids, xq, yscale, GGML_TYPE_NVFP4, aligned, cols, ld, rows * ld, rows * ld,
padded, rows, 1, 1, s);
}
} // namespace strata::prefill::mmq
+24
View File
@@ -0,0 +1,24 @@
// src/prefill/mmq_nvfp4_w4a8.cu - NVFP4 MMQ with 8-bit activations on Blackwell (W4A8).
//
// On sm_120 mmq.cuh compiles NVFP4 as FP4 x FP4 (W4A4): the activations are rounded to E2M1 too, and the first
// token's distribution drifts by KL 0.0004-0.03 from the exact FP16 prefill (8 prompts). Every other GPU gets
// mmq.cuh's int8 path for NVFP4 instead - weights decoded to int8, activations Q8_1, int8 tensor cores - which is
// the precision decode already runs at (vec_dot_nvfp4_q8_1, ggml-cpu's Q8_0). This TU compiles that path for
// sm_120 by hiding Blackwell's FP4 MMA from mmq.cuh on both sides: the device code (BLACKWELL_MMA_AVAILABLE) and
// the host's tile config (blackwell_mma_available(cc)) - they must agree, the host sizes shared memory for the
// device's layout. The two non-static templates are renamed so the linker cannot fold them with the W4A4 instance.
#include "common.cuh"
#undef BLACKWELL_MMA_AVAILABLE
#define blackwell_mma_available(cc) false
#define mul_mat_q_switch_J strata_w4a8_mul_mat_q_switch_J
#define mul_mat_q_case strata_w4a8_mul_mat_q_case
#include "mmq.cuh"
DECL_MMQ_CASE(GGML_TYPE_NVFP4);
namespace strata::prefill::mmq {
void run_nvfp4_w4a8(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s) {
strata_w4a8_mul_mat_q_case<GGML_TYPE_NVFP4>(ctx, a, s);
}
} // namespace strata::prefill::mmq
+169 -19
View File
@@ -11,6 +11,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace strata::prefill::mmq {
#if defined(STRATA_KQ_DSO)
@@ -44,28 +45,41 @@ void ck(cudaError_t e, const char* what) {
int64_t pad512(int64_t n) { return (n + 511) / 512 * 512; }
// ... plus, in the same launch, the expert's 16-byte NVFP4 tail (tail -> tail_dst) and the zeroed MMQ tails after
// the group's last slot (nz uint4 after ab_dst's and c_dst's copies): one launch per expert instead of a kernel,
// a 16-byte copy and, per group, two memsets.
__global__ void copy16_kernel(const uint4* __restrict__ a, int64_t na, const uint4* __restrict__ b, int64_t nb,
uint4* __restrict__ ab_dst, const uint4* __restrict__ c, int64_t nc, uint4* __restrict__ c_dst) {
uint4* __restrict__ ab_dst, const uint4* __restrict__ c, int64_t nc, uint4* __restrict__ c_dst,
const uint4* __restrict__ tail, uint4* __restrict__ tail_dst, int64_t nz) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
const int64_t n = na + nb + nc;
if (i < na) ab_dst[i] = a[i];
else if (i < na + nb) ab_dst[i] = b[i - na];
else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb];
else if (i < n) c_dst[i - na - nb] = c[i - na - nb];
else if (i < n + nz) ab_dst[na + nb + (i - n)] = make_uint4(0, 0, 0, 0);
else if (i < n + 2 * nz) c_dst[nc + (i - n - nz)] = make_uint4(0, 0, 0, 0);
else if (i == n + 2 * nz && tail != nullptr) *tail_dst = *tail;
}
// copy16_kernel for an MMQ group: blockIdx.y is the expert (first + y)
// copy16_kernel for an MMQ group: blockIdx.y is the expert (first + y); the last one (n - 1) also zeroes nz uint4
// after its gu and d slots, and each copies its NVFP4 tail (tail_off, in uint4; tail_dst null = none)
struct GroupArgs {
const uint8_t* blob[kGatherGroupMax];
int64_t up_off, down_off, gu_stride, d_stride; // in uint4
int64_t up_off, down_off, gu_stride, d_stride, tail_off; // in uint4
};
__global__ void copy16_group_kernel(GroupArgs ga, int first, int64_t na, int64_t nc, uint4* __restrict__ gu_dst,
uint4* __restrict__ d_dst) {
__global__ void copy16_group_kernel(GroupArgs ga, int first, int n, int64_t na, int64_t nc, int64_t nz,
uint4* __restrict__ gu_dst, uint4* __restrict__ d_dst, uint4* __restrict__ tail_dst) {
const int q = first + (int) blockIdx.y;
const uint4* src = (const uint4*) ga.blob[q];
uint4* ab = gu_dst + (int64_t) q * ga.gu_stride;
uint4* cd = d_dst + (int64_t) q * ga.d_stride;
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
const int64_t m = 2 * na + nc;
if (i < na) ab[i] = src[i];
else if (i < 2 * na) ab[i] = src[ga.up_off + (i - na)];
else if (i < 2 * na + nc) cd[i - 2 * na] = src[ga.down_off + (i - 2 * na)];
else if (i < m) cd[i - 2 * na] = src[ga.down_off + (i - 2 * na)];
else if (i < m + nz) { if (q == n - 1) ab[ga.gu_stride + (i - m)] = make_uint4(0, 0, 0, 0); }
else if (i < m + 2 * nz) { if (q == n - 1) cd[ga.d_stride + (i - m - nz)] = make_uint4(0, 0, 0, 0); }
else if (i == m + 2 * nz && tail_dst != nullptr) tail_dst[q] = src[ga.tail_off];
}
__global__ void copy1_kernel(const uint8_t* __restrict__ a, int64_t na, const uint8_t* __restrict__ b, int64_t nb,
uint8_t* __restrict__ ab_dst, const uint8_t* __restrict__ c, int64_t nc, uint8_t* __restrict__ c_dst) {
@@ -116,6 +130,29 @@ __global__ void swiglu_kernel(const float* __restrict__ gu, float* __restrict__
h[i] = g / (1.0f + __expf(-g)) * u;
}
// swiglu_kernel on the MMQ gate/up output with each expert's gate and up scales applied as it is read: the products
// scale_gu_rows stored, without the pass that stored them
__global__ void swiglu_scaled_kernel(const float* __restrict__ gu, float* __restrict__ h, int64_t rows, int64_t n_ff,
const int32_t* __restrict__ bounds, int n, const float* __restrict__ tails,
int64_t row0) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= rows * n_ff) return;
const int64_t r = i / n_ff, k = i % n_ff, ra = row0 + r;
int q = 0;
while (q + 1 < n && ra >= bounds[q + 1]) ++q;
const float* row = gu + r * 2 * n_ff;
const float g = row[k] * tails[4 * q], u = row[n_ff + k] * tails[4 * q + 1];
h[i] = g / (1.0f + __expf(-g)) * u;
}
__global__ void down_row_scales_kernel(float* __restrict__ sd, const int32_t* __restrict__ bounds, int n,
const float* __restrict__ tails, int64_t nrows) {
const int64_t r = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (r >= nrows) return;
int q = 0;
while (q + 1 < n && r >= bounds[q + 1]) ++q;
sd[r] = tails[4 * q + 2];
}
__global__ void iota_kernel(int32_t* dst, int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) dst[i] = (int32_t) i;
@@ -138,8 +175,28 @@ unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); }
} // namespace
// mmq_nvfp4_w4a8.cu: mmq.cuh's int8 NVFP4 path, compiled for this GPU with Blackwell's FP4 MMA hidden
void run_nvfp4_w4a8(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s);
// mmq_nvfp4_w4a4.cu (the one unit built for 12xa): FP4 x FP4 and its activation quantizer, if this card runs it
bool w4a4_available();
void run_nvfp4_w4a4(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s);
void quantize_nvfp4_w4a4(const float* x, const int32_t* ids, void* xq, float* yscale, bool aligned, int64_t cols,
int64_t ld, int64_t rows, int64_t padded, cudaStream_t s);
bool built() { return true; }
Nvfp4Mode nvfp4_mode() {
static const Nvfp4Mode m = [] {
const char* e = std::getenv("STRATA_PREFILL_NVFP4");
if (e == nullptr || std::strcmp(e, "w4a8") == 0) return Nvfp4Mode::W4A8;
if (std::strcmp(e, "w4a4") == 0) return Nvfp4Mode::W4A4;
if (std::strcmp(e, "fp16") == 0) return Nvfp4Mode::FP16;
std::fprintf(stderr, "STRATA_PREFILL_NVFP4=%s: expected w4a8, w4a4 or fp16\n", e);
std::exit(1);
}();
return m;
}
bool supported(int t) {
switch ((ggml_type) t) {
case GGML_TYPE_Q2_0:
@@ -154,6 +211,10 @@ bool supported(int t) {
// Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF projections (STRATA_DENSE_MMQ)
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: case GGML_TYPE_Q6_K:
return kq_ok();
#endif
#if !defined(GGML_USE_HIP)
case GGML_TYPE_NVFP4:
return nvfp4_mode() != Nvfp4Mode::FP16;
#endif
default:
return false;
@@ -196,8 +257,68 @@ size_t q8_bytes(int64_t rows, int64_t cols) {
return (size_t) rows * (size_t) pad512(cols) * sizeof(block_q8_1_mmq) / (4 * QK8_1) + 128 * sizeof(block_q8_1_mmq);
}
void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, int64_t ld, int64_t rows, void* stream) {
namespace {
__global__ void scale_gu_rows_kernel(float* __restrict__ gu, int64_t ld, int64_t n_ff, const int32_t* __restrict__ bounds,
int n, const float* __restrict__ tails, int64_t row0) {
const int64_t r = row0 + blockIdx.x;
int q = 0;
while (q + 1 < n && r >= bounds[q + 1]) ++q;
const float sg = tails[4 * q], su = tails[4 * q + 1];
float* row = gu + r * ld;
for (int64_t k = threadIdx.x; k < 2 * n_ff; k += blockDim.x) row[k] *= k < n_ff ? sg : su;
}
__global__ void scale_down_rows_kernel(float* __restrict__ d, int64_t ld, const int32_t* __restrict__ bounds, int n,
const float* __restrict__ tails) {
const int64_t r = blockIdx.x;
int q = 0;
while (q + 1 < n && r >= bounds[q + 1]) ++q;
const float sd = tails[4 * q + 2];
float* row = d + r * ld;
for (int64_t k = threadIdx.x; k < ld; k += blockDim.x) row[k] *= sd;
}
} // namespace
bool fp4_activations(int t) {
#if defined(GGML_USE_HIP) // no NVFP4 MMQ on HIP (and no W4A4 unit)
(void) t;
return false;
#else
if (t != GGML_TYPE_NVFP4 || nvfp4_mode() != Nvfp4Mode::W4A4) return false;
static const bool on = [] {
const bool ok = w4a4_available();
if (!ok) std::fprintf(stderr, "prefill mmq: STRATA_PREFILL_NVFP4=w4a4 needs an sm_12x card in a 12x build; W4A8\n");
return ok;
}();
return on;
#endif
}
void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, int n, const float* tails,
int64_t row0, int64_t nrows, void* stream) {
if (nrows <= 0 || n <= 0) return;
scale_gu_rows_kernel<<<(unsigned) nrows, 256, 0, (cudaStream_t) stream>>>(gu, ld, n_ff, bounds, n, tails, row0);
ck(cudaGetLastError(), "scale_gu_rows");
}
void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream) {
if (nrows <= 0 || n <= 0) return;
scale_down_rows_kernel<<<(unsigned) nrows, 256, 0, (cudaStream_t) stream>>>(d, ld, bounds, n, tails);
ck(cudaGetLastError(), "scale_down_rows");
}
void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, int64_t ld, int64_t rows, void* stream,
float* yscale) {
if (rows <= 0) return;
#if !defined(GGML_USE_HIP)
if (fp4_activations(t)) {
if (yscale == nullptr) { std::fprintf(stderr, "prefill mmq: NVFP4 activations need a scale buffer\n"); std::exit(1); }
const bool aligned = ((uintptr_t) x % 32 == 0) && ((size_t) ld * sizeof(float)) % 32 == 0;
quantize_nvfp4_w4a4(x, ids, xq, yscale, aligned, cols, ld, rows, pad512(cols), (cudaStream_t) stream);
ck(cudaGetLastError(), "quantize");
return;
}
#endif
(void) yscale;
quantize_mmq_q8_1_cuda(x, ids, xq, (ggml_type) t, cols, ld, rows * ld, rows * ld, pad512(cols), rows, 1, 1,
(cudaStream_t) stream);
ck(cudaGetLastError(), "quantize");
@@ -214,7 +335,7 @@ void Context::run(const Product& p, void* stream) {
if (p.n <= 0 || p.max_rows <= 0) return;
const ggml_type t = (ggml_type) p.type;
const int64_t qk = ggml_blck_size(t), bpr = p.w_cols / qk;
const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, nullptr,
const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, p.y_scale,
p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst,
p.n, p.n, (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0,
1, 1, 0, 0, 0,
@@ -248,6 +369,12 @@ void Context::run(const Product& p, void* stream) {
case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
#endif
#if !defined(GGML_USE_HIP) // NVFP4: CUDA only (no HIP instance, no W4A8 unit)
case GGML_TYPE_NVFP4:
if (fp4_activations(t)) run_nvfp4_w4a4(ctx, a, s);
else run_nvfp4_w4a8(ctx, a, s);
break;
#endif
default:
std::fprintf(stderr, "prefill mmq: type %d is not covered\n", (int) t);
@@ -257,15 +384,21 @@ void Context::run(const Product& p, void* stream) {
}
void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes,
void* gu_dst, void* d_dst, void* stream) {
void* gu_dst, void* d_dst, void* stream, const void* tail, void* tail_dst, size_t zero_bytes) {
const cudaStream_t s = (cudaStream_t) stream;
const bool a16 = ((uintptr_t) gate | (uintptr_t) up | (uintptr_t) down | (uintptr_t) gu_dst | (uintptr_t) d_dst |
gu_half_bytes | d_bytes) % 16 == 0;
(uintptr_t) tail | (uintptr_t) tail_dst | gu_half_bytes | d_bytes | zero_bytes) % 16 == 0;
if (a16) {
const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16;
copy16_kernel<<<blocks(2 * na + nc), 256, 0, s>>>((const uint4*) gate, na, (const uint4*) up, na, (uint4*) gu_dst,
(const uint4*) down, nc, (uint4*) d_dst);
const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16, nz = (int64_t) zero_bytes / 16;
copy16_kernel<<<blocks(2 * na + nc + 2 * nz + 1), 256, 0, s>>>(
(const uint4*) gate, na, (const uint4*) up, na, (uint4*) gu_dst, (const uint4*) down, nc, (uint4*) d_dst,
(const uint4*) tail, (uint4*) tail_dst, nz);
} else {
if (tail) cudaMemcpyAsync(tail_dst, tail, 16, cudaMemcpyDeviceToDevice, s);
if (zero_bytes) {
cudaMemsetAsync((uint8_t*) gu_dst + 2 * gu_half_bytes, 0, zero_bytes, s);
cudaMemsetAsync((uint8_t*) d_dst + d_bytes, 0, zero_bytes, s);
}
const int64_t na = (int64_t) gu_half_bytes, nc = (int64_t) d_bytes;
copy1_kernel<<<blocks(2 * na + nc), 256, 0, s>>>((const uint8_t*) gate, na, (const uint8_t*) up, na,
(uint8_t*) gu_dst, (const uint8_t*) down, nc, (uint8_t*) d_dst);
@@ -274,9 +407,12 @@ void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const
}
bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_bytes, size_t down_off, size_t d_bytes,
void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream) {
void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream, size_t tail_off,
void* tail_dst, size_t zero_bytes) {
if (g.first < 0 || g.n <= g.first || g.n > kGatherGroupMax) return false;
uintptr_t a = (uintptr_t) gu_dst | (uintptr_t) d_dst | up_off | gu_half_bytes | down_off | d_bytes | gu_stride | d_stride;
if (tail_off == 0) tail_dst = nullptr;
uintptr_t a = (uintptr_t) gu_dst | (uintptr_t) d_dst | up_off | gu_half_bytes | down_off | d_bytes | gu_stride | d_stride |
tail_off | (uintptr_t) tail_dst | zero_bytes;
for (int q = g.first; q < g.n; ++q) a |= (uintptr_t) g.blob[q];
if (a % 16 != 0) return false;
GroupArgs ga{};
@@ -285,9 +421,11 @@ bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_byt
ga.down_off = (int64_t) down_off / 16;
ga.gu_stride = (int64_t) gu_stride / 16;
ga.d_stride = (int64_t) d_stride / 16;
const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16;
copy16_group_kernel<<<dim3(blocks(2 * na + nc), (unsigned) (g.n - g.first)), 256, 0, (cudaStream_t) stream>>>(
ga, g.first, na, nc, (uint4*) gu_dst, (uint4*) d_dst);
ga.tail_off = (int64_t) tail_off / 16;
const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16, nz = (int64_t) zero_bytes / 16;
const int64_t work = 2 * na + nc + 2 * nz + (tail_dst != nullptr ? 1 : 0);
copy16_group_kernel<<<dim3(blocks(work), (unsigned) (g.n - g.first)), 256, 0, (cudaStream_t) stream>>>(
ga, g.first, g.n, na, nc, nz, (uint4*) gu_dst, (uint4*) d_dst, (uint4*) tail_dst);
ck(cudaGetLastError(), "gather_native_group");
return true;
}
@@ -298,6 +436,18 @@ void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stre
ck(cudaGetLastError(), "gather_strata_q2");
}
void swiglu_scaled(const float* gu, float* h, int64_t rows, int64_t n_ff, const int32_t* bounds, int n,
const float* tails, int64_t row0, void* stream) {
if (rows <= 0) return;
swiglu_scaled_kernel<<<blocks(rows * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h, rows, n_ff, bounds, n, tails, row0);
ck(cudaGetLastError(), "swiglu_scaled");
}
void down_row_scales(float* sd, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream) {
if (nrows <= 0 || n <= 0) return;
down_row_scales_kernel<<<blocks(nrows), 256, 0, (cudaStream_t) stream>>>(sd, bounds, n, tails, nrows);
ck(cudaGetLastError(), "down_row_scales");
}
void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream) {
if (rows <= 0) return;
swiglu_kernel<<<blocks(rows * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h, rows, n_ff, interleaved);
+98 -25
View File
@@ -66,14 +66,18 @@ bool supported(int) { return false; }
bool fits(int, int64_t) { return false; }
size_t matrix_bytes(int, int64_t, int64_t) { return 0; }
size_t q8_bytes(int64_t, int64_t) { return 0; }
void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*) {}
void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*, float*) {}
bool fp4_activations(int) { return false; }
Context::Context() {}
Context::~Context() {}
void Context::run(const Product&, void*) {}
void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*) {}
bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*) { return false; }
void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*, const void*, void*, size_t) {}
bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*, size_t,
void*, size_t) { return false; }
void gather_strata_q2(const uint8_t*, void*, void*, void*) {}
void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {}
void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {}
void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {}
void iota(int32_t*, int64_t, void*) {}
} // namespace strata::prefill::mmq
#endif
@@ -786,13 +790,16 @@ struct Prefill::Impl {
float* H = nullptr;
int32_t *ids_identity = nullptr, *bounds_dev = nullptr;
uint8_t *grp_gu = nullptr, *grp_d = nullptr;
float *Xscale = nullptr, *Hscale = nullptr, *grp_tail = nullptr; // NVFP4: activation scales, expert tails
float* row_sd = nullptr; // NVFP4 in MMQ: each Dm row's s_down, applied by the combine as it reads the row
std::vector<int32_t> bounds_host;
std::unique_ptr<mmq::Context> mmq_ctx;
std::vector<int32_t> ids_host, slot_host, src_host, cnt, off;
// set_cpu_pool: a small chunk's CPU experts. The layer's MoE input (T x N, from `mixed`) and the rows the pool
// writes (Dm's tail, in Dm's row order), both pinned; and the pool's per-token activations and jobs.
float *cpu_x = nullptr, *cpu_rows = nullptr;
size_t cpu_x_n = 0, cpu_rows_n = 0;
// set_cpu_pool: a small chunk's CPU experts. The layer's MoE input (T x N, from `mixed`), the rows the pool writes
// (Dm's tail, in Dm's row order), ones for row_sd (the CPU's rows carry s_down already), all pinned; and the
// pool's per-token activations and jobs.
float *cpu_x = nullptr, *cpu_rows = nullptr, *cpu_ones = nullptr;
size_t cpu_x_n = 0, cpu_rows_n = 0, cpu_ones_n = 0;
bool cpu_dead = false; // a pinned buffer of the share could not be had (host memory is short): the GPU does it all
std::vector<uint8_t> cpu_nact;
std::vector<kernels::cpu::ActQ> cpu_actq; // a Q2_0 layer's activations (the pool's Q2_0 kernels read ActQ)
@@ -941,7 +948,7 @@ void Prefill::release() {
impl_->steps_up.release();
impl_->tok_up.release();
impl_->up_ring.release();
for (float* p : {impl_->cpu_x, impl_->cpu_rows})
for (float* p : {impl_->cpu_x, impl_->cpu_rows, impl_->cpu_ones})
if (p) cudaFreeHost(p);
for (cudaEvent_t e : impl_->cpu_ev)
if (e) cudaEventDestroy(e);
@@ -1055,6 +1062,8 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
a.take<uint8_t>(mb.xq, ok);
a.take<float>(mb.h, ok);
a.take<uint8_t>(mb.hq, ok);
a.take<float>(T * K, ok); a.take<float>(T * K, ok); a.take<float>(MMQ_GROUP * 4, ok);
a.take<float>(T * K, ok);
}
return a.used;
}
@@ -1273,6 +1282,9 @@ bool Prefill::carve(size_t T, void* alloc) {
m.Xq = c.take<uint8_t>(mb.xq, ok);
m.H = c.take<float>(mb.h, ok);
m.Hq = c.take<uint8_t>(mb.hq, ok);
m.Xscale = c.take<float>(T * K, ok); m.Hscale = c.take<float>(T * K, ok);
m.grp_tail = c.take<float>(MMQ_GROUP * 4, ok);
m.row_sd = c.take<float>(T * K, ok);
}
if (base == nullptr) ok = false;
}
@@ -1659,6 +1671,11 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e
const bool host_route_ok = [] { const char* v = std::getenv("STRATA_PF_PEER_HOST"); return v == nullptr || std::atoi(v) != 0; }();
if (!peer->p2p() && !host_route_ok) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; }
if (!mmq_plan().any) { err = "prefill peer: needs the MMQ prompt path"; return false; }
{ // NVFP4: the peer's MMQ products have no per-expert scales (grp_tail, row_sd); its decode rows do
const auto& lay = strata::kernels::cpu::expert_layout();
for (const auto& f : lay.fmt)
if (lay.native && f.tail_off) { err = "prefill peer: not for NVFP4 experts yet"; return false; }
}
auto pp = std::make_unique<PeerPrefill>();
pp->peer = peer;
pp->p2p = peer->p2p();
@@ -3320,6 +3337,23 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return false;
}
}
// Diagnostics: STRATA_DUMP_MOE_INPUT=path, STRATA_DUMP_MOE_LAYER=l - the first chunk's MoE input
// of layer l ({T, N, K} int64, T x N floats, T x K expert ids) for testing products on real rows
static const char* dump_moe = std::getenv("STRATA_DUMP_MOE_INPUT");
static bool dumped_moe = false;
if (dump_moe && !dumped_moe && l == std::atoi(std::getenv("STRATA_DUMP_MOE_LAYER") ? std::getenv("STRATA_DUMP_MOE_LAYER") : "0")) {
dumped_moe = true;
std::vector<float> x((size_t) (T * N));
cudaMemcpyAsync(x.data(), m.mixed, x.size() * sizeof(float), cudaMemcpyDeviceToHost, m.cs);
cudaStreamSynchronize(m.cs);
if (std::FILE* f = std::fopen(dump_moe, "wb")) {
const int64_t hdr[3] = {(int64_t) T, (int64_t) N, (int64_t) K};
std::fwrite(hdr, sizeof hdr, 1, f);
std::fwrite(x.data(), sizeof(float), x.size(), f);
std::fwrite(ids_h, sizeof(int32_t), (size_t) (T * K), f);
std::fclose(f);
}
}
n_order = order.size();
// set_cpu_pool: the CPU's experts on a thread while this one streams and runs the GPU's; their
// unweighted rows land in Dm's row order, so the combine weights them as any other row
@@ -3337,6 +3371,20 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
m.cpu_rows_n = cap_rows * N;
}
// this fork (NVFP4): row_sd 1 for the CPU's rows, which carry s_down already - sized on its
// own, as the rows buffer is now taken once at its largest above (0.1.42)
if (m.cpu_ones_n < (size_t) rows_cpu) {
if (m.cpu_ones) cudaFreeHost(m.cpu_ones);
m.cpu_ones = nullptr;
m.cpu_ones_n = 0;
const size_t n1 = std::max<size_t>((size_t) rows_cpu * 2, m.cpu_rows_n / N);
if (cudaHostAlloc((void**) &m.cpu_ones, n1 * sizeof(float), cudaHostAllocDefault) != cudaSuccess) {
err = "prefill: cannot allocate the CPU experts' row scales";
return false;
}
std::fill(m.cpu_ones, m.cpu_ones + n1, 1.0f);
m.cpu_ones_n = n1;
}
const int64_t r0c = T * K - rows_cpu;
const strata::kernels::cpu::NativeFmt& cf = lay.fmt[(size_t) l];
if (cpu_share_env() < 0.0) {
@@ -3385,7 +3433,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
pt.mark(kPfGather, cs);
if (use_mmq) {
// step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs);
mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale);
// each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
// reads the group's own quantized H)
const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
@@ -3767,7 +3815,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
mmq::GatherGroup gg;
int gg_slots[MMQ_GROUP];
int gg_nslots = 0; // ring slots gathered by the next flush
auto flush = [&]() {
// `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush)
auto flush = [&](size_t zero) {
if (gg.n <= gg.first) return;
const auto& f = lay.fmt[(size_t) l];
if (gg_nslots > 0) { // the copies land in order: the last one covers the others
@@ -3775,12 +3824,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
cudaStreamWaitEvent(m.cs, m.copied[gg_slots[gg_nslots - 1]], 0);
pt.mark(kPfDequant, cs);
}
// NVFP4: each expert's scales go next to its group slot in the same launch
if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub,
m.grp_d, mmq_db, m.cs)) {
m.grp_d, mmq_db, m.cs, f.tail_off,
f.tail_off ? m.grp_tail : nullptr, zero)) {
for (int i = gg.first; i < gg.n; ++i) { // not 16-byte aligned: one at a time
const uint8_t* b = gg.blob[i];
mmq::gather_native(b, b + f.up_off, mmq_gub / 2, b + f.down_off, mmq_db,
m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs);
m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs,
f.tail_off ? b + f.tail_off : nullptr,
f.tail_off ? m.grp_tail + i * 4 : nullptr, i + 1 == gg.n ? zero : 0);
}
}
if (gg_nslots > 0) {
@@ -3799,19 +3852,28 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (use_mmq) {
// gather the expert into its group slot (GGUF blocks, unchanged or converted)
const size_t q = j % MMQ_GROUP;
// the group's last expert also zeroes the MMQ tail after its slot (see MMQ_TAIL)
const bool last_of_group = q + 1 == MMQ_GROUP || j + 1 == order.size();
if (group_gather) {
gg.blob[q] = blob_dev;
gg.n = (int) q + 1;
if (slot >= 0) gg_slots[gg_nslots++] = slot;
if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
flush();
if (!last_of_group) return true;
flush(MMQ_TAIL);
gg = mmq::GatherGroup{};
} else if (lay.native) {
const auto& f = lay.fmt[(size_t) l];
// NVFP4: this expert's scales go next to its group slot in the same launch
mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs,
f.tail_off ? blob_dev + f.tail_off : nullptr,
f.tail_off ? m.grp_tail + q * 4 : nullptr, last_of_group ? MMQ_TAIL : 0);
} else {
mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
if (last_of_group) {
cudaMemsetAsync(m.grp_gu + (size_t) (q + 1) * mmq_gub, 0, MMQ_TAIL, m.cs);
cudaMemsetAsync(m.grp_d + (size_t) (q + 1) * mmq_db, 0, MMQ_TAIL, m.cs);
}
}
if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; }
if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
@@ -3822,23 +3884,28 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
int64_t maxr = 0;
for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
pt.mark(kPfGemmGU, cs);
// the zeroed tail after the group's last expert (see MMQ_TAIL)
cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, m.cs);
cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, m.cs);
mmq::Product gu;
gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280;
gu.y_scale = mmq::fp4_activations(mmq_gt) ? m.Xscale : nullptr;
m.mmq_ctx->run(gu, m.cs);
mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
if (lay.native && lay.fmt[(size_t) l].tail_off) // gate/up scales applied as read
mmq::swiglu_scaled(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, m.bounds_dev + j0, ngx,
m.grp_tail, r0, m.cs);
else
mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
pt.mark(kPfGemmD, cs);
mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs);
mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs, m.Hscale);
mmq::Product dn;
dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
dn.ld_dst = N;
dn.y_scale = mmq::fp4_activations(mmq_dt) ? m.Hscale : nullptr;
m.mmq_ctx->run(dn, m.cs);
if (lay.native && lay.fmt[(size_t) l].tail_off) // s_down: applied by the combine
mmq::down_row_scales(m.row_sd + r0, dn.bounds, ngx, m.grp_tail, nr, m.cs);
return true;
}
const int q = (int) (j % DQ);
@@ -3846,8 +3913,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas
const auto& f = lay.fmt[(size_t) l];
strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
m.dq_gu[q], m.cs);
strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
m.dq_gu[q], m.cs,
f.tail_off ? (const float*) (blob_dev + f.tail_off) : nullptr);
strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs,
f.tail_off ? (const float*) (blob_dev + f.tail_off) + 2 : nullptr);
} else {
blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
}
@@ -3891,7 +3960,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const size_t kend = seq_start[(size_t) l + 1];
auto release_to = [&](int32_t e_stop) {
while (k < kend && seq[k].e < e_stop) {
if (gg_nslots > 0) flush(); // the open group's slots get their event first
if (gg_nslots > 0) flush(0); // the open group's slots get their event first
const int sl = (int) (k % (size_t) m.ring);
cudaEventRecord(m.used[sl], m.cs);
m.used_of[sl] = sl;
@@ -3926,7 +3995,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
}
pt.mark(kPfCombine, cs);
if (cpu_fut.valid()) { // set_cpu_pool: the CPU's rows into Dm's tail
if (cpu_fut.valid()) { // set_cpu_pool: the CPU's rows into Dm's tail, row_sd 1 (s_down is in them)
if (cpu_share_env() < 0.0) cudaEventRecord(m.cpu_ev[1], m.cs); // after the GPU's expert work
if (!cpu_fut.get()) { err = "prefill: a CPU expert has no blob"; return false; }
if (cpu_share_env() < 0.0 && n_stream > n_cpu) {
@@ -3939,6 +4008,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const int64_t r0c = T * K - rows_cpu;
cudaMemcpyAsync(m.Dm + (size_t) r0c * N, m.cpu_rows, (size_t) rows_cpu * N * sizeof(float),
cudaMemcpyHostToDevice, m.cs);
if (use_mmq && !fused_l && lay.native && lay.fmt[(size_t) l].tail_off)
cudaMemcpyAsync(m.row_sd + r0c, m.cpu_ones, (size_t) rows_cpu * sizeof(float),
cudaMemcpyHostToDevice, m.cs);
stats_.experts_cpu += n_cpu;
}
// no reading from a layer the share could not change (nothing taken) or with one-time costs
@@ -3959,7 +4031,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
else if (peer_now && m.pp->sums)
moe_combine_peer(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.pp->host_sum, m.pp->back_at, m.bo, T, m.cs);
else
moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);
moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs,
use_mmq && !fused_l && lay.native && lay.fmt[(size_t) l].tail_off ? m.row_sd : nullptr);
// debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values
if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {
cudaStreamSynchronize(m.cs);
+25 -5
View File
@@ -2796,8 +2796,13 @@ int main(int argc, char** argv) {
// link (the copy kernel, since 0.1.14), so on a slower link it must shrink or the window waits for it. The
// real H2D bandwidth is probed once; from 20 GB/s up (x16 PCIe 4/5) the measured default stays. The canonical
// pack keeps 0.2 as its start value (0.1.43: PcieAuto refines it on CUDA). `--calibrate` measures it outright.
// NVFP4 packs: 0.25. Their 2.76 MB experts cross the link twice as long as the i-quants' the 0.55 was
// measured on, and that copy sits on the GPU's critical path while the CPU pool runs beside it: decode
// 103 -> 117 tok/s short, 105 -> 124 at 32K (RTX 5090, PCIe 5 x16, 9950X3D; 0.10 and 0.40 both slower).
if (o.pcie_frac < 0.0) {
const double base = native_pack ? 0.55 : 0.2;
const auto& lay0 = strata::kernels::cpu::expert_layout();
const bool nvfp4_pack = native_pack && !lay0.fmt.empty() && lay0.fmt[0].gu_type == 40;
const double base = nvfp4_pack ? 0.25 : native_pack ? 0.55 : 0.2;
std::string bursts;
const char* pfd = std::getenv("STRATA_PCIE_FRAC_DEFAULT");
const bool pf_old = pfd != nullptr && std::strcmp(pfd, "old") == 0;
@@ -5125,7 +5130,10 @@ int main(int argc, char** argv) {
size_t free_b = 0, total_b = 0;
free_b = strata::core::device_free_bytes(); (void) total_b;
const auto& lay = strata::kernels::cpu::expert_layout();
const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granted
// what the uniform sizing granted, in the 256-byte slots the loop below counts: the blob formats of 1280 / 2560
// rows are whole multiples of 256 already; an NVFP4 blob's 16-byte scale tail is not, and the unrounded budget
// held one slot fewer than asked (--expert-cache 1: none)
const uint64_t budget = (uint64_t) o.expert_cache * ((lay.max_blob + 255) / 256 * 256);
uint64_t used = 0;
const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first;
size_t free_room = free_b > keep_free ? free_b - keep_free : 0;
@@ -8476,9 +8484,21 @@ int main(int argc, char** argv) {
const double max_cached = mcs != nullptr && mcs[0] != 0 ? std::atof(mcs) / 100.0 : max_cached_default;
const bool nearly_all_cached = !host_res.empty() && !all_experts_resident &&
(double) cached_experts >= max_cached * (double) host_res.size();
const bool tail_default_ok = tse == nullptr && !all_experts_resident && !nearly_all_cached && o.batch == 0 &&
decode_defaults_arch_ok() &&
o.peer_device < 0;
// NVFP4 experts (any layer): no default (sergqwer/strata-nvfp4 c83625c3). On the fork's qwen-nvfp4-gptq pack the
// skip moved the answers by teacher-forced KL 0.035 against it off - as much as the GPTQ quantization's own error
// against an all-Q8_0 reference (0.038) - for +11.5% decode (RTX 5090). STRATA_ROUTE_TAIL_SKIP=7 opts in.
bool nvfp4_experts = false;
if (native_pack)
for (const auto& f : strata::kernels::cpu::expert_layout().fmt)
nvfp4_experts = nvfp4_experts || f.gu_type == strata::kernels::cpu::kNvfp4Type ||
f.d_type == strata::kernels::cpu::kNvfp4Type;
const bool tail_default_path = tse == nullptr && !all_experts_resident && !nearly_all_cached && o.batch == 0 &&
decode_defaults_arch_ok() &&
o.peer_device < 0;
const bool tail_default_ok = tail_default_path && !nvfp4_experts;
if (tail_default_path && nvfp4_experts)
std::fprintf(stderr, "strata serve: STRATA_ROUTE_TAIL_SKIP is off by default with NVFP4 experts (it moved an NVFP4 "
"pack's answers by about as much as its quantization does); STRATA_ROUTE_TAIL_SKIP=7 turns it on\n");
if (tse == nullptr && nearly_all_cached && o.batch == 0 && o.peer_device < 0 && decode_defaults_arch_ok())
std::fprintf(stderr, "strata serve: STRATA_ROUTE_TAIL_SKIP is off by default: %.1f%% of the experts are in the GPU cache, so "
"few are missed and skipping them costs more draft acceptance than it saves; "
+5 -3
View File
@@ -182,11 +182,13 @@ if(STRATA_NATIVE_EXPERTS)
endif()
strata_resolve(_cpu_native src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp
src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_avx1.cpp # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rows
src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp) # 0.1.42: AVX1 (no AVX2) Q2_0 / i-quant rows
src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp # 0.1.42: AVX1 (no AVX2) Q2_0 / i-quant rows
src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp) # NVFP4 expert rows (native_expert.cpp calls them)
target_sources(strata_kernels_cpu PRIVATE ${_cpu_native})
target_include_directories(strata_kernels_cpu PRIVATE ${STRATA_ROOT}/third_party/ggml)
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx512.cpp ${STRATA_ROOT}/src/kernels/cpu/nvfp4_avx512.cpp
PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx")
+7 -4
View File
@@ -4518,8 +4518,9 @@ void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n
check("iq_mmvq");
}
void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream) {
if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); }
void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale) {
// scale: NVFP4's s_down (CUDA only; the SYCL port has no NVFP4 experts, so it is never given here)
if (n % 256 != 0 || !is_iq(t) || scale != nullptr) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); }
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
@@ -4616,9 +4617,11 @@ void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream)
check("iq_dequant_f32");
}
void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) {
void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream,
const float* tail) {
// checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error
if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); }
// (tail: NVFP4's per-expert scales, CUDA only - never given on SYCL)
if (n_embd % 256 != 0 || !is_iq(t) || tail != nullptr) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); }
const int64_t per_row = n_embd / 256;
{
+2 -1
View File
@@ -2934,7 +2934,8 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int
check("gather_rows16");
}
void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
int64_t T, void* stream) {
int64_t T, void* stream, const float* row_sd) {
if (row_sd != nullptr) { std::fprintf(stderr, "moe_combine: per-row scales (NVFP4) are CUDA only\n"); std::exit(1); }
#ifndef STRATA_W_NO_COMB
if (((reinterpret_cast<uintptr_t>(Dm) | reinterpret_cast<uintptr_t>(shared) | reinterpret_cast<uintptr_t>(bo)) & 15) == 0) {
{
+5 -3
View File
@@ -61,12 +61,14 @@ bool supported(int) { return false; }
bool fits(int, int64_t) { return false; }
size_t matrix_bytes(int, int64_t, int64_t) { return 0; }
size_t q8_bytes(int64_t, int64_t) { return 0; }
void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*) {}
void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*, float*) {}
bool fp4_activations(int) { return false; }
Context::Context() {}
Context::~Context() {}
void Context::run(const Product&, void*) {}
void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*) {}
bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*) { return false; }
void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*, const void*, void*, size_t) {}
bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*, size_t,
void*, size_t) { return false; }
void gather_strata_q2(const uint8_t*, void*, void*, void*) {}
void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {}
void iota(int32_t*, int64_t, void*) {}
+46 -4
View File
@@ -201,6 +201,7 @@ def check_split(files) -> None:
ROLES = ("gate", "up", "down")
N_EXPERT = 512
ALIGN = 64
NVFP4_TAIL = 16 # {s_gate, s_up, s_down, 0} after an NVFP4 expert blob
def read_index(path: pathlib.Path):
@@ -451,11 +452,25 @@ def expert_layout(model: Model, src: pathlib.Path):
if per[0] != per[1] or ts[0].type_name != ts[1].type_name:
return "layer %d: gate and up differ in type" % l
blob = per[0] + per[1] + per[2]
nvfp4 = ts[0].type_name == "NVFP4" or ts[2].type_name == "NVFP4"
if nvfp4:
# NVFP4 (ModelOpt) carries one F32 weight_scale_2 per expert and projection, which the block format has
# no room for. Each blob gets a 16-byte tail {s_gate, s_up, s_down, 0} so every consumer that already
# moves whole blobs (the arena, the device cache, the prefill staging, a second GPU) moves the scales
# with the weights; the gate/up kernels read it. See tools/nvfp4_convert.py.
# a mixed expert (e.g. NVFP4 gate/up + Q8_0 down) has the tail too, with 1.0 for the other projection
if any(t.type_name == "NVFP4" and "blk.%d.ffn_%s_exps.scale" % (l, r) not in T for t, r in zip(ts, ROLES)):
return "layer %d: NVFP4 experts without their .scale tensors" % l
blob += NVFP4_TAIL
layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts))
ws = [model.where[n] for n in names]
files = ["" if w[3] == src else w[3].name for w in ws]
column = files[0] if len(set(files)) == 1 else ",".join(files)
n_split += len(set(files)) != 1
if nvfp4: # no GGUF offsets: experts.bin is the only source that carries the scale tails
lines.append("%d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob))
offset += blob * n_expert
continue
line = "%d %d %d %d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob,
*[w[0].data_start + w[1].offset for w in ws])
lines.append(line + ("" if not column else " " + column))
@@ -522,14 +537,35 @@ def main() -> int:
print(got)
return 1
layout, text, n_expert, offset = got
if any(t.type_name == "NVFP4" for *_, ts in layout for t in ts):
a.experts_bin = True # the GGUF holds the weights without the scale tails: the engine must read experts.bin
path = out / "experts.bin"
sidecar = out / "experts.bin.src.json"
want = experts_source(model, text, offset)
reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want
def layer_blobs(blob, ts):
chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1)
assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert
def nvfp4_tails(l, ts):
"""(n_expert, NVFP4_TAIL) bytes {s_gate, s_up, s_down, 0} of a layer with an NVFP4 projection; a projection in
another format gets exactly 1.0 (the engine multiplies by the tail unconditionally). None for a bad scale."""
s = [np.frombuffer(model.bytes("blk.%d.ffn_%s_exps.scale" % (l, r)).tobytes(), dtype=np.float32)
if t.type_name == "NVFP4" else np.ones(n_expert, dtype=np.float32) for t, r in zip(ts, ROLES)]
tail = np.zeros((n_expert, NVFP4_TAIL // 4), dtype=np.float32)
tail[:, 0], tail[:, 1], tail[:, 2] = s[0], s[1], s[2]
if not np.isfinite(tail).all() or (tail[:, :3] <= 0).any():
print("layer %d: a non-finite or non-positive NVFP4 scale" % l)
return None
return tail.view(np.uint8)
def layer_blobs(l, blob, ts):
"""(n_expert, blob): gate | up | down [| the NVFP4 scale tail] per expert; None for a bad NVFP4 scale."""
parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts]
if any(t.type_name == "NVFP4" for t in ts):
tail = nvfp4_tails(l, ts)
if tail is None:
return None
parts.append(tail)
chunk = np.concatenate(parts, axis=1)
assert chunk.shape == (n_expert, blob)
return chunk
if reuse:
@@ -541,6 +577,9 @@ def main() -> int:
for e in (0, n_expert - 1):
f.seek(off + e * blob)
want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts)
if any(t.type_name == "NVFP4" for t in ts):
tail = nvfp4_tails(l, ts)
want_blob += tail[e].tobytes() if tail is not None else b""
if f.read(blob) != want_blob:
reuse = False
if not reuse:
@@ -586,7 +625,10 @@ def main() -> int:
part = out / "experts.bin.tmp"
with open(part, "wb") as fo:
for l, gt, dt, off, blob, ts in layout:
fo.write(layer_blobs(blob, ts).tobytes())
chunk = layer_blobs(l, blob, ts)
if chunk is None:
return 1
fo.write(chunk.tobytes())
if l % 8 == 0:
print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob,
off / 2**30), flush=True)
+128
View File
@@ -0,0 +1,128 @@
"""tools/nvfp4_convert.py - a ModelOpt NVFP4 Qwen3.8-Flash-Next checkpoint -> a GGUF Strata can pack.
python tools/nvfp4_convert.py --model <ModelOpt NVFP4 dir> --outfile <model.gguf>
This is llama.cpp's own converter (third_party/llama.cpp at the commit setup.py pins), run with the type policy
Strata's engine needs. The converter already repacks ModelOpt NVFP4 experts into ggml's block_nvfp4 without loss
(tools/nvfp4_verify.py proves it bit for bit) and writes each expert's weight_scale_2 as a separate F32 tensor
`blk.N.ffn_{gate,up,down}_exps.scale`, one value per expert. What it does not know is Strata's layout:
* the small projections the residual, router, GDN, QSA and PLE kernels read as BF16 (iq_pack.BF16_PROJECTIONS)
must be BF16 - the converter would otherwise write routers and indexer projections as F32, which iq_pack
refuses, and the rest as the --outtype;
* everything the engine serves natively (attention, ssm_out, shared experts, output) goes to Q8_0: the native
GEMV has no BF16 path, and Q8_0 is the closest to the checkpoint's BF16 it has;
* token_embd goes to Q8_0 too. The abliteration edited embed_tokens, so another model's table cannot be reused,
and gguf-py cannot write the IQ types the native embedding reads today - the engine learns Q8_0 instead;
* the 51.2B-parameter PLE n-gram table is left out. The engine only reads it as IQ4_NL (ngram.cpp), and
dequantizing the checkpoint's FP8 copy would need ~205 GB of RAM. The abliteration did not touch this table,
so the engine is pointed at ISTA-DASLab's IQ4_NL shard 2 with --ple-gguf. The PLE hash constants and the
row width still come from this checkpoint and are written into the metadata.
The MTP head is dropped here as llama.cpp does; tools/mtp_pack.py packs it separately.
"""
from __future__ import annotations
import argparse
import json
import pathlib
import subprocess
import sys
import time
ENGINE = pathlib.Path(__file__).resolve().parents[1]
LLAMA = ENGINE / "third_party" / "llama.cpp"
sys.path.insert(0, str(LLAMA / "gguf-py"))
sys.path.insert(0, str(LLAMA))
import gguf # noqa: E402
from conversion import qwen4exp as Q4 # noqa: E402
T = gguf.GGMLQuantizationType
# Strata reads these as BF16 (tools/iq_pack.py BF16_PROJECTIONS + BF16_OUTPUT, and the routers).
BF16_SUFFIXES = (
"hc_attn_down.weight", "hc_attn_up.weight", "hc_attn_inject.weight",
"hc_ffn_down.weight", "hc_ffn_up.weight", "hc_ffn_inject.weight",
"ssm_alpha.weight", "ssm_beta.weight", "indexer.q_proj.weight", "indexer.k_proj.weight",
"ple_value.weight", "ple_key.weight", "ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight",
"output_hc_down.weight", "output_hc_up.weight",
)
F16_SUFFIXES = ("ple_conv1d.weight",)
Q8_NAMES = {"token_embd.weight", "output.weight"}
dropped_ple: list[str] = []
def install_policy() -> None:
cls = Q4.Qwen4ExpTextModel
base_force = cls.tensor_force_quant
def tensor_force_quant(self, name, new_name, bid, n_dims):
if n_dims >= 2:
if new_name.endswith(BF16_SUFFIXES):
return T.BF16
if new_name.endswith(F16_SUFFIXES):
return T.F16
if new_name in Q8_NAMES:
return T.Q8_0
return base_force(self, name, new_name, bid, n_dims)
def place_ple_shard(self, data_torch, name):
# Record the shard so the parts check in prepare_tensors still holds, and the row width for the
# metadata; write nothing - the table comes from the IQ4_NL PLE GGUF at run time.
idx = int(name.rsplit("shard_", 1)[1].split(".", 1)[0])
self._ple_shards[idx] = name
self._ple_row_dim = int(data_torch.shape[-1])
dropped_ple.append(name)
return []
cls.tensor_force_quant = tensor_force_quant
cls._place_ple_shard = place_ple_shard
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True, help="the ModelOpt NVFP4 checkpoint directory")
ap.add_argument("--outfile", required=True)
ap.add_argument("--dry-run", action="store_true")
a = ap.parse_args()
model = pathlib.Path(a.model)
out = pathlib.Path(a.outfile)
out.parent.mkdir(parents=True, exist_ok=True)
install_policy()
import convert_hf_to_gguf as C # noqa: E402 (after the policy is installed on the class)
argv = [str(model), "--outtype", "q8_0", "--outfile", str(out)]
if a.dry_run:
argv.append("--dry-run")
sys.argv = ["convert_hf_to_gguf.py"] + argv
t0 = time.time()
rc = C.main()
took = time.time() - t0
try: # a release bundle ships the converter's files without git: its COMMIT file names the commit
commit = subprocess.run(["git", "-C", str(LLAMA), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
except OSError:
commit = ""
if not commit and (LLAMA / "COMMIT").exists():
commit = (LLAMA / "COMMIT").read_text(encoding="utf-8").strip()
manifest = {
"source": str(model),
"llama_cpp_commit": commit,
"policy": {"bf16": list(BF16_SUFFIXES), "f16": list(F16_SUFFIXES), "q8_0": sorted(Q8_NAMES),
"default_2d": "Q8_0", "experts": "NVFP4 (lossless repack) + per-expert F32 .scale"},
"ple_table": {"written": False, "shards_dropped": len(dropped_ple),
"use": "--ple-gguf with an IQ4_NL per_layer_token_embd (ISTA-DASLab shard 2)"},
"mtp": "dropped here; pack with tools/mtp_pack.py",
"seconds": round(took, 1),
}
if not a.dry_run:
out.with_suffix(".manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
print("nvfp4_convert: done in %.0f s, PLE shards dropped: %d" % (took, len(dropped_ple)))
return rc or 0
if __name__ == "__main__":
raise SystemExit(main())
+121
View File
@@ -0,0 +1,121 @@
"""tools/nvfp4_verify.py - prove the ModelOpt -> ggml NVFP4 repack is lossless on a real checkpoint.
python tools/nvfp4_verify.py --model <ModelOpt NVFP4 dir> [--experts 4] [--scan-all]
llama.cpp's converter repacks ModelOpt NVFP4 by moving bits: nibbles into ggml's split-half order, and each
E4M3 block scale into a UE4M3 byte by stripping its sign bit. That is lossless only while every scale is a
finite, non-negative E4M3 - a negative scale would silently flip, a NaN would propagate. So this checks two
things independently of the converter's own code path:
1. every weight_scale byte in the checkpoint (--scan-all): no sign bit set, no NaN encoding (0x7F / 0xFF);
2. for a few experts: dequantize ModelOpt directly (E2M1 value x E4M3 scale x weight_scale_2) and compare
with gguf-py's dequantization of the repacked block_nvfp4 bytes times the same weight_scale_2. They must
agree bit for bit in float32.
"""
from __future__ import annotations
import argparse
import json
import pathlib
import sys
import numpy as np
import torch
from safetensors import safe_open
LLAMA = pathlib.Path(__file__).resolve().parents[1] / "third_party" / "llama.cpp"
sys.path.insert(0, str(LLAMA / "gguf-py"))
sys.path.insert(0, str(LLAMA))
from gguf import GGMLQuantizationType as Q, quants # noqa: E402
from conversion.base import ModelBase # noqa: E402
E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
def modelopt_dequant(weight: torch.Tensor, scale: torch.Tensor, scale2: torch.Tensor) -> np.ndarray:
"""The ModelOpt definition, written out independently of the converter."""
rows = weight.shape[0]
lo = (weight & 0x0F).long()
hi = (weight >> 4).long()
nib = torch.stack([lo, hi], dim=-1).reshape(rows, -1) # element 2j low, 2j+1 high
vals = E2M1[nib]
s = scale.float().repeat_interleave(16, dim=1)
return (vals * s * scale2.float()).numpy().astype(np.float32)
def check_scales(model: pathlib.Path) -> int:
index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
by_shard: dict[str, list[str]] = {}
for name, shard in index.items():
if name.endswith(".weight_scale"):
by_shard.setdefault(shard, []).append(name)
n_bytes = n_sign = n_nan = n_tensors = 0
worst = []
for i, (shard, names) in enumerate(sorted(by_shard.items())):
with safe_open(model / shard, framework="pt") as f:
for name in names:
t = f.get_tensor(name)
if t.dtype != torch.float8_e4m3fn or t.ndim != 2:
continue # FP8 per-channel scales are not NVFP4
b = t.view(torch.uint8)
sign = int((b & 0x80).count_nonzero())
nan = int(((b & 0x7F) == 0x7F).sum())
n_bytes += b.numel()
n_sign += sign
n_nan += nan
n_tensors += 1
if sign or nan:
worst.append((name, sign, nan))
if i % 40 == 0:
print(" scanned %3d/%d shards, %d scale tensors" % (i + 1, len(by_shard), n_tensors), flush=True)
print("scale bytes %.2f GiB in %d tensors: sign bit set %d, NaN %d" % (n_bytes / 2**30, n_tensors, n_sign, n_nan))
for w in worst[:10]:
print(" BAD", *w)
return 1 if (n_sign or n_nan) else 0
def check_experts(model: pathlib.Path, n: int) -> int:
index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
picks = [name for name in sorted(index)
if ".experts." in name and name.endswith(".weight") and ".mtp." not in name
and name.replace(".weight", ".weight_scale") in index][:: max(1, 50000 // max(1, n))][:n * 3]
bad = 0
for name in picks:
shard = model / index[name]
with safe_open(shard, framework="pt") as f:
w = f.get_tensor(name)
s = f.get_tensor(name.replace(".weight", ".weight_scale"))
s2_name = name.replace(".weight", ".weight_scale_2")
s2 = f.get_tensor(s2_name) if s2_name in f.keys() else torch.tensor(1.0)
ref = modelopt_dequant(w, s, s2)
raw, shape = ModelBase._nvfp4_pack(w, s)
got = quants.dequantize(np.ascontiguousarray(raw), Q.NVFP4).reshape(shape).astype(np.float32)
got = (torch.from_numpy(got) * s2.float()).numpy()
# E2M1 code 8 is -0.0; ggml's kvalues_fp4 stores both zeros as integer 0, so the repacked weights give
# +0.0 where ModelOpt gives -0.0. That is the same value in every sum (x + -0 == x), so normalise zeros
# (adding +0.0 turns -0.0 into +0.0) and keep the comparison bitwise for everything else.
neg_zero = int(np.count_nonzero((ref == 0) & np.signbit(ref)))
same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got + np.float32(0)).view(np.uint32))
diff = float(np.abs(ref - got).max())
print(" %-70s %-12s bitwise %s max|diff| %.3g (-0.0 in source: %d)"
% (name[-70:], tuple(shape), "OK " if same else "NO ", diff, neg_zero))
bad += not same
return 1 if bad else 0
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True)
ap.add_argument("--experts", type=int, default=4, help="how many experts to compare (3 projections each)")
ap.add_argument("--scan-all", action="store_true", help="check every weight_scale byte in the checkpoint")
a = ap.parse_args()
model = pathlib.Path(a.model)
rc = check_experts(model, a.experts)
if a.scan_all:
rc |= check_scales(model)
print("RESULT:", "lossless" if rc == 0 else "NOT lossless")
return rc
if __name__ == "__main__":
raise SystemExit(main())
+161
View File
@@ -0,0 +1,161 @@
"""tools/nvfp4_verify_gguf.py - check a converted NVFP4 GGUF against its ModelOpt source, and a PLE GGUF against it.
python tools/nvfp4_verify_gguf.py --model <ModelOpt dir> --gguf <converted.gguf> [--ple-gguf <IQ4_NL PLE gguf>]
nvfp4_verify.py proves the repack function is lossless. This checks what was actually written, where the
converter's own bookkeeping could go wrong without the function being wrong:
* expert order: 512 experts are sorted and stacked per (layer, projection); expert e of the stacked tensor
must be the source's expert e - checked bit for bit (signed zeros normalised) on sampled (layer, expert);
* scale order: `.scale[e]` must be that expert's weight_scale_2;
* the dense policy: every tensor's type against the policy, and every non-PLE tensor name of the reference
layout present;
* the PLE table (with --ple-gguf): the engine will read another file's IQ4_NL table, which is only valid if it
is the same table. Sampled rows of it are compared with this checkpoint's FP8 rows by cosine similarity -
two quantizations of one table agree to ~0.99, different tables do not.
"""
from __future__ import annotations
import argparse
import json
import pathlib
import random
import sys
import numpy as np
import torch
from safetensors import safe_open
LLAMA = pathlib.Path(__file__).resolve().parents[1] / "third_party" / "llama.cpp"
sys.path.insert(0, str(LLAMA / "gguf-py"))
from gguf import GGUFReader, GGMLQuantizationType as Q, quants # noqa: E402
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from nvfp4_verify import modelopt_dequant # noqa: E402
PROJ = {"gate": "gate_proj", "up": "up_proj", "down": "down_proj"}
def tensor_map(reader: GGUFReader) -> dict:
return {t.name: t for t in reader.tensors}
def check_experts(model: pathlib.Path, T: dict, samples: int, rng: random.Random) -> int:
index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
bad = 0
for _ in range(samples):
layer, expert, role = rng.randrange(48), rng.randrange(512), rng.choice(list(PROJ))
g = T["blk.%d.ffn_%s_exps.weight" % (layer, role)]
s = T["blk.%d.ffn_%s_exps.scale" % (layer, role)]
if g.tensor_type != Q.NVFP4:
print(" blk.%d.ffn_%s_exps is %s, not NVFP4" % (layer, role, g.tensor_type.name))
bad += 1
continue
raw = np.asarray(g.data).reshape(512, -1)[expert] # one expert's block_nvfp4 bytes
rows = int(g.shape[1]) # ggml shape: [cols, rows, experts]
cols = int(g.shape[0])
got = quants.dequantize(np.ascontiguousarray(raw), Q.NVFP4).reshape(rows, cols).astype(np.float32)
scale_file = float(np.asarray(s.data).reshape(-1)[expert])
src = "model.language_model.layers.%d.mlp.experts.%d.%s.weight" % (layer, expert, PROJ[role])
with safe_open(model / index[src], framework="pt") as f:
w = f.get_tensor(src)
sc = f.get_tensor(src.replace(".weight", ".weight_scale"))
s2 = f.get_tensor(src.replace(".weight", ".weight_scale_2"))
ref = modelopt_dequant(w, sc, s2)
got = got * np.float32(scale_file)
same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got + np.float32(0)).view(np.uint32))
scale_ok = scale_file == float(s2.float())
print(" blk.%-2d expert %-3d %-4s weights %s scale %s (%.6g)"
% (layer, expert, role, "bitwise" if same else "DIFFER ", "ok" if scale_ok else "WRONG", scale_file))
bad += (not same) + (not scale_ok)
return bad
def check_policy(T: dict, reference: pathlib.Path | None) -> int:
bf16 = ("hc_attn_down", "hc_attn_up", "hc_attn_inject", "hc_ffn_down", "hc_ffn_up", "hc_ffn_inject",
"ssm_alpha", "ssm_beta", "indexer.q_proj", "indexer.k_proj", "ple_value", "ple_key",
"ffn_gate_inp", "ffn_gate_inp_shexp", "output_hc_down", "output_hc_up")
bad = 0
counts: dict[str, int] = {}
for name, t in T.items():
typ = t.tensor_type.name
counts[typ] = counts.get(typ, 0) + 1
stem = name.rsplit(".weight", 1)[0].split(".", 2)[-1] if name.startswith("blk.") else name.rsplit(".weight", 1)[0]
if name.endswith("_exps.weight") and typ != "NVFP4":
bad += 1; print(" policy: %s is %s" % (name, typ))
elif any(name.endswith(b + ".weight") for b in bf16) and typ != "BF16":
bad += 1; print(" policy: %s is %s, expected BF16" % (name, typ))
elif name in ("token_embd.weight", "output.weight") and typ != "Q8_0":
bad += 1; print(" policy: %s is %s, expected Q8_0" % (name, typ))
print(" types: " + ", ".join("%s x%d" % kv for kv in sorted(counts.items(), key=lambda kv: -kv[1])))
if reference and reference.exists():
want = {line.rsplit(":", 1)[0].strip() for line in reference.read_text(encoding="utf-8").splitlines()
if line and not line.startswith("#") and ":" in line}
missing = sorted(want - set(T))
extra = sorted(n for n in set(T) - want if not n.endswith((".scale", ".input_scale")))
print(" reference layout: %d names, missing here %d, unexpected here %d"
% (len(want), len(missing), len(extra)))
for n in (missing + extra)[:10]:
print(" ", "missing" if n in missing else "extra ", n)
bad += len(missing) + len(extra)
return bad
def check_ple(model: pathlib.Path, ple: pathlib.Path, samples: int, rng: random.Random) -> int:
reader = GGUFReader(ple)
t = {x.name: x for x in reader.tensors}.get("per_layer_token_embd.weight")
if t is None:
print(" PLE: per_layer_token_embd.weight not in", ple.name)
return 1
width, rows = int(t.shape[0]), int(t.shape[1])
print(" PLE file: %s %s, %d rows x %d" % (ple.name, t.tensor_type.name, rows, width))
if t.tensor_type != Q.IQ4_NL:
print(" PLE: the engine reads IQ4_NL only")
return 1
table = np.asarray(t.data).reshape(rows, -1)
index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
shard_rows = 2500012
worst, sims = 1.0, []
for _ in range(samples):
r = rng.randrange(rows)
shard, off = divmod(r, shard_rows)
name = "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_%d.weight" % shard
with safe_open(model / index[name], framework="pt") as f:
src = f.get_slice(name)[off:off + 1].float().numpy().reshape(-1)
sname = name.replace(".weight", ".weight_scale")
if sname in f.keys():
src = src * float(f.get_tensor(sname).float())
mine = quants.dequantize(np.ascontiguousarray(table[r]), Q.IQ4_NL).reshape(-1)
cos = float(np.dot(src, mine) / (np.linalg.norm(src) * np.linalg.norm(mine) + 1e-30))
sims.append(cos)
worst = min(worst, cos)
print(" PLE rows vs FP8 source: cosine mean %.4f, worst %.4f over %d random rows"
% (float(np.mean(sims)), worst, samples))
return 0 if worst > 0.95 else 1
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True)
ap.add_argument("--gguf", required=True)
ap.add_argument("--ple-gguf")
ap.add_argument("--reference", help="an rco-allocation.txt listing the reference tensor names")
ap.add_argument("--samples", type=int, default=12)
a = ap.parse_args()
rng = random.Random(20260929)
model = pathlib.Path(a.model)
T = tensor_map(GGUFReader(a.gguf))
print("GGUF: %d tensors" % len(T))
print("experts, sampled:")
bad = check_experts(model, T, a.samples, rng)
print("dense policy:")
bad += check_policy(T, pathlib.Path(a.reference) if a.reference else None)
if a.ple_gguf:
print("PLE table:")
bad += check_ple(model, pathlib.Path(a.ple_gguf), 64, rng)
print("RESULT:", "OK" if bad == 0 else "%d problems" % bad)
return 1 if bad else 0
if __name__ == "__main__":
raise SystemExit(main())
+180
View File
@@ -0,0 +1,180 @@
"""Tests for setup.py's NVFP4 family (ready-made packs, NVFP4_REPOS): every file fetched from its pinned revision and
checked against its size and SHA-256, a file both packs share linked instead of downloaded twice, a wrong file
refused, and the config's name read back as the same size. A local file:// mirror - nothing is downloaded.
python -m unittest tools.test_setup_nvfp4
"""
from __future__ import annotations
import contextlib
import hashlib
import io
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tools"))
import setup # noqa: E402
A, B = "owner/pack-a", "owner/pack-b"
REV_A, REV_B = "a" * 40, "b" * 40
def quiet(fn, *args, **kw):
with contextlib.redirect_stdout(io.StringIO()):
return fn(*args, **kw)
class ReadyPacks(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = Path(self.tmp.name)
self.mirror = self.root / "mirror"
self.models = self.root / "models"
bodies = {
(A, REV_A, "pack/index.txt"): b"index a", (A, REV_A, "pack/experts.bin"): b"experts a" * 50,
(A, REV_A, "dense-a.gguf"): b"dense a", (A, REV_A, "ple-fp8.gguf"): b"the shared table" * 100,
(B, REV_B, "pack/index.txt"): b"index b", (B, REV_B, "pack/experts.bin"): b"experts b" * 50,
(B, REV_B, "dense-b.gguf"): b"dense b", (B, REV_B, "ple-fp8.gguf"): b"the shared table" * 100,
}
roles = {"pack/index.txt": "pack", "pack/experts.bin": "pack", "dense-a.gguf": "dense", "dense-b.gguf": "dense",
"ple-fp8.gguf": "ple"}
repos = {A: {"revision": REV_A, "files": {}}, B: {"revision": REV_B, "files": {}}}
for (repo, rev, path), body in bodies.items():
f = self.mirror / repo / "resolve" / rev / path
f.parent.mkdir(parents=True, exist_ok=True)
f.write_bytes(body)
repos[repo]["files"][path] = (roles[path], len(body), hashlib.sha256(body).hexdigest())
models = {"NVFP4": {**setup.MODELS["NVFP4"], "repo": A}, "NVFP4-NVIDIA": {**setup.MODELS["NVFP4-NVIDIA"], "repo": B}}
self.patches = [mock.patch.object(setup, "NVFP4_REPOS", repos),
mock.patch.dict(setup.MODELS, models),
mock.patch.dict(os.environ, {"HF_ENDPOINT": "file://" + self.mirror.as_posix()})]
for p in self.patches:
p.start()
def tearDown(self):
for p in reversed(self.patches):
p.stop()
self.tmp.cleanup()
def test_fetch_checks_and_links_the_shared_file(self):
quiet(setup.ready_fetch, "NVFP4", self.models)
for f in setup.ready_files("NVFP4"):
self.assertTrue(setup.ready_verified(setup.ready_where(self.models, f), f[5]), f[3])
quiet(setup.ready_fetch, "NVFP4-NVIDIA", self.models)
a = self.models / "owner--pack-a" / "ple-fp8.gguf"
b = self.models / "owner--pack-b" / "ple-fp8.gguf"
self.assertTrue(setup.ready_verified(b, setup.NVFP4_REPOS[B]["files"]["ple-fp8.gguf"][2]))
self.assertTrue(os.path.samefile(a, b), "the shared table is linked, not a second copy")
p = setup.ready_paths("NVFP4-NVIDIA", self.models)
self.assertEqual(p["pack"], self.models / "owner--pack-b" / "pack")
self.assertEqual(p["dense"].name, "dense-b.gguf")
self.assertEqual(p["ple"], b)
def test_a_second_run_downloads_nothing(self):
quiet(setup.ready_fetch, "NVFP4", self.models)
with mock.patch.object(setup, "download", side_effect=AssertionError("downloaded again")):
quiet(setup.ready_fetch, "NVFP4", self.models)
def test_a_wrong_file_is_refused_and_deleted(self):
bad = self.mirror / A / "resolve" / REV_A / "dense-a.gguf"
bad.write_bytes(b"dense X") # same size, other bytes
with self.assertRaises(SystemExit):
quiet(setup.ready_fetch, "NVFP4", self.models)
self.assertFalse((self.models / "owner--pack-a" / "dense-a.gguf").exists())
def test_config_name_reads_back_as_the_size(self):
for model in ("NVFP4", "NVFP4-NVIDIA"):
cfg = self.root / f"strata-{(setup.FAMILIES['nvfp4']['tag'] + model).lower()}.json"
cfg.write_text('{"args": ["--max-context", "32768"]}', encoding="utf-8")
ch = setup.choices_from_config(cfg)
self.assertEqual((ch["family"], ch["model"]), ("nvfp4", model))
class Family(unittest.TestCase):
def test_sizes_and_family(self):
self.assertTrue(setup.FAMILIES["nvfp4"]["ready"])
names = [m for m in setup.MODELS if "nvfp4" in setup.MODELS[m].get("families", ())]
self.assertEqual(names, ["NVFP4", "NVFP4-NVIDIA"]) # the GPTQ pack first: the default size
for m in names:
d = setup.MODELS[m]
self.assertTrue(d["nvidia_only"])
self.assertTrue(d["vision"])
self.assertIn("License", d["license"])
self.assertEqual(d["engine"], setup.NVFP4_ENGINE)
def test_gguf_names_skip_the_ready_family(self):
self.assertIsNone(setup.gguf_choice("pack-a.gguf"))
self.assertEqual(setup.gguf_choice("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf"), ("qwen", "IQ3_XXS"))
class MockedInstall(unittest.TestCase):
"""setup.main() --family nvfp4 --yes on mocked PCs (test_setup_golden's harness): the run config's model flags."""
def run_install(self, prof, model=None, extra_argv=()):
import test_setup_golden as G
ram, found = G.PROFILES[prof]
return G.install(ram, found, ["--family", "nvfp4", "--no-start", *(["--model", model] if model else []),
*extra_argv])
def flag(self, args, name):
return args[args.index(name) + 1] if name in args else None
def test_recommended_size_on_128gb(self):
code, out, cfg, _ = self.run_install("128GB-1x24GB")
self.assertEqual(code, 0, out[-2000:])
a = cfg["args"]
self.assertTrue(self.flag(a, "--pack").endswith("Maximilian228--Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata/pack"))
dense = self.flag(a, "--native")
self.assertTrue(dense.endswith("/qwen-nvfp4-gptq-dense.gguf"))
self.assertEqual(self.flag(a, "--native-dense-gguf"), dense)
self.assertTrue(self.flag(a, "--ple-gguf").endswith("/ple-fp8.gguf"))
self.assertTrue(self.flag(a, "--embd-gguf").endswith("/token-embd-bf16.gguf"))
self.assertNotIn("--mmap-experts", a) # 128 GB: every expert in RAM
self.assertNotIn("--resident-experts", a)
self.assertNotIn("vision", cfg) # --yes: images default off, as for every model
self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-nvfp4-nvfp4")
self.assertIn("Qwen Community License", out)
def test_images_use_the_dense_gguf_and_the_pinned_encoder(self):
code, out, cfg, _ = self.run_install("128GB-1x24GB", extra_argv=["--vision", "gpu"])
self.assertEqual(code, 0, out[-2000:])
v = cfg["vision"]
self.assertTrue(v["model"].endswith("/qwen-nvfp4-gptq-dense.gguf"))
self.assertTrue(v["mmproj"].endswith("/mmproj-Qwen3.8-Flash-Next-BF16.gguf"))
self.assertTrue(v["gpu"])
self.assertIn("--vision", cfg["args"])
def test_nvidia_size_and_its_license(self):
code, out, cfg, _ = self.run_install("128GB-1x24GB", "NVFP4-NVIDIA")
self.assertEqual(code, 0, out[-2000:])
self.assertIn("NVIDIA-NVFP4-Strata/pack", self.flag(cfg["args"], "--pack"))
self.assertIn("NVIDIA Open Model License", out)
def test_96gb_keeps_every_expert_in_ram_64gb_takes_the_ram_budget(self):
code, out, cfg, _ = self.run_install("96GB-1x16GB") # 68 GB of experts + 10 GB beside them fit 95.8
self.assertEqual(code, 0, out[-2000:])
self.assertFalse({"--mmap-experts", "--resident-experts"} & set(cfg["args"]))
code, out, cfg, _ = self.run_install("64GB-1x32GB") # 64 GB: the RAM-budget mode (RAM less 24 GB)
self.assertEqual(code, 0, out[-2000:])
a = cfg["args"]
self.assertFalse({"--mmap-experts", "--resident-experts"} & set(a))
self.assertEqual(a[a.index("--resident-budget-gib") + 1], "40")
def test_amd_is_refused_with_a_recommendation(self):
import test_setup_golden as G
ram, _ = G.PROFILES["128GB-1x24GB"]
amd = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201"}]
code, out, cfg, _ = G.install(ram, [], ["--family", "nvfp4", "--no-start", "--backend", "hip"],
extra=[mock.patch.object(setup, "amd_gpus", lambda *a, **k: amd)])
self.assertNotEqual(code, 0)
self.assertIn("UD-IQ4_XS", out)
if __name__ == "__main__":
unittest.main()
+20
View File
@@ -53,12 +53,32 @@ def quiet(fn, *args, **kw):
class HuggingFacePins(unittest.TestCase):
def test_every_model_url_is_pinned(self):
for name, fam in setup.FAMILIES.items():
if fam.get("ready"): # ready-made packs: pinned per file (test_ready_packs_pinned)
continue
for key in ("hf", "mmproj_hf"):
with self.subTest(family=name, key=key):
self.assertRegex(fam[key], SHA)
self.assertNotIn("/resolve/main/", fam[key])
self.assertRegex(setup.HF, SHA)
def test_ready_packs_pinned(self):
"""NVFP4: every size names a repository of NVFP4_REPOS, pinned by a commit; every file has a size and a
SHA-256, and the pack folder, dense GGUF, n-gram table and embedding are each there."""
sizes = [m for m, d in setup.MODELS.items() if d.get("repo")]
self.assertEqual(sorted(sizes), ["NVFP4", "NVFP4-NVIDIA"])
for m in sizes:
t = setup.NVFP4_REPOS[setup.MODELS[m]["repo"]]
self.assertRegex(t["revision"], r"^[0-9a-f]{40}$")
for path, (role, size, sha) in t["files"].items():
with self.subTest(model=m, path=path):
self.assertIn(role, ("pack", "dense", "ple", "embd"))
self.assertGreater(size, 0)
self.assertRegex(sha, r"^[0-9a-f]{64}$")
p = setup.ready_paths(m, setup.Path("M"))
self.assertEqual(sorted(p), ["dense", "embd", "pack", "ple"])
self.assertEqual(p["pack"].name, "pack")
self.assertIn("experts.bin", t["files"] and [x.split("/")[-1] for x in t["files"]])
def test_unpinned(self):
url = setup.FAMILIES["swift"]["hf"] + "x.gguf"
self.assertEqual(setup.hf_unpinned(url),