Merge branch 'f-132-q4' into rel-0.1.32
# Conflicts: # setup.py
This commit is contained in:
commit
d9fe3019e0
11 files changed
+707
-36
No files matched your search
+21
-1
@@ -35,6 +35,10 @@ endif()
|
||||
option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF)
|
||||
option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201)" OFF)
|
||||
option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF)
|
||||
# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads
|
||||
# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every
|
||||
# model, and the UD-Q4_K_XL prompt is SSD-bound with or without them (docs/UNSLOTH_Q4.md)
|
||||
option(STRATA_MMQ_KQUANTS "Build the CUDA MMQ prompt kernels for Q4_K / Q5_K / Q5_1 experts" OFF)
|
||||
if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP)
|
||||
message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON")
|
||||
endif()
|
||||
@@ -822,7 +826,13 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
endif()
|
||||
set(_strata_mmq ${_strata_gg}/src/ggml-cuda)
|
||||
add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu)
|
||||
foreach(_t q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) # q8_0: the drafter's matrices (E-9)
|
||||
# q8_0: the drafter's matrices (E-9); with STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL
|
||||
# (docs/UNSLOTH_Q4.md; the dispatch follows eddoursul/Strata 7706c1b)
|
||||
set(_strata_mmq_cuda_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0)
|
||||
if(STRATA_MMQ_KQUANTS)
|
||||
list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1)
|
||||
endif()
|
||||
foreach(_t IN LISTS _strata_mmq_cuda_types)
|
||||
target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu)
|
||||
endforeach()
|
||||
target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}
|
||||
@@ -832,8 +842,18 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
target_compile_options(strata_mmq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=/bigobj>)
|
||||
endif()
|
||||
target_link_libraries(strata_mmq PUBLIC ggml-base ${_strata_gpu_runtime_target})
|
||||
if(STRATA_MMQ_KQUANTS)
|
||||
target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1)
|
||||
endif()
|
||||
target_link_libraries(strata_prefill PUBLIC strata_mmq)
|
||||
target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1)
|
||||
if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS)
|
||||
# the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds)
|
||||
add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp)
|
||||
target_link_libraries(prefill_mmq_kquant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target})
|
||||
add_test(NAME prefill_mmq_kquant_test COMMAND prefill_mmq_kquant_test)
|
||||
set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120)
|
||||
endif()
|
||||
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.
|
||||
|
||||
@@ -87,6 +87,12 @@ one later with `SETUP.bat` (the same as `START-HERE.bat --setup`; on Linux `./se
|
||||
For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](docs/ORCA.md).
|
||||
It needs an explicit packing conversion and is not an installer menu option.
|
||||
|
||||
**Unsloth's 4-bit UD-Q4_K_XL** (experimental) is the fourth version in setup's menu (`--family unsloth`): the closest
|
||||
to the full model, but a 111 GB download whose 77 GB of experts do not fit in RAM. Strata keeps your RAM minus 24 GB
|
||||
of them in RAM and reads the rest from the SSD while it answers: 7-8.5 tokens/s on a 64 GB PC with a 12 GB GPU, several
|
||||
times slower than the sizes above, and long prompts are slow. It needs 48 GB of RAM or more, an NVMe SSD and one
|
||||
NVIDIA GPU (no images yet). Details and measurements: [UD-Q4_K_XL](docs/UNSLOTH_Q4.md).
|
||||
|
||||
An **AMD Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT or Radeon AI PRO R9700 on Linux** works too (experimental; the
|
||||
RX 7800 XT / 7700 XT and RX 9060 XT were validated by their owners):
|
||||
`./setup.sh --backend hip`, chosen by itself on a PC with no NVIDIA card Strata can use. It installs ROCm without sudo
|
||||
@@ -258,8 +264,9 @@ Want the full picture? The [details](docs/DETAILS.md#how-it-works) explain every
|
||||
|
||||
- Model: [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; compressed versions by
|
||||
[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF);
|
||||
[Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) by UkisAI. Their licenses apply
|
||||
to the model files.
|
||||
[Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) by UkisAI; the experimental
|
||||
[UD-Q4_K_XL](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF) by Unsloth (its support follows
|
||||
[eddoursul/Strata](https://github.com/eddoursul/Strata)). Their licenses apply to the model files.
|
||||
- Built with parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT). Ideas from
|
||||
[Splash](https://github.com/incoai/splash), [ninfer](https://github.com/Neroued/ninfer) and
|
||||
[HyperQwen](https://github.com/syv-ai/HyperQwen). More in the [details](docs/DETAILS.md#credits-and-licenses).
|
||||
|
||||
+7
-4
@@ -221,11 +221,14 @@ thought about for 1,524 tokens. Not a benchmark, but consistent with the claim.
|
||||
START-HERE.bat --setup --family swift --model IQ2_XS
|
||||
```
|
||||
|
||||
### Experimental: Unsloth's UD-Q4_K_XL (manual import)
|
||||
### Experimental: Unsloth's UD-Q4_K_XL
|
||||
|
||||
A 4-bit quantization of the same model (111 GB, 72 GiB of experts). Not in setup: packing it and the server
|
||||
configuration are in **[docs/UNSLOTH_Q4.md](UNSLOTH_Q4.md)**. On a 64 GB PC with a 12 GB RTX 5070 it writes 7-8.5
|
||||
tokens/s, most experts read from the SSD; quality has not been measured against llama.cpp yet.
|
||||
A 4-bit quantization of the same model (111 GB, 72 GiB of experts). Setup offers it from engine 0.1.32
|
||||
(`--family unsloth --model UD-Q4_K_XL`: a RAM budget of your RAM less 24 GB, the rest read from the SSD); what it
|
||||
does and the manual workflow are in **[docs/UNSLOTH_Q4.md](UNSLOTH_Q4.md)**. On a 64 GB PC with a 12 GB RTX 5070 it writes 7-8.5
|
||||
tokens/s, most experts read from the SSD; it picks the same tokens as llama.cpp on the same file at 97.5-99% of
|
||||
the positions of short greedy answers, 90-91% after a 16K prompt, differing mostly at near-ties
|
||||
([measured](UNSLOTH_Q4.md#quality-against-llamacpp-on-the-same-file)).
|
||||
|
||||
## Before you start
|
||||
|
||||
|
||||
+87
-14
@@ -1,8 +1,8 @@
|
||||
# Unsloth UD-Q4_K_XL (experimental, manual import)
|
||||
# Unsloth UD-Q4_K_XL (experimental)
|
||||
|
||||
**Experimental, not in setup yet.** Engine 0.1.31 or newer. Validated on one PC: Windows 10, an RTX 5070 (12 GB),
|
||||
64 GB of RAM and an AVX-512 CPU, on 2026-10-01. Everything below is a manual workflow; `START-HERE.bat` / `setup.sh`
|
||||
do not offer this model.
|
||||
**Experimental.** Setup offers it from engine 0.1.32 ([below](#setup)); the manual workflow after that section works
|
||||
with engine 0.1.31 or newer. Validated on one PC: Windows 10, an RTX 5070 (12 GB), 64 GB of RAM and an AVX-512 CPU,
|
||||
on 2026-10-01.
|
||||
|
||||
The target is Unsloth's 4-bit quantization of the same model the other packs use:
|
||||
[unsloth/Qwen3.8-Flash-Next-GGUF, `UD-Q4_K_XL`, revision `38bb39e`](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/tree/38bb39ee97821de2c9009abb7e93950eec396e66/UD-Q4_K_XL).
|
||||
@@ -11,6 +11,28 @@ Q5_1 (Q8_0 in layers 2, 4, 30, 46, 47) for down; the token embedding, the output
|
||||
projections and the PLE key are Q8_0; the 28.8 GB PLE table is IQ4_NL. The routed experts are 71.7 GiB, about twice
|
||||
the 3-bit models'.
|
||||
|
||||
## Setup
|
||||
|
||||
`START-HERE.bat --setup` (Linux: `./setup.sh --setup`) and choose **Qwen3.8-Flash-Next (Unsloth)**, marked
|
||||
`[experimental]`; or directly:
|
||||
|
||||
```sh
|
||||
START-HERE.bat --setup --family unsloth --model UD-Q4_K_XL
|
||||
```
|
||||
|
||||
What setup does differently for this model:
|
||||
|
||||
- It needs 48 GB of RAM or more and engine 0.1.32 or newer (checked before anything is downloaded), and an NVIDIA
|
||||
GPU. One GPU only: with `--gpus` it uses the first one and says so. No images (the vision encoder is not wired to
|
||||
this file yet) and no experimental speed projection (not tested with it).
|
||||
- It downloads the four shards below from the pinned revision `38bb39e` (resumable, like the other models), then
|
||||
checks each one's size and SHA-256 against the table below; the check takes a few minutes once and is remembered
|
||||
in the file's finish mark. A file with the wrong hash is deleted, so the next run downloads it again.
|
||||
- It packs with `--compat-bf16` and never writes `experts.bin` (`--low-ram` does not apply).
|
||||
- The RAM budget is the PC's RAM less 24 GB: `--resident-budget-gib 40` on 64 GB, at most all 71 GiB of experts on
|
||||
96 GB or more. From a 64K context up, where the KV cache moves to RAM, its size comes out of the budget.
|
||||
- It recommends an 8K context on a GPU under 14 GB (every GB of KV cache is a GB less of cached experts).
|
||||
|
||||
## The files
|
||||
|
||||
Four shards, 111,334,654,784 bytes (111.3 GB) together. Shard 1 holds only the metadata; layer 11's down projection is
|
||||
@@ -24,7 +46,8 @@ in shard 2 and its gate/up in shard 3, which this engine handles (`native_expert
|
||||
| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf` | 12,087,983,520 | `753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a` |
|
||||
|
||||
Keep the four files together in one folder under these names (the engine finds shards 2-4 from shard 1's name; a
|
||||
missing shard is an error that names it). Check them before packing (`sha256sum -c`, or `Get-FileHash` on Windows).
|
||||
missing shard is an error that names it). Setup checks them itself; by hand, check them before packing
|
||||
(`sha256sum -c`, or `Get-FileHash` on Windows).
|
||||
Hugging Face snapshot symlinks work if you pass the snapshot's file name, not the hash-named blob it points to.
|
||||
|
||||
## What it needs
|
||||
@@ -35,7 +58,7 @@ Hugging Face snapshot symlinks work if you pass the snapshot's file name, not th
|
||||
| RAM | 64 GB measured. The RAM budget (below) holds the most-used experts; the rest come from the SSD through the OS file cache. |
|
||||
| GPU | 12 GB measured (RTX 5070): after the weights, the draft layer and the buffers, the expert cache held 1,280 of the 24,576 experts (3.7 GiB) at 4K context. |
|
||||
|
||||
## The pack
|
||||
## The pack (by hand)
|
||||
|
||||
Build Strata (or install 0.1.31+), then, from the repository root, with gguf-py from the pinned llama.cpp
|
||||
(setup installs it; `STRATA_GGUF_PY` can point to its `gguf-py` folder):
|
||||
@@ -61,8 +84,8 @@ source/destination type, method, whether it is exact, the largest absolute error
|
||||
264 F32 tensors (routers, injections, SSM gates) whose values are already BF16's are stored as BF16 exactly; the 195
|
||||
Q8_0 projections above are rounded to BF16 (largest absolute error 0.0144, in `hc_ffn_up`); the PLE convolution (F32)
|
||||
is narrowed to F16 when the engine loads it (largest error 3e-8). That is the compatibility Unsloth's file needs; it is
|
||||
not the original BF16 checkpoint. The output has not yet been compared with llama.cpp on the same GGUF (argmax
|
||||
agreement); treat quality as unmeasured.
|
||||
not the original BF16 checkpoint. The output matches llama.cpp's on the same file:
|
||||
[Quality](#quality-against-llamacpp-on-the-same-file).
|
||||
|
||||
## The MTP draft layer
|
||||
|
||||
@@ -123,13 +146,61 @@ low-RAM mode; `STRATA_RESIDENT_PIN=0` keeps the budget locked only (the CPU then
|
||||
| 40 GiB | **7-8.5 tok/s** (6 runs: 6.7-8.6, mean 7.9) | 1.1 GB read from the SSD per verify round, ~0.33 GB per token |
|
||||
|
||||
- The first answer comes about 60 s after the engine starts (mostly loading: the RAM budget is copied from the GGUF
|
||||
files at start). A 30-token prompt then took 5-6 s. Longer prompts have not been measured and will be slow: the
|
||||
prompt path dequantizes these formats to FP16 (fast prompt kernels for Q4_K/Q5_K/Q5_1 are future work).
|
||||
files at start). A 30-token prompt then took 5-6 s.
|
||||
- Long prompts (engine 0.1.32): a 16K prompt is read at **160 tokens/s** (15,873 tokens in 99 s; 0.1.31: 57 tokens/s,
|
||||
273-282 s). Reading a prompt streams every expert once per 4K chunk, and the third of them outside the RAM budget
|
||||
come from the SSD (~35 GB per chunk), so the prompt path now reads them with 32 threads and up to 128 blobs in
|
||||
flight when the experts are read from the GGUF in place (`STRATA_STAGER_THREADS` / `STRATA_STAGER_RING` override
|
||||
it; 4 and 16 before, still the default for every other model). Between the chunks, the 28.8 GB PLE table's rows
|
||||
take ~5 s per chunk.
|
||||
- An engine compiled with `-DSTRATA_MMQ_KQUANTS=ON` multiplies the Q4_K / Q5_K / Q5_1 experts of a prompt with
|
||||
llama.cpp's MMQ kernels (as the other models' formats always are) instead of dequantizing them to FP16: 4x less GPU
|
||||
time for those products, but on this PC the prompt waits for the SSD either way (29 s per 4K chunk with or
|
||||
without). Off in the released engine: it loads every kernel at start, and these took 1-3 expert slots of VRAM from
|
||||
every model.
|
||||
- The speed varies from run to run (6.7-8.6 tok/s at 40 GiB for the same prompt), with what the OS file cache holds.
|
||||
- For comparison, IQ3_S (all its experts in RAM) writes ~53 tok/s on the same PC ([the speed tables](DETAILS.md#speed-measured)).
|
||||
- Where the time goes (`--stats` on the command line): at 40 GiB about 550-750 ms of each verify round (3.5 tokens) is
|
||||
reading experts from the SSD, ~75 ms the CPU's expert kernels, ~13 ms the GPU.
|
||||
|
||||
## Quality: against llama.cpp on the same file
|
||||
|
||||
Strata and llama.cpp (the pinned commit `3cf0325`, a CPU build reading the GGUF memory-mapped) were given the same
|
||||
token sequences, and at every position each wrote its 20 most likely next tokens with their log-probabilities: Strata
|
||||
through its verify windows (`STRATA_LOGPOS` with `STRATA_LOGPOS_TOPK=20`), llama.cpp from `llama_get_logits_ith` over
|
||||
one batch. Strata ran with the recommended settings (RAM budget 40 GiB, the MTP draft layer on, greedy,
|
||||
`--adapt-every 100000` so the expert cache does not move during the run). Per position: whether the most likely token is the same (argmax
|
||||
agreement), how many of the 5 / 10 most likely tokens both have, the KL divergence (llama.cpp's distribution against
|
||||
Strata's, over llama.cpp's top 20 plus one bucket for the rest), and the perplexity of the sequence under each.
|
||||
|
||||
| Token set | Positions | Argmax agreement | Top-5 / top-10 overlap | KL | Perplexity Strata / llama.cpp |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| Code: Strata's greedy answer to a coding prompt (an LRU cache in Python, 56-token prompt) | 400 | **99.0%** | 95.6% / 95.3% | 0.0008 | 1.067 / 1.070 |
|
||||
| Thinking: Strata's greedy answer to a reasoning puzzle (with thinking, 55-token prompt) | 324 | **97.5%** | 96.2% / 96.4% | 0.0016 | 1.107 / 1.106 |
|
||||
| After a 16K prompt: Strata's greedy continuation (256 tokens) of the 16,384 real-text tokens below | 256 | 90.2% | 88.1% / 89.3% | 0.039 | 1.619 / 1.623 |
|
||||
| Real text after a 16K prompt: the last 510 tokens of 16,384 tokens of this repository's docs and code | 510 | 91.2% | 88.3% / 89.9% | 0.035 | 4.27 / 4.29 |
|
||||
| The same 511 positions with only 512 tokens before them | 511 | 89.2% | 86.0% / 86.3% | 0.061 | 8.99 / 8.87 |
|
||||
|
||||
For comparison, [eddoursul/Strata](https://github.com/eddoursul/Strata) reported 98.2-99.3% (code), 95.6-95.8%
|
||||
(thinking) and 97.7% (after a 16K prompt) for the same file against llama.cpp on an RTX 3090.
|
||||
|
||||
**Where they differ:** at near-ties. Grouped by llama.cpp's own gap between its two most likely tokens, Strata picks
|
||||
the same token at every position of the code and thinking answers where that gap is 0.2 or more (695 of 695) and at
|
||||
every position after the 16K prompt where it is 0.5 or more (144 of 144 in the continuation, 254 of 254 in the real
|
||||
text; 50 of 54 and 117 of 121 between 0.2 and 0.5). Text after a long document has many more near-ties than a short
|
||||
answer (58 of the continuation's 256 positions and 135 of the real text's 510 have a gap under 0.2, against 13 of the
|
||||
code answer's 400), which is why its agreement is lower. It is not the long context itself: the same real-text
|
||||
positions after only 512 tokens agree a little less (89.2%), and the perplexities match within 3% in every set. For
|
||||
scale, Strata's own greedy run and its teacher-forced rerun of the continuation pick different tokens at 6% of the
|
||||
positions (93.8% the same: other window sizes, other experts in VRAM), the same kind of near-tie flips. The 16K
|
||||
prompts were read by Strata's batched prompt path (15,872 tokens), the rest through the verify windows. These numbers
|
||||
are the FP16 prompt path's (the released engine's); with the MMQ prompt path (`-DSTRATA_MMQ_KQUANTS=ON`, above) the
|
||||
continuation after the 16K prompt agrees at 92.2% (KL 0.029, three runs, identical).
|
||||
|
||||
To repeat it: Strata's side is `STRATA_LOGPOS=<file>` with `STRATA_LOGPOS_TOPK=20` (engine 0.1.32) on a serve
|
||||
engine with `--short-read` covering the positions to compare; llama.cpp's side was a short program over
|
||||
`llama_decode` / `llama_get_logits_ith` writing the same top 20 per position.
|
||||
|
||||
## Opt-ins and switches (environment variables)
|
||||
|
||||
| | |
|
||||
@@ -137,7 +208,7 @@ low-RAM mode; `STRATA_RESIDENT_PIN=0` keeps the budget locked only (the CPU then
|
||||
| `STRATA_LOOKAHEAD=0` | Turns off the routing-aware prefetch (on by default in this mode): while the CPU works on a layer, a thread applies the next layer's router to this layer's input and asks the OS to read the predicted experts' pages. Pages only, the answers are the same. About half of the SSD reads were predicted; mean +14% (6.9 -> 7.9 tok/s). `STRATA_LOOKAHEAD_K` sets the experts per token (default 10). |
|
||||
| `STRATA_KQ256=1` | Multi-token AVX2 kernels for the Q4_K / Q5_1 / Q8_0 experts. Bit-exact with ggml's, but measured no faster, so off. |
|
||||
| `STRATA_PARTIAL_PIN=1` | Registers the hottest part of the RAM budget (up to `STRATA_PARTIAL_PIN_GIB`, default 24) with the GPU driver, so the GPU computes a share of the misses over PCIe (`--pcie-frac`). Measured no faster on this PC, and it changes the numerics of those experts (GPU kernels instead of the CPU's), so off. |
|
||||
| `STRATA_FETCH_THREADS=N` | Threads that read the experts from the GGUF (default 8; 16 was no faster). |
|
||||
| `STRATA_FETCH_THREADS=N` | Threads that read the experts from the GGUF while it answers (default 8; 16 was no faster). The prompt path has its own: `STRATA_STAGER_THREADS` (default 32 here) and `STRATA_STAGER_RING` (128). |
|
||||
|
||||
## Scope and validation
|
||||
|
||||
@@ -145,10 +216,12 @@ low-RAM mode; `STRATA_RESIDENT_PIN=0` keeps the budget locked only (the CPU then
|
||||
have kernels for; the engine checks every layer's formats at start and refuses an unsupported one by name.
|
||||
- Tests: the packer's synthetic 4-shard and conversion tests (`.venv/bin/python -m unittest discover -s tools -p
|
||||
test_iq_pack.py`); CTests `gguf_split_test`, `expert_layout_test`, `native_expert_parity_*` (the three real expert
|
||||
format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows); the in-place mode against `experts.bin` on the Coder
|
||||
format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the
|
||||
prompt path's MMQ products for Q4_K / Q5_K / Q5_1 / Q8_0 against ggml's dequantized weights); the in-place mode against `experts.bin` on the Coder
|
||||
(identical tokens and logits).
|
||||
- Real runs: greedy answers to a coding prompt (correct) at every budget and setting above, identical across them. Not
|
||||
yet: llama.cpp argmax agreement, long prompts, sampled decoding, long conversations. Please report what you see.
|
||||
- Real runs: greedy answers to a coding prompt (correct) at every budget and setting above, identical across them;
|
||||
the same tokens as llama.cpp at 97.5-99% of the positions of short greedy answers and 90-91% after a 16K prompt,
|
||||
differing mostly at near-ties (above). Not yet: sampled decoding, long conversations. Please report what you see.
|
||||
|
||||
## Credits
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ 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; IQ1_M is not covered).
|
||||
/// MMQ covers this ggml type (the i-quants and Q2_0 the packs use, Q8_0, and in a CUDA build with STRATA_MMQ_KQUANTS
|
||||
/// the Q4_K / Q5_K / Q5_1 of Unsloth's UD-Q4_K_XL; IQ1_M is not covered).
|
||||
bool supported(int ggml_type);
|
||||
/// 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);
|
||||
|
||||
@@ -35,6 +35,7 @@ import argparse
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
@@ -57,6 +58,7 @@ HF_REVISIONS = {
|
||||
"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", # 2026-09-29
|
||||
"ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "b22d729eae29b5796f76fb70f91aef549b9fc52c", # 2026-09-24
|
||||
"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29
|
||||
"unsloth/Qwen3.8-Flash-Next-GGUF": "38bb39ee97821de2c9009abb7e93950eec396e66", # 2026-09-30
|
||||
}
|
||||
|
||||
|
||||
@@ -104,7 +106,26 @@ MODELS = {
|
||||
# the Coder release: 256 of the 512 experts kept (the ones code, tools and vision use), IQ2_S-IQ4_XS like IQ3_S
|
||||
"IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4,
|
||||
"ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)},
|
||||
# EXPERIMENTAL (docs/UNSLOTH_Q4.md): Unsloth's 4-bit file; its 77 GB of experts do not fit a 64 GB PC, so the engine
|
||||
# keeps a RAM budget of them (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD
|
||||
"UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the "
|
||||
"SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48,
|
||||
"arena_gb": 77.0, "families": ("unsloth",), "budget": True},
|
||||
}
|
||||
# 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).
|
||||
UNSLOTH_SHARDS = {
|
||||
"Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf":
|
||||
(10946624, "4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082"),
|
||||
"Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf":
|
||||
(49859583136, "3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9"),
|
||||
"Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf":
|
||||
(49376141504, "56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3"),
|
||||
"Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf":
|
||||
(12087983520, "753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a"),
|
||||
}
|
||||
UNSLOTH_ENGINE = (0, 1, 32) # the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand)
|
||||
UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through
|
||||
# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will
|
||||
# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor
|
||||
# from the final context (final / 262144, at least 1) itself (below), keeps an explicit
|
||||
@@ -135,6 +156,14 @@ FAMILIES = {
|
||||
"mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF"),
|
||||
"mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-coder",
|
||||
"profile": "expert-profile-coder.bin"},
|
||||
# EXPERIMENTAL: Unsloth's UD-Q4_K_XL of the original model (docs/UNSLOTH_Q4.md): four shards, no images yet
|
||||
"unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's 4-bit quantization (EXPERIMENTAL)",
|
||||
"about": "4-bit, 111 GB download, most experts read from the SSD: slow (7-8.5 tokens/s on a 64 GB PC)",
|
||||
"hf": hf("unsloth/Qwen3.8-Flash-Next-GGUF") + "{q}/",
|
||||
"file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf", "shards": 4, "tag": "unsloth-",
|
||||
"mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"),
|
||||
"mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth",
|
||||
"experimental": True, "vision": False, "pack_args": ["--compat-bf16"], "sha256": UNSLOTH_SHARDS},
|
||||
}
|
||||
MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf"
|
||||
# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README
|
||||
@@ -727,6 +756,39 @@ def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]:
|
||||
return [first.with_name("%s-%05d-of-%05d.gguf" % (stem, i, total)) for i in range(1, total + 1)]
|
||||
|
||||
|
||||
def verify_sha256(s: Path, size: int, sha: str) -> None:
|
||||
"""A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark,
|
||||
so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again."""
|
||||
m = s.with_name(s.name + ".done")
|
||||
if m.exists() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace"):
|
||||
return
|
||||
have = s.stat().st_size if s.exists() else -1
|
||||
if have != size:
|
||||
fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)")
|
||||
say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...")
|
||||
h = hashlib.sha256()
|
||||
with open(s, "rb") as f:
|
||||
while True:
|
||||
b = f.read(16 << 20)
|
||||
if not b:
|
||||
break
|
||||
h.update(b)
|
||||
if h.hexdigest() != sha:
|
||||
s.unlink(missing_ok=True)
|
||||
m.unlink(missing_ok=True)
|
||||
fail(f"{s.name} has the wrong SHA-256 ({h.hexdigest()}, expected {sha}): deleted",
|
||||
"run setup again to download it again")
|
||||
mark(s, f"sha256 {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
|
||||
RAM; at most all of them, at least 8. 64 GB: 40, the measured setting (docs/UNSLOTH_Q4.md)."""
|
||||
gib = round(ram) - UNSLOTH_RAM_LEFT_GB - math.ceil(kv_ram_gb)
|
||||
return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824)))
|
||||
|
||||
|
||||
def check_shards(shards):
|
||||
"""Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long as
|
||||
its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part
|
||||
@@ -1686,7 +1748,9 @@ def choices_from_config(cfg_path: Path) -> dict:
|
||||
cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))
|
||||
tag = cfg_path.stem[len("strata-"):]
|
||||
family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen")
|
||||
model = tag.split("-")[-1].upper()
|
||||
model = (tag[len(FAMILIES[family]["tag"]):] if tag.startswith(FAMILIES[family]["tag"]) else tag).upper()
|
||||
if model not in MODELS: # (sizes have no dash except UD-Q4_K_XL: the old rule)
|
||||
model = tag.split("-")[-1].upper()
|
||||
a = cfg.get("args", [])
|
||||
val = lambda k: a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None # noqa: E731
|
||||
vis = cfg.get("vision")
|
||||
@@ -2240,7 +2304,10 @@ def main() -> int:
|
||||
say()
|
||||
for m, d in MODELS.items():
|
||||
verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit"
|
||||
if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":
|
||||
if d.get("budget"):
|
||||
verdict = (f"EXPERIMENTAL, fits with {resident_budget_gib(m, ram)} GiB of its experts in RAM, the rest "
|
||||
"read from the SSD" if ram >= d["ram_gb"] else "does not fit")
|
||||
elif low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":
|
||||
verdict = (f"fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}% "
|
||||
"of its experts, " + ("the rest stays in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"])
|
||||
else "the rest is read from the SSD as needed)"))
|
||||
@@ -2256,7 +2323,7 @@ def main() -> int:
|
||||
else:
|
||||
for i, f in enumerate(fams, 1):
|
||||
d = FAMILIES[f]
|
||||
say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}")
|
||||
say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}" + (" [experimental]" if d.get("experimental") else ""))
|
||||
family = fams[int(ask("Which model?", [str(i) for i in range(1, len(fams) + 1)], "1", a.yes)) - 1]
|
||||
fam = FAMILIES[family]
|
||||
ok(f"model: {fam['title']}")
|
||||
@@ -2269,25 +2336,48 @@ def main() -> int:
|
||||
for i, m in enumerate(names, 1):
|
||||
d = MODELS[m]
|
||||
fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"
|
||||
if d.get("budget"):
|
||||
say(f" {i}) {m} {d['about']}; download {d['download_gb']:.0f} GB, keeps ~"
|
||||
f"{resident_budget_gib(m, ram)} GB of its {d['arena_gb']:.0f} GB of experts in RAM{fit}")
|
||||
continue
|
||||
if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":
|
||||
fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%, "
|
||||
+ ("the rest in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) else "the rest from the SSD)"))
|
||||
say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}")
|
||||
rec = str(names.index("IQ3_XXS") + 1) if ram >= 60 and "IQ3_XXS" in names else "1"
|
||||
model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1]
|
||||
low_ram = a.low_ram in ("on", "resident", "mmap") or (a.low_ram == "auto" and low_ram_needed(model, ram))
|
||||
budget = None
|
||||
if MODELS[model].get("budget"):
|
||||
# Unsloth's UD-Q4_K_XL: a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM mode (no
|
||||
# experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode has no layer split)
|
||||
warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md): most of its experts are read from the SSD while it "
|
||||
"answers, so it is several times slower than the 2-3-bit models; quality checked against llama.cpp")
|
||||
if ram < MODELS[model]["ram_gb"]:
|
||||
fail(f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB",
|
||||
"choose one of the 2-3-bit models")
|
||||
budget = resident_budget_gib(model, ram)
|
||||
ok(f"RAM budget: {budget} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD")
|
||||
if a.low_ram not in ("auto", "off"):
|
||||
warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files")
|
||||
if multi:
|
||||
warn(f"{model} runs on one GPU: using " + gpu_name(gpu) + " only")
|
||||
multi, sel, chosen = [], [gpu["index"]], [gpu]
|
||||
low_ram = budget is None and (a.low_ram in ("on", "resident", "mmap") or
|
||||
(a.low_ram == "auto" and low_ram_needed(model, ram)))
|
||||
if low_ram and multi:
|
||||
warn("the low-RAM mode runs on one GPU: using " + gpu_name(gpu) + " only")
|
||||
for line in low_ram_one_gpu_why(model, ram, a.low_ram):
|
||||
say(" " + line)
|
||||
multi, sel, chosen = [], [gpu["index"]], [gpu]
|
||||
# (the low-RAM mode's variant is decided once the context is known, below)
|
||||
if not low_ram and ram < MODELS[model]["ram_gb"] - 4:
|
||||
if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4:
|
||||
confirm_paging(model, ram, a.low_ram, a.yes)
|
||||
ok(f"size: {model}")
|
||||
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
|
||||
if budget is not None: # UD-Q4_K_XL: every GB of KV is a GB fewer of cached experts
|
||||
rec_ctx = 8192 if small < 14 else 32768
|
||||
if a.context:
|
||||
ctx = a.context
|
||||
else:
|
||||
@@ -2344,7 +2434,11 @@ def main() -> int:
|
||||
kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1]
|
||||
if ctx > 8192:
|
||||
ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}")
|
||||
if hip:
|
||||
if fam.get("vision") is False:
|
||||
vision = "none"
|
||||
if a.vision not in (None, "no", "none"):
|
||||
warn(f"images are not available with {model} yet: off")
|
||||
elif hip:
|
||||
vision = hip_vision(a.vision)
|
||||
elif a.vision:
|
||||
vision = {"yes": "gpu", "no": "none"}.get(a.vision, a.vision)
|
||||
@@ -2393,10 +2487,11 @@ def main() -> int:
|
||||
fail(f"the experimental speed projection's vector is missing: {esp}")
|
||||
ok("experimental speed projection: " + ("ON (experimental)" if esp else "off"))
|
||||
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")
|
||||
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 / fam["file"].format(q=model, i=i) for i in (1, 2)]
|
||||
[models_dir / fam["file"].format(q=model, i=i) for i in range(1, fam.get("shards", 2) + 1)]
|
||||
if 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]
|
||||
@@ -2435,6 +2530,10 @@ def main() -> int:
|
||||
eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama)
|
||||
meta = json.loads((eng / "BUILD.json").read_text())
|
||||
lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs()
|
||||
engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())
|
||||
if budget is not None and engine_ver < UNSLOTH_ENGINE: # checked before the 111 GB download
|
||||
fail(f"{model} needs engine {'.'.join(map(str, UNSLOTH_ENGINE))} or newer; this one is {meta.get('version')}",
|
||||
"update Strata (or compile the engine with --build) and run setup again")
|
||||
ok(f"engine: {eng / EXE}")
|
||||
|
||||
# ---- 5. the model files
|
||||
@@ -2456,6 +2555,9 @@ def main() -> int:
|
||||
pass
|
||||
download(fam["hf"].format(q=model) + s.name, s)
|
||||
check_shards(shards)
|
||||
for s in shards: # the experimental Unsloth file: 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():
|
||||
@@ -2483,7 +2585,9 @@ def main() -> int:
|
||||
"--out", str(pack)], env=env) # writes <pack>/tokenizer/
|
||||
elif not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists():
|
||||
# every tensor as the GGUF stores it; the experts are read from the GGUF at start (seconds to build)
|
||||
run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack)], env=env)
|
||||
# (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():
|
||||
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),
|
||||
@@ -2513,7 +2617,8 @@ def main() -> int:
|
||||
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?)")
|
||||
args = ["--pack", str(pack), "--native", str(shards[0]), "--ple-gguf", str(ple),
|
||||
# (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 []),
|
||||
"--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)]
|
||||
@@ -2521,7 +2626,6 @@ def main() -> int:
|
||||
args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"]
|
||||
if ctx > 8192:
|
||||
args += ["--kv", kv]
|
||||
engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())
|
||||
if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE:
|
||||
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 "
|
||||
@@ -2543,6 +2647,11 @@ def main() -> int:
|
||||
elif ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1:
|
||||
args += ["--kv-resident", "32768"]
|
||||
ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM")
|
||||
if budget is not None: # its RAM comes out of the experts' budget
|
||||
budget = resident_budget_gib(model, ram, kv_ram_gb)
|
||||
ok(f"RAM budget: {budget} GiB (less the KV cache's RAM)")
|
||||
if budget is not None: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N GiB kept in RAM
|
||||
args += ["--resident-budget-gib", str(budget)]
|
||||
if vision != "none":
|
||||
args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])]
|
||||
if esp is not None:
|
||||
|
||||
+16
-1
@@ -1274,9 +1274,24 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3
|
||||
const double extra = has_extra ? (double) row[extra_id] - lse : NAN;
|
||||
const double without = has_extra && tgt != extra_id && sum_without > 0.0
|
||||
? (double) row[tgt] - (maxv + std::log(sum_without)) : NAN;
|
||||
std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f\n", (long long) (pos0 + t), (int) tgt,
|
||||
std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f", (long long) (pos0 + t), (int) tgt,
|
||||
(double) row[tgt] - lse, (long long) top, maxv - lse, (int) (top == (int64_t) tgt), extra,
|
||||
without);
|
||||
// STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a
|
||||
// top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md)
|
||||
static const int topk = [] {
|
||||
const char* v = std::getenv("STRATA_LOGPOS_TOPK");
|
||||
return v != nullptr ? std::max(0, std::min(256, std::atoi(v))) : 0;
|
||||
}();
|
||||
if (topk > 0) {
|
||||
std::vector<int32_t> order((size_t) n_vocab_);
|
||||
for (int64_t v = 0; v < n_vocab_; ++v) order[(size_t) v] = (int32_t) v;
|
||||
std::partial_sort(order.begin(), order.begin() + topk, order.end(),
|
||||
[&](int32_t a, int32_t b) { return row[a] > row[b]; });
|
||||
for (int j = 0; j < topk; ++j)
|
||||
std::fprintf(out, "\t%d:%.6f", order[(size_t) j], (double) row[order[(size_t) j]] - lse);
|
||||
}
|
||||
std::fprintf(out, "\n");
|
||||
}
|
||||
std::fflush(out);
|
||||
return true;
|
||||
|
||||
@@ -94,6 +94,9 @@ bool supported(int t) {
|
||||
case GGML_TYPE_Q2_0: case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S:
|
||||
case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS:
|
||||
case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9)
|
||||
#ifdef STRATA_MMQ_KQUANTS
|
||||
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: // Unsloth's UD-Q4_K_XL experts (CUDA)
|
||||
#endif
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
@@ -143,6 +146,11 @@ void Context::run(const Product& p, void* stream) {
|
||||
case GGML_TYPE_IQ4_NL: mul_mat_q_case<GGML_TYPE_IQ4_NL>(ctx, a, s); break;
|
||||
case GGML_TYPE_IQ4_XS: mul_mat_q_case<GGML_TYPE_IQ4_XS>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q8_0: mul_mat_q_case<GGML_TYPE_Q8_0>(ctx, a, s); break;
|
||||
#ifdef STRATA_MMQ_KQUANTS
|
||||
case GGML_TYPE_Q4_K: mul_mat_q_case<GGML_TYPE_Q4_K>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
|
||||
#endif
|
||||
default:
|
||||
std::fprintf(stderr, "prefill mmq: type %d is not covered\n", (int) t);
|
||||
std::exit(1);
|
||||
|
||||
@@ -525,8 +525,15 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
|
||||
m.stager = std::make_unique<Stager>();
|
||||
const int hw = (int) std::thread::hardware_concurrency();
|
||||
const char* stv = std::getenv("STRATA_STAGER_THREADS"); // D-5: the host copy threads of unpinned blobs
|
||||
if (!m.stager->init((size_t) MAXBLOB(), stv ? std::clamp(std::atoi(stv), 1, 32) : std::max(2, std::min(4, hw / 4))))
|
||||
ok = false;
|
||||
// A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the
|
||||
// SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s
|
||||
// instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source)
|
||||
bool files = false;
|
||||
for (int64_t l = 0; src != nullptr && !files && l < g.n_layers; ++l)
|
||||
for (int64_t e = 0; !files && e < g.n_expert; ++e) files = src->transient(l, e);
|
||||
const int threads = stv ? std::clamp(std::atoi(stv), 1, 32) : files ? 32 : std::max(2, std::min(4, hw / 4));
|
||||
if (files && std::getenv("STRATA_STAGER_RING") == nullptr) m.stager->kRing = 4 * threads;
|
||||
if (!m.stager->init((size_t) MAXBLOB(), threads)) ok = false;
|
||||
}
|
||||
m.steps_host.resize(T * strata::kernels::kStepCount);
|
||||
m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1);
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
// prefill_mmq_kquant_test - the prompt path's MMQ products for the expert formats of Unsloth's UD-Q4_K_XL (Q4_K and
|
||||
// Q5_K gate/up at 1280 x 2560, Q5_1 and Q8_0 down at 2560 x 640), on synthetic weights quantized by ggml's own
|
||||
// reference quantizers, against a double-precision product of ggml's dequantized weights. MMQ rounds the activations
|
||||
// to q8_1 by design, so this is a screen for layout, stride, expert-bound and row-id errors (the bounds of
|
||||
// tests/hip/prefill_mmq_parity.cpp), not a bit-exactness test. Several experts per product, permuted rows, an
|
||||
// all-zero row; the formats the build does not cover (Q6_K) must say so.
|
||||
#include "strata/prefill/moe_mmq.hpp"
|
||||
|
||||
#include "ggml.h"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
namespace mmq = strata::prefill::mmq;
|
||||
|
||||
void ck(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
|
||||
}
|
||||
|
||||
struct Dev {
|
||||
void* p = nullptr;
|
||||
explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); }
|
||||
~Dev() { cudaFree(p); }
|
||||
Dev(const Dev&) = delete;
|
||||
Dev& operator=(const Dev&) = delete;
|
||||
};
|
||||
|
||||
std::vector<uint8_t> make_matrix(ggml_type t, int64_t rows, int64_t cols, int expert, int trial) {
|
||||
const auto* tr = ggml_get_type_traits(t);
|
||||
if (tr == nullptr || tr->from_float_ref == nullptr) throw std::runtime_error("no reference quantizer");
|
||||
const size_t rb = ggml_row_size(t, cols);
|
||||
std::vector<uint8_t> out((size_t) rows * rb);
|
||||
std::vector<float> row((size_t) cols);
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
for (int64_t k = 0; k < cols; ++k) {
|
||||
const int code = (int) ((k * 37 + r * 19 + expert * 23 + trial * 11) % 101) - 50;
|
||||
row[(size_t) k] = 0.025f * std::sin(0.013f * (float) (k + 1) + 0.17f * (float) r + 0.31f * (float) expert) +
|
||||
0.0015f * (float) code;
|
||||
}
|
||||
tr->from_float_ref(row.data(), out.data() + (size_t) r * rb, cols);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<float> make_x(int rows, int64_t cols, int trial) {
|
||||
std::vector<float> x((size_t) rows * (size_t) cols);
|
||||
for (int r = 0; r < rows; ++r)
|
||||
for (int64_t k = 0; k < cols; ++k)
|
||||
x[(size_t) r * (size_t) cols + (size_t) k] =
|
||||
0.45f * std::sin(0.009f * (float) (k + 1) + 0.23f * (float) r + 0.07f * (float) trial) +
|
||||
0.17f * std::cos(0.021f * (float) (k + 3) - 0.19f * (float) r) +
|
||||
0.002f * (float) (((k * 7 + r * 13 + trial * 5) % 19) - 9);
|
||||
std::fill(x.end() - cols, x.end(), 0.0f); // an all-zero row: exactly zero out
|
||||
return x;
|
||||
}
|
||||
|
||||
std::vector<int32_t> perm(int n, int shift, bool reverse) {
|
||||
std::vector<int32_t> p((size_t) n);
|
||||
for (int i = 0; i < n; ++i) p[(size_t) i] = (int32_t) (((reverse ? n - 1 - i : i) + shift) % n);
|
||||
return p;
|
||||
}
|
||||
|
||||
// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them)
|
||||
void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, int64_t out_rows, int64_t cols,
|
||||
const std::vector<int>& counts, int trial) {
|
||||
if (!mmq::supported((int) t)) throw std::runtime_error(std::string(name) + ": not covered by this build");
|
||||
const int n = (int) counts.size(), rows = std::accumulate(counts.begin(), counts.end(), 0);
|
||||
std::vector<int32_t> bounds((size_t) n + 1, 0);
|
||||
for (int e = 0; e < n; ++e) bounds[(size_t) e + 1] = bounds[(size_t) e] + counts[(size_t) e];
|
||||
const auto src = perm(rows, trial + 1, false), dst = perm(rows, trial + 2, true);
|
||||
const std::vector<float> x = make_x(rows, cols, trial);
|
||||
const size_t eb = mmq::matrix_bytes((int) t, out_rows, cols);
|
||||
if (eb != (size_t) out_rows * ggml_row_size(t, cols)) throw std::runtime_error(std::string(name) + ": matrix_bytes");
|
||||
std::vector<std::vector<uint8_t>> ws;
|
||||
std::vector<uint8_t> w((size_t) n * eb + 4096, 0);
|
||||
for (int e = 0; e < n; ++e) {
|
||||
ws.push_back(make_matrix(t, out_rows, cols, e, trial));
|
||||
std::copy(ws.back().begin(), ws.back().end(), w.begin() + (ptrdiff_t) ((size_t) e * eb));
|
||||
}
|
||||
Dev dx(x.size() * 4), dsrc((size_t) rows * 4), ddst((size_t) rows * 4), db(bounds.size() * 4), dw(w.size()),
|
||||
dxq(mmq::q8_bytes(rows, cols)), dy((size_t) rows * (size_t) out_rows * 4);
|
||||
ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
|
||||
ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src");
|
||||
ck(cudaMemcpy(ddst.p, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst");
|
||||
ck(cudaMemcpy(db.p, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "bounds");
|
||||
ck(cudaMemcpy(dw.p, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
|
||||
ck(cudaMemset(dy.p, 0xff, (size_t) rows * (size_t) out_rows * 4), "sentinel");
|
||||
mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, dxq.p, (int) t, cols, cols, rows, s);
|
||||
mmq::Product p;
|
||||
p.w = dw.p; p.type = (int) t; p.w_rows = out_rows; p.w_cols = cols; p.expert_bytes = eb; p.n = n;
|
||||
p.xq = dxq.p; p.bounds = (const int32_t*) db.p; p.ids = (const int32_t*) ddst.p; p.total_rows = rows;
|
||||
p.max_rows = *std::max_element(counts.begin(), counts.end()); p.dst = (float*) dy.p; p.ld_dst = out_rows;
|
||||
ctx.run(p, s);
|
||||
ck(cudaGetLastError(), "launch");
|
||||
ck(cudaStreamSynchronize(s), "sync");
|
||||
std::vector<float> got((size_t) rows * (size_t) out_rows);
|
||||
ck(cudaMemcpy(got.data(), dy.p, got.size() * 4, cudaMemcpyDeviceToHost), "y");
|
||||
|
||||
const auto* tr = ggml_get_type_traits(t);
|
||||
std::vector<float> ref(got.size(), 0.0f), wd((size_t) out_rows * (size_t) cols);
|
||||
for (int e = 0; e < n; ++e) {
|
||||
const size_t rb = ggml_row_size(t, cols);
|
||||
for (int64_t o = 0; o < out_rows; ++o)
|
||||
tr->to_float(ws[(size_t) e].data() + (size_t) o * rb, wd.data() + (size_t) o * (size_t) cols, cols);
|
||||
for (int r = bounds[(size_t) e]; r < bounds[(size_t) e + 1]; ++r) {
|
||||
const float* xr = x.data() + (size_t) src[(size_t) r] * (size_t) cols;
|
||||
for (int64_t o = 0; o < out_rows; ++o) {
|
||||
double acc = 0;
|
||||
const float* wr = wd.data() + (size_t) o * (size_t) cols;
|
||||
for (int64_t k = 0; k < cols; ++k) acc += (double) wr[k] * xr[k];
|
||||
ref[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o] = (float) acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
double err2 = 0, ref2 = 0, max_abs = 0, zero_max = 0;
|
||||
for (size_t i = 0; i < got.size(); ++i) {
|
||||
if (!std::isfinite(got[i])) throw std::runtime_error(std::string(name) + ": unwritten or non-finite output");
|
||||
const double d = (double) got[i] - ref[i];
|
||||
err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, std::fabs(d));
|
||||
}
|
||||
for (int r = 0; r < rows; ++r)
|
||||
if (src[(size_t) r] == rows - 1) // the zero row
|
||||
for (int64_t o = 0; o < out_rows; ++o)
|
||||
zero_max = std::max(zero_max, (double) std::fabs(got[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o]));
|
||||
const double rms = std::sqrt(ref2 / (double) ref.size()), rel = std::sqrt(err2 / (double) ref.size()) / rms;
|
||||
std::printf("%-22s rows %2d experts %d ref_rms %.4g rel_l2 %.5f max/rms %.4f zero row %.3g\n", name, rows, n, rms,
|
||||
rel, max_abs / rms, zero_max);
|
||||
if (rel > 0.04 || max_abs / rms > 0.35 || zero_max > std::max(1e-5, 1e-4 * rms))
|
||||
throw std::runtime_error(std::string(name) + ": outside the screen");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
try {
|
||||
if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; }
|
||||
if (mmq::supported(GGML_TYPE_Q6_K)) throw std::runtime_error("Q6_K should not be covered");
|
||||
cudaStream_t s = nullptr;
|
||||
ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
|
||||
{
|
||||
mmq::Context ctx;
|
||||
const std::vector<std::vector<int>> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}, {17}};
|
||||
int trial = 0;
|
||||
for (const auto& counts : batches) {
|
||||
const std::string tag = "-" + std::to_string(trial);
|
||||
product(ctx, s, ("Q4_K gate/up" + tag).c_str(), GGML_TYPE_Q4_K, 1280, 2560, counts, trial);
|
||||
product(ctx, s, ("Q5_K gate/up" + tag).c_str(), GGML_TYPE_Q5_K, 1280, 2560, counts, trial + 5);
|
||||
product(ctx, s, ("Q5_1 down" + tag).c_str(), GGML_TYPE_Q5_1, 2560, 640, counts, trial + 9);
|
||||
product(ctx, s, ("Q8_0 down" + tag).c_str(), GGML_TYPE_Q8_0, 2560, 640, counts, trial + 13);
|
||||
++trial;
|
||||
}
|
||||
}
|
||||
ck(cudaStreamDestroy(s), "destroy");
|
||||
std::printf("prefill MMQ K-quant screen passed\n");
|
||||
return 0;
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "prefill MMQ K-quant screen failed: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Tests for setup.py's experimental Unsloth UD-Q4_K_XL choice (docs/UNSLOTH_Q4.md): the four pinned shards with
|
||||
their sizes and SHA-256, the RAM budget from the PC's RAM, the pack with --compat-bf16 (never experts.bin), the
|
||||
engine version it needs, one GPU, no images. Mocked - no GPU, no downloads, nothing written outside a temp folder.
|
||||
|
||||
python -m unittest tools.test_setup_unsloth
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import setup # noqa: E402
|
||||
|
||||
M = "UD-Q4_K_XL"
|
||||
REV = "38bb39ee97821de2c9009abb7e93950eec396e66"
|
||||
|
||||
|
||||
class Pins(unittest.TestCase):
|
||||
def test_the_four_shards(self):
|
||||
fam = setup.FAMILIES["unsloth"]
|
||||
names = [fam["file"].format(q=M, i=i) for i in range(1, fam["shards"] + 1)]
|
||||
self.assertEqual(names, list(setup.UNSLOTH_SHARDS))
|
||||
self.assertEqual(sum(b for b, _ in setup.UNSLOTH_SHARDS.values()), 111334654784)
|
||||
for _, sha in setup.UNSLOTH_SHARDS.values():
|
||||
self.assertRegex(sha, r"^[0-9a-f]{64}$")
|
||||
self.assertEqual(fam["hf"].format(q=M),
|
||||
f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/")
|
||||
self.assertEqual(setup.MODELS[M]["families"], ("unsloth",)) # no other family lists it
|
||||
self.assertTrue(fam["experimental"])
|
||||
self.assertEqual(list(setup.FAMILIES)[0], "qwen") # not the default choice
|
||||
|
||||
def test_not_in_the_other_families(self):
|
||||
for f in ("qwen", "swift", "coder"):
|
||||
self.assertNotIn(M, [m for m in setup.MODELS if f in setup.MODELS[m].get("families", ("qwen", "swift"))])
|
||||
|
||||
|
||||
class Budget(unittest.TestCase):
|
||||
def test_ram_less_24(self):
|
||||
self.assertEqual(setup.resident_budget_gib(M, 63.7), 40) # this PC (64 GB): the measured setting
|
||||
self.assertEqual(setup.resident_budget_gib(M, 47.8), 24)
|
||||
self.assertEqual(setup.resident_budget_gib(M, 96), 71) # at most all of the experts (77 GB = 71.7 GiB)
|
||||
self.assertEqual(setup.resident_budget_gib(M, 256), 71)
|
||||
self.assertEqual(setup.resident_budget_gib(M, 20), 8) # the floor
|
||||
self.assertEqual(setup.resident_budget_gib(M, 63.7, 1.7), 38) # a KV cache streamed to RAM comes out of it
|
||||
|
||||
|
||||
def quiet(fn, *args):
|
||||
"""-> (exit code or None, printed text)."""
|
||||
out = io.StringIO()
|
||||
code = None
|
||||
with contextlib.redirect_stdout(out):
|
||||
try:
|
||||
code = fn(*args)
|
||||
except SystemExit as e:
|
||||
code = e.code
|
||||
return code, out.getvalue()
|
||||
|
||||
|
||||
class Sha256(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.f = Path(self.tmp.name) / "x-00002-of-00004.gguf"
|
||||
self.f.write_bytes(b"strata" * 1000)
|
||||
self.sha = hashlib.sha256(self.f.read_bytes()).hexdigest()
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_good_file_marked_once(self):
|
||||
code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha)
|
||||
self.assertIsNone(code, out)
|
||||
self.assertIn(f"sha256 {self.sha}", self.f.with_name(self.f.name + ".done").read_text())
|
||||
with mock.patch("hashlib.sha256", side_effect=AssertionError("hashed again")):
|
||||
code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha) # the mark says it was checked
|
||||
self.assertIsNone(code, out)
|
||||
|
||||
def test_a_download_mark_alone_is_not_enough(self):
|
||||
setup.mark(self.f) # the download's finish mark (a date)
|
||||
with mock.patch("hashlib.sha256", wraps=hashlib.sha256) as h:
|
||||
code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha)
|
||||
self.assertIsNone(code, out)
|
||||
self.assertTrue(h.called)
|
||||
|
||||
def test_wrong_hash_deletes_it(self):
|
||||
setup.mark(self.f)
|
||||
code, out = quiet(setup.verify_sha256, self.f, 6000, "0" * 64)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("wrong SHA-256", out)
|
||||
self.assertFalse(self.f.exists())
|
||||
self.assertFalse(self.f.with_name(self.f.name + ".done").exists()) # downloaded again next time
|
||||
|
||||
def test_wrong_size(self):
|
||||
code, out = quiet(setup.verify_sha256, self.f, 6001, self.sha)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("6,000 bytes, not 6,001", out)
|
||||
self.assertTrue(self.f.exists())
|
||||
|
||||
|
||||
class Config(unittest.TestCase):
|
||||
def test_choices_from_config(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
for name, family, model in (("strata-unsloth-ud-q4_k_xl.json", "unsloth", M),
|
||||
("strata-swift-iq3_xxs.json", "swift", "IQ3_XXS"),
|
||||
("strata-iq3_s.json", "qwen", "IQ3_S"),
|
||||
("strata-coder-iq1_m.json", "coder", "IQ1_M")):
|
||||
p = Path(t) / name
|
||||
p.write_text(json.dumps({"args": ["--max-context", "8192"]}))
|
||||
ch = setup.choices_from_config(p)
|
||||
self.assertEqual((ch["family"], ch["model"]), (family, model), name)
|
||||
|
||||
|
||||
class FakeGGUF:
|
||||
"""gguf_reader.GGUFFile: shard 2 holds the PLE table."""
|
||||
def __init__(self, path):
|
||||
names = ["per_layer_token_embd.weight"] if "00002-of" in str(path) else ["blk.0.ffn_up_exps.weight"]
|
||||
self.tensors = [types.SimpleNamespace(name=n) for n in names]
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
"""setup.main() for the Unsloth choice, every outside effect mocked."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.t = Path(self.tmp.name)
|
||||
(self.t / "data" / "mtp" / "rt").mkdir(parents=True)
|
||||
(self.t / "data" / "mtp" / "rt" / "experts.bin").write_bytes(b"")
|
||||
self.downloads, self.runs, self.verified = [], [], []
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def main(self, argv, ram=63.7, version="0.1.32", n_gpus=1):
|
||||
eng = self.t / "engine"
|
||||
eng.mkdir(exist_ok=True)
|
||||
(eng / "BUILD.json").write_text(json.dumps({"version": version, "source": "local"}))
|
||||
found = [{"index": i, "name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.9, "arch": "120", "driver": "580.97"}
|
||||
for i in range(n_gpus)]
|
||||
|
||||
def fake_download(url, dst, what=None):
|
||||
self.downloads.append(url)
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
dst.write_bytes(b"")
|
||||
setup.mark(dst)
|
||||
|
||||
def fake_run(cmd, *a, **k):
|
||||
self.runs.append([str(x) for x in cmd])
|
||||
|
||||
patches = [
|
||||
mock.patch.object(setup, "ROOT", self.t),
|
||||
mock.patch.object(setup, "GPU_PICK", None),
|
||||
mock.patch.object(setup, "data_folder", lambda d: (self.t / "data", [])),
|
||||
mock.patch.object(setup, "installed_configs", lambda: []),
|
||||
mock.patch.object(setup, "gpus", lambda: found),
|
||||
mock.patch.object(setup, "amd_gpus", lambda: []),
|
||||
mock.patch.object(setup, "ram_gb", lambda: ram),
|
||||
mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)),
|
||||
mock.patch.object(setup, "page_file_gb", lambda: 16.0),
|
||||
mock.patch.object(setup, "free_gb", lambda p: 500.0),
|
||||
mock.patch.object(setup, "pip_install", lambda *a, **k: None),
|
||||
mock.patch.object(setup, "get_llama_cpp", lambda: self.t / "llama.cpp"),
|
||||
mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng),
|
||||
mock.patch.object(setup, "download", fake_download),
|
||||
mock.patch.object(setup, "check_shards", lambda shards: None),
|
||||
mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))),
|
||||
mock.patch.object(setup, "run", fake_run),
|
||||
mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None),
|
||||
mock.patch.object(setup, "write_run_script", lambda tag, cfg, port: self.t / f"start-{tag}.bat"),
|
||||
mock.patch.object(setup, "saved_calibration", lambda cfg: None),
|
||||
mock.patch.object(setup, "start", mock.Mock(side_effect=AssertionError("started"))),
|
||||
mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}),
|
||||
mock.patch.object(sys, "argv", ["setup.py", "--family", "unsloth", "--model", M, "--yes", "--no-start",
|
||||
"--models-dir", str(self.t / "models"), *argv]),
|
||||
mock.patch("builtins.input", mock.Mock(side_effect=AssertionError("asked"))),
|
||||
]
|
||||
with contextlib.ExitStack() as st:
|
||||
for p in patches:
|
||||
st.enter_context(p)
|
||||
code, out = quiet(setup.main)
|
||||
cfg = self.t / "strata-unsloth-ud-q4_k_xl.json"
|
||||
return code, out, (json.loads(cfg.read_text()) if cfg.exists() else None)
|
||||
|
||||
def test_install(self):
|
||||
code, out, cfg = self.main(["--context", "8192"])
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertIn("EXPERIMENTAL", out)
|
||||
base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/"
|
||||
self.assertEqual(self.downloads, [base + n for n in setup.UNSLOTH_SHARDS]) # no image encoder
|
||||
self.assertEqual([v[0] for v in self.verified], list(setup.UNSLOTH_SHARDS))
|
||||
self.assertEqual([v[1:] for v in self.verified], list(setup.UNSLOTH_SHARDS.values()))
|
||||
packs = [r for r in self.runs if r[1].endswith("iq_pack.py")]
|
||||
self.assertEqual(len(packs), 1, self.runs)
|
||||
self.assertIn("--compat-bf16", packs[0])
|
||||
self.assertNotIn("--experts-bin", packs[0])
|
||||
self.assertTrue(packs[0][packs[0].index("--gguf") + 1].endswith("UD-Q4_K_XL-00001-of-00004.gguf"))
|
||||
args = cfg["args"]
|
||||
self.assertEqual(args[args.index("--resident-budget-gib") + 1], "40")
|
||||
self.assertTrue(args[args.index("--native") + 1].endswith("-00001-of-00004.gguf"))
|
||||
for flag in ("--ple-gguf", "--mmap-experts", "--resident-experts", "--vision", "--control-vector-scaled",
|
||||
"--kv-resident"):
|
||||
self.assertNotIn(flag, args)
|
||||
self.assertEqual(args[args.index("--max-context") + 1], "8192")
|
||||
self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-q4_k_xl")
|
||||
self.assertNotIn("vision", cfg)
|
||||
|
||||
def test_recommended_context_on_12_gb(self):
|
||||
code, out, cfg = self.main([])
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--max-context") + 1], "8192")
|
||||
|
||||
def test_more_ram_bigger_budget(self):
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=95.8)
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "71")
|
||||
|
||||
def test_kv_streaming_comes_out_of_the_budget(self):
|
||||
code, out, cfg = self.main(["--context", "131072"])
|
||||
self.assertEqual(code, 0, out)
|
||||
args = cfg["args"]
|
||||
self.assertIn("--kv-resident", args)
|
||||
kv_gb = 131072 * 13 * 1056 / 1e9
|
||||
self.assertEqual(args[args.index("--resident-budget-gib") + 1], str(40 - int(-(-kv_gb // 1))))
|
||||
|
||||
def test_old_engine_stops_before_the_download(self):
|
||||
code, out, cfg = self.main(["--context", "8192"], version="0.1.31")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("needs engine 0.1.32 or newer; this one is 0.1.31", out)
|
||||
self.assertEqual(self.downloads, [])
|
||||
self.assertIsNone(cfg)
|
||||
|
||||
def test_too_little_ram(self):
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=31.9)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("needs 48 GB of RAM or more", out)
|
||||
self.assertEqual(self.downloads, [])
|
||||
|
||||
def test_one_gpu_and_no_images(self):
|
||||
code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--vision", "yes", "--low-ram", "on"],
|
||||
n_gpus=2)
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertIn("runs on one GPU", out)
|
||||
self.assertIn("images are not available with UD-Q4_K_XL", out)
|
||||
self.assertIn("--low-ram on does not apply", out)
|
||||
self.assertNotIn("layer_split", cfg)
|
||||
self.assertNotIn("--vision", cfg["args"])
|
||||
self.assertNotIn("--mmap-experts", cfg["args"])
|
||||
self.assertFalse(any("--experts-bin" in r for r in self.runs))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user