diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d46ee5a5..39b29fc5 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -921,17 +921,18 @@ print(r.choices[0].message.content) ``` Set `limit.context` to the context you chose in setup: OpenCode compacts the conversation before it gets there. - Keep `limit.output` well under it: a request whose prompt plus `max_tokens` runs past the context is refused (see - **Context** below), or add `"fit_max_tokens": true` to `strata-.json`. For a hard cap on the thinking, add + Keep `limit.output` well under it: a request whose prompt plus `max_tokens` runs past the context has its `max_tokens` + shortened to the room left (see **Context** below). For a hard cap on the thinking, add `"reasoning_budget_tokens": N` to `strata-.json` (see above). - **Claude Code** (Strata 0.1.17 or newer): set `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` and `ANTHROPIC_MODEL` to a Claude model name it knows (it refuses names it doesn't; Strata ignores the name), plus any `ANTHROPIC_AUTH_TOKEN` (or your `api_key`, if you set one). - **Codex CLI** (0.1.39): see [the Responses API](#the-responses-api-and-codex-cli) below. - **Context.** Chosen in setup (8K-262K). Requests longer than that are refused, never silently cut. A request whose - `max_tokens` would run past the context is refused too (400); agents that always ask for their full output cap - can instead get it shortened to the room left: add `"fit_max_tokens": true` to `strata-.json` (or pass - `--fit-max-tokens` to `serve/server.py`). A prompt that leaves no room at all is still refused. + `max_tokens` would run past the context is answered with `max_tokens` shortened to the room left (agents such as + Claude Code ask for 32,000 on every request); the thinking budget follows the shortened cap. For the strict llama.cpp + behaviour (400) set `"fit_max_tokens": false` in `strata-.json` or pass `--no-fit-max-tokens` to + `serve/server.py`. A prompt that leaves no room at all is always refused. - **Model aliases** (0.1.32). `"aliases": ["qwen", "local-model"]` in `strata-.json` lists the model under those names too in `/v1/models` (each with its own `id`, and in the model's `aliases`), like llama-server's `--alias`; a request naming one is answered under that name. Any other name is still served, as before. diff --git a/docs/MODELS.md b/docs/MODELS.md index 9427d7b1..d07691e2 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -164,6 +164,27 @@ NVIDIA, and AMD (experimental); not Intel Arc or the Mac. Images are off. Detail START-HERE.bat --setup --family gyro --model Gyro-S ``` + + +### NVIDIA's retrained 4-bit model (NVFP4-QAD) + +NVIDIA retrained Qwen3.8-Flash-Next for 4-bit experts (quantization-aware distillation) and published it as +[Qwen3.8-Flash-Next-FP4-Local](https://huggingface.co/nvidia/Qwen3.8-Flash-Next-FP4-Local). In setup's NVFP4 family it is +the size **NVFP4-QAD**. It is not a ready-made pack: setup downloads NVIDIA's files as they are (102 GB) and **turns them +into a Strata pack on your PC** (once, 20-40 minutes; about 110 GB more disk while it runs, and the 102 GB can be deleted +afterwards). Nothing of NVIDIA's weights is redistributed by Strata. + +| Size | Download | Memory it needs | In plain words | +| --- | ---: | ---: | --- | +| **NVFP4-QAD** | 102 GB (+110 GB of disk to prepare) | like NVFP4: ~80 GB of RAM keeps every expert in RAM | NVIDIA's FP4, trained for FP4 - slightly faster on short prompts than NVFP4 (GPTQ is the best quality of the NVFP4 versions); RTX 50 cards have FP4 tensor cores, other NVIDIA cards run it at 8-bit precision | + +NVIDIA cards only. Images are off for now. Its licenses are the NVIDIA Open Model Agreement and Qwen's Community License. +Technical details and measurements: [NVFP4.md](NVFP4.md#nvidias-fp4-local-checkpoint). + +``` +START-HERE.bat --setup --family nvfp4 --model NVFP4-QAD +``` + ### OrcaRouter Uncensored IQ3_XXS For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](ORCA.md). It needs an diff --git a/docs/NVFP4.md b/docs/NVFP4.md index c52c98a9..a5628894 100644 --- a/docs/NVFP4.md +++ b/docs/NVFP4.md @@ -217,3 +217,30 @@ guarded (`GGML_USE_HIP`). Neither was built for HIP here. - `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. + +## NVIDIA's FP4-Local checkpoint + +`nvidia/Qwen3.8-Flash-Next-FP4-Local` (setup size **NVFP4-QAD**) is NVIDIA's own retrained 4-bit model: ModelOpt 0.47 +safetensors, experts retrained by quantization-aware distillation. Strata reads it by converting it on the user's PC; +nothing of NVIDIA's weights is redistributed (licenses: NVIDIA Open Model Agreement and Qwen Community License 1.0). + +What the checkpoint holds, and what `tools/nvfp4_local_pack.py` does with it: + +| In the checkpoint | Becomes | +| --- | --- | +| routed experts: NVFP4 (E2M1, E4M3 scale per 16, F32 scale per tensor); the scales stored in NVIDIA's "CSF" form (`.nvfp4_csf_fixed` U8 + `.nvfp4_csf_exceptions` U32) | the scales are decoded to the plain E4M3 matrix (byte-exact; the format is the one vLLM's loader documents), then repacked exactly like every other NVFP4 pack: `experts.bin` with the same 36-byte super-blocks and the 16-byte scale tail. Checked: 304 complete experts and the whole `experts.bin` (SHA-256) equal the route through a full GGUF | +| attention, GDN projections, shared experts, indexer: MXFP8 (E4M3 values, E8M0 scale per 32) | dequantized exactly, then Q8_0 (same 32-value blocks; +0.6% RMS on top of MXFP8's own ~3%), or BF16 for the small projections the BF16 kernels read | +| n-gram (PLE) table, 26.8 GiB: NVFP4 rows of 160 values | a one-tensor GGUF of 90-byte rows (80 B codes + 10 E4M3 scales, one F32 for the table), read by the new PLE format `NVFP4` (`strata.ple.format = nvfp4x16`) in `ngram.cpp`; same row size as IQ4_NL | +| MTP head: NVFP4 experts, BF16 rest | a Q2_0 draft layer built with `mtp_pack.py` / `mtp_rt.py` (88.7% of drafts accepted over 225 test requests) | +| vision tower | not converted yet (text only) | + +`python tools/nvfp4_local_pack.py prepare --model --out ` runs every step (setup does this): the n-gram +table, the dense GGUF (no experts), the pack (experts written straight from the checkpoint) and the draft layer. It needs +about 110 GB of free disk beside the 102 GB download, which can be deleted afterwards. On a Threadripper PRO with the files +on NVMe it took about 12 minutes. + +Measured on an RTX PRO 5000 72 GB (Blackwell), 128K context, int8 KV, every expert in VRAM (`tools/strata_bench.py`): +decode 159 tokens/s (median of chat answers, 137-216), 4K prompt 3,981 tokens/s, 16K 4,813, 32K 4,916 (first token 6.6 s), +agent session 151 tokens/s; the engine holds 69 GB of RAM beside 72 GB of VRAM. Quality is in the table below +(`tools/quant_quality.py`, set v1, against Unsloth's Q8_0): top-1 90.5%, mean KL 0.085, perplexity 3.95 (Q8_0: 4.05). +This is a retrained model, so its distance to the original's Q8_0 includes real weight changes, not only rounding. diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index 207707d0..4452b4f6 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -49,20 +49,21 @@ inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: inline constexpr int PLE_ROW_BYTES_Q5_1 = (PLE_HEAD_DIM / 32) * 24; // 120: a Q5_1 row (a Q5_K_M finetune) inline constexpr int PLE_ROW_BYTES_Q8_0 = (PLE_HEAD_DIM / 32) * 34; // 170: a Q8_0 row (UD-Q6_K_XL, Swift-1.5 Q4_K_L) inline constexpr int PLE_ROW_BYTES_BF16 = PLE_HEAD_DIM * 2; // 320: a BF16 row, two bytes a value +inline constexpr int PLE_ROW_BYTES_NVFP4 = PLE_HEAD_DIM / 2 + PLE_HEAD_DIM / 16; // 90: 80 B of E2M1 codes + 10 E4M3 block scales inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_BF16; // the widest row any format in `ple_formats()` has /// THE FORMATS OF THE TABLE, ONE ROW EACH. A table type is one entry here (its GGUF type name, the bytes of one /// 160-value row, how to turn a row into floats) and nothing else: `PleTable::open`, `format()`, the reader's row size, /// the error string and the buffers' size all read this list, so a new format cannot be in one switch and missing from /// another. A row is always `PLE_HEAD_DIM` = 160 values = 5 blocks of 32 for the block formats. -enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0, Q4_0, BF16 }; +enum class PleFormat : uint8_t { IQ4_NL, Q5_0, F8_E4M3, Q5_1, Q8_0, Q4_0, BF16, NVFP4 }; struct PleFormatInfo { PleFormat id; const char* name; ///< what `PleTable::format()` returns const char* gguf_type; ///< `TensorInfo::type_name()` of the table tensor ("I8" for F8_E4M3: GGUF has no FP8 type) uint32_t row_bytes; ///< bytes of one 160-value row in the file - bool needs_scale; ///< the table has one scale in the GGUF metadata (`strata.ple.scale`), F8_E4M3 only + bool needs_scale; ///< the table has one scale in the GGUF metadata (`strata.ple.scale`): F8_E4M3 and NVFP4 void (*dequant)(const uint8_t* row, float scale, float* out160); }; diff --git a/serve/runconfig.py b/serve/runconfig.py index 842554ab..62aea1bb 100644 --- a/serve/runconfig.py +++ b/serve/runconfig.py @@ -23,7 +23,7 @@ EDITABLE = [ ("sampling.top_k", ("sampling", "1..64"), "Default top_k for requests that send none (1-64)"), ("sampling.min_p", ("sampling", "0<=x<=1"), "Default min_p for requests that send none"), ("reasoning_budget_tokens", "int>=0", "Cap the thinking of every request at this many tokens (0 or empty: no cap)"), - ("fit_max_tokens", "bool", "Shorten a max_tokens that does not fit the context instead of answering 400"), + ("fit_max_tokens", "bool", "Shorten a max_tokens that does not fit the context (on by default); off: answer 400 like llama.cpp"), ("anthropic_thinking", ("enum", ["model", "on_request"]), "Anthropic requests that do not ask for thinking: think as the model does (model) or not (on_request)"), ("effort_position", ("enum", ["start", "end"]), diff --git a/serve/server.py b/serve/server.py index 229e30b9..f1edd6b9 100644 --- a/serve/server.py +++ b/serve/server.py @@ -14,7 +14,10 @@ Images (optional, when the config has a "vision" entry): OpenAI image_url parts data, http(s) URLs or local file paths) go through `strata-vision` (the model's mmproj file) and reach the engine as embeddings (`GENI`). JPEG/PNG/BMP/GIF go straight in; WebP, TIFF, AVIF, ... (agents like omp send WebP) are converted to PNG first with Pillow. -Requests whose prompt plus max tokens exceed the engine's context are REJECTED with 400, never truncated. +A request whose prompt alone does not fit the engine's context is REJECTED with 400, never truncated. When the prompt +fits but prompt plus max tokens does not (Claude Code asks for 32000, the Harness for 16384), max tokens is shortened to +the room left (less CTX_SLACK) and the thinking budget follows it; `--no-fit-max-tokens` / `"fit_max_tokens": false` +brings back the strict 400 of llama.cpp. An unset (or 0, or -1) max tokens means "unlimited": whatever the prompt leaves of the context. The engine boundary is `Engine.generate(prompt_ids, max_new, sampling, cancel) -> iterator of token ids`. @@ -3271,10 +3274,10 @@ def slot_save_dir(value, base: str | None = None) -> str: class Service: def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", vision: Vision | None = None, sampling_defaults: dict | None = None, - fit_max_tokens: bool = False): + fit_max_tokens: bool = True): self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, vision self.literals = literal_tags(getattr(tokenizer, "control_tokens", ())) # texts that stay text inside a message - self.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400 + self.fit_max_tokens = fit_max_tokens # default: clamp the output cap to the room left; False (--no-fit-max-tokens) = 400 self.aliases: list[str] = [] # #297: other names of the model (the config's `aliases`) self.answer_room = True # 0.1.45: see ANSWER_ROOM_MIN_CAP (the config's "answer_room": false turns it off) self.reasoning_close_retry = False # #1053 (opt-in): close the thinking once when a reply ends inside it @@ -4298,7 +4301,9 @@ class Service: f"({ctx}); requests are never truncated. Send a smaller " f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the " "model's strata-.json to shorten it to the room left (#545)") - max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400 + print(f"[strata] max_tokens {max_new} shortened to {max(1, room)}: the prompt ({len(ids)} tokens) leaves that much " + f"of the context ({ctx}); \"fit_max_tokens\": false answers 400 instead", flush=True) + max_new = max(1, room) # a shorter completion beats a 400 (the default) if images: # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the # request: one refused after it (the engine starting, no room) left it in the vision directory for good, @@ -7426,7 +7431,10 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in ap.add_argument("--open", action="store_true", help="open the local page in the browser once the model is ready") ap.add_argument("--fit-max-tokens", action="store_true", help="clamp max_tokens to the remaining context instead of rejecting the request " - "(default: reject with 400, like llama.cpp; also \"fit_max_tokens\": true in the config)") + "(the default; kept so older scripts keep working)") + ap.add_argument("--no-fit-max-tokens", action="store_true", + help="answer 400 when prompt + max_tokens does not fit the context, like llama.cpp " + "(also \"fit_max_tokens\": false in the config). A prompt that alone does not fit is always 400") ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""), help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY. " "Several keys: separate them with commas (key1,key2), as llama.cpp does") @@ -7655,7 +7663,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"), model_name=default_model_name(cfg), vision=vision, sampling_defaults=sampling_defaults, - fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True) + fit_max_tokens=a.fit_max_tokens or (not a.no_fit_max_tokens and cfg.get("fit_max_tokens") is not False)) svc.launch_attestation = launch_attestation svc.offline = a.offline svc.max_queue = max_queue diff --git a/serve/test_context_overflow.py b/serve/test_context_overflow.py index 8c68b77e..ff26c0a1 100644 --- a/serve/test_context_overflow.py +++ b/serve/test_context_overflow.py @@ -85,6 +85,23 @@ class ContextOverflow(unittest.TestCase): else: self.assertEqual(set(error), {"type", "message"}) + def test_default_service_shortens_an_overshooting_budget_in_every_dialect(self): + # the Service default (fit_max_tokens on): a prompt that fits is answered, streaming or not; the prompt that + # alone leaves no room is the 400 of the strict test above + self.assertTrue(Service(self.engine, ByteTokenizer(), self.svc.template).fit_max_tokens) + self.svc.fit_max_tokens = True + for path, key in APIS: + for stream in (False, True): + with self.subTest(path=path, stream=stream): + if not stream: # (a 200 stream is SSE, not the JSON post() reads) + with mock.patch.object(self.engine, "generate", wraps=self.engine.generate) as generate: + status, _, body = self.post(path, key, 1024, CTX, stream) + self.assertEqual(status, 200, body) + self.assertEqual(generate.call_args.args[1], CTX - CTX_SLACK - 1024) + status, _, body = self.post(path, key, CTX - CTX_SLACK, CTX, stream) + self.assertEqual(status, 400, body) + self.assertIn("no room to answer", body["error"]["message"]) + def test_one_token_of_room_still_answers_but_zero_is_rejected(self): for path, key in APIS: for fit in (False, True): diff --git a/serve/test_monitor.py b/serve/test_monitor.py index 0c82cb0b..6c64b111 100644 --- a/serve/test_monitor.py +++ b/serve/test_monitor.py @@ -109,7 +109,11 @@ class Monitor(unittest.TestCase): self.assertNotIn("response", record) def test_error_and_engine_death_are_not_successes(self): + # a request the server refuses is an error record: the strict mode (fit_max_tokens off) refuses a max_tokens + # that overshoots the context, the default shortens it (serve/test_server.py MaxTokens) + self.svc.fit_max_tokens = False self.assertEqual(self.chat(max_tokens=20000)[0], 400) + self.svc.fit_max_tokens = True self.assertEqual(self.latest()["state"], "error") for api in ("openai", "anthropic"): for stream in (False, True): diff --git a/serve/test_server.py b/serve/test_server.py index 9dd296d5..b9789709 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -22,7 +22,7 @@ from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate, literal_tags, mark_think_literals, unmark_think_literals # noqa: E402 -from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, EngineNonFinite, GpuBusy, MockEngine, # noqa: E402 +from serve.server import (ANSWER_RESERVE_MIN, CTX_SLACK, ByteTokenizer, EngineDied, EngineNonFinite, GpuBusy, MockEngine, # noqa: E402 PP_DONE_TAIL, Service, StrataEngine, api_key_of, engine_args, key_matches, layer_split_value, prompt_progress, prompt_tokens_seen, @@ -137,14 +137,84 @@ class MaxTokens(unittest.TestCase): self.assertEqual(self.engine.last_max_new, want) self.assertEqual(ct, want) - def test_explicit_budget_over_the_context_is_rejected(self): - for api in ("openai", "anthropic"): + def responses(self, text="hi", **budget): + """-> (status, body, prompt tokens, completion tokens) for /v1/responses.""" + s, b = self.post("/v1/responses", {"model": "m", "input": text, **budget}) + u = b.get("usage", {}) if isinstance(b, dict) else {} + return s, b, u.get("input_tokens"), u.get("output_tokens") + + def call_any(self, api, text="hi", **budget): + """The three dialects; `budget` is given in the chat/messages spelling (max_tokens).""" + if api == "responses": + if "max_tokens" in budget: + budget["max_output_tokens"] = budget.pop("max_tokens") + return self.responses(text, **budget) + return self.call(api, text, **budget) + + def test_explicit_budget_over_the_context_is_shortened_to_the_room_left(self): + # Claude Code asks for max_tokens 32000 on every request: a prompt that fits must be answered, with the output + # cap cut to what the context has left (less CTX_SLACK), not refused. + for api in ("openai", "anthropic", "responses"): with self.subTest(api=api): - s, b, _, _ = self.call(api, max_tokens=CTX) - self.assertEqual(s, 400) - self.assertIn("exceeds the context", b["error"]["message"]) - self.assertIn("\"fit_max_tokens\": true", b["error"]["message"]) # #545: says how to get past it - self.assertRegex(b["error"]["message"], r"at most \d+ here") + s, b, pt, ct = self.call_any(api, max_tokens=CTX) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, CTX - CTX_SLACK - pt) + self.assertLessEqual(pt + ct, CTX - CTX_SLACK) + + def test_budget_that_fits_exactly_or_less_is_untouched(self): + for api in ("openai", "anthropic", "responses"): + _, _, pt, _ = self.call_any(api, max_tokens=1) + room = CTX - CTX_SLACK - pt + for budget in (50, room): + with self.subTest(api=api, budget=budget): + s, b, _, _ = self.call_any(api, max_tokens=budget) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, budget) # exactly what the client asked for + with self.subTest(api=api, budget="room + 1"): + s, b, _, _ = self.call_any(api, max_tokens=room + 1) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, room) # one over: cut by one + + def test_a_prompt_that_alone_does_not_fit_is_still_a_400(self): + _, _, pt0, _ = self.call("openai", max_tokens=1) + overhead = pt0 - len("hi") + for api in ("openai", "anthropic", "responses"): + with self.subTest(api=api): + s, b, _, _ = self.call_any(api, text="y" * (CTX - overhead + 50), max_tokens=CTX) + self.assertEqual(s, 400, b) + self.assertIn("exceeds the context window", b["error"]["message"]) + self.assertIn("no room to answer", b["error"]["message"]) + self.assertIn("never truncated", b["error"]["message"]) + + def test_thinking_budget_follows_the_shortened_cap(self): + # answer_room: thinking gets 3/4 of the cap; with the cap cut to the room left the budget is cut with it + import contextlib + import io + for api in ("openai", "anthropic", "responses"): + with self.subTest(api=api): + out = io.StringIO() + with contextlib.redirect_stdout(out): + s, b, pt, _ = self.call_any(api, max_tokens=CTX) + self.assertEqual(s, 200, b) + room = CTX - CTX_SLACK - pt + text = out.getvalue() + self.assertIn(f"shortened to {room}", text) + if api != "anthropic": # Anthropic thinks only when asked (#278) + cap = room - min(max(ANSWER_RESERVE_MIN, room // 4), room // 2) + self.assertIn(f"thinking limited to {cap} of max_tokens {room}", text) + + def test_strict_mode_keeps_the_llama_cpp_400(self): + self.svc.fit_max_tokens = False + try: + for api in ("openai", "anthropic", "responses"): + with self.subTest(api=api): + s, b, _, _ = self.call_any(api, max_tokens=CTX) + self.assertEqual(s, 400) + self.assertIn("exceeds the context", b["error"]["message"]) + self.assertIn("\"fit_max_tokens\": true", b["error"]["message"]) # #545: says how to get past it + self.assertRegex(b["error"]["message"], r"at most \d+ here") + finally: + self.svc.fit_max_tokens = True def test_unset_budget_with_a_near_full_prompt(self): _, _, pt0, _ = self.call("openai", max_tokens=1) diff --git a/setup.py b/setup.py index 0f888be0..42d94b86 100644 --- a/setup.py +++ b/setup.py @@ -256,8 +256,47 @@ NVFP4_REPOS = { "qwen-nvidia-nvfp4-dense.gguf": ("dense", 5992176896, "0f795ca0cbb908e0cf2b894b30103e21455b5a05346a7ef79da208540cfd2be3"), **_NVFP4_SHARED}}, } +NVFP4_FP4LOCAL_REPO = "nvidia/Qwen3.8-Flash-Next-FP4-Local" # NVIDIA's QAD checkpoint (ModelOpt safetensors), prepared here +# Not a ready-made pack: the safetensors (95 GiB) are downloaded as NVIDIA ships them and tools/nvfp4_local_pack.py prepare +# turns them into the pack, the dense GGUF, the n-gram table and the draft layer on this PC (nothing of NVIDIA's weights is +# redistributed). Role "src" = a file of the checkpoint; the prepared files are in FP4LOCAL_PREPARED. +NVFP4_REPOS[NVFP4_FP4LOCAL_REPO] = {"revision": "b9ce18a6887e18c089fdea8509a33e63429a3300", "files": { + "config.json": ("src", 75217, "b50dbc52a0c83b0cd2a44a372c1fb6b5e0e6827d22f2611c97d4d030f92f6b28"), + "generation_config.json": ("src", 202, "e70c136c1b78ddc1fb0905bac8e733a4dc448d4f852a5dd75143fffc70be550e"), + "chat_template.jinja": ("src", 8952, "c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041"), + "merges.txt": ("src", 3353259, "a9d356d7bdf1ef4949e3e748e95b8e10ad9d4e2e838eddc38a0a7b6b94d1db8d"), + "tokenizer.json": ("src", 12809320, "0997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3"), + "tokenizer_config.json": ("src", 17928, "b11349aafa7cdc6a320767cf7ceb29ed82f7eda5d65e8e0819e76f0ce947bf27"), + "vocab.json": ("src", 6722759, "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003"), + "model.safetensors.index.json": ("src", 47280974, "5fa166bbb1cf25adda455117563efa72a2072272001f459eedece131ffc913e1"), + "tensors/model-00001-of-00021.safetensors": ("src", 5000643504, "ebf3648c5f4cd1f24e79789e7803498dc4e74cb52515cc515b2d22cf8161953b"), + "tensors/model-00002-of-00021.safetensors": ("src", 5002792096, "79a643fc5c024089cecd32ca27dc43e671cbec70ff3628b728909b7656ac43ec"), + "tensors/model-00003-of-00021.safetensors": ("src", 5002927400, "c45f942203db4c7f5a1071700b93b908495cc790271acddfff39091c2b953923"), + "tensors/model-00004-of-00021.safetensors": ("src", 5003194672, "071ab9cf963ca0f1a6a194b4cec485f5de18ef9804da915b2e6abd0eb0c707af"), + "tensors/model-00005-of-00021.safetensors": ("src", 5003151448, "f80d17870eb1d36917257494770984953476583c57737f61fdbd341c957b9715"), + "tensors/model-00006-of-00021.safetensors": ("src", 5002892148, "3e9183d4ebb267fa92429184d5132d302cb1a98fd049149e5d01dccd4ca65795"), + "tensors/model-00007-of-00021.safetensors": ("src", 5002907708, "aa1ad959c4d62e0bc4600fd0b57cc2939b463e9fb53dc01020e188552b52ce5a"), + "tensors/model-00008-of-00021.safetensors": ("src", 5003103756, "0b18844027be74b84b240f23bf3a744bc29b35de0bd384f41c40cd85e6339326"), + "tensors/model-00009-of-00021.safetensors": ("src", 5002976316, "2d0b6c66790c17f8b1fdcf442f541778c8f0a381aca26c11b9d7cfcf7c96f2f0"), + "tensors/model-00010-of-00021.safetensors": ("src", 5002834136, "3ed9bd73745aebf6dc136f437b67d6b9fc3d38d25ad84300b399164bc87a72b7"), + "tensors/model-00011-of-00021.safetensors": ("src", 5002685828, "4936ff28c6cc8b66653ddb9cae28bc284569a1a2f7116819a017dc1a0e517ed8"), + "tensors/model-00012-of-00021.safetensors": ("src", 5002912920, "dd7df5a6ff73e9960412243f744eab9ec35f4be40da5bb158dc4ba8796b33742"), + "tensors/model-00013-of-00021.safetensors": ("src", 5003237060, "28a455c8ea4ebaa847fb4cbed2bc1de9eff0b501dd3f848a3a3cfc38778e8500"), + "tensors/model-00014-of-00021.safetensors": ("src", 4845006312, "6941676e685abf9817d9c48a17fdeda20b2b72d16217555252aa4c602b7f98b8"), + "tensors/model-00015-of-00021.safetensors": ("src", 4860574920, "2a1129b5acfc24a45bf402aa63dcef08b531aedfdaf5233c65fd3d12dc303fdd"), + "tensors/model-00016-of-00021.safetensors": ("src", 4950031028, "635e97fbad78fa988647d407e2b58e55d551ef94d798c9b6fb5550de25e86429"), + "tensors/model-00017-of-00021.safetensors": ("src", 4950030896, "bf60d564d89a805b67f8be5f2847a1b1567a70dbc23d19754395c127568474ad"), + "tensors/model-00018-of-00021.safetensors": ("src", 4950030896, "c5bde22f9364e82eb25973456795592fdcb4b158bc2095898979a2566bf4c562"), + "tensors/model-00019-of-00021.safetensors": ("src", 4950030904, "da3dc3b4f428f5b9dd53362691043d0242f48d03adca9b7b553bd9f3a1e96350"), + "tensors/model-00020-of-00021.safetensors": ("src", 4950030904, "4978bb6b8480cfc02d3c8bc84ba86202889f5f10d090bb17c21fee663cea7683"), + "tensors/model-00021-of-00021.safetensors": ("src", 2700016864, "48203838f2c76921bddbf1cc51d20a23858c128821a21add55fa1778e5e25283"), +}} +FP4LOCAL_PREPARED = "prepared" # /nvidia--Qwen3.8-Flash-Next-FP4-Local/prepared/ + # the first release engine with NVFP4 experts (a source build of this checkout has them whatever its number says) NVFP4_ENGINE = (0, 1, 44) +# the first engine that reads NVIDIA's NVFP4 n-gram table (strata.ple.format = nvfp4x16); a source build of this checkout has it +FP4LOCAL_ENGINE = (0, 1, 45) # agentionai's Gyro files (Qwen3.8-Flash-Next with trellis-coded, Hadamard-rotated experts, TQ2_T / TQK6 / TQK7): one # GGUF per size, the n-gram table inside it (hence the 58 / 92 GB downloads for 27.6 / 35 GB of memory). The engine @@ -336,8 +375,8 @@ MODELS = { "about 20% slower than Q2_0 on 12 GB cards", "download_gb": 92.0, "ram_gb": 35.0, "arena_gb": 32.1, "families": ("gyro",), "mem_total": True, "file": "Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf", "shards": 1, "engine": GYRO_ENGINE, "vision": False}, - "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, + "NVFP4": {"about": "best quality of the NVFP4 versions (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"}, @@ -348,6 +387,15 @@ MODELS = { "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"}, + "NVFP4-QAD": {"about": "NVIDIA's FP4, trained for FP4 (NVIDIA's Qwen3.8-Flash-Next-FP4-Local) - slightly faster on short prompts; " + "a 102 GB download that this PC turns into a Strata pack once (about 20-40 minutes, 110 GB more disk); " + "RTX 50 cards have FP4 tensor cores, other NVIDIA cards run it at 8-bit precision. No images yet", + "download_gb": 102.2, "prepare_gb": 110.0, "ram_gb": 80, "arena_gb": 68.0, + "families": ("nvfp4",), "nvidia_only": True, "vision": False, "repo": NVFP4_FP4LOCAL_REPO, + "prepare": "fp4-local", "engine": FP4LOCAL_ENGINE, + "license": "NVIDIA Open Model Agreement (Licensed by NVIDIA Corporation under the NVIDIA Open Model " + "Agreement) with Qwen3.8-Flash-Next's Qwen Community License 1.0: " + "https://huggingface.co/nvidia/Qwen3.8-Flash-Next-FP4-Local"}, } # 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). @@ -1904,8 +1952,23 @@ def ready_where(models_dir: Path, f) -> Path: return Path(models_dir) / f[1].replace("/", "--") / f[3] +def prepared_dir(model: str, models_dir: Path) -> Path: + """Where a model that is prepared on this PC (MODELS[..]["prepare"]) keeps what it prepared.""" + return Path(models_dir) / MODELS[model]["repo"].replace("/", "--") / FP4LOCAL_PREPARED + + +def prepared_done(model: str, models_dir: Path) -> bool: + """Every step of tools/nvfp4_local_pack.py prepare is marked done (its marks, written when each step is whole).""" + d = prepared_dir(model, models_dir) + return all((d / m).is_file() for m in ("ple-nvfp4.gguf.done", "dense.gguf.done", "pack.done", "draft.done")) + + def ready_paths(model: str, models_dir: Path) -> dict: - """What the engine is given: the pack folder and the dense, PLE and embedding GGUFs.""" + """What the engine is given: the pack folder and the dense, PLE and embedding GGUFs (a prepared model also has its + own draft layer, "mtp", and no separate embedding: the token embedding is in its dense GGUF).""" + if MODELS[model].get("prepare"): + d = prepared_dir(model, models_dir) + return {"pack": d / "pack", "dense": d / "dense.gguf", "ple": d / "ple-nvfp4.gguf", "mtp": d / "mtp"} out = {} for f in ready_files(model): p = ready_where(models_dir, f) @@ -6858,7 +6921,9 @@ def main() -> int: 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) + \ + prep_gb = MODELS[model].get("prepare_gb", 0.0) if ready and MODELS[model].get("prepare") and \ + not prepared_done(model, models_dir) else 0.0 + need = to_fetch + prep_gb + (2 if mtp_have else 8) + \ (40 if q2_avx and not pack_bin else 0) + (1 if vision != "none" else 0) + \ (MODELS[model]["arena_gb"] + 1 if low_ram and not q2_avx and not pack_bin else 0) if free_gb(models_dir) < need: @@ -6950,6 +7015,15 @@ 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")) + prepared = bool(ready and MODELS[model].get("prepare")) + if prepared and not prepared_done(model, models_dir): + say(" NVIDIA's checkpoint is turned into a Strata pack on this PC (once; 20-40 minutes, reads the 102 GB, writes about") + say(f" {MODELS[model]['prepare_gb']:.0f} GB). Nothing of NVIDIA's weights leaves this PC.") + run([sys.executable, str(ROOT / "tools" / "nvfp4_local_pack.py"), "prepare", + "--model", str(ready_where(models_dir, ("src", MODELS[model]["repo"], "", "", 0, ""))), + "--out", str(prepared_dir(model, models_dir))], env=env) + ok("prepared; the downloaded checkpoint is no longer needed and can be deleted to get its 102 GB back: " + + str(ready_where(models_dir, ("src", MODELS[model]["repo"], "", "", 0, "")))) 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": @@ -6972,9 +7046,10 @@ def main() -> int: run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), "--experts-bin"], env=env) ok(f"model prepared: {pack}") - mtp = (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent + mtp = ready_paths(model, models_dir)["mtp"] if prepared else \ + (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent rt = mtp / "rt" - corrupt = (rt / "experts.bin").exists() and mtp_corrupt(mtp, env) + corrupt = (rt / "experts.bin").exists() and not prepared and mtp_corrupt(mtp, env) if corrupt: warn("some MTP tensors are not the checkpoint's (a download mirror that ignored range requests, #327): " "fetching them again and rebuilding the draft layer") @@ -7002,7 +7077,7 @@ def main() -> int: 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"])] + "--ple-gguf", str(ple), *(["--embd-gguf", str(rp["embd"])] if "embd" in rp else [])] 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: diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 91de3705..a0685bd5 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -152,6 +152,20 @@ void bf16_dequant_row(const uint8_t* row, float* out160) { } } +// NVIDIA's FP4-Local table: a row of 160 values is 80 bytes of E2M1 codes (element 2i in the low nibble, 2i+1 in the +// high one) followed by 10 E4M3 block scales (one per 16 values, sign bit always 0); one F32 scales the whole table. +// value = e2m1(code) * e4m3(block scale) * table scale, exactly what vLLM's nvfp4 PLE lookup computes. +void nvfp4_row_dequant(const uint8_t* row, float scale, float* out160) { + static const float kE2M1[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + for (int j = 0; j < PLE_HEAD_DIM; ++j) { + const uint8_t byte = row[j >> 1]; + const uint8_t code = (j & 1) ? (uint8_t) (byte >> 4) : (uint8_t) (byte & 15); + const float v = kE2M1[code & 7]; + const float s = kFp8.v[row[PLE_HEAD_DIM / 2 + (j >> 4)]]; + out160[j] = ((code & 8) ? -v : v) * s * scale; + } +} + // --------------------------------------------------------------------------------------------------- // THE FORMAT TABLE (see PleFormatInfo). One entry per table type; the block formats decode 5 blocks of 32. namespace { @@ -162,6 +176,7 @@ void dequant_blocks(const uint8_t* row, float /*scale*/, float* out160) { void dequant_iq4_nl(const uint8_t* row, float, float* out160) { iq4nl_dequant_row(row, out160); } void dequant_fp8(const uint8_t* row, float scale, float* out160) { fp8_e4m3_dequant_row(row, scale, out160); } void dequant_bf16(const uint8_t* row, float, float* out160) { bf16_dequant_row(row, out160); } +void dequant_nvfp4(const uint8_t* row, float scale, float* out160) { nvfp4_row_dequant(row, scale, out160); } const PleFormatInfo kPleFormats[] = { {PleFormat::IQ4_NL, "IQ4_NL", "IQ4_NL", PLE_ROW_BYTES, false, dequant_iq4_nl}, @@ -175,6 +190,9 @@ const PleFormatInfo kPleFormats[] = { // BF16 (#586): the checkpoint's own table at full precision, 320-byte rows; self-describing, so no scale and no // metadata to trust (tools/ple_fp8_pack.py writes the FP8 form of the same table) {PleFormat::BF16, "BF16", "BF16", PLE_ROW_BYTES_BF16, false, dequant_bf16}, + // NVFP4 x16 (NVIDIA's Qwen3.8-Flash-Next-FP4-Local, tools/nvfp4_local_pack.py ple): 90-byte rows, I8 bytes marked + // strata.ple.format = nvfp4x16 with strata.ple.scale. The tensor is [90, rows]: ne0 is the row's byte count. + {PleFormat::NVFP4, "NVFP4", "I8", PLE_ROW_BYTES_NVFP4, true, dequant_nvfp4}, }; constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]); } // namespace @@ -192,7 +210,7 @@ std::string ple_format_list() { for (int i = 0; i < kPleFormatCount; ++i) { const PleFormatInfo& f = kPleFormats[i]; if (i > 0) out += i + 1 == kPleFormatCount ? " or " : ", "; - out += std::strcmp(f.gguf_type, "I8") == 0 ? "FP8 (I8)" : f.name; + out += std::strcmp(f.gguf_type, "I8") == 0 ? (f.id == PleFormat::NVFP4 ? "NVFP4 (I8)" : "FP8 (I8)") : f.name; } return out; } @@ -245,8 +263,12 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - // [160, 320001536]: ne0 = 160 is the FAST axis, so the ROW index is shape[1] and a row is contiguous. - if (t->shape.size() != 2 || t->shape[0] != (uint64_t) PLE_HEAD_DIM) { + // [160, 320001536]: ne0 = 160 is the FAST axis, so the ROW index is shape[1] and a row is contiguous. The NVFP4 table + // is I8 bytes with ne0 = 90 (the row's byte count), marked strata.ple.format = nvfp4x16. + const MetaValue* fmt_key = impl_->file->get("strata.ple.format"); + const bool nvfp4x16 = std::strcmp(t->type_name(), "I8") == 0 && fmt_key != nullptr && fmt_key->s == "nvfp4x16"; + const uint64_t want_ne0 = nvfp4x16 ? (uint64_t) PLE_ROW_BYTES_NVFP4 : (uint64_t) PLE_HEAD_DIM; + if (t->shape.size() != 2 || t->shape[0] != want_ne0) { err = "per_layer_token_embd.weight has an unexpected shape"; close(); return false; @@ -254,7 +276,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // The table's type is looked up in the format list (ple_formats()): IQ4_NL (ISTA-DASLab's shard 2, the original's // own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as shipped: I8 bytes marked strata.ple.format = // f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) - const PleFormatInfo* fmt = ple_format_for_type(t->type_name()); + const PleFormatInfo* fmt = nvfp4x16 ? &ple_format_info(PleFormat::NVFP4) : ple_format_for_type(t->type_name()); if (fmt == nullptr) { err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not " + ple_format_list(); close(); @@ -263,8 +285,9 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO if (fmt->needs_scale) { const MetaValue* f = impl_->file->get("strata.ple.format"); const MetaValue* s = impl_->file->get("strata.ple.scale"); - if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) { - err = "per_layer_token_embd.weight is I8 without strata.ple.format = f8_e4m3 and a positive strata.ple.scale"; + const char* want = nvfp4x16 ? "nvfp4x16" : "f8_e4m3"; + if (f == nullptr || f->s != want || s == nullptr || !(s->num() > 0.0)) { + err = std::string("per_layer_token_embd.weight is I8 without strata.ple.format = ") + want + " and a positive strata.ple.scale"; close(); return false; } diff --git a/src/kernels/ple_fp8_parity.cpp b/src/kernels/ple_fp8_parity.cpp index 09dd199a..bc54956c 100644 --- a/src/kernels/ple_fp8_parity.cpp +++ b/src/kernels/ple_fp8_parity.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -51,7 +52,7 @@ int main(int argc, char** argv) { std::printf("%-6s %s, %llu rows: read_row %d/%zu values differ, gather_batch %s %d differ\n", mode == k::PleIo::Direct ? "Direct" : "Mmap", t.format(), (unsigned long long) t.rows(), diff, got.size(), ok ? "ok," : "FAILED,", bdiff); - bad += diff + bdiff + (ok ? 0 : 1) + (std::strcmp(t.format(), "F8_E4M3") != 0); + bad += diff + bdiff + (ok ? 0 : 1) + (std::strcmp(t.format(), std::getenv("PLE_EXPECT_FORMAT") ? std::getenv("PLE_EXPECT_FORMAT") : "F8_E4M3") != 0); } if (argc > 3) { k::PleTable q; diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index 4663455f..11c41e75 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -105,7 +105,7 @@ void bf16_widening_is_exact() { /// and the type lookup all have to be right for every format, not only for IQ4_NL. uint32_t gguf_type_id(const char* name) { static const struct { const char* name; uint32_t id; } ids[] = { - {"IQ4_NL", 20}, {"Q4_0", 2}, {"Q4_1", 3}, {"Q5_0", 6}, {"Q5_1", 7}, {"Q8_0", 8}, {"BF16", 30}, {"F8_E4M3", 24}}; + {"IQ4_NL", 20}, {"Q4_0", 2}, {"Q4_1", 3}, {"Q5_0", 6}, {"Q5_1", 7}, {"Q8_0", 8}, {"BF16", 30}, {"F8_E4M3", 24}, {"NVFP4", 24}}; for (const auto& e : ids) if (std::strcmp(e.name, name) == 0) return e.id; return 0xFFFFFFFFu; @@ -129,11 +129,11 @@ std::string write_format_table(const std::string& dir, const k::PleFormatInfo& f const float scale = 0.75f; uint32_t sb; std::memcpy(&sb, &scale, 4); - head += str("strata.ple.format") + le(8u, 4) + str("f8_e4m3"); + head += str("strata.ple.format") + le(8u, 4) + str(f.id == k::PleFormat::NVFP4 ? "nvfp4x16" : "f8_e4m3"); head += str("strata.ple.scale") + le(6u, 4) + le(sb, 4); // 6 = FLOAT32 } head += str("per_layer_token_embd.weight") + le(2u, 4); - head += le((uint64_t) k::PLE_HEAD_DIM, 8) + le(claimed_rows != 0 ? claimed_rows : (uint64_t) rows, 8); + head += le(f.id == k::PleFormat::NVFP4 ? (uint64_t) f.row_bytes : (uint64_t) k::PLE_HEAD_DIM, 8) + le(claimed_rows != 0 ? claimed_rows : (uint64_t) rows, 8); head += le(gguf_type_id(f.name), 4) + le(0ull, 8); while (head.size() % 32) head += '\0'; out.write(head.data(), (std::streamsize) head.size()); @@ -249,7 +249,9 @@ void all_formats_round_trip(const std::string& dir) { for (int i = 0; i < k::ple_format_count(); ++i) { const k::PleFormatInfo& f = k::ple_formats()[i]; CHECK((int) f.id == i, "%s: the table is not in PleFormat order", f.name); - CHECK(k::ple_format_for_type(f.gguf_type) == &f, "%s: type lookup", f.name); + // NVFP4 and F8_E4M3 are both I8 bytes: the type finds the FP8 entry, `strata.ple.format` picks NVFP4 in PleTable::open + const k::PleFormatInfo* want = f.id == k::PleFormat::NVFP4 ? &k::ple_format_info(k::PleFormat::F8_E4M3) : &f; + CHECK(k::ple_format_for_type(f.gguf_type) == want, "%s: type lookup", f.name); format_round_trip(dir, f, 2000); } CHECK(k::ple_format_for_type("Q6_K") == nullptr, "Q6_K must not be a PLE format"); diff --git a/tools/nvfp4_local_pack.py b/tools/nvfp4_local_pack.py new file mode 100644 index 00000000..a00b1145 --- /dev/null +++ b/tools/nvfp4_local_pack.py @@ -0,0 +1,666 @@ +"""tools/nvfp4_local_pack.py - NVIDIA's Qwen3.8-Flash-Next-FP4-Local (ModelOpt, QAD) -> files Strata can pack. + + python tools/nvfp4_local_pack.py convert --model --outfile + python tools/nvfp4_local_pack.py ple --model --out + python tools/nvfp4_local_pack.py mtp --model --out (then tools/mtp_pack.py, tools/mtp_rt.py) + python tools/nvfp4_local_pack.py pack --model --dense-gguf --out (instead of iq_pack on a full GGUF) + python tools/nvfp4_local_pack.py verify --model --gguf [--experts 6] + python tools/iq_pack.py --gguf --out + +Nothing of NVIDIA's weights is shipped: the user downloads the checkpoint from NVIDIA's repository and this runs +locally. What the checkpoint stores, and what is done with it: + + * routed experts: NVFP4 (E2M1 codes, E4M3 scale per 16 values, F32 weight_scale_2). The block scales are stored + in NVIDIA's "CSF" form (config `weight_scale_encoding: "csf"`, codec byte-window4-fixed-stream-u24-exceptions/1): + per tensor a `.nvfp4_csf_fixed` U8 stream and a `.nvfp4_csf_exceptions` U32 stream. They are decoded here to the + plain E4M3 matrix (the format is documented by vLLM's loader, PR 60646, and flashinfer's b12x decoder, both + Apache-2.0; this is a fresh implementation of that description), and from there the ordinary ModelOpt NVFP4 + repack of tools/nvfp4_convert.py applies, bit for bit. + * attention, GDN projections, shared experts, indexer: MXFP8 (E4M3 values, E8M0 scale per 32 values). They are + dequantized exactly to BF16 and then take the type policy of tools/nvfp4_convert.py (Q8_0 for the big ones, + BF16 for the small projections the BF16 kernels read). Q8_0 has the same 32-value blocks; the added error is + ~0.6% RMS against MXFP8's own ~3%. + * the 26.8 GiB n-gram (PLE) table is NVFP4 too (160 values a row: 80 B of codes, 10 E4M3 scales, one F32 for the + whole table). `ple` copies it row by row into a one-tensor GGUF of 90-byte rows. + * the MTP head (NVFP4 experts, BF16 rest) is dequantized by `mtp` into the folder form tools/mtp_pack.py reads. + The vision tower is not written (text first). +""" +from __future__ import annotations + +import argparse +import json +import pathlib +import struct +import sys +import time + +import numpy as np + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + +CSF_FIXED = ".nvfp4_csf_fixed" +CSF_EXC = ".nvfp4_csf_exceptions" +PLE_ROW_BYTES = 90 # 80 B of E2M1 codes + 10 E4M3 block scales, per 160-value row + + +# --------------------------------------------------------------------------------------------- safetensors access +class Checkpoint: + """Header-indexed, memory-mapped access to a checkpoint's safetensors shards (raw bytes, any dtype).""" + + def __init__(self, folder, partial_ok=False): + self.dir = pathlib.Path(folder) + index = self.dir / "model.safetensors.index.json" + if index.exists(): + wmap = json.loads(index.read_text(encoding="utf-8"))["weight_map"] + files = sorted(set(wmap.values())) + else: + files = sorted(p.name for p in self.dir.glob("*.safetensors")) + if not files: + raise FileNotFoundError("no .safetensors files in " + str(self.dir)) + self.meta: dict[str, tuple[str, str, list[int], int, int]] = {} + self._mm: dict[str, np.memmap] = {} + for fn in files: + path = self.dir / fn + if not path.exists() and partial_ok: + continue # a subset of the shards (the MTP head is in two) + with open(path, "rb") as f: + n = struct.unpack(" np.ndarray: + fn, _, _, a, b = self.meta[name] + if fn not in self._mm: + self._mm[fn] = np.memmap(self.dir / fn, dtype=np.uint8, mode="r") + return self._mm[fn][a:b] + + def array(self, name, np_dtype) -> np.ndarray: + return self.raw(name).view(np_dtype).reshape(self.shape(name)) + + +# ----------------------------------------------------------------------------------------------------- CSF decoding +def csf_decode(fixed: np.ndarray, exceptions: np.ndarray) -> np.ndarray: + """The CSF stream pair -> the plain E4M3 block-scale matrix as uint8 [rows, cols] (cols = K / 16). + + fixed: uint8 [rows / 16, 16 * (1 + cols / 2)]. Per slab of 16 rows: the 16 rows' base bytes, then each + row's cols 4-bit codes (two to a byte, low nibble first). A scale byte is base + code. + exceptions: uint32 words, low 24 bits = flat row * cols + col, high 8 bits = the scale byte there. + """ + if fixed.dtype != np.uint8 or fixed.ndim != 2 or fixed.shape[1] % 16 or fixed.shape[1] < 32: + raise ValueError("invalid CSF fixed stream %s %s" % (fixed.dtype, fixed.shape)) + if exceptions.dtype != np.uint32: + raise ValueError("invalid CSF exceptions dtype %s" % exceptions.dtype) + rows = fixed.shape[0] * 16 + cols = (fixed.shape[1] // 16 - 1) * 2 + bases = fixed[:, :16].reshape(rows, 1).astype(np.int16) + if (bases > 240).any(): + raise ValueError("CSF row bases must be in 0..240") + packed = fixed[:, 16:].reshape(rows, cols // 2) + codes = np.stack((packed & 0xF, packed >> 4), axis=-1).reshape(rows, cols) + out = (bases + codes).reshape(-1) + words = exceptions.reshape(-1).astype(np.int64) + pos = words & 0xFFFFFF + if pos.size and int(pos.max()) >= rows * cols: + raise ValueError("CSF exception position out of range") + out[pos] = words >> 24 + return out.astype(np.uint8).reshape(rows, cols) + + +def csf_encode(scales: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """The inverse, for the tests: uint8 [rows, cols] -> (fixed, exceptions). Base = the row's most common + window start; whatever falls outside base..base+15 is an exception.""" + rows, cols = scales.shape + assert rows % 16 == 0 and cols % 2 == 0 + base = np.zeros(rows, np.int16) + for r in range(rows): + v = scales[r].astype(np.int16) + best = (-1, 0) + for b in range(max(0, int(v.min()) - 0), int(v.max()) + 1): + c = int(((v >= b) & (v <= b + 15)).sum()) + if c > best[0]: + best = (c, b) + base[r] = min(best[1], 240) + code = scales.astype(np.int16) - base[:, None] + exc = (code < 0) | (code > 15) + code = np.where(exc, 0, code).astype(np.uint8) + pk = (code[:, 0::2] | (code[:, 1::2] << 4)).astype(np.uint8) + fixed = np.empty((rows // 16, 16 * (1 + cols // 2)), np.uint8) + for s in range(rows // 16): + fixed[s, :16] = base[s * 16:(s + 1) * 16].astype(np.uint8) + fixed[s, 16:] = pk[s * 16:(s + 1) * 16].reshape(-1) + pos = np.flatnonzero(exc.reshape(-1)) + words = (pos.astype(np.uint64) | (scales.reshape(-1)[pos].astype(np.uint64) << 24)).astype(np.uint32) + return fixed, words + + +# --------------------------------------------------------------------------------------------- MXFP8 dequantizing +def mxfp8_dequant(values_u8: np.ndarray, scales_u8: np.ndarray): + """MXFP8 (E4M3 values [R, K], E8M0 scale bytes [R, K/32]) -> float32 [R, K]. Exact (4-bit significands).""" + import torch + R, K = values_u8.shape + if scales_u8.shape != (R, K // 32) or K % 32: + raise ValueError("MXFP8 shapes %s / %s" % (values_u8.shape, scales_u8.shape)) + if (scales_u8 == 255).any(): + raise ValueError("MXFP8 scale byte 255 (NaN) in a weight") + v = torch.from_numpy(np.ascontiguousarray(values_u8)).view(torch.float8_e4m3fn).to(torch.float32) + s = torch.from_numpy(np.exp2(scales_u8.astype(np.float32) - 127.0)) + return (v.reshape(R, K // 32, 32) * s[:, :, None]).reshape(R, K) + + +# --------------------------------------------------------------------------- the overlay on llama.cpp's tensor index +def _orig_name(ck: Checkpoint, name: str): + """The converter strips `language_model.`; find the checkpoint's own name.""" + if name in ck: + return name + for cand in (name.replace("model.", "model.language_model.", 1), "model.language_model." + name): + if cand in ck: + return cand + return None + + +def overlay(tensors: dict, ck: Checkpoint, stats: dict, dense_only: bool = False) -> dict: + """Replace the CSF stream pairs by plain `weight_scale` tensors, the MXFP8 weights by BF16, and drop what + the PLE writer and the MTP packer own.""" + import torch + out = dict(tensors) + if dense_only: # the GGUF the engine reads the dense weights from: no experts in it + out = {k: v for k, v in out.items() if ".mlp.experts." not in k} + for name in list(out): + if name not in out: + continue + if name.endswith(CSF_FIXED): + base = name[: -len(CSF_FIXED)] # ...weight_scale + o_fix = _orig_name(ck, name) + o_exc = _orig_name(ck, base + CSF_EXC) + if o_fix is None or o_exc is None: + raise ValueError("CSF fixed stream without its exceptions: " + name) + + def gen(o_fix=o_fix, o_exc=o_exc): + dec = csf_decode(ck.array(o_fix, np.uint8), ck.array(o_exc, np.uint32)) + return torch.from_numpy(dec).view(torch.float8_e4m3fn) + del out[name] + out.pop(base + CSF_EXC, None) + out[base] = gen + stats["csf"] = stats.get("csf", 0) + 1 + elif ".ngram_embedding." in name and (name.endswith(".weight_scale") or name.endswith(".weight_scale_2")): + del out[name] # the PLE table has its own writer (`ple`) + for name in list(out): + if not name.endswith(".weight") or ".ngram_embedding." in name: + continue + sname = name[: -len(".weight")] + ".weight_scale" + o_w, o_s = _orig_name(ck, name), _orig_name(ck, sname) + if o_w is None or o_s is None or sname not in out: + continue + if ck.dtype(o_w) == "F8_E4M3" and ck.dtype(o_s) == "U8": # MXFP8 + def gen(o_w=o_w, o_s=o_s): + f = mxfp8_dequant(np.asarray(ck.raw(o_w)).reshape(ck.shape(o_w)), np.asarray(ck.raw(o_s)).reshape(ck.shape(o_s))) + return f.to(torch.bfloat16) + out[name] = gen + del out[sname] + stats["mxfp8"] = stats.get("mxfp8", 0) + 1 + return out + + +def install(ck: Checkpoint, stats: dict, dense_only: bool = False): + """Import the converter, give it nvfp4_convert's type policy, and hook the tensor index.""" + import nvfp4_convert as base + base.install_policy() + from conversion.base import ModelBase + from conversion import qwen4exp as Q4 + orig_index = ModelBase.index_tensors + + def index_tensors(self, remote_hf_model_id=None): + return overlay(orig_index(self, remote_hf_model_id), ck, stats, dense_only) + ModelBase.index_tensors = index_tensors + + # NVIDIA's repo keeps the shards in a `tensors/` folder that its index names; the converter only lists the top level + orig_parts = ModelBase.get_model_part_names + + def get_model_part_names(dir_model, prefix, suffix): + names = orig_parts(dir_model, prefix, suffix) + sub = pathlib.Path(dir_model) / "tensors" + if not names and suffix == ".safetensors" and prefix == "model" and sub.is_dir(): + names = sorted("tensors/" + p.name for p in sub.glob("model*.safetensors")) + return names + ModelBase.get_model_part_names = staticmethod(get_model_part_names) + + cls = Q4.Qwen4ExpTextModel + + def place_ple_shard(self, data_torch, name): + # the shards are NVFP4 here: two values a byte, so a row of 160 values is 80 bytes + idx = int(name.rsplit("shard_", 1)[1].split(".", 1)[0]) + self._ple_shards[idx] = name + self._ple_row_dim = int(data_torch.shape[-1]) * 2 + base.dropped_ple.append(name) + return [] + cls._place_ple_shard = place_ple_shard + return base + + +def cmd_convert(a) -> int: + model = pathlib.Path(a.model) + ck = Checkpoint(model) + stats: dict = {} + base = install(ck, stats, a.dense_only) + import convert_hf_to_gguf as C + out = pathlib.Path(a.outfile) + out.parent.mkdir(parents=True, exist_ok=True) + argv = [str(model), "--outtype", "q8_0", "--outfile", str(out)] + (["--dry-run"] if a.dry_run else []) + sys.argv = ["convert_hf_to_gguf.py"] + argv + t0 = time.time() + rc = C.main() + took = time.time() - t0 + print("nvfp4_local_pack: done in %.0f s; CSF scale tensors decoded %d, MXFP8 weights dequantized %d, PLE shards dropped %d" + % (took, stats.get("csf", 0), stats.get("mxfp8", 0), len(base.dropped_ple))) + if not a.dry_run: + out.with_suffix(".manifest.json").write_text(json.dumps({ + "source": str(model), "csf_decoded": stats.get("csf", 0), "mxfp8_dequantized": stats.get("mxfp8", 0), + "ple_table": "written separately: nvfp4_local_pack.py ple", "mtp": "not written", "seconds": round(took, 1)}, + indent=2) + "\n", encoding="utf-8") + return rc or 0 + + +# ------------------------------------------------------------------------------------------------- the PLE table +GGUF_TYPE_STRING, GGUF_TYPE_F32 = 8, 6 +GGML_TYPE_I8 = 24 +ALIGN = 32 + + +def _gs(s): + b = s.encode("utf-8") + return struct.pack(" np.ndarray: + """[n, 80] codes + [n, 10] E4M3 scale bytes -> [n, 90]: the codes, then the scales.""" + return np.concatenate([codes, scales], axis=1) + + +def cmd_ple(a) -> int: + model, out = pathlib.Path(a.model), pathlib.Path(a.out) + ck = Checkpoint(model, partial_ok=True) # the table is in six of the shards; a folder with only those works + shards = {} + for name in ck.meta: + if ".ngram_embedding.shard_" in name and name.endswith(".weight"): + shards[int(name.rsplit(".shard_", 1)[1].split(".")[0])] = name + if not shards or sorted(shards) != list(range(len(shards))): + sys.exit("the n-gram shards are missing or not numbered 0..N-1") + g = [k for k in ck.meta if k.endswith(".ngram_embedding.weight_scale_2")] + if len(g) != 1: + sys.exit("expected one ngram_embedding.weight_scale_2") + scale2 = float(ck.array(g[0], np.float32).reshape(-1)[0]) + rows, dim = 0, None + for k in range(len(shards)): + n = shards[k] + r, c = ck.shape(n) + if ck.dtype(n) != "U8" or c != 80 or ck.shape(n[:-6] + "weight_scale") != [r, 10]: + sys.exit("%s: not an NVFP4 160-value row table" % n) + rows += r + print("%d shards, %d rows x 160, global scale %.9g, %.2f GB" % (len(shards), rows, scale2, rows * PLE_ROW_BYTES / 1e9), flush=True) + kvs = (_gs("general.architecture") + struct.pack(" np.ndarray: + x = np.arange(256) + s, e, m = x >> 7, (x >> 3) & 15, x & 7 + f = np.where(e == 0, np.ldexp(m / 8.0, -6), np.ldexp(1.0 + m / 8.0, e.astype(np.int32) - 7)) + f = np.where((e == 15) & (m == 7), np.nan, f) + return np.where(s == 1, -f, f).astype(np.float32) + + +def nvfp4_dequant(codes: np.ndarray, scales_u8: np.ndarray, scale2: float) -> np.ndarray: + """ModelOpt NVFP4 -> float32: codes [R, K/2] (low nibble first), E4M3 scale bytes [R, K/16], one F32.""" + R = codes.shape[0] + lo, hi = codes & 15, codes >> 4 + v = E2M1[np.stack([lo, hi], axis=-1).reshape(R, -1)] + sc = e4m3_table()[scales_u8] + return (v.reshape(R, -1, 16) * sc[:, :, None] * np.float32(scale2)).reshape(R, -1) + + +def f32_to_bf16_bits(x: np.ndarray) -> np.ndarray: + u = np.ascontiguousarray(x, np.float32).view(np.uint32) + r = u + 0x7FFF + ((u >> 16) & 1) # round to nearest even + return (r >> 16).astype(np.uint16) + + +def cmd_mtp(a) -> int: + """The MTP head in tools/mtp_fetch.py's folder form (raw BF16 files + mtp-manifest.json), so tools/mtp_pack.py and + tools/mtp_rt.py take it as they take Qwen's own: the 31 tensors, experts fused as gate_up_proj / down_proj.""" + import hashlib + ck = Checkpoint(a.model, partial_ok=True) + out = pathlib.Path(a.out) + out.mkdir(parents=True, exist_ok=True) + manifest = [] + + def put(name, bits, shape): + fn = name.replace("/", "_") + ".bin" + data = np.ascontiguousarray(bits, np.uint16) + (out / fn).write_bytes(data.tobytes()) + manifest.append({"name": name, "dtype": "BF16", "shape": list(shape), "file": fn, + "sha256": hashlib.sha256(data.tobytes()).hexdigest()}) + + for name in sorted(k for k in ck.meta if k.startswith("mtp.") and ".experts." not in k): + if ck.dtype(name) != "BF16": + sys.exit("%s is %s, expected BF16" % (name, ck.dtype(name))) + put(name, ck.array(name, np.uint16), ck.shape(name)) + n_exp = 512 + for fused, parts in (("mtp.layers.0.mlp.experts.gate_up_proj", ("gate_proj", "up_proj")), + ("mtp.layers.0.mlp.experts.down_proj", ("down_proj",))): + rows = [ck.shape("mtp.layers.0.mlp.experts.0.%s.weight" % p)[0] for p in parts] + cols = ck.shape("mtp.layers.0.mlp.experts.0.%s.weight" % parts[0])[1] * 2 + shape = [n_exp, sum(rows), cols] + fn = fused + ".bin" + with open(out / fn, "wb") as f: + h = hashlib.sha256() + for e in range(n_exp): + mats = [] + for p in parts: + b = "mtp.layers.0.mlp.experts.%d.%s." % (e, p) + mats.append(nvfp4_dequant(np.asarray(ck.array(b + "weight", np.uint8)), + np.asarray(ck.array(b + "weight_scale", np.uint8)), + float(ck.array(b + "weight_scale_2", np.float32).reshape(-1)[0]))) + blob = f32_to_bf16_bits(np.concatenate(mats, axis=0)).tobytes() + f.write(blob) + h.update(blob) + manifest.append({"name": fused, "dtype": "BF16", "shape": shape, "file": fn, "sha256": h.hexdigest()}) + print(" %s %s" % (fused, shape), flush=True) + (out / "mtp-manifest.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8") + print("wrote %d MTP tensors to %s" % (len(manifest), out)) + return 0 + + +# ------------------------------------------------------------------------------------------------------ the slim GGUF +def cmd_slim(a) -> int: + """Copy a converted GGUF without its routed experts (and their .scale / .input_scale tensors): the file the engine + reads the dense weights from (--native / --native-dense-gguf), ~9 GB instead of ~74 GB, once experts.bin is cut.""" + from _paths import add_gguf_py + add_gguf_py() + import gguf + from gguf import GGUFReader, GGUFWriter, GGUFValueType as VT + rd = GGUFReader(a.gguf) + arch = rd.fields["general.architecture"].contents() + w = GGUFWriter(a.out, arch) + for key, f in rd.fields.items(): + if key.startswith("GGUF.") or key == "general.architecture": + continue + vt = f.types[0] + w.add_key_value(key, f.contents(), vt, sub_type=f.types[-1] if vt == VT.ARRAY else None) + kept = skipped = 0 + for t in rd.tensors: + if "_exps." in t.name: + skipped += 1 + continue + data = np.asarray(t.data) + qt = t.tensor_type + if qt in (gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16): + w.add_tensor(t.name, data) + else: # raw bytes with the type: the quantized blocks (BF16 rides as uint16) + raw = np.ascontiguousarray(data).view(np.uint8) + w.add_tensor(t.name, raw, raw_dtype=qt, raw_shape=[int(x) for x in raw.shape]) + kept += 1 + w.write_header_to_file() + w.write_kv_data_to_file() + w.write_tensors_to_file() + w.close() + print("slim: %d tensors kept, %d expert tensors left out -> %s" % (kept, skipped, a.out)) + return 0 + + +# ------------------------------------------------------------------------------------------- the pack, without a big GGUF +def nvfp4_blocks(weight_u8: np.ndarray, scale_u8: np.ndarray) -> np.ndarray: + """ModelOpt NVFP4 rows -> ggml's block_nvfp4 rows: weight [R, K/2] (two E2M1 codes a byte, element 2i low), scale [R, K/16] + E4M3 bytes -> [R, K/64 * 36] bytes of super-blocks `[4 UE4M3 scales | 32 code bytes]`. The same bits as llama.cpp's + ModelBase._nvfp4_pack (the scale's sign bit is dropped; it is 0 in every scale of this checkpoint).""" + R, nb = scale_u8.shape + w = weight_u8.reshape(R, nb, 8) + vals = np.stack([w & 0x0F, w >> 4], axis=-1).reshape(R, nb, 16) + qs = (vals[:, :, :8] | (vals[:, :, 8:] << 4)).astype(np.uint8) + d = (scale_u8 & 0x7F).reshape(R, nb // 4, 4) + qs = qs.reshape(R, nb // 4, 32) + return np.concatenate([d, qs], axis=-1).reshape(R, (nb // 4) * 36) + + +class _VTensor: + """A tensor info for iq_pack: an expert tensor (or its scale) whose bytes come from the checkpoint.""" + + def __init__(self, name, shape, type_id, type_name, nbytes): + self.name, self.shape, self.type_id, self.type_name, self.offset = name, shape, type_id, type_name, 0 + self._n = nbytes + + def expected_bytes(self): + return self._n + + +class _VGguf: + data_start = 0 + + +def experts_from_checkpoint(model, ck: Checkpoint, n_layers: int = 48, n_exp: int = 512): + """Give an iq_pack.Model of the dense-only GGUF the routed experts of the checkpoint as virtual tensors.""" + from _paths import add_gguf_py + add_gguf_py() + from gguf import GGMLQuantizationType as Q + src = next(iter(model.where.values()))[3] + cache: dict = {} + base = "model.language_model.layers.%d.mlp.experts.%d.%s_proj." + + def layer_role(l, role): + key = (l, role) + if key not in cache: + cache.clear() + rows = [] + for e in range(n_exp): + b = base % (l, e, role) + dec = csf_decode(np.asarray(ck.array(b + "weight_scale" + CSF_FIXED, np.uint8)), + np.asarray(ck.array(b + "weight_scale" + CSF_EXC, np.uint32))) + rows.append(nvfp4_blocks(np.asarray(ck.array(b + "weight", np.uint8)), dec).reshape(-1)) + cache[key] = (np.stack(rows),) + return cache[key] + + # shapes in ggml order (ne0 = K, ne1 = rows, ne2 = experts) + geo = {"gate": (2560, 640), "up": (2560, 640), "down": (640, 2560)} + + class _Mem(_VGguf): # a tiny tensor held in memory: iq_pack reads it like any dense one + pass + + for l in range(n_layers): + for role, (k, rows) in geo.items(): + n = "blk.%d.ffn_%s_exps.weight" % (l, role) + vt = _VTensor(n, [k, rows, n_exp], Q.NVFP4.value, "NVFP4", n_exp * rows * (k // 64) * 36) + model.where[n] = (_VGguf(), vt, None, src) + # the per-expert F32 scales (weight_scale_2 -> .scale, input_scale -> .input_scale), as the converter writes them + for suffix, key in ((".scale", "weight_scale_2"), (".input_scale", "input_scale")): + vals = np.array([ck.array(base % (l, e, role) + key, np.float32).reshape(-1)[0] for e in range(n_exp)], np.float32) + sn = "blk.%d.ffn_%s_exps%s" % (l, role, suffix) + raw = vals.view(np.uint8) + model.where[sn] = (_Mem(), _VTensor(sn, [n_exp], Q.F32.value, "F32", n_exp * 4), raw, src) + orig_bytes = type(model).bytes + + def bytes_(name): + if name.startswith("blk.") and "_exps." in name: + if not name.endswith(".weight"): # the small F32 scale tensors are in memory + return model.where[name][2] + l = int(name.split(".")[1]); role = name.split("ffn_")[1].split("_exps")[0] + return layer_role(l, role)[0].reshape(-1) + return orig_bytes(model, name) + model.bytes = bytes_ + return model + + +def cmd_pack(a) -> int: + """tools/iq_pack.py on the dense-only GGUF, with the experts read from the checkpoint: experts.bin, native_experts.txt, + dense.bin, index.txt and the tokenizer, with no 74 GB GGUF in between.""" + import iq_pack + ck = Checkpoint(a.model) + orig_model = iq_pack.Model + + class M(orig_model): + def __init__(self, first): + super().__init__(first) + experts_from_checkpoint(self, ck) + iq_pack.Model = M + sys.argv = ["iq_pack.py", "--gguf", a.dense_gguf, "--out", a.out, "--experts-bin"] + return iq_pack.main() + + +# ------------------------------------------------------------------------------------------------------- prepare (setup) +def cmd_prepare(a) -> int: + """Everything setup needs from the downloaded checkpoint, each step skipped when its mark is there: + /ple-nvfp4.gguf the n-gram table /dense.gguf the dense weights (no experts) + /pack/ index.txt, dense.bin, experts.bin, native_experts.txt, tokenizer/ + /mtp/rt/ the draft layer (a Q2_0 copy of NVIDIA's MTP experts) + The checkpoint is read, never changed; it can be deleted afterwards (the pack and the two GGUFs hold everything).""" + import subprocess + model, out = pathlib.Path(a.model), pathlib.Path(a.out) + out.mkdir(parents=True, exist_ok=True) + me = [sys.executable, str(pathlib.Path(__file__).resolve())] + tools = pathlib.Path(__file__).resolve().parent + + def run(cmd): + r = subprocess.run(cmd) + if r.returncode: + sys.exit("prepare: %s failed (exit %d)" % (cmd[1] if len(cmd) > 1 else cmd[0], r.returncode)) + + def step(name, mark, fn): + if mark.exists(): + print("prepare: %s already done" % name, flush=True) + return + print("prepare: %s ..." % name, flush=True) + t0 = time.time() + fn() + mark.write_text("done %.0f s\n" % (time.time() - t0)) + + step("the n-gram table", out / "ple-nvfp4.gguf.done", + lambda: run(me + ["ple", "--model", str(model), "--out", str(out / "ple-nvfp4.gguf")])) + step("the dense weights", out / "dense.gguf.done", + lambda: run(me + ["convert", "--dense-only", "--model", str(model), "--outfile", str(out / "dense.gguf")])) + step("the experts and the pack", out / "pack.done", # (native_experts.txt is the pack's own marker, not ours) + lambda: run(me + ["pack", "--model", str(model), "--dense-gguf", str(out / "dense.gguf"), "--out", str(out / "pack")])) + + mtp = out / "mtp" + + def draft_layer(): + src = mtp / "src" + run(me + ["mtp", "--model", str(model), "--out", str(src)]) + run([sys.executable, str(tools / "mtp_pack.py"), "--src", str(src), "--experts", "q2_0", + "--out", str(mtp / "mtp-q2_0.gguf")]) + run([sys.executable, str(tools / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(mtp / "rt")]) + import shutil + shutil.rmtree(src, ignore_errors=True) + step("the draft layer", out / "draft.done", draft_layer) + print("prepare: done -> %s" % out) + return 0 + +# ------------------------------------------------------------------------------------------------------ verifying +def cmd_verify(a) -> int: + """Experts: decode the checkpoint (CSF + ModelOpt definition) and compare with gguf-py's dequantization of the + GGUF's NVFP4 blocks times the scale tensor, bit for bit (zeros normalised: ggml has one zero).""" + import torch + import nvfp4_verify as V + from gguf import GGUFReader, GGMLQuantizationType as Q, quants + ck = Checkpoint(a.model) + rd = GGUFReader(a.gguf) + T = {t.name: t for t in rd.tensors} + bad = 0 + rng = np.random.default_rng(1) + layers = sorted({int(k.split(".layers.")[1].split(".")[0]) for k in ck.meta if ".mlp.experts." in k and k.startswith("model.language_model")}) + for _ in range(a.experts): + L = int(rng.choice(layers)); e = int(rng.integers(0, 512)) + for proj, gname in (("gate_proj", "ffn_gate_exps"), ("up_proj", "ffn_up_exps"), ("down_proj", "ffn_down_exps")): + b = "model.language_model.layers.%d.mlp.experts.%d.%s." % (L, e, proj) + w = torch.from_numpy(np.array(ck.array(b + "weight", np.uint8))) + sc = csf_decode(ck.array(b + "weight_scale" + CSF_FIXED, np.uint8), ck.array(b + "weight_scale" + CSF_EXC, np.uint32)) + s = torch.from_numpy(sc).view(torch.float8_e4m3fn) + s2 = torch.from_numpy(np.array(ck.array(b + "weight_scale_2", np.float32))).reshape(()) + ref = V.modelopt_dequant(w, s, s2) + t = T["blk.%d.%s.weight" % (L, gname)] + blob = np.asarray(t.data) # [512, rows, bytes] of NVFP4 blocks + got = quants.dequantize(np.ascontiguousarray(blob[e]), Q.NVFP4).astype(np.float32) + sct = T["blk.%d.%s.scale" % (L, gname)] + got = got * np.float32(np.asarray(sct.data)[e]) + same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got.reshape(ref.shape) + np.float32(0)).view(np.uint32)) + print(" layer %2d expert %3d %-9s bitwise %s" % (L, e, proj, "OK" if same else "NO"), flush=True) + bad += not same + print("RESULT:", "lossless" if not bad else "MISMATCH") + return 1 if bad else 0 + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + sub = ap.add_subparsers(dest="cmd", required=True) + c = sub.add_parser("convert") + c.add_argument("--model", required=True) + c.add_argument("--outfile", required=True) + c.add_argument("--dry-run", action="store_true") + c.add_argument("--dense-only", action="store_true", + help="leave the routed experts out: the GGUF that --native-dense-gguf reads (~9 GB) beside an experts.bin") + p = sub.add_parser("ple") + p.add_argument("--model", required=True) + p.add_argument("--out", required=True) + m = sub.add_parser("mtp") + m.add_argument("--model", required=True) + m.add_argument("--out", required=True) + pk = sub.add_parser("pack") + pk.add_argument("--model", required=True) + pk.add_argument("--dense-gguf", required=True, help="the output of `convert --dense-only` (or `slim`)") + pk.add_argument("--out", required=True) + pr = sub.add_parser("prepare") + pr.add_argument("--model", required=True) + pr.add_argument("--out", required=True) + sl = sub.add_parser("slim") + sl.add_argument("--gguf", required=True) + sl.add_argument("--out", required=True) + v = sub.add_parser("verify") + v.add_argument("--model", required=True) + v.add_argument("--gguf", required=True) + v.add_argument("--experts", type=int, default=4) + a = ap.parse_args() + return {"convert": cmd_convert, "ple": cmd_ple, "mtp": cmd_mtp, "slim": cmd_slim, "pack": cmd_pack, "prepare": cmd_prepare, "verify": cmd_verify}[a.cmd](a) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index f6a70f33..23848624 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -91,6 +91,9 @@ FALLBACK_MODELS = { "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",), "vision": True}, + "NVFP4-QAD": {"about": "NVIDIA's FP4, trained for FP4 - slightly faster on short prompts; a 102 GB download " + "that this PC turns into a Strata pack once; no images yet", + "download_gb": 102.2, "ram_gb": 80, "arena_gb": 68.0, "families": ("nvfp4",), "vision": False}, } FALLBACK_FAMILIES = { "qwen": {"title": "Qwen3.8-Flash-Next", "about": "the original model", "tag": ""}, diff --git a/tools/test_nvfp4_local_pack.py b/tools/test_nvfp4_local_pack.py new file mode 100644 index 00000000..6d85b619 --- /dev/null +++ b/tools/test_nvfp4_local_pack.py @@ -0,0 +1,111 @@ +"""Tests for tools/nvfp4_local_pack.py: the CSF scale decode, the MXFP8 dequantization, the PLE rows.""" +import pathlib +import sys + +import numpy as np +import pytest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import nvfp4_local_pack as P # noqa: E402 + + +def _scales(rows, cols, seed, outliers=0.01): + rng = np.random.default_rng(seed) + base = rng.integers(60, 100, size=(rows, 1)) + s = base + rng.integers(0, 16, size=(rows, cols)) + m = rng.random((rows, cols)) < outliers + s[m] = rng.integers(0, 127, size=int(m.sum())) + return s.astype(np.uint8) + + +@pytest.mark.parametrize("rows,cols", [(32, 8), (640, 160), (2560, 40)]) +def test_csf_roundtrip_is_exact(rows, cols): + s = _scales(rows, cols, rows + cols) + fixed, exc = P.csf_encode(s) + assert fixed.shape == (rows // 16, 16 * (1 + cols // 2)) # the shapes of the real tensors + assert np.array_equal(P.csf_decode(fixed, exc), s) + + +def test_csf_matches_the_spec_by_hand(): + # one 16-row slab, 4 columns: base bytes 10..25, rows' codes = col index, one exception at row 3 col 2 + rows, cols = 16, 4 + fixed = np.zeros((1, 16 * (1 + cols // 2)), np.uint8) + fixed[0, :16] = np.arange(10, 26) + for r in range(rows): + fixed[0, 16 + r * 2] = 0 | (1 << 4) # cols 0 (low nibble), 1 (high) + fixed[0, 16 + r * 2 + 1] = 2 | (3 << 4) # cols 2, 3 + exc = np.array([(3 * cols + 2) | (99 << 24)], np.uint32) + got = P.csf_decode(fixed, exc) + assert got[0].tolist() == [10, 11, 12, 13] + assert got[5].tolist() == [15, 16, 17, 18] + assert got[3].tolist() == [13, 14, 99, 16] + + +def test_csf_rejects_bad_streams(): + with pytest.raises(ValueError): + P.csf_decode(np.zeros((1, 33), np.uint8), np.zeros(0, np.uint32)) + fixed = np.zeros((1, 32), np.uint8) + fixed[0, 0] = 250 + with pytest.raises(ValueError): + P.csf_decode(fixed, np.zeros(0, np.uint32)) + with pytest.raises(ValueError): + P.csf_decode(np.zeros((1, 32), np.uint8), np.array([16 * 4], np.uint32)) + + +def test_mxfp8_dequant_exact(): + torch = pytest.importorskip("torch") + rng = np.random.default_rng(3) + vals = rng.integers(0, 126, size=(4, 64)).astype(np.uint8) | (rng.integers(0, 2, size=(4, 64)).astype(np.uint8) << 7) + sc = rng.integers(100, 130, size=(4, 2)).astype(np.uint8) + got = P.mxfp8_dequant(vals, sc).numpy() + ref = torch.from_numpy(vals).view(torch.float8_e4m3fn).to(torch.float32).numpy().reshape(4, 2, 32) + ref = ref * np.exp2(sc.astype(np.float64) - 127)[:, :, None] + assert np.array_equal(got.reshape(4, 2, 32), ref.astype(np.float32)) + # exactly representable in BF16 (what the converter hands on) + bf = torch.from_numpy(got).to(torch.bfloat16).to(torch.float32).numpy() + assert np.array_equal(bf, got) + + +def test_mxfp8_rejects_nan_scale(): + pytest.importorskip("torch") + with pytest.raises(ValueError): + P.mxfp8_dequant(np.zeros((1, 32), np.uint8), np.full((1, 1), 255, np.uint8)) + + +def test_ple_rows_are_codes_then_scales(): + c = np.arange(160, dtype=np.uint8).reshape(2, 80) + s = np.arange(20, dtype=np.uint8).reshape(2, 10) + 200 + r = P.interleave_rows(c, s) + assert r.shape == (2, P.PLE_ROW_BYTES) + assert np.array_equal(r[1, :80], c[1]) and np.array_equal(r[1, 80:], s[1]) + + +def test_nvfp4_dequant_by_hand(): + # element 2i in the low nibble: byte 0x21 = codes 1 (0.5) and 2 (1.0); 0xF7 = 7 (6.0) and 15 (-6.0) + codes = np.zeros((1, 8), np.uint8) + codes[0, 0], codes[0, 1] = 0x21, 0xF7 + sc = np.array([[0x38]], np.uint8) # E4M3 0x38 = 1.0 + got = P.nvfp4_dequant(codes, sc, 2.0) + assert got[0, :4].tolist() == [1.0, 2.0, 12.0, -12.0] + + +def test_e4m3_table_and_bf16_rounding(): + t = P.e4m3_table() + assert t[0x38] == 1.0 and t[0x7E] == 448.0 and np.isnan(t[0x7F]) and t[0x01] == 2.0 ** -9 + x = np.array([1.0, 1.0 + 2.0 ** -8, 1.0 + 3 * 2.0 ** -9, -2.5], np.float32) + b = P.f32_to_bf16_bits(x) + back = (b.astype(np.uint32) << 16).view(np.float32) + assert back.tolist() == [1.0, 1.0, 1.0078125, -2.5] # ties to even; 1+3*2^-9 rounds up + + +def test_nvfp4_blocks_layout_by_hand(): + # one row of 64 values: codes 0..15 repeated; scales 0x38 0x39 0x3A 0x3B with a sign bit set on the first (dropped) + codes = np.arange(64) % 16 + packed = (codes[0::2] | (codes[1::2] << 4)).astype(np.uint8).reshape(1, 32) + sc = np.array([[0xB8, 0x39, 0x3A, 0x3B]], np.uint8) + out = P.nvfp4_blocks(packed, sc) + assert out.shape == (1, 36) + assert out[0, :4].tolist() == [0x38, 0x39, 0x3A, 0x3B] + # within a 16-block: element j in the low nibble, element j+8 in the high one + blk0 = out[0, 4:12] + assert [int(b & 15) for b in blk0] == list(range(8)) and [int(b >> 4) for b in blk0] == list(range(8, 16)) diff --git a/tools/test_setup_nvfp4.py b/tools/test_setup_nvfp4.py index d4304feb..4909c9e6 100644 --- a/tools/test_setup_nvfp4.py +++ b/tools/test_setup_nvfp4.py @@ -50,6 +50,7 @@ class ReadyPacks(unittest.TestCase): f.parent.mkdir(parents=True, exist_ok=True) f.write_bytes(body) repos[repo]["files"][path] = (roles[path], len(body), hashlib.sha256(body).hexdigest()) + repos[setup.NVFP4_FP4LOCAL_REPO] = setup.NVFP4_REPOS[setup.NVFP4_FP4LOCAL_REPO] # listed, never fetched here 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), @@ -100,19 +101,53 @@ 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 + self.assertEqual(names, ["NVFP4", "NVFP4-NVIDIA", "NVFP4-QAD"]) # 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) + self.assertEqual(d["vision"], m != "NVFP4-QAD") # the prepared QAD model: text first + self.assertRegex(d["license"], "Licen[sc]e|Agreement") + self.assertEqual(d["engine"], setup.FP4LOCAL_ENGINE if m == "NVFP4-QAD" else 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 PreparedModel(unittest.TestCase): + """NVFP4-QAD (NVIDIA's FP4-Local): the checkpoint is downloaded pinned, the pack is prepared on this PC.""" + + def test_the_checkpoint_files_are_pinned(self): + files = setup.ready_files("NVFP4-QAD") + names = {f[3] for f in files} + self.assertEqual(sum(1 for n in names if n.startswith("tensors/model-")), 21) + self.assertTrue({"config.json", "model.safetensors.index.json", "tokenizer.json"} <= names) + self.assertEqual(sum(f[4] for f in files) / 1e9 // 1, setup.MODELS["NVFP4-QAD"]["download_gb"] // 1) + for f in files: + self.assertEqual(f[0], "src") + self.assertRegex(f[5], "^[0-9a-f]{64}$") + self.assertEqual(f[2], "b9ce18a6887e18c089fdea8509a33e63429a3300") + + def test_paths_are_the_prepared_files(self): + m = Path("/models") + p = setup.ready_paths("NVFP4-QAD", m) + d = m / "nvidia--Qwen3.8-Flash-Next-FP4-Local" / "prepared" + self.assertEqual(p, {"pack": d / "pack", "dense": d / "dense.gguf", "ple": d / "ple-nvfp4.gguf", "mtp": d / "mtp"}) + self.assertNotIn("embd", p) + + def test_prepared_done_needs_every_mark(self): + with tempfile.TemporaryDirectory() as t: + self.assertFalse(setup.prepared_done("NVFP4-QAD", Path(t))) + d = setup.prepared_dir("NVFP4-QAD", Path(t)) + d.mkdir(parents=True) + marks = ("ple-nvfp4.gguf.done", "dense.gguf.done", "pack.done", "draft.done") + for m in marks[:-1]: + (d / m).write_text("x") + self.assertFalse(setup.prepared_done("NVFP4-QAD", Path(t))) + (d / marks[-1]).write_text("x") + self.assertTrue(setup.prepared_done("NVFP4-QAD", Path(t))) + + class MockedInstall(unittest.TestCase): """setup.main() --family nvfp4 --yes on mocked PCs (test_setup_golden's harness): the run config's model flags.""" @@ -156,6 +191,20 @@ class MockedInstall(unittest.TestCase): self.assertIn("NVIDIA-NVFP4-Strata/pack", self.flag(cfg["args"], "--pack")) self.assertIn("NVIDIA Open Model License", out) + def test_qad_size_is_prepared_and_uses_its_own_files(self): + code, out, cfg, _ = self.run_install("128GB-1x24GB", "NVFP4-QAD") + self.assertEqual(code, 0, out[-2500:]) + a = cfg["args"] + base = "nvidia--Qwen3.8-Flash-Next-FP4-Local/prepared" + self.assertTrue(self.flag(a, "--pack").endswith(base + "/pack")) + self.assertTrue(self.flag(a, "--native").endswith(base + "/dense.gguf")) + self.assertEqual(self.flag(a, "--native-dense-gguf"), self.flag(a, "--native")) + self.assertTrue(self.flag(a, "--ple-gguf").endswith(base + "/ple-nvfp4.gguf")) + self.assertNotIn("--embd-gguf", a) # its dense GGUF holds the token embedding + self.assertTrue(self.flag(a, "--mtp").endswith(base + "/mtp/rt")) # NVIDIA's own draft layer, not Qwen's + self.assertIn("NVIDIA Open Model Agreement", out) + self.assertIn("turned into a Strata pack on this PC", 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:]) diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py index 11b19be1..cf82cbd2 100644 --- a/tools/test_setup_pins.py +++ b/tools/test_setup_pins.py @@ -65,8 +65,17 @@ class HuggingFacePins(unittest.TestCase): """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"]) + self.assertEqual(sorted(sizes), ["NVFP4", "NVFP4-NVIDIA", "NVFP4-QAD"]) for m in sizes: + if setup.MODELS[m].get("prepare"): # NVIDIA's checkpoint: pinned files, prepared on the PC + 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(): + self.assertEqual(role, "src") + self.assertGreater(size, 0) + self.assertRegex(sha, r"^[0-9a-f]{64}$") + self.assertEqual(sorted(setup.ready_paths(m, setup.Path("M"))), ["dense", "mtp", "pack", "ple"]) + continue 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():