From 5abf03bba39c7531bc1e2b5fc0cdba59e16c2bb7 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sat, 14 Nov 2026 23:14:46 -0500 Subject: [PATCH 01/11] Prepare Inkling 2 Small NVFP4 across four hosts for DGX Spark TP4 The Inkling 2 Small NVFP4 recipe prepared only on four GPUs of one host: it rejected a multi-host rendezvous, built its collectives on CUDA peer memory, and admitted compute capability 12.0 alone. Each rank holds a quarter of the 344 GB checkpoint, which fits a DGX Spark (GB10, 121 GiB unified memory), so four Sparks joined by RoCE can serve the model once the recipe places one rank per host. The recipe follows the multi-host shape the DeepSeek V4 recipe uses (51864a2b, #240): host placement and the ring or chain choice travel in PreparationConfig, and one RoCEnante runtime replaces the per-role peer-memory channels when the rank group spans hosts. RoCEnante reductions carry BF16 only, so cross-host ranks round each partial sum to BF16 before reducing; the single-host path keeps its FP32 reductions, because that precision is available there and its prepared graphs must not change. What changed, in ignition/recipes/inkling2. Before, recipe.prepare raised when given `ranks` and always used process-local GPUs 0 through 3. Now, with `ranks`, each rank uses GPU 0 of its own host, and hosts, roce_ring and roce_chain flow from the plan into PreparationConfig, which requires four distinct (host, GPU) placements and validates the routing shape with ignition.planning.host_shape_error. bootstrap._collective_runtimes allocates the channels: when the coordinator spans hosts, one RoCEnante runtime carries the hidden reductions and the vocabulary, sampling and log-probability gathers, sized from the decode rows, the drafter's block of every request, the prefill chunk and each rank's vocabulary partition; otherwise it creates the same all-reduce and all-gather peer-memory runtimes with the same arguments as before. The shared runtime is closed once. decoder.reduction_dtype selects BF16 for a RoCE runtime and FP32 otherwise, and the embedding, attention and expert partial sums are cast to it before each reduction. prepare_rank admits compute capability (12, 1) beside (12, 0); the exact check existed because the recipe had been tested on RTX PRO 6000 alone. On an integrated GPU it releases the checkpoint's page cache after loading weights, since unified memory counts those pages against the GPU. The request limit stays 8 and the declared defaults are unchanged. docs/model-preparation.md gives the four-host export, join and serve commands and the qualified configuration, docs/roce-ring.md lists the recipe among multi-host preparations, and docs/TODO.txt records the unrun comparisons. The result is that `ignition export --ranks 4` with three `ignition join` peers prepares this recipe on four hosts, and `flare run` serves the core across them. Single-host preparation builds the same channels and FP32 reductions as before. Evidence, on four DGX Sparks (GB10, compute capability 12.1, one GPU each), RoCE over ConnectX-7 with mesh routing, the checkpoint on rank zero only and peers reading their tensor ranges from it (80.27 GiB each, about 2.3 Gbit/s). Before this change the recipe rejected `ranks`. After it, a reduced core (--no-mtp --language-model-only --max-concurrency 1 --prefill-chunk-size 512 --autotune-effort off --no-compile, no memory reserve) exported 8 graphs in 18 min 43 s and served across the four hosts: 82.91 GiB loaded per rank and a 24.5 GiB cache with 6,414,336 KV tokens. A chat completion, a streamed completion (90 events), two requests against the one slot, and a 7,150-token lookup prefilled in fourteen 512-token chunks returned the expected answers, and SIGTERM shutdown completed in 3.5 s. The RoCE loss counters (out_of_sequence, packet_seq_err, local_ack_timeout_err, rnr_nak_retry_err, summed over sixteen ports) did not change during export or serving. tests/recipes/test_inkling2_hosts.py (14 passed, CPU only) covers placement and routing validation, the plan fitting four GB10 hosts, dispatch of the plan to the rank group, the RoCE runtime's capacities, the unchanged peer-memory channel arguments, and the reduction element type. With tests/cli/test_inkling2.py, tests/cli/test_planning.py and tests/recipes/test_declarations.py: 249 passed, 9 failed, 14 skipped; the same three files on the parent commit give 235 passed, 14 skipped and the same 9 failures (Qwen declaration assertions, a missing Kimi checkpoint directory, DeepSeek V4.1 and Muse Spark collective-policy cases, and the collective ladder round trip). Limitations. An export of the declared eight-request configuration with drafting, vision, tuning and compilation was started on the four Sparks and stopped at graph construction after about seven minutes; it has not completed there. Not run: a numerical comparison of BF16 cross-host reductions with single-host FP32 output, the server tests of tests/server/test_inkling2.py on Sparks, ring and chain routing, and single-host GPU preparation after this change. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/TODO.txt | 6 + docs/model-preparation.md | 59 +++++++++- docs/roce-ring.md | 3 +- ignition/recipes/inkling2/bootstrap.py | 84 +++++++++++--- ignition/recipes/inkling2/decoder.py | 31 ++++-- ignition/recipes/inkling2/recipe.py | 14 ++- tests/recipes/test_inkling2_hosts.py | 148 +++++++++++++++++++++++++ 7 files changed, 310 insertions(+), 35 deletions(-) create mode 100644 tests/recipes/test_inkling2_hosts.py diff --git a/docs/TODO.txt b/docs/TODO.txt index de548f44e..d03031093 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -8,6 +8,12 @@ populated large vision graphs. Canonical vision comparisons cover at most 256 live patches. +[ ] Compare Inkling 2 output across four DGX Sparks, where cross-host hidden + reductions round partial sums to BF16, with the single-host FP32 + reductions, and run the effort-zero cases of tests/server/test_inkling2.py + there. Complete an export of the declared eight-request configuration on + DGX Sparks and run the default-effort cases against it. + [ ] Fix native TP4 shutdown reporting "free(): double free detected in tcache 2" after server drain with Inkling 2 cores. Reproduces with compiled and uncompiled graphs; preserve the successful request drain and GPU release. diff --git a/docs/model-preparation.md b/docs/model-preparation.md index ea2c33aeb..a490b21ef 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1306,8 +1306,9 @@ flare-cli/target/release/flare run /data/flare-runtime/minimax-m3.1-flash-tp4.sa ## Inkling 2 Small NVFP4 The `inkling-2-small-nvfp4` alias selects the local checkpoint -`/data/models/Inkling-2-Small-NVFP4`. Preparation requires four SM120 GPUs and -the bundled DSpark weights in `mtp.safetensors`. Target experts retain the +`/data/models/Inkling-2-Small-NVFP4`. Preparation requires four SM120 or SM121 +GPUs, in one host or one per host, and the bundled DSpark weights in +`mtp.safetensors`. Target experts retain the checkpoint's static NVFP4 scales, with A4 activations for prefill and A16 activations for decoding and speculative verification. DSpark uses MXFP8 feed-forward projections and BF16 attention and recurrent state. Target and @@ -1358,6 +1359,60 @@ FLARE_RUN_CUDA_TESTS=1 FLARE_INKLING2_TEST_URL=http://127.0.0.1:8000 \ .venv/bin/python -m pytest tests/server/test_inkling2.py -k default-effort -q ``` +Each rank holds a quarter of the 344 GB checkpoint, so DGX Spark serving runs +one rank on each of four hosts, reducing through RoCEnante over their +ConnectX-7 ports. Ranks on one host reduce FP32 partial sums; ranks on separate +hosts round each partial sum to BF16 before the reduction, because RoCEnante +reduces BF16. One runtime carries the hidden reductions, the vocabulary gathers +of FP32 logits as BF16 column pairs, the sampling and log-probability gathers, +and the sampling broadcasts. Multi-host export requires the checkpoint +directory on rank zero only; peers read their tensor ranges from it. On rank +zero, whose preparation address is `10.200.0.13`, with +`[memory] reserve = "4G"`: + +```sh +ulimit -Sn 65536 +.venv/bin/ignition export /data/models/Inkling-2-Small-NVFP4 \ + --ranks 4 --rendezvous 10.200.0.13:29630 --gpus 0 \ + --max-concurrency 8 --image-concurrency 4 \ + --prefill-chunk-size 4096 --mtp-draft-tokens 7 \ + --speculative-token-capacity 64 --speculative-graph-budget 64 \ + --autotune-effort default +``` + +On each peer, with its rank from 1 through 3: + +```sh +.venv/bin/ignition join 10.200.0.13:29630 --rank 1 --ranks 4 +``` + +Serve with `flare run CACHE_ENTRY --rank 0 --rendezvous 10.200.0.13:29800 +--gpus 0 --mtp-draft-tokens 7 --no-history-drafts` on rank zero and +`flare run --rank R --rendezvous 10.200.0.13:29800 --gpus 0` with the same +serving options on each peer. Follow the [multi-host guide](multi-host.md) for +preparation authentication, rank placement and publisher acceptance. Hosts +that share a switch need neither `--roce-ring` nor `--roce-chain`. + +Disk: rank zero holds the complete core. Each peer holds the payloads it +prepares, about a quarter of the core, and for serving the rank core it +receives, of the same size; the prepared payloads can be removed after export. +Drop the page cache on every host before export and before serving. + +Qualification on four DGX Sparks (GB10, SM121, 121 GiB each) joined by a +switch, with one pair also cabled directly, covers a reduced core: no drafting +and no vision, one request, 512-token chunks, no kernel tuning and uncompiled +forwards (`--no-mtp --language-model-only --max-concurrency 1 +--prefill-chunk-size 512 --autotune-effort off --no-compile`, with no memory +reserve). It exported 8 graphs in 18 min 43 s. Native loading used 82.9 GiB +per rank and allocated a 24.5 GiB cache with 6414336 KV-token slots. The +service answered a chat completion, a streamed completion, two requests +against its one slot, and a 7150-token prompt prefilled in fourteen chunks, +with no change in the RoCE loss counters. The eight-request configuration +above has not completed an export on DGX Sparks. Also not run there: the +default-effort and effort-zero cases of `tests/server/test_inkling2.py`, +`--roce-ring`, `--roce-chain`, and a comparison of BF16 cross-host reductions +with single-host FP32 output. + ## Muse Spark Open The `muse-spark-open-nvfp4` alias selects diff --git a/docs/roce-ring.md b/docs/roce-ring.md index 8e0ad8481..810bd03e8 100644 --- a/docs/roce-ring.md +++ b/docs/roce-ring.md @@ -5,7 +5,8 @@ its neighbors in rank order. A native CPU proxy forwards transfers addressed to other ranks through those neighbors. The transport supports 2 through 16 ranks; each model recipe determines which tensor-parallel sizes it can prepare, and the multi-host preparation rendezvous admits two, three, or four ranks. -GLM-5.3 Flash, MiMo V2.6, DeepSeek V4 Flash, and Qwen3.8 Flash prepare multi-host TP2 and TP4 cores. +GLM-5.3 Flash, MiMo V2.6, DeepSeek V4 Flash, and Qwen3.8 Flash prepare multi-host TP2 and TP4 cores; +Inkling 2 Small NVFP4 prepares multi-host TP4 cores. Ring routing applies to RoCEnante's one-shot reductions, two-shot reductions, and variable-length gathers. The collective algorithms and arithmetic belong diff --git a/ignition/recipes/inkling2/bootstrap.py b/ignition/recipes/inkling2/bootstrap.py index fc7a2fde6..886f9c8bd 100644 --- a/ignition/recipes/inkling2/bootstrap.py +++ b/ignition/recipes/inkling2/bootstrap.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Prepare Inkling 2 text, vision and complete DSpark generation graphs on four local GPUs.""" +"""Prepare Inkling 2 text, vision and complete DSpark generation graphs on four GPUs of one host or of four hosts.""" import contextlib import hashlib @@ -23,7 +23,8 @@ from ignition.components.state_transfer import StateCommands from ignition.preparation.capture import capture_forwards from ignition.preparation.checkpoint import inspect_indexed_checkpoint -from ignition.preparation.collectives import CollectivePreparation, create_all_reduce_runtime, create_all_gather_runtime +from ignition.preparation.collectives import (CollectivePreparation, create_all_reduce_runtime, create_all_gather_runtime, + create_roce_runtime) from ignition.preparation.execution import GraphSignature from ignition.preparation.fixtures.recurrent import register_benchmark_state from ignition.preparation.host_memory import release_unused @@ -54,6 +55,10 @@ class PreparationConfig: autotune_effort: str = "off" tuning_replica: TuningReplica | None = None devices: tuple[int, ...] = (0, 1, 2, 3) + # Device ordinals are host-local when each rank runs on its own host. + hosts: tuple[str, ...] | None = None + roce_ring: bool = False + roce_chain: bool = False context: int = 1048576 prefill_chunk_size: int = 4096 max_active: int = 8 @@ -73,8 +78,17 @@ class PreparationConfig: benchmark_selection: object | None = None def __post_init__(self): - if len(self.devices) != WORLD_SIZE or len(set(self.devices)) != WORLD_SIZE or min(self.devices) < 0: - raise ValueError("Inkling 2 preparation requires four distinct GPUs on one host") + placements = tuple(zip(self.hosts or ("",) * len(self.devices), self.devices)) + if (not isinstance(self.devices, tuple) or len(self.devices) != WORLD_SIZE + or len(set(placements)) != WORLD_SIZE + or self.hosts is not None and (not isinstance(self.hosts, tuple) or len(self.hosts) != WORLD_SIZE) + or any(type(d) is not int or d < 0 for d in self.devices)): + raise ValueError("Inkling 2 preparation requires four distinct GPUs") + from ignition.planning import host_shape_error + + error = host_shape_error(self.roce_ring, self.roce_chain, None if self.hosts is None else len(self.hosts)) + if error: + raise ValueError(error) request_capacity(self.max_active) if not 1 <= self.max_active <= 8: raise ValueError("Inkling 2 request capacity must be in [1, 8]") @@ -124,6 +138,41 @@ def _logit_gather_bytes(rows, width): return rows * width * 4 +def _collective_runtimes(config, group, device, *, coordinator, core_storage, hidden, local_vocabulary, draft_block): + """Allocate the hidden reduction and the vocabulary, sampling and log-probability gather channels. + + `hidden` is the model width, `local_vocabulary` one rank's padded vocabulary columns and `draft_block` + the positions the drafter reduces per request. Ranks on separate hosts run every collective in + rank-serial order over one RoCEnante runtime, which all four roles share; the sampling and + log-probability channels are None without drafting. + """ + slots, world = request_capacity(config.max_active), len(config.devices) + tokens = max(config.prefill_chunk_size, config.decode_tokens) + vocabulary_rows = max(config.decode_samples, slots) + if coordinator.spans_hosts: + # One-shot reductions cover decode and verification rows and the drafter's block of every request; + # prefill chunks reduce through the pipelined two-shot path. The largest gather is each rank's FP32 + # vocabulary partition of every sampled row, carried as BF16 column pairs: 4 * local_vocabulary + # bytes per row. A row of the other gathers is at most 1024 bytes (the FP32 log-probability summary), + # and the packed sampling results of all rows fit in one vocabulary row. + runtime = create_roce_runtime(group, device, + max_tokens=max(config.decode_tokens, slots * draft_block if config.drafting else 0), pipe_tokens=tokens, + hidden_size=hidden, gather_bytes=vocabulary_rows * local_vocabulary * 4, + ring=config.roce_ring, ring_open=config.roce_chain, core_storage=core_storage) + drafting = runtime if config.drafting else None + return runtime, runtime, drafting, drafting + ipc = core_storage.peer_storage + runtime = create_all_reduce_runtime(group, device, max_tokens=min(tokens, 1024), + hidden_size=hidden, element_bytes=4, ipc=ipc, collective_tuning=config.collective_tuning) + vocabulary = create_all_gather_runtime(group, device, max_rows=vocabulary_rows, + columns=2 * local_vocabulary * world, ipc=ipc) + sampling = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, + columns=64 * world, ipc=ipc) if config.drafting else None) + logprob = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, + columns=512 * world, ipc=ipc) if config.drafting else None) + return runtime, vocabulary, sampling, logprob + + class _Softcapped: def __init__(self, projection, softcap): self.projection, self.softcap = projection, softcap @@ -155,8 +204,8 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): shard = TensorParallelShard(rank, world) device = torch.device("cuda", config.devices[rank]) torch.cuda.set_device(device) - if torch.cuda.get_device_capability(device) != (12, 0): - raise ValueError("Inkling 2 preparation requires SM120 GPUs") + if torch.cuda.get_device_capability(device) not in ((12, 0), (12, 1)): + raise ValueError("Inkling 2 preparation requires SM120 or SM121 GPUs") with phase(progress, "Inspect checkpoint"): manifest = inspect_indexed_checkpoint(snapshot) headers = [entry.header_sha256 for entry in manifest.shards] @@ -170,6 +219,11 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): weights = ModelWeights.load(manifest, device, shard=shard, layers=config.decoder_layers, progress=progress, drafting=config.drafting, vision=config.vision) weights_bytes = torch.cuda.memory_allocated(device) + if torch.cuda.get_device_properties(device).is_integrated: + from ignition.preparation.host_memory import release_page_cache + + # Unified memory counts cached checkpoint pages against the GPU; drop them after loading. + release_page_cache(manifest.shard_paths) del manifest release_unused() transient = contextlib.ExitStack() @@ -200,16 +254,10 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): width = max((w for _, w, _ in config.speculative_round_shapes), default=1) completion = CompletionOutputs.allocate((2, slots, VECTOR_TOKENS_FIELD + width), device=device) coordinator = CollectivePreparation(group) - runtime = create_all_reduce_runtime(group, device, max_tokens=min(tokens, 1024), - hidden_size=text.hidden, element_bytes=4, ipc=core_storage.peer_storage, - collective_tuning=config.collective_tuning) - vocabulary_runtime = create_all_gather_runtime(group, device, - max_rows=max(config.decode_samples, slots), columns=2 * weights.head.shape[0] * world, - ipc=core_storage.peer_storage) - sampling_runtime = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, - columns=64 * world, ipc=core_storage.peer_storage) if config.drafting else None) - logprob_runtime = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, - columns=512 * world, ipc=core_storage.peer_storage) if config.drafting else None) + runtime, vocabulary_runtime, sampling_runtime, logprob_runtime = _collective_runtimes( + config, group, device, coordinator=coordinator, core_storage=core_storage, + hidden=text.hidden, local_vocabulary=weights.head.shape[0], + draft_block=model.draft.block) identity = hashlib.sha256(json.dumps({"text": model.text.__dict__ | {"local_layers": sorted(model.text.local_layers)}, "quantization": model.quantization, "headers": headers, "world_size": world, "decoder_layers": len(weights.layers), "contract": "inkling2.paged-text.v1"}, @@ -369,4 +417,6 @@ def add(name, forward, kind, rows, tokens, fields, enabled=None, packed=0): export_zero_ranges=completion.zero_ranges(), resources=(weights, pool, requests, inputs, admission, commands, completion, forwards, arena, session, compiled, stream, graph_pool, coordinator, runtime, vocabulary_runtime, sampling_runtime, logprob_runtime, speculation, vision_state), - close_resources=tuple(r for r in (runtime, vocabulary_runtime, sampling_runtime, logprob_runtime) if r is not None)) + # Ranks on separate hosts share one runtime across these roles; close it once. + close_resources=tuple(dict.fromkeys( + r for r in (runtime, vocabulary_runtime, sampling_runtime, logprob_runtime) if r is not None))) diff --git a/ignition/recipes/inkling2/decoder.py b/ignition/recipes/inkling2/decoder.py index 46337ccac..89e6241b5 100644 --- a/ignition/recipes/inkling2/decoder.py +++ b/ignition/recipes/inkling2/decoder.py @@ -1,7 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Tensor-parallel target execution with complete accepted-state commits.""" +"""Tensor-parallel target execution with complete accepted-state commits. + +Ranks on one host reduce FP32 partial sums. Ranks on separate hosts reduce through RoCEnante, +which carries BF16: each rank rounds its partial sum to BF16 before the reduction. +""" from dataclasses import dataclass from types import SimpleNamespace @@ -9,7 +13,7 @@ import torch from ignition.components.causal_convolution import PreparedCausalConvolution -from ignition.components.collectives import PreparedAllGather, PreparedChunkedAllReduce +from ignition.components.collectives import PreparedAllGather, PreparedChunkedAllReduce, _roce from ignition.components.linear import UnquantizedProjection from ignition.components.rms_norm import PreparedTorchRMSNorm from ignition.components.moe import PreparedRouter, PreparedRoutedExperts, RouterScratch @@ -36,6 +40,11 @@ def rows(self, tokens, samples): return type(self)(self.logits[:samples], self.local_logits[:samples], tokens) +def reduction_dtype(runtime): + """Element type of cross-rank hidden reductions: BF16 over RoCEnante, FP32 on one host.""" + return torch.bfloat16 if runtime is not None and _roce(runtime) else torch.float32 + + @dataclass(frozen=True) class ResidualState: blocks: tuple[torch.Tensor, ...] @@ -43,11 +52,11 @@ class ResidualState: class PreparedLayer(torch.nn.Module): - def __init__(self, layer, weights, text, pool, metadata, reduction, *, mode, tokens, + def __init__(self, layer, weights, text, pool, metadata, reduction, reduction_dtype, *, mode, tokens, session, workspace, name, examples=None): super().__init__() self.layer, self.weights, self.text, self.mode = layer, weights, text, mode - self.reduction = reduction + self.reduction, self.reduction_dtype = reduction, reduction_dtype self.attention = PreparedAttention(layer, weights.attention, text, LayerCache.of(pool, layer), metadata, mode=mode, tokens=tokens, session=session, workspace=workspace, name=name + ".attention", examples=examples, tuning_page_count=((int(pool.memory_capacity[0].item()) - 1) * pool.ring_row_pages + pool.geometry.ring // 128 @@ -85,7 +94,7 @@ def forward(self, state, metadata): streams = (tuple(norm(state.partial) for norm in self.input_norms) if self.input_mix is None else self.input_mix((*state.blocks, state.partial))) _, attention_partial, attention_values = self.attention.attend(streams, m) - attention_raw = self.reduction(attention_partial).to(torch.bfloat16) + attention_raw = self.reduction(attention_partial.to(self.reduction_dtype)).to(torch.bfloat16) attention, attention_previous = self.attention_convolution(attention_raw, m) if self.layer % t.residual_block == 0: mlp_input = self.mlp_mix((*state.blocks, state.partial, attention))[0] @@ -93,7 +102,7 @@ def forward(self, state, metadata): mlp_input = self.mlp_mix((*state.blocks, state.partial), addend=attention)[0] routes = self.router(self.router_projection(mlp_input.float()), num_valid_tokens=m.live_counts[:1]) expert_partial = self.experts(mlp_input, routes.ids, routes.weights) - mlp_raw = self.reduction(expert_partial.float()).to(torch.bfloat16) + mlp_raw = self.reduction(expert_partial.to(self.reduction_dtype)).to(torch.bfloat16) mlp, mlp_previous = self.mlp_convolution(mlp_raw, m) if self.mode != "verify": self.attention_convolution.commit(attention_previous, attention_raw, m) @@ -124,10 +133,12 @@ def __init__(self, weights, tables, scratch, metadata, pool, *, mode, session, n examples = {} if examples is None else examples def example(role, shape, dtype=torch.bfloat16): return declaration_tensor(examples, "inkling.decoder." + role, shape, dtype, device) - partial = example("partial", (tokens, text.hidden), torch.float32) - self.reduce = PreparedChunkedAllReduce(partial, example("reduced", partial.shape, torch.float32), + # Traced forwards read this attribute, never the runtime, which compile workers see as a placeholder. + self.reduction_dtype = reduction_dtype(runtime) + partial = example("partial", (tokens, text.hidden), self.reduction_dtype) + self.reduce = PreparedChunkedAllReduce(partial, example("reduced", partial.shape, self.reduction_dtype), runtime=runtime, coordinator=coordinator, session=session, name=name + ".reduction").functional(session=session) - self.layers = [PreparedLayer(index, layer, text, pool, metadata, self.reduce, mode=mode, tokens=tokens, + self.layers = [PreparedLayer(index, layer, text, pool, metadata, self.reduce, self.reduction_dtype, mode=mode, tokens=tokens, session=session, workspace=workspace, name=f"{name}.layer{index}", examples=examples) for index, layer in enumerate(weights.layers)] self.logits = PreparedLogits(weights.head, text, weights.rank, tokens=samples, @@ -155,7 +166,7 @@ def release_outputs(self): def __call__(self, metadata): w, t, m = self.weights, self.weights.config.text, metadata embedded = embedding_rows(w.embedding, m.token_ids, self.first_token) - hidden = self.reduce(embedded.float()).to(torch.bfloat16) + hidden = self.reduce(embedded.to(self.reduction_dtype)).to(torch.bfloat16) hidden = self.embedding_norm(hidden) if self.vision_state is not None and self.mode == "prefill": self.vision_state.inject(m, hidden) diff --git a/ignition/recipes/inkling2/recipe.py b/ignition/recipes/inkling2/recipe.py index 5ce5d314c..ec4fd292d 100644 --- a/ignition/recipes/inkling2/recipe.py +++ b/ignition/recipes/inkling2/recipe.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Inkling 2 Small NVFP4 preparation on four GPUs with bundled DSpark and vision.""" +"""Inkling 2 Small NVFP4 preparation on four GPUs, of one host or one per host, with bundled DSpark and vision.""" from types import MappingProxyType @@ -12,11 +12,13 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_graphs=False, core_storage=None, ranks=None): + """Prepare the plan's catalog on process-local GPUs 0 through 3. + + With `ranks`, rank zero's multi-host rendezvous, each rank uses its own host's GPU 0. + """ from ignition.preparation.rank_group import prepare_group from .bootstrap import PreparationConfig, prepare_rank - if ranks is not None: - raise ValueError("Inkling 2 preparation requires four GPUs on one host") if plan.prompt_logprobs: raise ValueError("Inkling 2 preparation does not capture prompt scoring graphs") speculation = plan.speculation @@ -31,7 +33,9 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ native_dense_activations=plan.native_dense_activations, lock_gpu_clocks=plan.lock_gpu_clocks and plan.autotune_effort != "off", autotune_effort=plan.autotune_effort, tuning_replica=plan.tuning_replica, - devices=tuple(range(plan.world_size)), context=plan.context, prefill_chunk_size=plan.prefill_chunk, + devices=tuple(range(plan.world_size)) if ranks is None else (0,) * plan.world_size, + hosts=None if ranks is None else ranks.hosts, roce_ring=plan.roce_ring, roce_chain=plan.roce_chain, + context=plan.context, prefill_chunk_size=plan.prefill_chunk, max_active=plan.concurrency, image_concurrency=plan.image_concurrency, snapshot_budget_bytes=plan.snapshots * plan.costs.state_row_bytes, headroom_bytes=plan.headroom_bytes + plan.reserve_bytes, compile_decoder=compile_forwards, @@ -40,7 +44,7 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ mtp_only=speculation is not None and speculation.mtp_only, benchmark_selection=plan.benchmark_selection, **drafting) return prepare_group(snapshot, config, prepare_rank, progress=progress, core_storage=core_storage, - checkpoint=plan.checkpoint) + ranks=ranks, checkpoint=plan.checkpoint) def usage(prepared): diff --git a/tests/recipes/test_inkling2_hosts.py b/tests/recipes/test_inkling2_hosts.py new file mode 100644 index 000000000..cbb438e1b --- /dev/null +++ b/tests/recipes/test_inkling2_hosts.py @@ -0,0 +1,148 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling 2 TP4 host placement and channels preserve the local preparation contract.""" + +from dataclasses import replace +from types import SimpleNamespace + +import pytest +import torch + +from ignition import planning +from ignition.recipes.inkling2 import bootstrap, decoder, recipe + +HOSTS = ("hertz", "maxwell", "ampere", "faraday") +HIDDEN, LOCAL_VOCABULARY, DRAFT_BLOCK = 4608, 201024 // 4, 8 +GEOMETRY = dict(hidden=HIDDEN, local_vocabulary=LOCAL_VOCABULARY, draft_block=DRAFT_BLOCK) + + +def test_four_hosts_may_each_use_their_own_gpu_zero(): + config = bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS) + assert config.devices == (0,) * 4 + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0,) * 4) + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0,) * 4, hosts=("hertz",) * 4) + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS[:3]) + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0, 1), hosts=HOSTS[:2]) + + +def test_ring_and_chain_need_hosts_in_rank_order(): + with pytest.raises(ValueError, match="--roce-ring"): + bootstrap.PreparationConfig(roce_ring=True) + with pytest.raises(ValueError, match="exclude each other"): + bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, roce_ring=True, roce_chain=True) + assert bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, roce_ring=True).roce_ring + assert bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, roce_chain=True).roce_chain + + +def _gb10(count): + return tuple(planning.Gpu(i, "GB10", f"GPU-{i}", 121 << 30, 115 << 30, (12, 1)) for i in range(count)) + + +@pytest.mark.parametrize("concurrency, chunk, capacity", [(8, 4096, 64)]) +def test_four_gb10_hosts_fit_the_declared_configuration(concurrency, chunk, capacity): + speculation = replace(recipe.RECIPE.speculation, token_capacity=capacity) + plan = planning.plan(recipe.RECIPE, recipe.RECIPE.checkpoints[0], _gb10(4), selected=(0, 1, 2, 3), + concurrency=concurrency, reserve_bytes=4 << 30, speculation=speculation, + prefill_chunk=chunk) + assert plan.fits and plan.world_size == 4 + assert (plan.concurrency, plan.prefill_chunk, plan.speculative_token_capacity) == (concurrency, chunk, capacity) + assert plan.guaranteed_tokens >= planning.MINIMUM_REQUEST_TOKENS + # Request rows, their prefix-cache snapshots and the chunk's scratch leave most of the supply to KV pages. + assert plan.page_bytes >= 16 << 30 + + +@pytest.mark.parametrize("remote", [False, True]) +@pytest.mark.parametrize("ring", [False, True]) +def test_recipe_dispatches_the_complete_plan_to_the_rank_group(monkeypatch, remote, ring): + from ignition.preparation import rank_group + + ring = ring and remote + plan = planning.fit(recipe.RECIPE, recipe.RECIPE.checkpoints[0], _gb10(4), concurrency=8, + reserve_bytes=4 << 30, speculation=recipe.RECIPE.speculation, roce_ring=ring) + ranks = SimpleNamespace(hosts=HOSTS) if remote else None + calls, result, storage = [], object(), object() + monkeypatch.setattr(rank_group, "prepare_group", lambda *args, **kwargs: calls.append((args, kwargs)) or result) + assert recipe.prepare("checkpoint", plan, compile_forwards=True, kernel_cache=None, progress=None, + core_storage=storage, ranks=ranks) is result + (snapshot, config, forward), kwargs = calls[0] + assert snapshot == "checkpoint" and forward is bootstrap.prepare_rank + assert config.devices == ((0,) * 4 if remote else (0, 1, 2, 3)) + assert config.hosts == (HOSTS if remote else None) + assert config.roce_ring is ring and not config.roce_chain + assert config.max_active == 8 and config.drafting and config.vision and config.draft_tokens == 7 + assert kwargs["ranks"] is ranks and kwargs["checkpoint"] is plan.checkpoint + assert kwargs["core_storage"] is storage + + +@pytest.mark.parametrize("drafting", [False, True]) +@pytest.mark.parametrize("chain", [False, True]) +def test_remote_channels_share_one_roce_runtime_without_pcie(monkeypatch, drafting, chain): + from ignition.components.collectives import packed_broadcast_layout + from ignition.components.vocabulary_logprobs import _SUMMARY + from ignition.components.vocabulary_sampling import SUMMARY_WORDS + + config = bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, max_active=8, drafting=drafting, + roce_chain=chain) + calls, runtime, storage = [], object(), object() + monkeypatch.setattr(bootstrap, "create_roce_runtime", + lambda group, device, **kwargs: calls.append(kwargs) or runtime) + for name in ("create_all_reduce_runtime", "create_all_gather_runtime"): + monkeypatch.setattr(bootstrap, name, lambda *args, **kwargs: pytest.fail("host ranks cannot use CUDA IPC")) + channels = bootstrap._collective_runtimes(config, None, None, + coordinator=SimpleNamespace(spans_hosts=True), core_storage=storage, **GEOMETRY) + assert channels == (runtime, runtime, runtime if drafting else None, runtime if drafting else None) + (call,) = calls + assert call["core_storage"] is storage and call["hidden_size"] == HIDDEN + assert call["ring"] is False and call["ring_open"] is chain + # One reduction covers a whole prefill chunk; decode, verification and draft rows reduce one-shot. + assert call["pipe_tokens"] == max(config.prefill_chunk_size, config.decode_tokens) == 4096 + assert call["max_tokens"] >= config.decode_tokens + assert call["max_tokens"] * HIDDEN * 2 % 16 == 0 and call["pipe_tokens"] * HIDDEN * 2 % 16 == 0 + rows = max(config.decode_samples, 8) + # FP32 vocabulary partitions of every sampled row travel as BF16 column pairs. + assert call["gather_bytes"] == rows * LOCAL_VOCABULARY * 4 and call["gather_bytes"] % 16 == 0 + sampled = [((rows,), torch.int64), ((rows,), torch.bool), ((rows,), torch.float32), ((rows,), torch.float32)] + assert call["gather_bytes"] >= (packed_broadcast_layout(sampled)[1] + 15) // 16 * 16 + if drafting: + assert call["max_tokens"] >= 8 * DRAFT_BLOCK + assert (config.decode_tokens, config.decode_samples) == (64, 64) + # Sampling statistics and log-probability summaries are FP32 rows of 32 and 256 words per rank. + assert call["gather_bytes"] >= rows * max(SUMMARY_WORDS, _SUMMARY) * 4 + else: + assert call["max_tokens"] == config.decode_tokens == 8 + + +@pytest.mark.parametrize("drafting", [False, True]) +def test_local_channels_are_unchanged(monkeypatch, drafting): + config = bootstrap.PreparationConfig(max_active=8, drafting=drafting, collective_tuning="runtime") + gathers, reductions = [], [] + monkeypatch.setattr(bootstrap, "create_all_gather_runtime", + lambda group, device, **kwargs: gathers.append(kwargs) or object()) + monkeypatch.setattr(bootstrap, "create_all_reduce_runtime", + lambda group, device, **kwargs: reductions.append(kwargs) or object()) + monkeypatch.setattr(bootstrap, "create_roce_runtime", + lambda *args, **kwargs: pytest.fail("local ranks share CUDA IPC")) + ipc = object() + channels = bootstrap._collective_runtimes(config, None, None, + coordinator=SimpleNamespace(spans_hosts=False), core_storage=SimpleNamespace(peer_storage=ipc), **GEOMETRY) + present = [channel for channel in channels if channel is not None] + assert len(present) == (4 if drafting else 2) and len({id(channel) for channel in present}) == len(present) + assert reductions == [dict(max_tokens=1024, hidden_size=HIDDEN, element_bytes=4, ipc=ipc, + collective_tuning="runtime")] + samples = config.decode_samples + assert gathers[0] == dict(max_rows=max(samples, 8), columns=2 * 201024, ipc=ipc) + assert gathers[1:] == ([dict(max_rows=samples, columns=64 * 4, ipc=ipc), + dict(max_rows=samples, columns=512 * 4, ipc=ipc)] if drafting else []) + + +def test_hidden_reductions_round_to_bf16_only_over_roce(monkeypatch): + local, remote = object(), object() + monkeypatch.setattr(decoder, "_roce", lambda runtime: runtime is remote) + assert decoder.reduction_dtype(None) == torch.float32 + assert decoder.reduction_dtype(local) == torch.float32 + assert decoder.reduction_dtype(remote) == torch.bfloat16 From a4f446a21c1f05fb28893a74aa7bb97bf94052ab Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sat, 14 Nov 2026 23:16:12 -0500 Subject: [PATCH 02/11] Raise the Inkling 2 Small NVFP4 request limit to 32 The Inkling 2 Small NVFP4 recipe rejected more than eight concurrent requests: PreparationConfig bounded the request capacity to [1, 8] and the recipe declared max_concurrency=8. Four DGX Sparks hold enough memory beside the weights for a 32-request core with 8192-token prefill chunks, and nothing in the recipe depends on eight. Request slots, batch capacities, pool rows, DSpark scratch, vision slots, gather rows, prefill scratch and the page count already derive from the configured request count, so raising the bound is sufficient and no capacity needed a separate change. What changed. Before, bootstrap.PreparationConfig raised for max_active above 8 and planning rejected --max-concurrency above 8 for this recipe. Now the bound is [1, 32] and the recipe declares max_concurrency=32. The default concurrency (8), default prefill chunk (4096) and default verification capacity (64 rows, 64-graph budget) are unchanged, so an export without flags prepares the same catalog as before. tests/server/test_inkling2.py no longer pins eight requests and 4096-token chunks: it accepts a service with at least eight requests and 4096- or 8192-token chunks and scales its chunk-crossing prompts with the chunk size the service reports. tests/cli/test_inkling2.py asserts the declared maximum, and tests/recipes/test_inkling2_hosts.py adds the 32-request bound, round shapes, RoCE capacities and planning fit. docs/model-preparation.md documents the 32-request, 8192-token DGX Spark configuration in place of the eight-request one, and docs/TODO.txt replaces the pending eight-request Spark export with the planner estimate described below. The result is that the recipe prepares and serves up to 32 concurrent requests. On four DGX Sparks the 32-request, 8192-token configuration with seven drafts and vision exports, loads with 7.6 GiB or more available per host, and answers 32 concurrent requests correctly. These are functional results; no throughput was measured. Evidence, on four DGX Sparks (GB10, 121 GiB unified memory each, one rank per host, RoCE over ConnectX-7 with mesh routing). Before this change the configuration could not be requested. After it, export with --max-concurrency 32 --image-concurrency 4 --prefill-chunk-size 8192 --mtp-draft-tokens 7 --speculative-token-capacity 128 --speculative-graph-budget 64 --autotune-effort default and a 4 GiB memory reserve took 1 h 25 min 30 s and produced 152 graphs in a 351 GB core (350,544,415,417 bytes): kernel tuning 675 s, compilation 1,893 s, compiled warmup 586 s, capture 485 s, export 1,078 s. The lowest MemAvailable during export was 11.5, 12.6, 12.5 and 13.1 GiB on ranks 0 through 3, and the graph pool is 2,840 MiB per rank. Verification capacity 128 with graph budget 64 is the value the DeepSeek V4.1 recipe declares for 32 requests and seven drafts. Serving loaded 90.06 to 90.24 GiB per rank. With the exported 4 GiB reserve the cache was 12.4 GiB with 2,392,064 KV tokens and 78 shared snapshot slots, leaving 12.0 to 12.5 GiB MemAvailable. With --memory-limit=-0G it was 16.5 GiB with 3,252,224 KV tokens and 106 snapshot slots, leaving 7.76 to 8.26 GiB after loading and 7.64 GiB at the lowest sample during 32 concurrent requests. On that service, tests/server/test_inkling2.py -k default-effort passed 7 cases: eight concurrent requests, streamed reasoning, prefix reuse and branching across a chunk, a tool call, a structured response, images across a chunk, and four images with four concurrent image requests. 16 and 32 concurrent exact-repeat requests were all correct, and a streamed completion succeeded. An 18,832-token lookup was answered correctly in four of four runs with a 2048-token output limit and in one of two runs with a 512-token limit; the other run spent all 512 tokens in reasoning. Its cause was not investigated, and docs/TODO.txt already records an intermittent long-prefix output-limit failure for this recipe. The RoCE loss counters did not change and earlyoom, the hosts' out-of-memory daemon, killed no process. CPU tests: tests/recipes/test_inkling2_hosts.py 18 passed; with tests/cli/test_inkling2.py, tests/cli/test_planning.py and tests/recipes/test_declarations.py, 253 passed, 9 failed, 14 skipped, the 9 failures being the ones the same files produce on main (Qwen declaration assertions, a missing Kimi checkpoint directory, DeepSeek V4.1 and Muse Spark collective-policy cases, and the collective ladder round trip). Limitations. The planner estimated 22.9 GiB of KV pages per rank where serving allocated 12.4 GiB at the same reserve; docs/TODO.txt records the correction of the declared rank costs. Not run: the 32-request configuration on RTX PRO 6000, a 16-request core, the eight-request configuration on DGX Sparks, the effort-zero server cases, and benchmarks. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/TODO.txt | 5 ++- docs/model-preparation.md | 61 ++++++++++++++------------ ignition/recipes/inkling2/bootstrap.py | 4 +- ignition/recipes/inkling2/recipe.py | 2 +- tests/cli/test_inkling2.py | 1 + tests/recipes/test_inkling2_hosts.py | 40 ++++++++++++++++- tests/server/test_inkling2.py | 21 +++++---- 7 files changed, 91 insertions(+), 43 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index d03031093..fab2560af 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -11,8 +11,9 @@ [ ] Compare Inkling 2 output across four DGX Sparks, where cross-host hidden reductions round partial sums to BF16, with the single-host FP32 reductions, and run the effort-zero cases of tests/server/test_inkling2.py - there. Complete an export of the declared eight-request configuration on - DGX Sparks and run the default-effort cases against it. + there. Planning at 32 requests and 8192-token chunks predicts 22.9 GiB of + KV pages per rank where native loading allocates 12.4 GiB; correct the + declared rank costs from a measured GB10 memory report. [ ] Fix native TP4 shutdown reporting "free(): double free detected in tcache 2" after server drain with Inkling 2 cores. Reproduces with compiled and diff --git a/docs/model-preparation.md b/docs/model-preparation.md index a490b21ef..1771ce7a2 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1366,17 +1366,17 @@ hosts round each partial sum to BF16 before the reduction, because RoCEnante reduces BF16. One runtime carries the hidden reductions, the vocabulary gathers of FP32 logits as BF16 column pairs, the sampling and log-probability gathers, and the sampling broadcasts. Multi-host export requires the checkpoint -directory on rank zero only; peers read their tensor ranges from it. On rank -zero, whose preparation address is `10.200.0.13`, with -`[memory] reserve = "4G"`: +directory on rank zero only; peers read their tensor ranges from it. The recipe +accepts up to 32 concurrent requests. On rank zero, whose preparation address +is `10.200.0.13`, with `[memory] reserve = "4G"`: ```sh ulimit -Sn 65536 .venv/bin/ignition export /data/models/Inkling-2-Small-NVFP4 \ --ranks 4 --rendezvous 10.200.0.13:29630 --gpus 0 \ - --max-concurrency 8 --image-concurrency 4 \ - --prefill-chunk-size 4096 --mtp-draft-tokens 7 \ - --speculative-token-capacity 64 --speculative-graph-budget 64 \ + --max-concurrency 32 --image-concurrency 4 \ + --prefill-chunk-size 8192 --mtp-draft-tokens 7 \ + --speculative-token-capacity 128 --speculative-graph-budget 64 \ --autotune-effort default ``` @@ -1387,31 +1387,36 @@ On each peer, with its rank from 1 through 3: ``` Serve with `flare run CACHE_ENTRY --rank 0 --rendezvous 10.200.0.13:29800 ---gpus 0 --mtp-draft-tokens 7 --no-history-drafts` on rank zero and -`flare run --rank R --rendezvous 10.200.0.13:29800 --gpus 0` with the same -serving options on each peer. Follow the [multi-host guide](multi-host.md) for +--gpus 0 --mtp-draft-tokens 7 --no-history-drafts --memory-limit=-0G` on rank +zero and `flare run --rank R --rendezvous 10.200.0.13:29800 --gpus 0` with the +same serving options on each peer. `--memory-limit=-0G` replaces the exported +4 GiB reserve, so the cache takes everything outside the integrated-memory +allowances, which leave about 8 GiB available on each host. Follow the [multi-host guide](multi-host.md) for preparation authentication, rank placement and publisher acceptance. Hosts that share a switch need neither `--roce-ring` nor `--roce-chain`. -Disk: rank zero holds the complete core. Each peer holds the payloads it -prepares, about a quarter of the core, and for serving the rank core it -receives, of the same size; the prepared payloads can be removed after export. -Drop the page cache on every host before export and before serving. - -Qualification on four DGX Sparks (GB10, SM121, 121 GiB each) joined by a -switch, with one pair also cabled directly, covers a reduced core: no drafting -and no vision, one request, 512-token chunks, no kernel tuning and uncompiled -forwards (`--no-mtp --language-model-only --max-concurrency 1 ---prefill-chunk-size 512 --autotune-effort off --no-compile`, with no memory -reserve). It exported 8 graphs in 18 min 43 s. Native loading used 82.9 GiB -per rank and allocated a 24.5 GiB cache with 6414336 KV-token slots. The -service answered a chat completion, a streamed completion, two requests -against its one slot, and a 7150-token prompt prefilled in fourteen chunks, -with no change in the RoCE loss counters. The eight-request configuration -above has not completed an export on DGX Sparks. Also not run there: the -default-effort and effort-zero cases of `tests/server/test_inkling2.py`, -`--roce-ring`, `--roce-chain`, and a comparison of BF16 cross-host reductions -with single-host FP32 output. +Disk: rank zero holds the complete core, 351 GB for this configuration. Each +peer needs about 87 GB for the payloads it prepares and another 87 GB for the +rank core it receives when serving; the prepared payloads can be removed after +export. Drop the page cache on every host before export and before serving. + +On four DGX Sparks (GB10, SM121, 121 GiB each) joined by a switch, with one +pair also cabled directly, this configuration compiled and captured all 152 +graphs in 1 h 26 min. The lowest available memory during export was 11.5 GiB on +rank zero and 12.5 to 13.1 GiB on the peers; the captured graph pool uses +2840 MiB per rank. Native loading used 90.1 to 90.2 GiB per rank and, with +`--memory-limit=-0G`, allocated a 16.5 GiB cache: 3252224 KV-token slots and +106 shared snapshot slots, limited by memory, leaving 7.8 to 8.3 GiB available +per host after loading and at least 7.6 GiB during 32 concurrent requests. With +the exported 4 GiB reserve the cache is 12.4 GiB, 2392064 KV-token slots and +78 snapshot slots, with 12.0 to 12.5 GiB available. The service passed the +seven default-effort tests of `tests/server/test_inkling2.py`, 32 concurrent +requests, streaming, and an 18832-token prompt with a 2048-token output limit, +with no change in the RoCE loss counters. A core without drafting and vision, +prepared for one request with 512-token chunks, loaded 82.9 GiB per rank and +passed text, streaming and a 7150-token prompt. Not run on Sparks: the +effort-zero tests, `--roce-ring`, `--roce-chain`, and a comparison of BF16 +cross-host reductions with single-host FP32 output. ## Muse Spark Open diff --git a/ignition/recipes/inkling2/bootstrap.py b/ignition/recipes/inkling2/bootstrap.py index 886f9c8bd..8210ca87e 100644 --- a/ignition/recipes/inkling2/bootstrap.py +++ b/ignition/recipes/inkling2/bootstrap.py @@ -90,8 +90,8 @@ def __post_init__(self): if error: raise ValueError(error) request_capacity(self.max_active) - if not 1 <= self.max_active <= 8: - raise ValueError("Inkling 2 request capacity must be in [1, 8]") + if not 1 <= self.max_active <= 32: + raise ValueError("Inkling 2 request capacity must be in [1, 32]") if not PAGE_TOKENS <= self.context <= 1048576 or self.context % PAGE_TOKENS: raise ValueError("Inkling 2 context must be 128-aligned in [128, 1048576]") if not PAGE_TOKENS <= self.prefill_chunk_size <= self.context or self.prefill_chunk_size % PAGE_TOKENS: diff --git a/ignition/recipes/inkling2/recipe.py b/ignition/recipes/inkling2/recipe.py index ec4fd292d..192907937 100644 --- a/ignition/recipes/inkling2/recipe.py +++ b/ignition/recipes/inkling2/recipe.py @@ -57,7 +57,7 @@ def usage(prepared): checkpoints=(Checkpoint(alias="inkling-2-small-nvfp4", repository="/data/models/Inkling-2-Small-NVFP4", revision="local", architecture="Inkling2ForConditionalGeneration", stored_bytes=344_366_116_864, device_bytes=344_366_116_864, expansion_bytes=5_673_717_760, draft_bytes=2_684_203_392),), - context=1048576, page_tokens=128, concurrency=8, max_concurrency=8, prefill_chunk=4096, + context=1048576, page_tokens=128, concurrency=8, max_concurrency=32, prefill_chunk=4096, speculation=Speculation(draft_tokens=7, token_capacity=64, packed_verification=True, graph_budget=64), max_draft_tokens=7, max_images=4, image_bytes=32 << 20, verification_rows=0, language_model_only=True, ranks=MappingProxyType({4: RankCosts(31_293_440, 655_360, 5 << 30)}), diff --git a/tests/cli/test_inkling2.py b/tests/cli/test_inkling2.py index 44ebdc706..c614160f0 100644 --- a/tests/cli/test_inkling2.py +++ b/tests/cli/test_inkling2.py @@ -16,6 +16,7 @@ def test_inkling_defaults_cover_tp4_seven_drafts_and_vision(): assert RECIPE.tensor_parallel == (4,) assert (RECIPE.context, RECIPE.concurrency, RECIPE.prefill_chunk) == (1048576, 8, 4096) + assert RECIPE.max_concurrency == 32 assert (RECIPE.max_images, RECIPE.image_bytes) == (4, 32 << 20) model = ResolvedModel(RECIPE, RECIPE.checkpoints[0]) args = _parser().parse_args(["export", model.checkpoint.alias]) diff --git a/tests/recipes/test_inkling2_hosts.py b/tests/recipes/test_inkling2_hosts.py index cbb438e1b..42895f13f 100644 --- a/tests/recipes/test_inkling2_hosts.py +++ b/tests/recipes/test_inkling2_hosts.py @@ -43,8 +43,8 @@ def _gb10(count): return tuple(planning.Gpu(i, "GB10", f"GPU-{i}", 121 << 30, 115 << 30, (12, 1)) for i in range(count)) -@pytest.mark.parametrize("concurrency, chunk, capacity", [(8, 4096, 64)]) -def test_four_gb10_hosts_fit_the_declared_configuration(concurrency, chunk, capacity): +@pytest.mark.parametrize("concurrency, chunk, capacity", [(8, 4096, 64), (32, 8192, 128)]) +def test_four_gb10_hosts_fit_the_declared_and_the_largest_configuration(concurrency, chunk, capacity): speculation = replace(recipe.RECIPE.speculation, token_capacity=capacity) plan = planning.plan(recipe.RECIPE, recipe.RECIPE.checkpoints[0], _gb10(4), selected=(0, 1, 2, 3), concurrency=concurrency, reserve_bytes=4 << 30, speculation=speculation, @@ -56,6 +56,29 @@ def test_four_gb10_hosts_fit_the_declared_configuration(concurrency, chunk, capa assert plan.page_bytes >= 16 << 30 +def test_request_capacity_is_bounded_by_thirty_two(): + from ignition.errors import UsageError + + assert bootstrap.PreparationConfig(max_active=32, prefill_chunk_size=8192, + speculative_token_capacity=128).max_active == 32 + with pytest.raises(ValueError, match=r"\[1, 32\]"): + bootstrap.PreparationConfig(max_active=33) + with pytest.raises(UsageError, match="must be 1 through 32"): + planning.plan(recipe.RECIPE, recipe.RECIPE.checkpoints[0], _gb10(4), selected=(0, 1, 2, 3), + concurrency=33, reserve_bytes=4 << 30, speculation=recipe.RECIPE.speculation) + + +def test_thirty_two_requests_size_rounds_scratch_rows_and_prefill_graphs(): + config = bootstrap.PreparationConfig(max_active=32, prefill_chunk_size=8192, speculative_token_capacity=128) + shapes = config.speculative_round_shapes + assert {batch for batch, _, _ in shapes} == {1, 2, 4, 8, 16, 32} + assert all(packed <= 128 for _, _, packed in shapes) and (32, 8, 128) in shapes and (32, 1, 32) in shapes + # Packed verification bounds target rows; every request still samples each of its eight positions. + assert (config.decode_tokens, config.decode_samples) == (128, 256) + assert config.image_concurrency == 4 + assert bootstrap.prefill_capacities(8192)[-1] == 8192 + + @pytest.mark.parametrize("remote", [False, True]) @pytest.mark.parametrize("ring", [False, True]) def test_recipe_dispatches_the_complete_plan_to_the_rank_group(monkeypatch, remote, ring): @@ -79,6 +102,19 @@ def test_recipe_dispatches_the_complete_plan_to_the_rank_group(monkeypatch, remo assert kwargs["core_storage"] is storage +def test_remote_capacities_follow_thirty_two_requests_and_8192_token_chunks(monkeypatch): + config = bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, max_active=32, prefill_chunk_size=8192, + speculative_token_capacity=128) + calls = [] + monkeypatch.setattr(bootstrap, "create_roce_runtime", lambda group, device, **kwargs: calls.append(kwargs)) + bootstrap._collective_runtimes(config, None, None, coordinator=SimpleNamespace(spans_hosts=True), + core_storage=None, **GEOMETRY) + (call,) = calls + # The drafter reduces an eight-position block of each of 32 requests in one shot. + assert call["max_tokens"] == 32 * DRAFT_BLOCK == 256 and call["pipe_tokens"] == 8192 + assert call["gather_bytes"] == 256 * LOCAL_VOCABULARY * 4 + + @pytest.mark.parametrize("drafting", [False, True]) @pytest.mark.parametrize("chain", [False, True]) def test_remote_channels_share_one_roce_runtime_without_pcie(monkeypatch, drafting, chain): diff --git a/tests/server/test_inkling2.py b/tests/server/test_inkling2.py index 509e3476b..c7231b69c 100644 --- a/tests/server/test_inkling2.py +++ b/tests/server/test_inkling2.py @@ -4,7 +4,9 @@ """Inkling 2 text, TML tools, images and cached continuations through native TP4 serving. Set FLARE_RUN_CUDA_TESTS=1 and FLARE_INKLING2_TEST_URL to an exported core -running with flare run, concurrency eight, 4096-token prefill and vision. +running with flare run, concurrency of at least eight, 4096- or 8192-token +prefill and vision. Prompts that cross a prefill chunk scale with the chunk +size the service reports. """ from concurrent.futures import ThreadPoolExecutor @@ -30,8 +32,9 @@ def service(request): with urllib.request.urlopen(url + "/v1/models", timeout=10) as response: model = json.load(response)["data"][0] assert "inkling" in model["id"].lower(), model - assert model["flare"]["max_concurrency"] == 8 - assert model["flare"]["prefill_chunk_size"] == 4096 + assert model["flare"]["max_concurrency"] >= 8 + chunk = model["flare"]["prefill_chunk_size"] + assert chunk in (4096, 8192) assert "image" in model["flare"]["input_modalities"] def ask(content, **options): @@ -61,6 +64,7 @@ def ask(content, **options): assert result["usage"]["completion_tokens"] == len(choice["token_ids"]) return result + ask.chunk = chunk return ask @@ -87,14 +91,15 @@ def test_streamed_reasoning_and_answer(service): def test_chunked_prefix_reuse_and_branching(service): - prefix = " ".join(f"Item {i} records code {i * 17 % 997}." for i in range(700)) + chunk = service.chunk + prefix = " ".join(f"Item {i} records code {i * 17 % 997}." for i in range(700 * chunk // 4096)) history = [dict(role="user", content=prefix), dict(role="assistant", content="I have the item records.")] for index in (211, 677, 211): messages = history + [dict(role="user", content=f"What code does item {index} record? Reply with only the integer.")] first, second = service("", messages=messages), service("", messages=messages) - assert first["usage"]["prompt_tokens"] > 4096 - assert second["usage"]["prompt_tokens_details"]["cached_tokens"] > 4096 + assert first["usage"]["prompt_tokens"] > chunk + assert second["usage"]["prompt_tokens_details"]["cached_tokens"] > chunk assert answer(first) == answer(second) == str(index * 17 % 997) @@ -122,11 +127,11 @@ def test_structured_response(service): def test_images_across_a_prefill_chunk(service): - content = [dict(type="text", text="filler " * 4100), + content = [dict(type="text", text="filler " * (service.chunk + 4)), image("red", "FIRST 128"), image("blue", "SECOND 256"), dict(type="text", text="Read both image labels in their original order. Only output the labels.")] response = service(content) - assert response["usage"]["prompt_tokens"] > 4096 + assert response["usage"]["prompt_tokens"] > service.chunk result = answer(response) assert "FIRST 128" in result and "SECOND 256" in result assert result.index("FIRST 128") < result.index("SECOND 256") From 803d6268e7a70c1d135b29776420a4234dc29058 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sat, 14 Nov 2026 23:12:21 -0500 Subject: [PATCH 03/11] Release the page cache of rank cores sent to peer ranks When `flare run` starts a multi-host core, rank zero reads every peer's rank core through the page cache and sends it over TCP. On a host whose GPU allocates from system memory, such as a DGX Spark (GB10), those cached pages are not free memory for CUDA, so the pages of several rank cores can keep rank zero from creating its CUDA context. Helios already releases the page cache of a rank's own core files before it creates the context (Files::release_page_cache in helios/src/runtime_core/model.rs), and a receiving rank syncs the files it writes; the files rank zero reads on behalf of other ranks were never released. Releasing them where the distribution source stops closes that gap with the same eos operation and needs no change to loading or to the transfer protocol. Before this change the distribution source in flare-cli/src/distribution.rs returned when its serving threads had joined and left the pages it had read in the cache. Now release_served_pages calls flare_eos::release_page_cache (POSIX_FADV_DONTNEED on Linux, a no-op on Windows) on every file of ranks one and above when the source thread finishes, whether distribution succeeded or failed. Rank zero's own files are left to the existing release in Helios. flare-cli gains a path dependency on the in-tree eos crate, which the lock file records. The result is that a rank-zero host returns the memory used to read peer cores before GPU initialization, without a manual page-cache drop. Evidence, on four DGX Sparks (121 GiB unified memory each, one rank per host) serving a 351 GB four-rank Inkling 2 Small NVFP4 core. Before: after rank zero distributed three rank cores, its host showed 114 GiB of page cache and 2 GiB free, and rank zero failed at "Initialize GPU" with CudaError { operation: "cuCtxCreate_v2", code: 2, name: "CUDA_ERROR_OUT_OF_MEMORY" }. The failure was intermittent: the first launch of a smaller core went through the same distribution without it. After, with rebuilt binaries on all four hosts, the peers' rank cores removed and no manual cache drop: three rank cores were sent in 70.2 s, /proc/meminfo on rank zero at the end of distribution showed MemAvailable 115.9 GiB and Cached 0.12 GiB, and GPU initialization succeeded. The Linux test source_releases_the_page_cache_of_peer_core_files_when_it_finishes serves a 4 MiB on-disk file to one peer and checks with mincore that the file has resident pages after the transfer and none after the source finishes. cargo test --release --manifest-path flare-cli/Cargo.toml distribution: 30 passed, 0 failed, 2 ignored (they need external fixtures). Not run: other models, two- and three-rank cores, and hosts with discrete GPUs, where the release changes only the page cache. Design-Signed-Off-By: flare-02; design-review=ed22 --- flare-cli/Cargo.lock | 1 + flare-cli/Cargo.toml | 1 + flare-cli/src/distribution.rs | 82 ++++++++++++++++++++++++++++++++++- 3 files changed, 82 insertions(+), 2 deletions(-) diff --git a/flare-cli/Cargo.lock b/flare-cli/Cargo.lock index 14f081e4d..94a252e72 100644 --- a/flare-cli/Cargo.lock +++ b/flare-cli/Cargo.lock @@ -989,6 +989,7 @@ version = "0.1.0" dependencies = [ "clap", "flare", + "flare-eos", "flare-helios", "libc", "libloading", diff --git a/flare-cli/Cargo.toml b/flare-cli/Cargo.toml index 82e64ac0b..10be10791 100644 --- a/flare-cli/Cargo.toml +++ b/flare-cli/Cargo.toml @@ -24,6 +24,7 @@ flare = { path = "../flare" } serde = { version = "1", features = ["derive"] } toml = "0.8" clap = { version = "4.6", features = ["derive"] } +flare-eos = { path = "../eos" } flare-helios = { path = "../helios", features = ["runtime-core", "server"] } libc = "0.2.189" serde_json = "1.0" diff --git a/flare-cli/src/distribution.rs b/flare-cli/src/distribution.rs index 4edb8129f..6cc2d74ba 100644 --- a/flare-cli/src/distribution.rs +++ b/flare-cli/src/distribution.rs @@ -1004,6 +1004,17 @@ impl Drop for Payload<'_> { } } +/// Drop the clean page-cache pages of every core file the source read for a peer rank. +/// +/// Rank zero reads each peer's core ranges through the page cache to send them. An integrated +/// GPU such as GB10 allocates from system memory, where cached file pages are not free, so the +/// pages of several rank cores can keep rank zero from creating its CUDA context. +fn release_served_pages(files: &[Vec>]) { + for file in files.iter().skip(1).flatten() { + flare_eos::release_page_cache(file); + } +} + struct Source { port: u16, stopping: Arc, @@ -1024,7 +1035,7 @@ impl Source { let (stop, held) = (stopping.clone(), channels.clone()); let worker = thread::spawn(move || { let slots = Mutex::new(std::collections::HashSet::new()); - thread::scope(|scope| -> Result<(), Failure> { + let result = thread::scope(|scope| -> Result<(), Failure> { let mut workers = Vec::new(); let (sender, receiver) = std::sync::mpsc::channel(); let mut error = None; @@ -1066,7 +1077,9 @@ impl Source { } } error.map_or(Ok(()), Err) - }) + }); + release_served_pages(&files); + result }); Ok(Self { port, @@ -1395,6 +1408,71 @@ mod tests { source.finish().unwrap(); } + /// Pages of `file` that the page cache holds. + #[cfg(target_os = "linux")] + fn resident_pages(file: &File, size: usize) -> usize { + use std::os::fd::AsRawFd; + + let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize; + let mut resident = vec![0u8; size.div_ceil(page)]; + unsafe { + let map = libc::mmap( + std::ptr::null_mut(), + size, + libc::PROT_READ, + libc::MAP_SHARED, + file.as_raw_fd(), + 0, + ); + assert_ne!(map, libc::MAP_FAILED); + assert_eq!(libc::mincore(map, size, resident.as_mut_ptr()), 0); + libc::munmap(map, size); + } + resident.iter().filter(|&&page| page & 1 != 0).count() + } + + #[cfg(target_os = "linux")] + #[test] + fn source_releases_the_page_cache_of_peer_core_files_when_it_finishes() { + use std::os::unix::fs::MetadataExt; + + // A memory-backed file system keeps its pages; the crate directory is on disk. + let directory = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap(); + let size = 4 << 20; + let path = directory.path().join("core"); + fs::write(&path, vec![7u8; size]).unwrap(); + let file = File::open(&path).unwrap(); + file.sync_all().unwrap(); + assert_ne!(file.metadata().unwrap().blocks(), 0); + let observer = File::open(&path).unwrap(); + let spec = || { + vec![FileSpec { + name: "core".into(), + size: size as u64, + ranges: vec![(0, size as u64)], + }] + }; + let source = Source::start(vec![Vec::new(), vec![Arc::new(file)]], vec![spec(), spec()], 1).unwrap(); + let mut socket = TcpStream::connect(("127.0.0.1", source.port)).unwrap(); + configure(&socket, IO_TIMEOUT).unwrap(); + socket.write_all(&[1, 0, 0, 0, 0, 0, 0, 0]).unwrap(); + write( + &mut socket, + &Request { + file: 0, + ranges: vec![(0, size as u64)], + }, + ) + .unwrap(); + let mut bytes = vec![0; 8 + size]; + socket.read_exact(&mut bytes).unwrap(); + assert!(bytes[8..].iter().all(|&byte| byte == 7)); + assert_ne!(resident_pages(&observer, size), 0); + socket.shutdown(Shutdown::Both).unwrap(); + source.finish().unwrap(); + assert_eq!(resident_pages(&observer, size), 0); + } + #[test] fn sparse_rank_distribution_reuses_channels_across_files_and_cached_launches() { for (world, ring) in [(2, false), (4, false), (4, true)] { From ae94c1572bb3608aa6d4e07629eee79913d1645a Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sun, 15 Nov 2026 06:03:54 -0500 Subject: [PATCH 04/11] Shorten Inkling 2 prefill with BF16 router operands and a fused mix and norm Inkling 2 Small prefill on DGX Spark TP4 spent 994 ms of a 3,808 ms 8,192-row chunk in the expert router's projection, which widened its BF16 source and weight to FP32 so that only b12x's FP32-operand kernels were eligible, and 376 ms in attention-residual mixtures that stored an FP32 mixture per stream for a separate RMSNorm launch. The router needs FP32 accumulation, not FP32 operands: the product of two BF16 values is exact in FP32. The mixture and its norm read and write the same rows, so one program can normalize without storing the mixture. The router projection takes its BF16 source and a BF16 router weight and declares accumulation="fp32", which UnquantizedProjection passes to b12x so that only plans carrying the whole sum in FP32 are raced. The weight loader delivers the FP32 checkpoint tensor as BF16 only after checking that every value is an exact BF16 upcast. PreparedResidualMix normalizes each stream in the mixture kernel with FP32 mean square, scale and weight and one rounding to BF16; PreparedRMSNorm leaves this path. Prefill attention writes its partial sum in the cross-rank reduction's element type, BF16 over RoCEnante and FP32 on one host, in place of FP32 followed by a cast; decode and verification keep FP32. Prefill time to first token on four DGX Sparks falls by a factor of 1.5 to 1.6. Router selection is unchanged in value class: operands are the same numbers and only summation order differs. The fused norm differs from the unfused one by at most one BF16 unit in at most ten elements per million. Evidence: one exported core per tree served by flare run at TP4 on GB10, 8,192-row chunks, warm and uncached, three repeats. Time to first token was 2.59 to 2.69 s at 7,668 prompt tokens (4.18 to 4.51 s before), 22.4 to 23.0 s at 67,145 (35.2 to 35.4 s) and 48.8 to 49.8 s at 131,990 (73.5 s). The measured core also contained FlashInfer's swapped-operand FC1 selection and the drafting changes, so the factor is not attributable to this commit alone. In a kernel trace of rank 0, an 8,192-row chunk spans 2,509 ms with routing at 159 ms and mixtures with norms at 247 ms. On one GB10 the router projection for 8,192 rows takes 2.14 ms against 19.5 ms, with the same top-8 experts on every row. tests/recipes/test_inkling2_target.py passes 87 tests on a GB10 with the checkpoint, including attention against the reference in prefill, decode and verification and the fused-norm bound. Limitations: the projection requires GemvQuery.accumulation from FlashInfer (local-inference-lab/flashinfer#110), which the pinned FlashInfer revision lacks. Completion length was compared between a core from this tree with the drafting changes and a core from the unmodified tree: over lookup prompts with seeds 1 to 30, median completion tokens were 363 against 420 and the share at or above 1,024 tokens differed by -1.7 points (95% interval -7.2 to +3.8), with no wrong answer in 540 and 480 responses. tests/server/test_inkling2.py's prefix-reuse case, which fixes one seed and a 1,024-token limit, fails in 9 of 20 repeats on the changed core and 5 of 20 on the unmodified one. Single-host RTX PRO 6000 serving was not run. Design-Signed-Off-By: flare-02; design-review=ed22 --- ignition/components/linear.py | 11 +++- ignition/recipes/inkling2/attention.py | 9 +-- ignition/recipes/inkling2/decoder.py | 10 +++- ignition/recipes/inkling2/residual.py | 82 ++++++++++++++++++-------- ignition/recipes/inkling2/weights.py | 10 +++- tests/recipes/test_inkling2_target.py | 48 +++++++++++++-- 6 files changed, 129 insertions(+), 41 deletions(-) diff --git a/ignition/components/linear.py b/ignition/components/linear.py index ff92a995d..48b6d495b 100644 --- a/ignition/components/linear.py +++ b/ignition/components/linear.py @@ -144,7 +144,13 @@ def __init__( session: PreparationSession, name: str, bias: torch.Tensor | None = None, + accumulation: str = "any", ) -> None: + """Declare `source @ weight.T` (plus `bias`) into `output`. + + `accumulation="fp32"` admits only b12x plans that carry the whole sum of products in FP32, the + accuracy of the product of FP32 operands; `"any"` also admits tensor-core and library accumulation. + """ if any(t.dtype not in (torch.bfloat16, torch.float32) for t in (source, weight, output)): raise TypeError("unquantized projections require BF16 or FP32 operands") for tensor in (weight, bias): @@ -152,7 +158,7 @@ def __init__( record_numeric_tensor(tensor) # FlashInfer's GEMMs read and write contiguous rows; column slices of wider rows keep b12x's GEMV. rows = source.numel() // source.shape[-1] - self.dense = (sm103_projection.is_sm103(source.device) and bias is None + self.dense = (sm103_projection.is_sm103(source.device) and bias is None and accumulation == "any" and source.dtype == weight.dtype == torch.bfloat16 and source.is_contiguous() and output.is_contiguous() and sm103_projection.dense_serves(rows, output.shape[-1])) @@ -169,7 +175,8 @@ def __init__( session=session), weight=weight, bias=None)),)) return - query = bf16_gemv.query_from_call(source, weight, out=output, bias=bias) + query = bf16_gemv.query_from_call(source, weight, out=output, bias=bias, + **({} if accumulation == "any" else {"accumulation": accumulation})) self.plan = bf16_gemv.plan(query) self.weight = weight self.bias = bias diff --git a/ignition/recipes/inkling2/attention.py b/ignition/recipes/inkling2/attention.py index 4b430ddfa..e0c885333 100644 --- a/ignition/recipes/inkling2/attention.py +++ b/ignition/recipes/inkling2/attention.py @@ -8,8 +8,9 @@ or convolution histories. Accepted counts commit those histories afterward. Full-attention candidates write private request pages. Attention uses BF16 queries and relative-bias operands, FP8 K/V and FP32 row sinks. The gated -BF16 result projects to FP32 partial sums for cross-rank reduction before the -replicated BF16 output convolution. +BF16 result projects to partial sums of the cross-rank reduction's element type +(FP32 on one host, BF16 over RoCEnante, where the projection rounds its FP32 +accumulation once) before the replicated BF16 output convolution. """ from __future__ import annotations @@ -173,7 +174,7 @@ class PreparedAttention(torch.nn.Module): """A rank's attention for prefill, decode or speculative verification.""" def __init__(self, layer, weights: AttentionWeights, text, cache: LayerCache, metadata, *, mode, tokens, - session, workspace, name, examples=None, tuning_page_count=None): + session, workspace, name, examples=None, tuning_page_count=None, partial_dtype=torch.float32): super().__init__() if mode not in ("prefill", "decode", "verify"): raise ValueError(f"unsupported Inkling attention mode: {mode}") @@ -201,7 +202,7 @@ def example(role, shape, dtype=torch.bfloat16): for index, (weight, width) in enumerate(zip(weights.projections, self.columns.widths(), strict=True))) attended = example("inkling.attention.attended", (tokens, self.heads * self.dim)) self.output_projection = UnquantizedProjection(attended, weights.output, - example("inkling.attention.partial", (tokens, text.hidden), torch.float32), + example("inkling.attention.partial", (tokens, text.hidden), partial_dtype), session=session, name=f"{name}.output").functional(session=session) query = example("inkling.attention.query", (tokens, self.heads, self.dim)) output = example("inkling.attention.output", (tokens, self.heads, self.dim)) diff --git a/ignition/recipes/inkling2/decoder.py b/ignition/recipes/inkling2/decoder.py index 89e6241b5..d86763cd4 100644 --- a/ignition/recipes/inkling2/decoder.py +++ b/ignition/recipes/inkling2/decoder.py @@ -59,6 +59,9 @@ def __init__(self, layer, weights, text, pool, metadata, reduction, reduction_dt self.reduction, self.reduction_dtype = reduction, reduction_dtype self.attention = PreparedAttention(layer, weights.attention, text, LayerCache.of(pool, layer), metadata, mode=mode, tokens=tokens, session=session, workspace=workspace, name=name + ".attention", examples=examples, + # Prefill writes the attention partial sum in the reduction's element type. At prefill row counts the + # BF16 projection equals the FP32 projection rounded once; decode and verification keep FP32. + partial_dtype=reduction_dtype if mode == "prefill" else torch.float32, tuning_page_count=((int(pool.memory_capacity[0].item()) - 1) * pool.ring_row_pages + pool.geometry.ring // 128 if text.local(layer) else int(pool.memory_capacity[1].item()))) device = weights.router.device @@ -66,8 +69,9 @@ def example(role, shape, dtype=torch.bfloat16): return declaration_tensor(examples, "inkling.mlp." + role, shape, dtype, device) source = example("source", (tokens, text.hidden)) logits = example("router_logits", (tokens, text.experts), torch.float32) - self.router_projection = UnquantizedProjection(example("router_source", source.shape, torch.float32), - weights.router, logits, session=session, name=name + ".router").functional(session=session) + # BF16 operands with the sum carried in FP32: each product of two BF16 values is exact in FP32. + self.router_projection = UnquantizedProjection(source, weights.router, logits, session=session, + name=name + ".router", accumulation="fp32").functional(session=session) routes = RouterScratch.allocate(tokens, device, experts=text.experts, top_k=text.experts_per_token) self.router = PreparedRouter(logits, routes, session=session, name=name + ".routing", score_func="sigmoid", renormalize=True, routed_scaling_factor=text.route_scale, correction_bias=weights.correction, @@ -100,7 +104,7 @@ def forward(self, state, metadata): mlp_input = self.mlp_mix((*state.blocks, state.partial, attention))[0] else: mlp_input = self.mlp_mix((*state.blocks, state.partial), addend=attention)[0] - routes = self.router(self.router_projection(mlp_input.float()), num_valid_tokens=m.live_counts[:1]) + routes = self.router(self.router_projection(mlp_input), num_valid_tokens=m.live_counts[:1]) expert_partial = self.experts(mlp_input, routes.ids, routes.weights) mlp_raw = self.reduction(expert_partial.to(self.reduction_dtype)).to(torch.bfloat16) mlp, mlp_previous = self.mlp_convolution(mlp_raw, m) diff --git a/ignition/recipes/inkling2/residual.py b/ignition/recipes/inkling2/residual.py index 2081eece3..b3b748fa3 100644 --- a/ignition/recipes/inkling2/residual.py +++ b/ignition/recipes/inkling2/residual.py @@ -1,24 +1,31 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Prepared FP32 attention-residual mixtures over normalized source values.""" +"""Prepared attention-residual mixtures over normalized source values, fused with their RMSNorm. + +One program per row mixes the sources in FP32 and normalizes the mixture without storing it: the mean +square, the product with the reciprocal root and then with the norm weight are FP32, and only the +result rounds to BF16. That is the arithmetic of the mixture followed by `PreparedRMSNorm`, whose +tuned plans differ from one another only in the summation order of the mean square, so the fused +result differs from any of them by at most one BF16 unit in a few elements per million. +""" import torch import triton import triton.language as tl -from ignition.components.rms_norm import PreparedRMSNorm from ignition.preparation.examples import declaration_tensor from ignition.preparation.triton import launch_triton, prepare_triton @triton.jit def _mixture(Source0, Source1, Source2, Source3, Source4, Source5, Source6, Source7, Source8, - Queries, Output0, Output1, Output2, Addend, STRIDES: tl.constexpr, HIDDEN: tl.constexpr, - SOURCES: tl.constexpr, STREAMS: tl.constexpr, ADD: tl.constexpr, ADD_STRIDE: tl.constexpr, - EPS: tl.constexpr, BLOCK: tl.constexpr): + Queries, Output0, Output1, Output2, Addend, Norm0, Norm1, Norm2, STRIDES: tl.constexpr, + HIDDEN: tl.constexpr, SOURCES: tl.constexpr, STREAMS: tl.constexpr, ADD: tl.constexpr, + ADD_STRIDE: tl.constexpr, EPS: tl.constexpr, NORMALIZE: tl.constexpr, BLOCK: tl.constexpr): Sources = (Source0, Source1, Source2, Source3, Source4, Source5, Source6, Source7, Source8) Outputs = (Output0, Output1, Output2) + Norms = (Norm0, Norm1, Norm2) row = tl.program_id(0).to(tl.int64) columns = tl.arange(0, BLOCK) valid = columns < HIDDEN @@ -39,47 +46,72 @@ def _mixture(Source0, Source1, Source2, Source3, Source4, Source5, Source6, Sour denominator = denominator * rescale + probability mixture = mixture * rescale + value * (inverse * probability) maximum = peak - tl.store(Outputs[stream] + row * HIDDEN + columns, mixture / denominator, valid) + mixed = mixture / denominator + if NORMALIZE: + # The mixture is scaled before the weight is applied, as the unfused RMSNorm does. + scale = tl.rsqrt(tl.sum(mixed * mixed, 0) / HIDDEN + EPS) + weight = tl.load(Norms[stream] + columns, valid, other=0.).to(tl.float32) + tl.store(Outputs[stream] + row * HIDDEN + columns, (mixed * scale * weight).to(tl.bfloat16), valid) + else: + tl.store(Outputs[stream] + row * HIDDEN + columns, mixed, valid) class PreparedResidualMix: + """Normalized attention-residual mixtures of one to nine BF16 sources for one to three output streams. + + Calling the object returns each stream's BF16 `RMSNorm(mixture) * norm` from one kernel launch. + `mix` returns the FP32 mixtures alone, which the fused kernel never stores; tests compare the two. + """ + def __init__(self, source, queries, norms, *, sources, eps, session, name, addend=False, examples=None): + del session, name if not 1 <= sources <= 9 or not 1 <= len(norms) <= 3: raise ValueError('attention-residual mixtures require one to nine sources and one to three output streams') if queries.dtype != torch.float32 or queries.shape != (len(norms), source.shape[1]): raise ValueError('attention-residual queries must contain one FP32 row per output stream') - self.queries, self.norms, self.sources = queries, norms, sources + if any(norm.shape != source.shape[1:] or not norm.is_contiguous() + or norm.dtype not in (torch.bfloat16, torch.float32) for norm in norms): + raise ValueError('attention-residual norm weights must be contiguous BF16 or FP32 rows of the hidden width') + self.queries, self.norms, self.sources = queries, tuple(norms), sources self.eps, self.streams, self.addend = eps, len(norms), addend self.tokens, self.hidden = source.shape self.options = dict(HIDDEN=self.hidden, SOURCES=sources, STREAMS=self.streams, ADD=addend, ADD_STRIDE=source.stride(0), EPS=eps, BLOCK=triton.next_power_of_2(self.hidden), STRIDES=(source.stride(0),) * sources, num_warps=8, enable_fp_fusion=False) declarations = {} if examples is None else examples - mixtures = tuple(declaration_tensor(declarations, f"inkling.residual.mixture{index}", - tuple(source.shape), torch.float32, source.device) for index in range(len(norms))) outputs = tuple(declaration_tensor(declarations, f"inkling.residual.output{index}", tuple(source.shape), torch.bfloat16, source.device) for index in range(len(norms))) - arguments = ((source,) * 9 + (queries,) + mixtures - + (mixtures[0],) * (3 - self.streams) + (source,)) - self.compiled = prepare_triton(_mixture, arguments, (self.tokens, 1, 1), **self.options).compiled - self.normalizers = tuple(PreparedRMSNorm(value, norm, output, - eps=eps, session=session, name=f'{name}.norm{index}').functional() - for index, (value, norm, output) in enumerate(zip(mixtures, norms, outputs, strict=True))) + self.compiled = prepare_triton(_mixture, self._arguments((source,) * sources, outputs, source), + (self.tokens, 1, 1), NORMALIZE=True, **self.options).compiled + self.unnormalized = None - def mix(self, sources, *, addend=None): + def _arguments(self, sources, outputs, addend): + return (sources + (sources[0],) * (9 - self.sources) + (self.queries,) + outputs + + (outputs[0],) * (3 - self.streams) + (addend,) + + self.norms + (self.norms[0],) * (3 - self.streams)) + + def _check(self, sources, addend): if len(sources) != self.sources: raise ValueError('attention-residual source count differs from the prepared layer') - output = tuple(torch.empty((self.tokens, self.hidden), dtype=torch.float32, - device=sources[0].device) for _ in range(self.streams)) if (addend is not None) != self.addend: raise ValueError('attention-residual addend differs from the prepared layer') - options = self.options - arguments = (sources + (sources[0],) * (9 - self.sources) + (self.queries,) + output - + (output[0],) * (3 - self.streams) + (sources[0] if addend is None else addend,)) - launch_triton(_mixture, self.compiled, - arguments, (self.tokens, 1, 1), **options) + + def mix(self, sources, *, addend=None): + """The FP32 mixtures without normalization.""" + self._check(sources, addend) + output = tuple(torch.empty((self.tokens, self.hidden), dtype=torch.float32, + device=sources[0].device) for _ in range(self.streams)) + arguments = self._arguments(sources, output, sources[0] if addend is None else addend) + if self.unnormalized is None: + self.unnormalized = prepare_triton(_mixture, arguments, (self.tokens, 1, 1), NORMALIZE=False, + **self.options).compiled + launch_triton(_mixture, self.unnormalized, arguments, (self.tokens, 1, 1), NORMALIZE=False, **self.options) return output def __call__(self, sources, *, addend=None): - return tuple(norm(value) for norm, value in zip(self.normalizers, - self.mix(sources, addend=addend), strict=True)) + self._check(sources, addend) + output = tuple(torch.empty((self.tokens, self.hidden), dtype=torch.bfloat16, + device=sources[0].device) for _ in range(self.streams)) + launch_triton(_mixture, self.compiled, self._arguments(sources, output, sources[0] if addend is None else addend), + (self.tokens, 1, 1), NORMALIZE=True, **self.options) + return output diff --git a/ignition/recipes/inkling2/weights.py b/ignition/recipes/inkling2/weights.py index f30ff6fd5..7a851c2d1 100644 --- a/ignition/recipes/inkling2/weights.py +++ b/ignition/recipes/inkling2/weights.py @@ -15,6 +15,14 @@ from .config import ModelConfig, TEXT_PREFIX +def load_exact_bfloat16(loader, name): + """An FP32 checkpoint tensor whose values are exact BF16 upcasts, delivered as BF16.""" + narrowed = loader.load_tensor(name, dtype=torch.bfloat16) + if not torch.equal(narrowed.float(), loader.load_tensor(name, temporary=True)): + raise ValueError(f"{name}: FP32 values are not exact BF16 upcasts, so BF16 delivery would round them") + return narrowed + + def scaled_query(query, hidden): return persistent_copy(query.float().reshape(-1, hidden) * hidden ** -0.5) @@ -160,7 +168,7 @@ def load_layer(self, index): attention_query = None if index == 0 else scaled_query( self.load_tensor(prefix + ".attention_input.query"), c.hidden) return LayerWeights(attention, load_experts(self, index, shard=s), - self.load_tensor(prefix + ".mlp.gate.weight"), + load_exact_bfloat16(self, prefix + ".mlp.gate.weight"), self.load_tensor(prefix + ".mlp.gate.e_score_correction_bias"), self.load_tensor(prefix + ".post_attention_convolution.conv1d.weight"), self.load_tensor(prefix + ".post_mlp_convolution.conv1d.weight"), norms, diff --git a/tests/recipes/test_inkling2_target.py b/tests/recipes/test_inkling2_target.py index 1977c63a1..fb0d9fee9 100644 --- a/tests/recipes/test_inkling2_target.py +++ b/tests/recipes/test_inkling2_target.py @@ -224,7 +224,6 @@ def test_prepared_attention_residual_reference_and_capture(tokens, streams, sour workload_schema='inkling2-residual', numerical_policy='default', autotune_effort='off') as session: operation = PreparedResidualMix(values[0], queries, norms, sources=sources, eps=1e-6, session=session, name='residual', addend=add) - session.tune() reference = residual_mix(values, queries, addend=addend) mixture = operation.mix(values, addend=addend) for actual, expected in zip(mixture, reference, strict=True): @@ -234,11 +233,11 @@ def test_prepared_attention_residual_reference_and_capture(tokens, streams, sour for got, want in zip(actual, expected, strict=True): torch.testing.assert_close(got, want, rtol=2 ** -7, atol=2e-5) graph = torch.cuda.CUDAGraph(keep_graph=True) - with session.capture(), torch.cuda.graph(graph): + with torch.cuda.graph(graph): outputs = operation(values, addend=addend) status, _, count = driver.cuGraphGetNodes(graph.raw_cuda_graph()) assert status == driver.CUresult.CUDA_SUCCESS - assert count == 1 + streams + assert count == 1 for _ in range(3): before = torch.cuda.memory_stats()['allocation.all.allocated'] graph.replay() @@ -276,7 +275,6 @@ def test_prepared_attention_residual_aot_restore_and_replay(tmp_path, tokens, st workload_schema='inkling2-residual-aot', numerical_policy='default') as session: operation = PreparedResidualMix(values[0], queries, norms, sources=sources, eps=1e-6, session=session, name='residual', addend=add) - session.tune() forward = _ResidualForward(operation, values, addend) expected = forward() compiled = aot_forward(forward) @@ -289,9 +287,8 @@ def test_prepared_attention_residual_aot_restore_and_replay(tmp_path, tokens, st restored = torch.compiler.load_compiled_function(file) restored(forward) graph = torch.cuda.CUDAGraph() - with session.capture(), torch.cuda.graph(graph): + with torch.cuda.graph(graph): outputs = restored(forward) - session.freeze() for _ in range(3): for value in values: value.normal_() @@ -384,3 +381,42 @@ def forward(): assert (((gated.double() - expected_gate).abs() - bound).max() <= 0).item() torch.testing.assert_close(normalized, expected_norm, rtol=2 ** -7, atol=2 ** -126) graph.reset() + + +@pytest.mark.skipif(os.environ.get('FLARE_RUN_CUDA_TESTS') != '1', reason='requires an assigned SM120 GPU') +@pytest.mark.parametrize('effort', ['off', 'default']) +@pytest.mark.parametrize('tokens,streams,sources,add', [(4096, 1, 5, True), (4096, 3, 9, False), (128, 1, 2, False)]) +@torch.no_grad() +def test_fused_residual_norm_stays_within_the_norm_plans_variation(effort, tokens, streams, sources, add): + """The fused kernel against the FP32 mixture followed by `PreparedRMSNorm`. + + The two differ only in the summation order of the mean square, as the norm's own tuned plans do + (85 of 37.7 million elements between two plans on a GB10): no element differs by more than one + BF16 unit, and at most ten elements per million differ. + """ + from ignition.components.rms_norm import PreparedRMSNorm + from ignition.preparation.tuning import RecordedPreparationSession + from ignition.recipes.inkling2.residual import PreparedResidualMix + + torch.manual_seed(23) + device = torch.device('cuda', 0) + values = tuple(torch.randn(tokens, 4608, device=device).bfloat16() for _ in range(sources)) + queries = torch.randn(streams, 4608, device=device) * 4608 ** -.5 + norms = tuple((1 + .1 * torch.randn(4608, device=device)).bfloat16() for _ in range(streams)) + addend = (.3 * torch.randn_like(values[-1].float())).bfloat16() if add else None + with RecordedPreparationSession(device=device, checkpoint='inkling2-residual-bound', + workload_schema='inkling2-residual-bound', numerical_policy='default', autotune_effort=effort) as session: + operation = PreparedResidualMix(values[0], queries, norms, sources=sources, eps=1e-6, + session=session, name='residual', addend=add) + mixture = torch.empty((tokens, 4608), dtype=torch.float32, device=device) + unfused = [PreparedRMSNorm(mixture, norm, torch.empty((tokens, 4608), dtype=torch.bfloat16, device=device), + eps=1e-6, session=session, name=f'norm{index}') for index, norm in enumerate(norms)] + session.tune() + fused = operation(values, addend=addend) + differing = 0 + for got, value, norm in zip(fused, operation.mix(values, addend=addend), unfused, strict=True): + want = norm(value) + units = (got.view(torch.int16).int() - want.view(torch.int16).int()).abs() + assert int(units.max()) <= 1 + differing += int((units != 0).sum()) + assert differing <= max(1, streams * tokens * 4608 // 100_000) From f22305a57b4c91aa2c3b8da844710ec36284c1f1 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sun, 15 Nov 2026 06:04:22 -0500 Subject: [PATCH 05/11] Cut the fixed cost of Inkling 2 drafting rounds and add proposal-head formats On DGX Spark TP4 a drafting round of Inkling 2 Small cost about 39 ms plus 4.5 ms per verified draft against a 28 ms decode step, so 11 ms of each round bought no tokens and the balanced policy rarely chose to draft. Verification staged each sliding-window layer's history with PyTorch gathers over whole rings and committed accepted rows by rewriting whole rings, the recurrent head projected its draw-independent context once per draft position, and proposal heads read BF16 only. These costs do not depend on the draws or on the number of drafts, so they can leave the per-round path without changing what verification computes. Verification attention stages each request's preceding window and its candidate rows with one PreparedWindowStaging kernel per layer and commits accepted rows with one PreparedRingCommit kernel. PreparedWindowStaging gains lookback, the count of preceding positions staged from a ring that retains more than attention reads, and PreparedRingCommit gains candidate_offset, the record index at which staged candidates start; both default to their earlier meaning. The recurrent proposal head projects the block's states and target context once per block, proposals read one embedding row per request, and staging plans are shared between layers. --draft-head-quantization nvfp4 or mxfp8 and --markov-head-quantization fp8 prepare proposal-only copies computed from checkpoint values at load; target verification keeps the BF16 head, so they change which tokens are proposed, never the output distribution. Both flags default to omitted. A drafting round at one request costs about 34.7 ms plus 4.7 ms per verified draft: the fixed cost over a decode step falls from about 11 ms to about 6 ms and the per-draft cost is unchanged. The preparation graph pool falls from 2,840 MiB to 2,092 MiB per rank. Evidence: one exported core per tree served by flare run at TP4 on GB10, one request, ordinary prompts, a fresh launch per verification row budget. Rounds verifying 2 to 8 target rows took 39.3, 45.0, 49.9, 54.4, 58.9, 62.1 and 67.3 ms against 43.7, 48.5, 53.2, 57.4, 61.6, 67.1 and 70.5 ms. Drafting rounds took 215 to 248 ms at 16 requests (237 to 272 ms) and 279 ms at 32 (342 to 461 ms). The measured core used --draft-head-quantization nvfp4; acceptance at draft depths 1 to 4 was 81, 63, 48 and 35% on ordinary prompts against 79, 61, 48 and 36% with the BF16 head, so the NVFP4 head neither raised nor lowered acceptance. The measured core also contained the prefill changes of the preceding commit. On a GB10 with the checkpoint, test_inkling2_target.py (87), test_inkling2_window.py (9) and test_inkling2_dspark_cuda.py (15) pass, covering verification attention against the reference and staged and committed rings against PyTorch. Limitations: verification staging requires WindowStageKernel's lookback from FlashInfer (local-inference-lab/flashinfer#112), which the pinned revision lacks. --markov-head-quantization fp8 and the MXFP8 draft head were not measured in serving. Aggregate decode throughput is within a few percent of the unmodified tree. lookback and candidate_offset extend two existing component contracts with defaulted parameters; no graph kind is added. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/cli-design.md | 4 +- docs/model-preparation.md | 12 + ignition/components/parallel_draft.py | 6 +- ignition/components/recurrent_proposal.py | 51 +++- ignition/components/ring_commit.py | 21 +- ignition/components/window_staging.py | 24 +- ignition/recipes/inkling2/attention.py | 74 +++--- ignition/recipes/inkling2/bootstrap.py | 18 +- ignition/recipes/inkling2/dspark.py | 82 ++++--- ignition/recipes/inkling2/dspark_state.py | 86 +++++-- ignition/recipes/inkling2/dspark_weights.py | 50 +++- ignition/recipes/inkling2/recipe.py | 9 +- ignition/recipes/inkling2/weights.py | 6 +- tests/cli/test_inkling2.py | 60 +++++ tests/components/test_inkling2_dspark.py | 160 +++++++++++- tests/components/test_inkling2_dspark_cuda.py | 64 +++-- tests/components/test_ring_commit_cuda.py | 10 + tests/components/test_window_staging_cuda.py | 7 + tests/recipes/test_inkling2_target.py | 42 ---- tests/recipes/test_inkling2_window.py | 231 ++++++++++++++++++ 20 files changed, 820 insertions(+), 197 deletions(-) create mode 100644 tests/recipes/test_inkling2_window.py diff --git a/docs/cli-design.md b/docs/cli-design.md index cde639a96..23b3e74cf 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -448,8 +448,8 @@ explicit flags take precedence. | `--no-mtp` | Disable multi-token speculation: load no draft model, keep no verification rows, and decode one token per step. | Speculation on | | `--mtp-only` | Omit MTP-disabled prefill, decode, maintenance, and mixed graphs during preparation. Retain width-one speculative rounds and vision graphs. Requires positive draft depth; rejects `--no-mtp`. The core cannot load with native `--mtp-draft-tokens 0`. | Capture both execution modes | | `--draft-body-quantization {mxfp8}` | Prepare eligible DFlash2 body context, attention latent/query/output, and MLP projections as MXFP8, independently of target conversion and proposal-head precision. Kimi K3.1 Pro requires `--speculative-method dflash2` and positive learned draft depth; DSpark and other recipes reject it. Normalization, convolution, candidate-selector, and absorbed key/value weights retain their precision. Omission preserves checkpoint precision or the existing `online_mxfp8_scope all` behavior. | No additional override | -| `--draft-head-quantization {nvfp4,mxfp8}` | Prepare a separate proposal vocabulary head while retaining target-head precision. NVFP4 supports DeepSeek V4/V4.1; MXFP8 supports DeepSeek V4.1. Qwen3.8 dense supports both when the source checkpoint head is BF16, including `qwen3.8-27b-qad`; the packed NVIDIA head cannot be converted through this option. Flash Next supports both with `--speculative-method dflash2` and a BF16 target vocabulary head. Kimi K3.1 Pro supports both with `--speculative-method dflash2` only. This does not quantize the draft body. | Checkpoint precision | -| `--markov-head-quantization {nvfp4,fp8}` | Prepare the draft Markov transition projection as NVFP4 or row-scaled E4M3 FP8. DeepSeek V4 supports NVFP4; DeepSeek V4.1 supports both. Requires positive draft depth. | Checkpoint precision | +| `--draft-head-quantization {nvfp4,mxfp8}` | Prepare a separate proposal vocabulary head while retaining target-head precision. NVFP4 supports DeepSeek V4/V4.1; MXFP8 supports DeepSeek V4.1. Qwen3.8 dense supports both when the source checkpoint head is BF16, including `qwen3.8-27b-qad`; the packed NVIDIA head cannot be converted through this option. Flash Next supports both with `--speculative-method dflash2` and a BF16 target vocabulary head. Kimi K3.1 Pro supports both with `--speculative-method dflash2` only. Inkling 2 Small NVFP4 supports both. This does not quantize the draft body. | Checkpoint precision | +| `--markov-head-quantization {nvfp4,fp8}` | Prepare the draft Markov transition projection as NVFP4 or row-scaled E4M3 FP8. DeepSeek V4 supports NVFP4; DeepSeek V4.1 supports both. Inkling 2 Small NVFP4 supports FP8 for its recurrent correction head. Requires positive draft depth. | Checkpoint precision | | `--vocabulary-parallel-sampling` | Prepare vocabulary-sharded DSpark proposals and block rejection sampling. DeepSeek V4.1 on four GPUs only; three-GPU preparation rejects it. Requires positive draft depth and recipe sampling defaults without top-k, top-p, or min-p filtering, and rejects `--markov-head-quantization nvfp4`. | Full-vocabulary sampling | | `--mtp-draft-tokens N` | Most draft tokens verified in one round; see `MODEL --help` for its limit. Verification capacities cover counts from 0 through `N` within the speculative token capacity. Each complete speculative program records its actual proposal depth independently of target width and aggregate rows. Prefix selection uses measured complete-program cost and completed acceptance or confidence. Zero retains draft state with width-one execution; `--no-mtp` excludes draft weights and state. | Recipe declaration | | `--speculative-token-capacity N` | Maximum physical target-token rows in wider speculative graphs; width one covers every request bucket. Applies to every speculative recipe. | Recipe declaration: 32 for Muse Spark and 128 for the other recipes that declare one. Gemma 4 declares none and derives it from concurrency and draft depth (6 at its defaults) | diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 1771ce7a2..1457b42d1 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1325,6 +1325,18 @@ reasoning, tool calls, and structured responses. Sampling defaults are temperature 1.0 and top-p 1.0; the prompt encoder defaults to reasoning effort 0.9 when the request does not specify one. +Each drafting round projects eight block rows through the vocabulary head and +then, for each of up to seven draft positions, corrects those logits with the +recurrent head: its output map folded through the vocabulary head, one +vocabulary row by 256 values. Both read BF16 by default, 463 MB and 25.7 MB +per rank. `--draft-head-quantization nvfp4` or `mxfp8` prepares a quantized +copy of the target's vocabulary shard that only proposals read, and +`--markov-head-quantization fp8` stores the folded correction head as E4M3 +values with one FP32 scale per vocabulary row. Both are computed at load from +checkpoint values; target verification keeps the BF16 head, so a quantized +proposal head changes which tokens are proposed and how often they are +accepted, never the output distribution. The default omits both flags. + Export with default tuning and Torch compilation: ```sh diff --git a/ignition/components/parallel_draft.py b/ignition/components/parallel_draft.py index fcf439d39..34652bbdc 100644 --- a/ignition/components/parallel_draft.py +++ b/ignition/components/parallel_draft.py @@ -442,11 +442,11 @@ def propose(self, advance_rng=True, allowed=None, *, probabilities): hidden = features["hidden"].view(b, block, -1) context = features["recurrent_context"] state = self.recurrent.begin(context) + # The draft states and target context do not depend on the draws: project them once. + fixed = self.recurrent.project_context(hidden[:, o.logit_offset:], context) scores = torch.empty_like(draft_logits)[:, o.logit_offset:o.logit_offset + w - 1] for index in range(w - 1): - state, logits = self.recurrent.step(state, markov_token, - hidden[:, index + o.logit_offset].contiguous(), context, - base[:, index]) + state, logits = self.recurrent.step(state, markov_token, fixed[:, index], base[:, index]) scores[:, index].copy_(logits) self.full_proposal.run_step(index, scores, drafts, pending=markov_token, seeds=seed, offsets=base_offset, probabilities=probabilities, valid=valid, diff --git a/ignition/components/recurrent_proposal.py b/ignition/components/recurrent_proposal.py index d76b02730..8c21b4465 100644 --- a/ignition/components/recurrent_proposal.py +++ b/ignition/components/recurrent_proposal.py @@ -7,6 +7,7 @@ from .embedding import PreparedEmbedding from .linear import UnquantizedProjection +from .markov_sampling import PreparedRowScaledFP8MarkovProjection, RowScaledFP8MarkovWeight def recurrent_gate(raw, state): @@ -27,33 +28,61 @@ def corrected_logits(base, correction, softcap): class PreparedRecurrentProposalHead: - """Keep recurrence state inside one block while retaining its actual sampled q.""" + """Keep recurrence state inside one block while retaining its actual sampled q. - def __init__(self, weights, tokens, *, session, name): + The recurrence input has a part that depends on the previous draw (state and predecessor + embedding) and a part that does not (draft hidden state and target context). `project_context` + computes the second part for every position of the block in one projection; `step` adds the + first. `weights.head` maps the recurrent output to vocabulary corrections as BF16 rows, or as + row-scaled E4M3 rows whose FP32 product takes the BF16 bias before rounding to BF16. + """ + + def __init__(self, weights, tokens, *, positions, session, name): rows, device = tokens.numel(), tokens.device rank = weights.embedding.shape[1] hidden = weights.context_weight.shape[1] // 2 - self.rank, self.softcap = rank, weights.softcap + if type(positions) is not int or positions < 1: + raise ValueError("a recurrent proposal head corrects at least one position per row") + self.rank, self.softcap, self.positions = rank, weights.softcap, positions self.context_bias = weights.bias embedding = torch.empty((rows, rank), dtype=torch.bfloat16, device=device) dynamic = torch.empty((rows, 2 * rank), dtype=torch.bfloat16, device=device) - context = torch.empty((rows, 2 * hidden), dtype=torch.bfloat16, device=device) + context = torch.empty((rows * positions, 2 * hidden), dtype=torch.bfloat16, device=device) + fixed = torch.empty((rows * positions, 3 * rank), dtype=torch.float32, device=device) raw = torch.empty((rows, 3 * rank), dtype=torch.float32, device=device) - correction = torch.empty((rows, weights.head.shape[0]), dtype=torch.bfloat16, device=device) self.embed = PreparedEmbedding(weights.embedding, tokens, embedding, session=session, name=name + ".embedding").functional(session=session, dynamic_inputs=True) - self.context = UnquantizedProjection(context, weights.context_weight, raw, + self.context = UnquantizedProjection(context, weights.context_weight, fixed, session=session, name=name + ".context").functional(session=session) self.dynamic = UnquantizedProjection(dynamic, weights.state_weight, raw, session=session, name=name + ".dynamic").functional(session=session) - self.output = UnquantizedProjection(embedding, weights.head, correction, - bias=weights.head_bias, session=session, name=name + ".output").functional(session=session) + self.output_bias = None + if isinstance(weights.head, RowScaledFP8MarkovWeight): + correction = torch.empty((rows, weights.head.out_features), dtype=torch.float32, device=device) + self.output = PreparedRowScaledFP8MarkovProjection(embedding, weights.head, correction, + session=session, name=name + ".output").functional(session=session) + self.output_bias = weights.head_bias + else: + correction = torch.empty((rows, weights.head.shape[0]), dtype=torch.bfloat16, device=device) + self.output = UnquantizedProjection(embedding, weights.head, correction, + bias=weights.head_bias, session=session, name=name + ".output").functional(session=session) def begin(self, hidden): return torch.zeros((hidden.shape[0], self.rank), dtype=torch.bfloat16, device=hidden.device) - def step(self, state, previous, hidden, context, base): - fixed = self.context(torch.cat((hidden, context), -1)) + self.context_bias + def project_context(self, hidden, context): + """Return FP32 [rows, positions, 3 * rank] recurrence inputs from [rows, positions, hidden] draft states.""" + rows, positions, width = hidden.shape + if positions != self.positions: + raise ValueError("recurrent context projection covers every prepared block position") + source = torch.cat((hidden, context[:, None].expand(rows, positions, width)), -1) + fixed = self.context(source.view(rows * positions, 2 * width)) + self.context_bias + return fixed.view(rows, positions, 3 * self.rank) + + def step(self, state, previous, fixed, base): dynamic = self.dynamic(torch.cat((state, self.embed(token_ids=previous)), -1)) state, latent = recurrent_gate(dynamic + fixed, state) - return state, corrected_logits(base, self.output(latent), self.softcap) + correction = self.output(latent) + if self.output_bias is not None: + correction = (correction + self.output_bias.float()).bfloat16() + return state, corrected_logits(base, correction, self.softcap) diff --git a/ignition/components/ring_commit.py b/ignition/components/ring_commit.py index ec5b69486..1eb37ca41 100644 --- a/ignition/components/ring_commit.py +++ b/ignition/components/ring_commit.py @@ -15,7 +15,7 @@ def _commit(Staged, Backing, Offsets, Rows, Starts, Lengths, ROW_STRIDE: tl.constexpr, STAGED_STRIDE: tl.constexpr, REGION_STRIDE: tl.constexpr, ROWS_STRIDE: tl.constexpr, STARTS_STRIDE: tl.constexpr, LENGTHS_STRIDE: tl.constexpr, - WINDOW: tl.constexpr, RECORD: tl.constexpr, BLOCK: tl.constexpr): + WINDOW: tl.constexpr, CANDIDATES: tl.constexpr, RECORD: tl.constexpr, BLOCK: tl.constexpr): item, request, region = tl.program_id(0), tl.program_id(1), tl.program_id(2) length = tl.load(Lengths + request * LENGTHS_STRIDE) start, row = tl.load(Starts + request * STARTS_STRIDE), tl.load(Rows + request * ROWS_STRIDE) @@ -23,7 +23,7 @@ def _commit(Staged, Backing, Offsets, Rows, Starts, Lengths, ROW_STRIDE: tl.cons byte = tl.arange(0, BLOCK) live = (token < length) & (row > 0) & (byte < RECORD) value = tl.load(Staged + region * REGION_STRIDE + request * STAGED_STRIDE - + (WINDOW + token) * RECORD + byte, live, other=0) + + (CANDIDATES + token) * RECORD + byte, live, other=0) offset = tl.load(Offsets + region) tl.store(Backing + row * ROW_STRIDE + offset + ((start + token) % WINDOW) * RECORD + byte, value, live) @@ -35,9 +35,15 @@ class PreparedRingCommit: Admission validates distinct positive destination rows and bounds accepted counts by token_capacity. Row zero and unaccepted ring records are preserved. The complete backing tensor exposes mutations to forward compilation. + + Each request's staging holds its candidate records from record index + `candidate_offset`, which defaults to `window_tokens` for staging that + places the candidates after one window of history. Position `p` commits to + ring slot `p mod window_tokens`. """ - def __init__(self, backing, offsets, rows, starts, *, token_capacity, window_tokens, record_bytes, staging=None): + def __init__(self, backing, offsets, rows, starts, *, token_capacity, window_tokens, record_bytes, staging=None, + candidate_offset=None): if (backing.device.type != "cuda" or backing.dtype != torch.uint8 or backing.ndim != 2 or backing.stride(1) != 1 or backing.stride(0) < backing.shape[1] or rows.ndim != 1 or rows.numel() == 0 or starts.shape != rows.shape @@ -46,6 +52,9 @@ def __init__(self, backing, offsets, rows, starts, *, token_capacity, window_tok raise ValueError("ring commits require byte rows and matching int64 row/position vectors") if any(type(value) is not int or value <= 0 for value in (token_capacity, window_tokens, record_bytes)): raise ValueError("ring and staging capacities must be positive integers") + candidate_offset = window_tokens if candidate_offset is None else candidate_offset + if type(candidate_offset) is not int or candidate_offset < 0: + raise ValueError("staged candidates start at a nonnegative record index") offsets = tuple(offsets) size = window_tokens * record_bytes if (not offsets or any(type(offset) is not int or offset < 0 or offset + size > backing.shape[1] @@ -57,12 +66,12 @@ def __init__(self, backing, offsets, rows, starts, *, token_capacity, window_tok record_numeric_tensor(self.offsets) from ignition.preparation.scratch import bind_scratch - shape = (len(offsets), rows.numel(), (window_tokens + token_capacity) * record_bytes) + shape = (len(offsets), rows.numel(), (candidate_offset + token_capacity) * record_bytes) self.staging_shape, self.rows_shape = shape, tuple(rows.shape) self.staging = bind_scratch({"staging": (shape, torch.uint8)}, device=backing.device, workspace=None if staging is None else {"staging": staging})["staging"] self.staging.zero_() - self.window_tokens, self.record_bytes = window_tokens, record_bytes + self.window_tokens, self.record_bytes, self.candidate_offset = window_tokens, record_bytes, candidate_offset self.grid = (min(token_capacity, window_tokens), rows.numel(), len(offsets)) def functional(self): @@ -76,4 +85,4 @@ def __call__(self, counts, *, staging, rows, starts): staging, self.backing, self.offsets, rows, starts, counts, self.backing.stride(0), staging.stride(1), staging.stride(0), rows.stride(0), starts.stride(0), counts.stride(0), - self.window_tokens, self.record_bytes, triton.next_power_of_2(self.record_bytes)) + self.window_tokens, self.candidate_offset, self.record_bytes, triton.next_power_of_2(self.record_bytes)) diff --git a/ignition/components/window_staging.py b/ignition/components/window_staging.py index 652240018..7ae6a3504 100644 --- a/ignition/components/window_staging.py +++ b/ignition/components/window_staging.py @@ -22,6 +22,7 @@ class Query: window: int history_dtype: str first_position: int + lookback: int CONTRACT = native_contract(component_id="flare.window_stage", query_type=Query, tactics=lambda q: (0,)) @@ -50,10 +51,12 @@ def compile_staging(payload, ordinal): tuple(cute.sym_int(64) for _ in range(rank - 1)) + (1,), assumed_align=4) for rank, dtype in _operands(q.history_dtype)) with torch.cuda.device(ordinal): + # The kernel takes a lookback only when it differs from the history length. + lookback = {} if q.lookback == q.window else {"lookback": q.lookback} return compile_kernel(WindowStageKernel(heads=q.heads, dim=q.dim, capacity=q.capacity, - window=q.window, first_position=q.first_position), *operands, cutlass.Int32(1), current_cuda_stream(), - compile_spec=KernelCompileSpec.from_key("attention.window_stage", 2, - (q.heads, q.dim, q.capacity, q.window, q.history_dtype, q.first_position))) + window=q.window, first_position=q.first_position, **lookback), *operands, cutlass.Int32(1), + current_cuda_stream(), compile_spec=KernelCompileSpec.from_key("attention.window_stage", 2, + (q.heads, q.dim, q.capacity, q.window, q.history_dtype, q.first_position, q.lookback))) @dataclass(frozen=True) @@ -113,10 +116,16 @@ def _overlap(left, right): class PreparedWindowStaging: - """Gather paired history and candidates with BF16 selection and FP8 saturation.""" + """Gather paired history and candidates with BF16 selection and FP8 saturation. + + The history's second dimension is its ring: position `p` occupies slot `p` + modulo that length. Each request's output lists positions in order from + `max(start - lookback, first_position)`; `lookback` defaults to the ring + length and may be shorter when the ring retains more than attention reads. + """ def __init__(self, history_key, history_value, key, value, output_key, output_value, metadata, *, - counts=None, first_position=0, session, name): + counts=None, first_position=0, lookback=None, session, name): from b12x.attention.paged_kv_write._preparation import _check_layout m = metadata @@ -133,6 +142,9 @@ def __init__(self, history_key, history_value, key, value, output_key, output_va or output_key.shape[0] * output_key.shape[1] % rows or output_key.numel() == 0 or type(first_position) is not int): raise ValueError("window staging requires matching positive BF16 candidates, BF16/FP8 history and FP8 output geometry") + lookback = history_key.shape[1] if lookback is None else lookback + if type(lookback) is not int or not 0 < lookback <= history_key.shape[1]: + raise ValueError("window staging looks back over a positive count of at most the history's positions") capacity = output_key.shape[0] * output_key.shape[1] // rows self.page_shapes = tuple(output_key.shape), tuple(output_value.shape) outputs = tuple(t.view(rows, capacity, *key.shape[1:]) for t in (output_key, output_value)) @@ -152,7 +164,7 @@ def __init__(self, history_key, history_value, key, value, output_key, output_va if _overlap(*outputs): raise ValueError("window staging outputs must not overlap") q = Query(key.shape[1], key.shape[2], capacity, history_key.shape[1], - str(history_key.dtype).removeprefix("torch."), first_position) + str(history_key.dtype).removeprefix("torch."), first_position, lookback) payload = CONTRACT.encode_query(q) arguments = self.arguments device_index = key.device.index diff --git a/ignition/recipes/inkling2/attention.py b/ignition/recipes/inkling2/attention.py index e0c885333..819ea633b 100644 --- a/ignition/recipes/inkling2/attention.py +++ b/ignition/recipes/inkling2/attention.py @@ -23,8 +23,10 @@ from ignition.components.head_gate import PreparedHeadGate from ignition.components.linear import UnquantizedProjection from ignition.components.paged_attention import PreparedPagedAttention, PreparedPagedKVWriter +from ignition.components.ring_commit import PreparedRingCommit from ignition.components.rms_norm import PreparedRMSNorm from ignition.components.state import gather_rows, scatter_rows +from ignition.components.window_staging import PreparedWindowStaging from ignition.preparation.persistent import persistent_empty from .arithmetic import l2_clip, log_scaling @@ -125,7 +127,9 @@ class LayerCache: Local layers also expose each continuation row's K and V rings as bytes (`key_rings`, `value_rings`, `[rows, ring bytes]`), which prefill reads and - rewrites one request row at a time. + rewrites one request row at a time, and the continuation rows with the byte + offsets of the K and V rings (`rows`, `ring_offsets`), where verification + commits accepted positions. """ key: torch.Tensor @@ -135,13 +139,17 @@ class LayerCache: ring_row_pages: int = 0 key_rings: torch.Tensor | None = None value_rings: torch.Tensor | None = None + rows: torch.Tensor | None = None + ring_offsets: tuple[int, int] | None = None @classmethod def of(cls, pool, layer): if pool.text.local(layer): return cls(pool.ring_pages(layer, "key"), pool.ring_pages(layer, "value"), pool.history(layer, "key_convolution"), pool.history(layer, "value_convolution"), - pool.ring_row_pages, pool.ring_rows(layer, "key"), pool.ring_rows(layer, "value")) + pool.ring_row_pages, pool.ring_rows(layer, "key"), pool.ring_rows(layer, "value"), + pool.reserved_backing, + tuple(pool.layout.region(f"layer{layer}.{kind}").offset for kind in ("key", "value"))) return cls(pool.cache(layer, "key"), pool.cache(layer, "value"), pool.history(layer, "key_convolution"), pool.history(layer, "value_convolution")) @@ -230,6 +238,16 @@ def example(role, shape, dtype=torch.bfloat16): cache_value = example("inkling.attention.staged_value", (count, PAGE_TOKENS, self.kv_heads, self.dim), KV_DTYPE) pages = torch.arange(count, dtype=torch.int32, device=device).view(requests, self.staged_pages) self.staged_table = pages + if mode == "verify": + # One kernel stages each request's preceding window and its rows from the K and V rings; + # one kernel commits the accepted rows' records to both rings. + shape = (-1, self.ring, self.kv_heads, self.dim) + self.staging = PreparedWindowStaging(cache.key_rings.view(KV_DTYPE).view(shape), + cache.value_rings.view(KV_DTYPE).view(shape), key, value, cache_key, cache_value, metadata, + lookback=self.window - 1, session=session, name=f"{name}.staging").functional(session=session) + self.ring_commit = PreparedRingCommit(cache.rows, cache.ring_offsets, metadata.state_rows, + metadata.starts, token_capacity=metadata.max_query_tokens, window_tokens=self.ring, + record_bytes=self.kv_heads * self.dim * KV_DTYPE.itemsize, candidate_offset=0).functional() else: cache_key, cache_value = cache.key, cache.value pages = (example("inkling.attention.ring_table", (requests, self.ring // PAGE_TOKENS), torch.int32) @@ -336,10 +354,8 @@ def _decode(self, v, m): def _verify(self, v, m): if self.local: - cache_key, lengths = stage_batch(self.cache.key_rings, v["key"], m, - window=self.window, pages=self.staged_pages) - cache_value, _ = stage_batch(self.cache.value_rings, v["value"], m, - window=self.window, pages=self.staged_pages) + cache_key, cache_value = self.staging(v["key"], v["value"], metadata=m) + lengths = staged_lengths(m, self.window) pages = self.staged_table kwargs = dict(k_cache=cache_key, v_cache=cache_value) else: @@ -355,38 +371,26 @@ def commit(self, values, counts, metadata): self.key_convolution.commit(values["key_previous"], values["key_raw"], metadata, counts=counts) self.value_convolution.commit(values["value_previous"], values["value_raw"], metadata, counts=counts) if self.local: - retain_batch(self.cache.key_rings, values["key"], counts, metadata) - retain_batch(self.cache.value_rings, values["value"], counts, metadata) + records = accepted_records(values["key"], values["value"], metadata) + self.ring_commit(counts, staging=records, rows=metadata.state_rows, starts=metadata.starts) -def stage_batch(rings, values, m, *, window, pages): - rows, capacity = m.starts.numel(), pages * PAGE_TOKENS - ring = torch.empty((rows, rings.shape[1]), dtype=torch.uint8, device=rings.device) - gather_rows(rings, m.state_rows, ring) - ring = ring.view(KV_DTYPE).view(rows, -1, *values.shape[1:]) +def staged_lengths(m, window): + """Each request's staged key count: its preceding `window - 1` positions, bounded by its start, and its rows.""" first = (m.starts - window + 1).clamp_min(0) - positions = first[:, None] + torch.arange(capacity, device=values.device) - previous = ring[torch.arange(rows, device=values.device)[:, None], positions.remainder(ring.shape[1])].to(values.dtype) - index = (m.query_start_loc[:-1, None] + positions - m.starts[:, None]).clamp(0, values.shape[0] - 1) - staged = torch.where((positions < m.starts[:, None])[:, :, None, None], previous, values[index]) - lengths = torch.where(m.lengths > 0, m.starts - first + m.lengths, 0).int() - staged = torch.where((positions < (m.starts + m.lengths)[:, None])[:, :, None, None], staged, 0) - return staged.clamp(-448, 448).to(KV_DTYPE).view(rows * pages, PAGE_TOKENS, *values.shape[1:]), lengths - - -def retain_batch(rings, values, counts, m): - rows = m.starts.numel() - previous = torch.empty((rows, rings.shape[1]), dtype=torch.uint8, device=rings.device) - gather_rows(rings, m.state_rows, previous) - ring = previous.view(KV_DTYPE).view(rows, -1, *values.shape[1:]) - capacity = ring.shape[1] - first = m.starts + counts - capacity - positions = first[:, None] + (torch.arange(capacity, device=values.device) - first[:, None]).remainder(capacity) - indices = (m.query_start_loc[:-1, None] + positions - m.starts[:, None]).clamp(0, values.shape[0] - 1) - current = values[indices].clamp(-448, 448) - keep = ((positions < m.starts[:, None]) | (positions < 0))[:, :, None, None] - retained = torch.where(keep, ring.to(values.dtype), current).to(KV_DTYPE) - scatter_rows(retained.view(torch.uint8).view(rows, -1), m.state_rows, rings, counts > 0) + return torch.where(m.lengths > 0, m.starts - first + m.lengths, 0).int() + + +def accepted_records(key, value, m): + """FP8 K and V records of each request's rows, as bytes `[2, requests, width * record bytes]`. + + Record `t` of a request is its row `t`; columns past a request's rows hold other + requests' records, which a commit bounded by the request's accepted count never reads. + """ + width = m.max_query_tokens + index = (m.query_start_loc[:-1, None] + torch.arange(width, device=key.device)).clamp(0, key.shape[0] - 1) + records = torch.stack((key[index], value[index])).clamp(-448, 448).to(KV_DTYPE) + return records.view(torch.uint8).view(2, index.shape[0], -1) def _page_slots(m): diff --git a/ignition/recipes/inkling2/bootstrap.py b/ignition/recipes/inkling2/bootstrap.py index 8210ca87e..cb7f6ca7d 100644 --- a/ignition/recipes/inkling2/bootstrap.py +++ b/ignition/recipes/inkling2/bootstrap.py @@ -75,6 +75,9 @@ class PreparationConfig: speculative_token_capacity: int | None = 64 speculative_graph_budget: int = 64 mtp_only: bool = False + # Proposal-only quantized copies derived from checkpoint values at load; None keeps BF16. + draft_head_quantization: str | None = None + markov_head_quantization: str | None = None benchmark_selection: object | None = None def __post_init__(self): @@ -107,6 +110,13 @@ def __post_init__(self): raise ValueError("--mtp-only requires enabled learned speculation with positive draft depth") if self.drafting and (not self.speculative_widths or not set(self.speculative_widths) <= set(range(1, 9))): raise ValueError("Inkling 2 verification widths must be in [1, 8]") + if self.draft_head_quantization not in (None, "nvfp4", "mxfp8"): + raise ValueError("Inkling 2 draft head quantization must be omitted, nvfp4 or mxfp8") + if self.markov_head_quantization not in (None, "fp8"): + raise ValueError("Inkling 2 recurrent correction head quantization must be omitted or fp8") + if (self.draft_head_quantization is not None or self.markov_head_quantization is not None) and ( + not self.drafting or self.draft_tokens < 1): + raise ValueError("proposal head quantization requires learned speculation with positive draft depth") if self.snapshot_budget_bytes <= 0 or self.headroom_bytes < 0: raise ValueError("snapshot budget must be positive and headroom nonnegative") object.__setattr__(self, "image_concurrency", image_capacity(self.max_active, self.image_concurrency) if self.vision else 0) @@ -217,7 +227,9 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): raise ValueError("a decoder-layer prefix must include a global-attention layer, whose K/V use pages") with phase(progress, "Load weights"): weights = ModelWeights.load(manifest, device, shard=shard, layers=config.decoder_layers, - progress=progress, drafting=config.drafting, vision=config.vision) + progress=progress, drafting=config.drafting, vision=config.vision, + draft_head_quantization=config.draft_head_quantization, + markov_head_quantization=config.markov_head_quantization) weights_bytes = torch.cuda.memory_allocated(device) if torch.cuda.get_device_properties(device).is_integrated: from ignition.preparation.host_memory import release_page_cache @@ -406,7 +418,9 @@ def add(name, forward, kind, rows, tokens, fields, enabled=None, packed=0): prefill_capacities=prefills, free_device_bytes=free, total_device_bytes=total, allocated_tensor_bytes=torch.cuda.memory_allocated(device), reserved_tensor_bytes=torch.cuda.memory_reserved(device), headroom_bytes=config.headroom_bytes, - tuning=tuning, compiled_decoder=config.compile_decoder) + tuning=tuning, compiled_decoder=config.compile_decoder, + draft_head_quantization=config.draft_head_quantization, + markov_head_quantization=config.markov_head_quantization) # Each decoder layer's weights form one stable payload; vocabulary shards, norms and the output query share misc. rebuild_weights = declare_weights(weights, components=("embedding", "embedding_norm", "final_norm", "output_query", "unembedding", "draft", "vision")) diff --git a/ignition/recipes/inkling2/dspark.py b/ignition/recipes/inkling2/dspark.py index 93944531e..83095c9e6 100644 --- a/ignition/recipes/inkling2/dspark.py +++ b/ignition/recipes/inkling2/dspark.py @@ -9,7 +9,7 @@ from ignition.components.collectives import PreparedAllReduce from ignition.components.embedding import PreparedEmbedding -from ignition.components.linear import UnquantizedProjection +from ignition.components.linear import QuantizedProjection, UnquantizedProjection from ignition.components.mlp import MLPScratch, PreparedMLP from ignition.components.paged_attention import PreparedPagedAttention, PreparedPagedKVWriter from ignition.components.recurrent_proposal import PreparedRecurrentProposalHead @@ -18,7 +18,8 @@ from ignition.components.state import gather_rows, save_hidden from ignition.preparation.persistent import persistent_copy, persistent_zeros -from .dspark_state import context_slots, mix_features, rotary, stage_paged_tail, stage_window +from .dspark_state import (block_inputs, context_slots, mix_features, rotary_table, rotate, stage, tail_plan, + window_plan) def inverse_frequencies(draft, device): @@ -66,11 +67,12 @@ def __call__(self, auxiliary, counts, metadata): m = metadata full_slots = context_slots(m, counts) local_slots = context_slots(m, counts, window=self.window) + table = rotary_table(m.positions, self.inverse) for index, (projection, key_norm, context_norm, writer, local) in enumerate(self.stages): context = mix_features(auxiliary, self.alpha[index], context_norm, self.eps) key, value = projection(context).chunk(2, -1) key = key_norm(key.contiguous().view(-1, self.key_shape[-1])).view(self.key_shape) - writer(rotary(key, m.positions, self.inverse), value.contiguous().view(self.key_shape), + writer(rotate(key, table), value.contiguous().view(self.key_shape), local_slots if local else full_slots) indices = (m.query_start_loc[:-1].long() + counts.long() - 1).clamp(0, auxiliary.shape[0] - 1) context = mix_features(auxiliary[indices], self.alpha[-1], self.recurrent_norm, self.eps) @@ -82,6 +84,8 @@ def scratch_tensors(self): @dataclass(frozen=True) class DraftScratch: + # One row per request: the block's first position is the only one that embeds a token. + anchor: torch.Tensor hidden: torch.Tensor accumulator: torch.Tensor qkv: torch.Tensor @@ -99,7 +103,9 @@ def allocate(cls, config, shard, tokens, block, device): start, end = shard.padded_partition(config.vocabulary, alignment=64) def empty(*shape, dtype=torch.bfloat16): return torch.empty(shape, dtype=dtype, device=device) - return cls(empty(tokens, hidden), empty(tokens, hidden, dtype=torch.float32), + if tokens % block: + raise ValueError("Inkling2 DSpark scratch holds whole blocks") + return cls(empty(tokens // block, hidden), empty(tokens, hidden), empty(tokens, hidden, dtype=torch.float32), empty(tokens, (q + 2 * kv) * d.head_dim), empty(tokens, q, d.head_dim), empty(tokens, kv, d.head_dim), empty(tokens, q, d.head_dim), empty(tokens, hidden), MLPScratch.allocate(tokens, hidden, d.text["intermediate_size"] // shard.world_size, device), @@ -108,7 +114,11 @@ def empty(*shape, dtype=torch.bfloat16): def rows(self, tokens, samples): if samples != tokens: raise ValueError("Inkling2 DSpark projects every block position") - return type(self)(*(self.mlp.rows(tokens) if field == "mlp" else getattr(self, field)[:tokens] + block = self.hidden.shape[0] // self.anchor.shape[0] + if tokens % block: + raise ValueError("Inkling2 DSpark scratch holds whole blocks") + counts = {"mlp": None, "anchor": tokens // block} + return type(self)(*(self.mlp.rows(tokens) if field == "mlp" else getattr(self, field)[:counts.get(field, tokens)] for field in self.__dataclass_fields__)) @@ -118,7 +128,6 @@ def __init__(self, index, weights, config, scratch, metadata, pool, *, shard, ru d = config.draft self.query_shape, self.key_shape = tuple(scratch.query.shape), tuple(scratch.key.shape) self.window, self.local = d.window, index in d.local_layers - self.inverse = inverse_frequencies(d, scratch.hidden.device) self.qkv = UnquantizedProjection(scratch.hidden, weights.qkv, scratch.qkv, session=session, name=name + ".qkv").functional(session=session) self.query_norm = norm(scratch.query.flatten(0, 1), weights.query_norm, scratch.query.flatten(0, 1), @@ -134,6 +143,7 @@ def __init__(self, index, weights, config, scratch, metadata, pool, *, shard, ru shape = (rows * self.pages_per_row, 128, *self.key_shape[1:]) key, value = (torch.empty(shape, dtype=torch.bfloat16, device=scratch.hidden.device) for _ in range(2)) tail = {} + self.staging = (window_plan, d.window, self.pages_per_row) else: self.key_cache, self.value_cache = pool.key(index, draft=True), pool.value(index, draft=True) self.pages = None @@ -142,6 +152,7 @@ def __init__(self, index, weights, config, scratch, metadata, pool, *, shard, ru shape = (rows * self.tail_pages, key.shape[1], *self.key_shape[1:]) tail = {role: torch.empty(shape, dtype=key.dtype, device=key.device) for role in ("tail_key", "tail_value")} + self.staging = (tail_plan, key.shape[1], self.tail_pages) self.attention = PreparedPagedAttention(scratch.query, key, value, self.pages if self.local else metadata.page_table, metadata.lengths, metadata.query_start_loc, scratch.attended, mode="verify", width=d.block_size, window=-1, causal=False, @@ -155,26 +166,23 @@ def __init__(self, index, weights, config, scratch, metadata, pool, *, shard, ru self.reduce = PreparedAllReduce(scratch.partial, scratch.hidden, runtime=runtime, coordinator=coordinator, session=session, name=name + ".reduce").functional(session=session) - def __call__(self, hidden, metadata): + def __call__(self, hidden, metadata, plan, table): + """Attend with `plan`, this layer's staging plan, and `table`, the rows' rotary cosines and sines.""" m = metadata q_width = self.query_shape[1] * self.query_shape[2] kv_width = self.key_shape[1] * self.key_shape[2] q, k, v = self.qkv(hidden).split((q_width, kv_width, kv_width), -1) q = self.query_norm(q.contiguous().view(-1, self.query_shape[-1])).view(self.query_shape) k = self.key_norm(k.contiguous().view(-1, self.key_shape[-1])).view(self.key_shape) - q, k = rotary(q, m.positions, self.inverse), rotary(k, m.positions, self.inverse) + q, k = rotate(q, table), rotate(k, table) v = v.contiguous().view(self.key_shape) if self.local: - key = stage_window(self.key_cache, k, m, self.pages_per_row) - value = stage_window(self.value_cache, v, m, self.pages_per_row) - lengths = torch.where(m.lengths > 0, m.starts.clamp(max=self.window).int() + m.lengths, 0) + key, value = stage(self.key_cache, k, plan), stage(self.value_cache, v, plan) tail = {} else: key, value = self.key_cache, self.value_cache - tail = dict(tail_key=stage_paged_tail(key, k, m, self.tail_pages), - tail_value=stage_paged_tail(value, v, m, self.tail_pages)) - lengths = torch.where(m.lengths > 0, m.starts.int() + m.lengths, 0) - attended = self.attention(q, k_cache=key, v_cache=value, cache_seqlens=lengths, + tail = dict(tail_key=stage(key, k, plan), tail_value=stage(value, v, plan)) + attended = self.attention(q, k_cache=key, v_cache=value, cache_seqlens=plan.lengths, cu_seqlens_q=m.query_start_loc, **tail, **({} if self.local else {"page_table": m.page_table})) return self.reduce(self.output(attended.flatten(1))) @@ -195,13 +203,13 @@ def __init__(self, index, weights, owner, scratch, metadata, pool, *, session, n self.reduce = PreparedAllReduce(s.output, scratch.hidden, runtime=runtime, coordinator=coordinator, session=session, name=name + ".mlp.reduce").functional(session=session) - def __call__(self, hidden, residual, metadata): + def __call__(self, hidden, residual, metadata, plan, table): if residual is None: residual = hidden else: hidden = hidden.float() + residual.float() residual = hidden.bfloat16() - attended = self.attention(self.input_norm(hidden), metadata) + attended = self.attention(self.input_norm(hidden), metadata, plan, table) summed = attended.float() + residual.float() residual = summed.bfloat16() return self.reduce(self.mlp(self.post_norm(summed))), residual @@ -221,36 +229,50 @@ def __init__(self, weights, scratch, metadata, pool, *, runtime, coordinator, se first, _ = weights.shard.padded_partition(weights.config.vocabulary, alignment=64) self.vocabulary_start = persistent_copy(torch.tensor([first], dtype=torch.int64, device=device)) self.embedding_weight = weights.embedding - ids = metadata.token_ids.clamp(0, weights.embedding.shape[0] - 1) - self.embedding = PreparedEmbedding(weights.embedding, ids, scratch.hidden, session=session, + self.inverse = inverse_frequencies(d, device) + # Positions after the first take the learned mask, so only each request's first row is + # embedded, reduced across the vocabulary shards and normalized. + ids = metadata.token_ids[::self.block].clamp(0, weights.embedding.shape[0] - 1) + self.embedding = PreparedEmbedding(weights.embedding, ids, scratch.anchor, session=session, name=name + ".embed").functional(session=session, dynamic_inputs=True) - self.embed_reduce = PreparedAllReduce(scratch.hidden, scratch.hidden, runtime=runtime, + self.embed_reduce = PreparedAllReduce(scratch.anchor, scratch.anchor, runtime=runtime, coordinator=coordinator, session=session, name=name + ".embed.reduce").functional(session=session) - self.embed_norm = norm(scratch.hidden, weights.embedding_norm, scratch.hidden, + self.embed_norm = norm(scratch.anchor, weights.embedding_norm, scratch.anchor, eps=d.text["rms_norm_eps"], session=session, name=name + ".embed.norm") self.layers = [DraftLayer(i, layer, weights, scratch, metadata, pool, runtime=runtime, coordinator=coordinator, session=session, name=f"{name}.{i}", workspace=workspace) for i, layer in enumerate(weights.draft.layers)] + # Layers with equal history geometry share one staging plan per forward. + self.staging = tuple(dict.fromkeys(layer.attention.staging for layer in self.layers)) + self.layer_plans = tuple(self.staging.index(layer.attention.staging) for layer in self.layers) self.norm = norm(scratch.accumulator, weights.draft.norm, scratch.hidden, eps=d.text["rms_norm_eps"], session=session, name=name + ".norm") - self.head = UnquantizedProjection(scratch.hidden, weights.head, scratch.local_logits, - session=session, name=name + ".head").functional(session=session) + if weights.draft.draft_head is None: + self.head = UnquantizedProjection(scratch.hidden, weights.head, scratch.local_logits, + session=session, name=name + ".head").functional(session=session) + else: + # A quantized copy of the target's vocabulary shard serves proposals; verification keeps the target's. + self.head = QuantizedProjection(scratch.hidden, weights.draft.draft_head, scratch.local_logits, + session=session, name=name + ".head", activation_mode="a16", + workspace=workspace).functional(session=session) self.recurrent = PreparedRecurrentProposalHead(weights.draft.recurrent, - torch.zeros(metadata.lengths.numel(), dtype=torch.int64, device=device), session=session, name=name + ".recurrent") + torch.zeros(metadata.lengths.numel(), dtype=torch.int64, device=device), + positions=self.block - 1, session=session, name=name + ".recurrent") def release_outputs(self): return self def __call__(self, metadata): - ids = metadata.token_ids - self.vocabulary_start + ids = metadata.token_ids[::self.block] - self.vocabulary_start owned = (ids >= 0) & (ids < self.embedding_weight.shape[0]) local = self.embedding(token_ids=ids.clamp(0, self.embedding_weight.shape[0] - 1)) - hidden = self.embed_norm(self.embed_reduce(torch.where(owned[:, None], local, 0))) - positions = torch.arange(hidden.shape[0], device=hidden.device) % self.block - hidden = torch.where((positions == 0)[:, None], hidden, self.mask) + anchor = self.embed_norm(self.embed_reduce(torch.where(owned[:, None], local, 0))) + hidden = block_inputs(anchor, self.mask, self.block) + table = rotary_table(metadata.positions, self.inverse) + plans = [plan(metadata, *geometry) for plan, *geometry in self.staging] residual = None - for layer in self.layers: - hidden, residual = layer(hidden, residual, metadata) + for layer, plan in zip(self.layers, self.layer_plans): + hidden, residual = layer(hidden, residual, metadata, plans[plan], table) hidden = self.norm(hidden.float() + residual.float())[metadata.sample_indices] logits = self.head(hidden) context = torch.empty((metadata.state_rows.numel(), self.recurrent_context.shape[1]), diff --git a/ignition/recipes/inkling2/dspark_state.py b/ignition/recipes/inkling2/dspark_state.py index 71c9399f3..a6c9886a9 100644 --- a/ignition/recipes/inkling2/dspark_state.py +++ b/ignition/recipes/inkling2/dspark_state.py @@ -3,6 +3,8 @@ """Inkling2 draft feature mixing, rotary positions, and committed context selection.""" +from dataclasses import dataclass + import torch @@ -14,46 +16,78 @@ def mix_features(features, alpha, weight, eps): return (mixed * scale * weight.float()).bfloat16() -def rotary(values, positions, inverse): +def block_inputs(anchor, mask, block): + """Expand one normalized first-position embedding per request into its block of learned masks.""" + return torch.cat((anchor[:, None], mask.expand(anchor.shape[0], block - 1, -1)), 1).flatten(0, 1) + + +def rotary_table(positions, inverse): + """Return FP32 cosines and sines of each row's position, shared by every rotation of those rows.""" angle = positions.clamp_min(0).float()[:, None] * inverse[None] - cosine, sine = angle.cos()[:, None], angle.sin()[:, None] + return angle.cos()[:, None], angle.sin()[:, None] + + +def rotate(values, table): + cosine, sine = table left, right = values.float().chunk(2, -1) return torch.cat((left * cosine - right * sine, right * cosine + left * sine), -1).to(values.dtype) -def stage_window(history, values, metadata, pages): - """Stage the same committed suffix before every query in a noncausal block.""" +def rotary(values, positions, inverse): + return rotate(values, rotary_table(positions, inverse)) + + +@dataclass(frozen=True) +class StagingPlan: + """Where each slot of a request's private attention pages comes from. + + The plan depends on request metadata only, so one plan serves the key and value histories of + every draft layer with the same history geometry. A slot holds committed history + (`history[rows, slots]`), a row of the block being drafted (`values[indices]`), or zero. + `lengths` is each request's visible key count. + """ + + rows: torch.Tensor + slots: torch.Tensor + indices: torch.Tensor + committed: torch.Tensor + valid: torch.Tensor + lengths: torch.Tensor + page_tokens: int + + +def window_plan(metadata, window, pages, *, page_tokens=128): + """Plan the same committed suffix of a `window`-position ring before every query of a noncausal block.""" m = metadata - rows, window = m.starts.numel(), history.shape[1] - capacity = pages * 128 - offsets = torch.arange(capacity, device=values.device)[None] + offsets = torch.arange(pages * page_tokens, device=m.starts.device)[None] prefix = m.starts.clamp(max=window)[:, None] positions = m.starts[:, None] - prefix + offsets - previous = history[m.state_rows[:, None], positions.remainder(window)] - indices = (m.query_start_loc[:-1, None] + offsets - prefix).clamp(0, values.shape[0] - 1) - current = values[indices] - valid = (m.lengths[:, None] > 0) & (offsets < prefix + m.lengths[:, None]) - return torch.where(valid[:, :, None, None], - torch.where((offsets < prefix)[:, :, None, None], previous, current), 0).view( - rows * pages, 128, *values.shape[1:]) + return StagingPlan(m.state_rows[:, None], positions.remainder(window), + (m.query_start_loc[:-1, None] + offsets - prefix).clamp(0, m.positions.numel() - 1), + offsets < prefix, (m.lengths[:, None] > 0) & (offsets < prefix + m.lengths[:, None]), + torch.where(m.lengths > 0, m.starts.clamp(max=window).int() + m.lengths, 0), page_tokens) -def stage_paged_tail(history, values, metadata, pages): - """Copy the committed partial page and proposal rows into private attention pages.""" +def tail_plan(metadata, page_tokens, pages): + """Plan the committed partial page followed by the block's rows in private tail pages.""" m = metadata - rows, page_tokens = m.starts.numel(), history.shape[1] - offsets = torch.arange(pages * page_tokens, device=values.device)[None] + rows = m.starts.numel() + offsets = torch.arange(pages * page_tokens, device=m.starts.device)[None] prefix = m.starts.remainder(page_tokens)[:, None] columns = (m.starts // page_tokens).clamp(max=m.page_table.shape[1] - 1) - requests = torch.arange(rows, device=values.device) + requests = torch.arange(rows, device=m.starts.device) source_pages = m.page_table[requests, columns].long().clamp_min(0) - previous = history[source_pages[:, None], offsets.remainder(page_tokens)] - indices = (m.query_start_loc[:-1, None] + offsets - prefix).clamp(0, values.shape[0] - 1) - current = values[indices] - valid = (m.lengths[:, None] > 0) & (offsets < prefix + m.lengths[:, None]) - return torch.where(valid[:, :, None, None], - torch.where((offsets < prefix)[:, :, None, None], previous, current), 0).view( - rows * pages, page_tokens, *values.shape[1:]) + return StagingPlan(source_pages[:, None], offsets.remainder(page_tokens), + (m.query_start_loc[:-1, None] + offsets - prefix).clamp(0, m.positions.numel() - 1), + offsets < prefix, (m.lengths[:, None] > 0) & (offsets < prefix + m.lengths[:, None]), + torch.where(m.lengths > 0, m.starts.int() + m.lengths, 0), page_tokens) + + +def stage(history, values, plan): + """Copy the planned history and block rows into private attention pages without changing either source.""" + staged = torch.where(plan.valid[:, :, None, None], + torch.where(plan.committed[:, :, None, None], history[plan.rows, plan.slots], values[plan.indices]), 0) + return staged.view(-1, plan.page_tokens, *values.shape[1:]) def accepted_rows(metadata, counts, *, window=None): diff --git a/ignition/recipes/inkling2/dspark_weights.py b/ignition/recipes/inkling2/dspark_weights.py index 37ace67cb..8d7652ac3 100644 --- a/ignition/recipes/inkling2/dspark_weights.py +++ b/ignition/recipes/inkling2/dspark_weights.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Checkpoint-preserving tensor partitions for Inkling2's dense DSpark decoder.""" +"""Tensor partitions for Inkling2's dense DSpark decoder and its optional quantized proposal heads.""" from dataclasses import dataclass from functools import cached_property @@ -10,6 +10,8 @@ import torch +from ignition.components.markov_sampling import fp8_markov_head +from ignition.components.vocabulary import mxfp8_draft_head, nvfp4_draft_head from ignition.components.weights import DirectWeightLoader, MLPWeights from ignition.preparation.checkpoint import IndexedCheckpoint, _read_header from ignition.preparation.persistent import persistent_copy, persistent_empty @@ -74,25 +76,36 @@ class DraftLayerWeights: mlp: MLPWeights +DRAFT_HEAD_FORMATS = {"nvfp4": nvfp4_draft_head, "mxfp8": mxfp8_draft_head} + + +def _transient(shape, dtype, device): + return torch.empty(shape, dtype=dtype, device=device) + + @dataclass(frozen=True) class RecurrentWeights: embedding: torch.Tensor state_weight: torch.Tensor context_weight: torch.Tensor bias: torch.Tensor - head: torch.Tensor + # Vocabulary rows by recurrent rank: BF16, or row-scaled E4M3 when the correction head is quantized. + head: object head_bias: torch.Tensor context_norm: torch.Tensor softcap: float = 30. -def fold_recurrent_head(head, hidden_out, hidden_bias, *, chunk=4096): - """Fold the BF16 output map through the vocabulary head with FP64 products.""" +def fold_recurrent_head(head, hidden_out, hidden_bias, *, chunk=4096, allocate=persistent_empty): + """Fold the BF16 output map through the vocabulary head with FP64 products. + + `allocate` places the folded matrix; a caller that quantizes it passes a transient allocator. + """ if (head.ndim != 2 or hidden_out.ndim != 2 or hidden_out.shape[0] != head.shape[1] or hidden_bias.shape != (head.shape[1],) or any(t.dtype != torch.bfloat16 or t.device != head.device for t in (head, hidden_out, hidden_bias))): raise ValueError("recurrent output folding requires compatible BF16 output and vocabulary matrices") - weight = persistent_empty((head.shape[0], hidden_out.shape[1]), torch.bfloat16, head.device) + weight = allocate((head.shape[0], hidden_out.shape[1]), torch.bfloat16, head.device) bias = persistent_empty((head.shape[0],), torch.bfloat16, head.device) projection, offset = hidden_out.double(), hidden_bias.double() for start in range(0, head.shape[0], chunk): @@ -110,9 +123,22 @@ class DraftWeights: norm: torch.Tensor layers: tuple[DraftLayerWeights, ...] recurrent: RecurrentWeights + # Quantized copy of the target vocabulary shard that only proposals read; None projects with the target's. + draft_head: object | None = None @classmethod - def load(cls, snapshot, config, device, shard, *, target_head, progress=None): + def load(cls, snapshot, config, device, shard, *, target_head, progress=None, + draft_head_quantization=None, markov_head_quantization=None): + """Load one rank's drafter and derive its proposal heads from checkpoint values. + + `draft_head_quantization` (`nvfp4` or `mxfp8`) adds a quantized copy of `target_head` for the block's + vocabulary logits. `markov_head_quantization` (`fp8`) stores the recurrent correction head, the + output map folded through `target_head`, as row-scaled E4M3. The target head keeps BF16. + """ + if draft_head_quantization not in (None, *DRAFT_HEAD_FORMATS): + raise ValueError("Inkling2 draft head quantization must be omitted, nvfp4 or mxfp8") + if markov_head_quantization not in (None, "fp8"): + raise ValueError("Inkling2 recurrent correction head quantization must be omitted or fp8") snapshot = Path(snapshot) sidecar, tensors = _read_header(snapshot / "mtp.safetensors", "mtp.safetensors") manifest = DraftCheckpoint(snapshot, tensors, (sidecar,)) @@ -160,8 +186,16 @@ def vector(name, width): raise ValueError("Inkling2 predecessor embedding must be a BF16 vocabulary by recurrent-rank matrix") hidden_out = loader.load_tensor("markov_head.hidden_out.weight", temporary=True) hidden_bias = vector("markov_head.hidden_out.bias", hidden) - head, head_bias = fold_recurrent_head(target_head, hidden_out, hidden_bias) + if markov_head_quantization is None: + head, head_bias = fold_recurrent_head(target_head, hidden_out, hidden_bias) + else: + folded, head_bias = fold_recurrent_head(target_head, hidden_out, hidden_bias, allocate=_transient) + head = fp8_markov_head(folded) + del folded recurrent = RecurrentWeights(embedding, persistent_copy(state[:, :2 * rank].contiguous()), persistent_copy(state[:, 2 * rank:].contiguous()), persistent_copy(vector("markov_head.rnn_proj.bias", 3 * rank).float()), head, head_bias, vector("markov_head.dflare_norm.weight", hidden)) - return cls(alpha, vector("mask_embed", hidden), vector("norm.weight", hidden), tuple(layers), recurrent) + draft_head = (None if draft_head_quantization is None + else DRAFT_HEAD_FORMATS[draft_head_quantization](target_head)) + return cls(alpha, vector("mask_embed", hidden), vector("norm.weight", hidden), tuple(layers), recurrent, + draft_head) diff --git a/ignition/recipes/inkling2/recipe.py b/ignition/recipes/inkling2/recipe.py index 192907937..29e3b9c01 100644 --- a/ignition/recipes/inkling2/recipe.py +++ b/ignition/recipes/inkling2/recipe.py @@ -22,12 +22,11 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ if plan.prompt_logprobs: raise ValueError("Inkling 2 preparation does not capture prompt scoring graphs") speculation = plan.speculation - if speculation is not None and (speculation.draft_head_quantization is not None - or speculation.markov_head_quantization is not None): - raise ValueError("Inkling 2 retains the bundled draft checkpoint precision") drafting = {} if speculation is None else dict(speculative_widths=speculation.widths, speculative_fixed_width=speculation.fixed_width, speculative_token_capacity=plan.speculative_token_capacity, - speculative_graph_budget=speculation.graph_budget or 64) + speculative_graph_budget=speculation.graph_budget or 64, + draft_head_quantization=speculation.draft_head_quantization, + markov_head_quantization=speculation.markov_head_quantization) config = PreparationConfig(collective_tuning=plan.collective_tuning, collective_ladder=plan.collective_ladder, prompt_logprobs=plan.prompt_logprobs, compile_workers=plan.compile_workers, native_dense_activations=plan.native_dense_activations, @@ -54,6 +53,8 @@ def usage(prepared): RECIPE = Recipe(name="inkling2", served_model_name="Inkling-2-Small-NVFP4", prepare=prepare, usage=usage, sampling_defaults=SAMPLING_DEFAULTS, + # Proposal-only copies: the block's vocabulary head, and the recurrent correction head as row-scaled E4M3. + draft_head_quantizations=("nvfp4", "mxfp8"), markov_head_quantizations=("fp8",), checkpoints=(Checkpoint(alias="inkling-2-small-nvfp4", repository="/data/models/Inkling-2-Small-NVFP4", revision="local", architecture="Inkling2ForConditionalGeneration", stored_bytes=344_366_116_864, device_bytes=344_366_116_864, expansion_bytes=5_673_717_760, draft_bytes=2_684_203_392),), diff --git a/ignition/recipes/inkling2/weights.py b/ignition/recipes/inkling2/weights.py index 7a851c2d1..72731dba7 100644 --- a/ignition/recipes/inkling2/weights.py +++ b/ignition/recipes/inkling2/weights.py @@ -72,7 +72,8 @@ def embed_norm(self): return self.embedding_norm @classmethod - def load(cls, manifest, device, *, shard, progress=None, drafting=True, vision=True, layers=None): + def load(cls, manifest, device, *, shard, progress=None, drafting=True, vision=True, layers=None, + draft_head_quantization=None, markov_head_quantization=None): before = torch.cuda.memory_allocated(device) with InklingWeightLoader(manifest, device, shard=shard, progress=progress, vision=vision) as loader: c = loader.config @@ -105,7 +106,8 @@ def vocabulary_rows(name): draft = None if drafting: from .dspark_weights import DraftWeights - draft = DraftWeights.load(manifest.snapshot, c, device, shard, target_head=head, progress=progress) + draft = DraftWeights.load(manifest.snapshot, c, device, shard, target_head=head, progress=progress, + draft_head_quantization=draft_head_quantization, markov_head_quantization=markov_head_quantization) return cls(c, shard, loaded, embedding, embed_norm, norm, query, head, torch.cuda.memory_allocated(device) - before, draft, tower) diff --git a/tests/cli/test_inkling2.py b/tests/cli/test_inkling2.py index c614160f0..8d3472320 100644 --- a/tests/cli/test_inkling2.py +++ b/tests/cli/test_inkling2.py @@ -55,3 +55,63 @@ def capture_config(**kwargs): assert config.speculative_widths == tuple(range(1, 9)) assert config.speculative_token_capacity == 64 assert config.speculative_graph_budget == 64 + + +def test_inkling_declares_quantized_proposal_heads_with_checkpoint_precision_as_default(): + assert RECIPE.draft_head_quantizations == ("nvfp4", "mxfp8") + assert RECIPE.markov_head_quantizations == ("fp8",) + assert RECIPE.speculation.draft_head_quantization is None + assert RECIPE.speculation.markov_head_quantization is None + model = ResolvedModel(RECIPE, RECIPE.checkpoints[0]) + args = _parser().parse_args(["export", model.checkpoint.alias, "--draft-head-quantization", "nvfp4", + "--markov-head-quantization", "fp8"]) + speculation = preparation.speculation(args, model) + assert (speculation.draft_head_quantization, speculation.markov_head_quantization) == ("nvfp4", "fp8") + assert speculation.draft_tokens == 7 + + +@pytest.mark.parametrize("draft_head,markov_head", [(None, None), ("nvfp4", "fp8"), ("mxfp8", None), (None, "fp8")]) +def test_inkling_adapter_passes_proposal_head_formats_to_preparation(monkeypatch, tmp_path, draft_head, markov_head): + from ignition.recipes.inkling2 import bootstrap + + devices = tuple(gpu(i, 95) for i in range(4)) + speculation = replace(RECIPE.speculation, draft_head_quantization=draft_head, + markov_head_quantization=markov_head) + plan = derive(model=RECIPE, gpus=devices, selected=(0, 1, 2, 3), concurrency=8, speculation=speculation) + captured = [] + configuration = bootstrap.PreparationConfig + + class ConfigurationCaptured(Exception): + pass + + def capture_config(**kwargs): + captured.append(configuration(**kwargs)) + raise ConfigurationCaptured + + monkeypatch.setattr(bootstrap, "PreparationConfig", capture_config) + with pytest.raises(ConfigurationCaptured): + RECIPE.prepare(tmp_path, plan, compile_forwards=False, kernel_cache=None, progress=None) + config = captured.pop() + assert (config.draft_head_quantization, config.markov_head_quantization) == (draft_head, markov_head) + + +def test_inkling_plan_rejects_an_nvfp4_recurrent_correction_head(): + from ignition.errors import UsageError + + devices = tuple(gpu(i, 95) for i in range(4)) + speculation = replace(RECIPE.speculation, markov_head_quantization="nvfp4") + with pytest.raises(UsageError, match="--markov-head-quantization nvfp4"): + derive(model=RECIPE, gpus=devices, selected=(0, 1, 2, 3), concurrency=8, speculation=speculation) + + +@pytest.mark.parametrize("arguments,message", [ + (dict(draft_head_quantization="fp8"), "draft head quantization"), + (dict(markov_head_quantization="nvfp4"), "correction head quantization"), + (dict(draft_head_quantization="nvfp4", drafting=False), "positive draft depth"), + (dict(markov_head_quantization="fp8", speculative_widths=(1,)), "positive draft depth"), +]) +def test_inkling_preparation_config_validates_proposal_head_formats(arguments, message): + from ignition.recipes.inkling2.bootstrap import PreparationConfig + + with pytest.raises(ValueError, match=message): + PreparationConfig(**arguments) diff --git a/tests/components/test_inkling2_dspark.py b/tests/components/test_inkling2_dspark.py index bd5a0d430..c2f727db5 100644 --- a/tests/components/test_inkling2_dspark.py +++ b/tests/components/test_inkling2_dspark.py @@ -10,10 +10,11 @@ from ignition.components.paged_batch import Metadata from ignition.components.parallel import TensorParallelShard -from ignition.components.recurrent_proposal import corrected_logits, recurrent_gate -from ignition.recipes.inkling2.dspark_state import context_slots, mix_features, rotary, stage_paged_tail, stage_window -from ignition.recipes.inkling2.dspark_weights import fold_recurrent_head, mtp_quantization -from ignition.recipes.inkling2.dspark import PreparedContext, PreparedDraft, SpeculativePreparation +from ignition.components.recurrent_proposal import PreparedRecurrentProposalHead, corrected_logits, recurrent_gate +from ignition.recipes.inkling2.dspark_state import (block_inputs, context_slots, mix_features, rotary, rotary_table, + rotate, stage, tail_plan, window_plan) +from ignition.recipes.inkling2.dspark_weights import DraftWeights, fold_recurrent_head, mtp_quantization +from ignition.recipes.inkling2.dspark import DraftScratch, PreparedContext, PreparedDraft, SpeculativePreparation @pytest.mark.parametrize("draft_tokens", [0, 1, 7]) @@ -31,6 +32,7 @@ def test_speculative_preparation_retains_context_at_zero_draft_depth(draft_token assert preparation.forwards.context is PreparedContext assert preparation.forwards.draft is PreparedDraft assert preparation.draft_scratch.hidden.shape == (8, 128) + assert preparation.draft_scratch.anchor.shape == (1, 128) assert not preparation.offset.count_nonzero() assert not preparation.generation.count_nonzero() @@ -87,7 +89,9 @@ def test_noncausal_staging_retains_one_prefix_for_all_eight_positions(start): m = Metadata.pack(torch.tensor([start]), torch.tensor([8]), torch.tensor([1]), torch.tensor([[0] * 16], dtype=torch.int32), torch.zeros(1, block, dtype=torch.int64), torch.tensor([1], dtype=torch.int32), token_capacity=8, sample_count=8) - staged = stage_window(history, values, m, 9).flatten(0, 1) + plan = window_plan(m, window, 9) + staged = stage(history, values, plan).flatten(0, 1) + assert plan.lengths.tolist() == [min(start, window) + block] prefix = min(start, window) expected = torch.arange(start - prefix, start + block).bfloat16() assert torch.equal(staged[:prefix + block, 0, 0], expected) @@ -115,7 +119,9 @@ def test_paged_tail_preserves_committed_prefix_with_one_target_page(): m = Metadata.pack(torch.tensor([127]), torch.tensor([8]), torch.tensor([1]), torch.tensor([[2]], dtype=torch.int32), torch.zeros(1, 8, dtype=torch.int64), torch.tensor([1], dtype=torch.int32), token_capacity=8, sample_count=8) - staged = stage_paged_tail(history, proposal, m, 2).flatten(0, 1) + plan = tail_plan(m, 128, 2) + staged = stage(history, proposal, plan).flatten(0, 1) + assert plan.lengths.tolist() == [135] assert torch.equal(staged[:127], history[2, :127]) assert torch.equal(staged[127:135], proposal) assert not staged[135:].count_nonzero() @@ -147,3 +153,145 @@ def test_mtp_mxfp8_metadata_requires_activation_quantization_and_complete_covera mtp_quantization(changed, names) with pytest.raises(ValueError, match="cover exactly"): mtp_quantization(config, names + ["undeclared.weight"]) + + +def test_one_staging_plan_serves_key_and_value_histories_of_every_layer(): + generator = torch.Generator().manual_seed(9) + window, block, pages = 1024, 8, 9 + m = Metadata.pack(torch.tensor([1027, 5, 300]), torch.tensor([8, 8, 0]), torch.tensor([2, 1, 0]), + torch.tensor([[0] * 16, [1] * 16, [-1] * 16], dtype=torch.int32), torch.zeros(3, block, dtype=torch.int64), + torch.tensor([3], dtype=torch.int32), token_capacity=24, sample_count=24) + plan = window_plan(m, window, pages) + offsets = torch.arange(pages * 128)[None] + prefix = m.starts.clamp(max=window)[:, None] + for _ in range(2): + history = torch.randn(3, window, 2, 4, generator=generator).bfloat16() + values = torch.randn(24, 2, 4, generator=generator).bfloat16() + previous = history[m.state_rows[:, None], (m.starts[:, None] - prefix + offsets).remainder(window)] + current = values[(m.query_start_loc[:-1, None] + offsets - prefix).clamp(0, 23)] + valid = (m.lengths[:, None] > 0) & (offsets < prefix + m.lengths[:, None]) + expected = torch.where(valid[:, :, None, None], + torch.where((offsets < prefix)[:, :, None, None], previous, current), 0).view(3 * pages, 128, 2, 4) + assert torch.equal(stage(history, values, plan), expected) + assert plan.lengths.tolist() == [1032, 13, 0] + assert not stage(history, values, plan)[2 * pages:].count_nonzero() + + +def test_shared_rotary_table_matches_per_call_rotation(): + generator = torch.Generator().manual_seed(12) + positions = torch.tensor([0, 7, 1025, -1, 1048575]) + inverse = 1 / (1e6 ** (torch.arange(0, 128, 2).float() / 128)) + table = rotary_table(positions, inverse) + for heads in (2, 12): + values = torch.randn(5, heads, 128, generator=generator).bfloat16() + assert torch.equal(rotate(values, table), rotary(values, positions, inverse)) + + +def test_block_inputs_embed_only_each_request_first_position(): + generator = torch.Generator().manual_seed(15) + anchor = torch.randn(3, 32, generator=generator).bfloat16() + mask = torch.randn(32, generator=generator).bfloat16() + positions = torch.arange(24) % 8 + expected = torch.where((positions == 0)[:, None], anchor.repeat_interleave(8, 0), mask) + assert torch.equal(block_inputs(anchor, mask, 8), expected) + + +def test_draft_scratch_keeps_one_anchor_row_per_block(): + config = SimpleNamespace(text={"hidden_size": 128}, vocabulary=256, + draft=SimpleNamespace(heads=4, kv_heads=4, head_dim=128, text={"intermediate_size": 256})) + scratch = DraftScratch.allocate(config, TensorParallelShard(0, 4), 32, 8, torch.device("cpu")) + assert scratch.anchor.shape == (4, 128) and scratch.hidden.shape == (32, 128) + rows = scratch.rows(16, 16) + assert rows.anchor.shape == (2, 128) and rows.hidden.shape == (16, 128) + assert rows.anchor.data_ptr() == scratch.anchor.data_ptr() + with pytest.raises(ValueError, match="whole blocks"): + scratch.rows(12, 12) + with pytest.raises(ValueError, match="whole blocks"): + DraftScratch.allocate(config, TensorParallelShard(0, 4), 12, 8, torch.device("cpu")) + + +def _recurrent_head(weight, bias, head, head_bias, positions, *, row_scaled): + """Bind FP64 reference projections to the recurrent head's arithmetic.""" + rank = head.shape[1] + operation = object.__new__(PreparedRecurrentProposalHead) + operation.rank, operation.softcap, operation.positions = rank, 30., positions + operation.context_bias = bias + operation.context = lambda source: (source.double() @ weight[:, 2 * rank:].double().T).float() + operation.dynamic = lambda source: (source.double() @ weight[:, :2 * rank].double().T).float() + operation.embed = lambda token_ids: torch.zeros(token_ids.numel(), rank, dtype=torch.bfloat16) + if row_scaled: + operation.output = lambda latent: (latent.double() @ head.double().T).float() + operation.output_bias = head_bias + else: + operation.output = lambda latent: (latent.double() @ head.double().T + head_bias.double()).bfloat16() + operation.output_bias = None + return operation + + +def test_block_context_projection_matches_one_projection_per_position(): + generator = torch.Generator().manual_seed(18) + rows, positions, hidden, rank, vocabulary = 3, 7, 16, 8, 24 + weight = (torch.randn(3 * rank, 2 * rank + 2 * hidden, generator=generator) / 8).bfloat16() + bias = torch.randn(3 * rank, generator=generator) / 8 + head = (torch.randn(vocabulary, rank, generator=generator) / 4).bfloat16() + head_bias = (torch.randn(vocabulary, generator=generator) / 4).bfloat16() + states = torch.randn(rows, positions, hidden, generator=generator).bfloat16() + context = torch.randn(rows, hidden, generator=generator).bfloat16() + operation = _recurrent_head(weight, bias, head, head_bias, positions, row_scaled=False) + fixed = operation.project_context(states, context) + assert fixed.shape == (rows, positions, 3 * rank) and fixed.dtype == torch.float32 + for index in range(positions): + source = torch.cat((states[:, index], context), -1) + assert torch.equal(fixed[:, index], operation.context(source) + bias) + with pytest.raises(ValueError, match="every prepared block position"): + operation.project_context(states[:, :3], context) + + +def test_row_scaled_correction_adds_the_bf16_bias_in_fp32_before_bf16_rounding(): + generator = torch.Generator().manual_seed(21) + rows, hidden, rank, vocabulary = 2, 16, 8, 24 + weight = (torch.randn(3 * rank, 2 * rank + 2 * hidden, generator=generator) / 8).bfloat16() + bias = torch.randn(3 * rank, generator=generator) / 8 + head = (torch.randn(vocabulary, rank, generator=generator) / 4).bfloat16() + head_bias = (torch.randn(vocabulary, generator=generator) / 4).bfloat16() + base = torch.randn(rows, vocabulary, generator=generator).bfloat16() + fixed = torch.randn(rows, 3 * rank, generator=generator) + previous = torch.zeros(rows, dtype=torch.int64) + outputs = [] + for row_scaled in (False, True): + operation = _recurrent_head(weight, bias, head, head_bias, 1, row_scaled=row_scaled) + state, logits = operation.step(operation.begin(base), previous, fixed, base) + outputs.append((state, logits)) + state, latent = recurrent_gate(fixed, torch.zeros(rows, rank, dtype=torch.bfloat16)) + correction = ((latent.double() @ head.double().T).float() + head_bias.float()).bfloat16() + assert torch.equal(outputs[1][0], state) + assert torch.equal(outputs[1][1], corrected_logits(base, correction, 30.)) + # With identical weights the two bias placements differ only by one FP32 addition before BF16 rounding. + assert torch.equal(outputs[0][0], outputs[1][0]) + torch.testing.assert_close(outputs[0][1].float(), outputs[1][1].float(), rtol=2**-7, atol=2**-9) + + +def test_folded_correction_head_uses_the_supplied_allocator(): + generator = torch.Generator().manual_seed(24) + head = torch.randn(64, 32, generator=generator).bfloat16() + weight = torch.randn(32, 8, generator=generator).bfloat16() + bias = torch.randn(32, generator=generator).bfloat16() + calls = [] + + def transient(shape, dtype, device): + calls.append(shape) + return torch.empty(shape, dtype=dtype, device=device) + + folded, offset = fold_recurrent_head(head, weight, bias, allocate=transient) + assert calls == [(64, 8)] + persistent, persistent_offset = fold_recurrent_head(head, weight, bias) + assert torch.equal(folded, persistent) and torch.equal(offset, persistent_offset) + + +@pytest.mark.parametrize("arguments,message", [ + (dict(draft_head_quantization="fp8"), "draft head quantization"), + (dict(markov_head_quantization="nvfp4"), "correction head quantization"), +]) +def test_draft_weights_reject_unsupported_head_formats_before_reading(tmp_path, arguments, message): + with pytest.raises(ValueError, match=message): + DraftWeights.load(tmp_path, None, torch.device("cpu"), TensorParallelShard(0, 4), target_head=None, **arguments) diff --git a/tests/components/test_inkling2_dspark_cuda.py b/tests/components/test_inkling2_dspark_cuda.py index 7da8173e2..4a837f851 100644 --- a/tests/components/test_inkling2_dspark_cuda.py +++ b/tests/components/test_inkling2_dspark_cuda.py @@ -20,7 +20,10 @@ from ignition.components.parallel import TensorParallelShard from ignition.recipes.inkling2.dspark import DraftAttention, DraftScratch, PreparedContext, PreparedDraft from ignition.components.weights import MLPWeights -from ignition.recipes.inkling2.dspark_state import mix_features, rotary +from ignition.components.markov_sampling import fp8_markov_head +from ignition.components.vocabulary import nvfp4_draft_head +from ignition.recipes.inkling2.dspark import inverse_frequencies +from ignition.recipes.inkling2.dspark_state import mix_features, rotary, rotary_table from ignition.recipes.inkling2.dspark_weights import DraftWeights from ignition.components.weights import DirectWeightLoader from ignition.preparation.checkpoint import inspect_indexed_checkpoint @@ -31,9 +34,10 @@ reason="requires an explicitly assigned CUDA device") -@pytest.mark.parametrize("batch,depth", [(1, 7), (4, 7), (4, 1)]) +@pytest.mark.parametrize("batch,depth,row_scaled", [(1, 7, False), (4, 7, False), (4, 1, False), + (1, 7, True), (4, 7, True)]) @torch.no_grad() -def test_sequential_recurrent_draws_record_actual_q_and_reset_state(batch, depth): +def test_sequential_recurrent_draws_record_actual_q_and_reset_state(batch, depth, row_scaled): device = torch.device("cuda:0") generator = torch.Generator().manual_seed(422) hidden, rank, vocabulary, local = 128, 256, 513, 576 @@ -43,6 +47,10 @@ def values(*shape, denominator=64): recurrent = SimpleNamespace(embedding=values(vocabulary, rank), state_weight=weight[:, :2 * rank].contiguous(), context_weight=weight[:, 2 * rank:].contiguous(), bias=values(3 * rank).float(), head=values(local, rank), head_bias=values(local), softcap=30.) + correction_head = recurrent.head + if row_scaled: + recurrent.head = fp8_markov_head(correction_head) + correction_head = recurrent.head.values.float() * recurrent.head.scale[:, None] features, context = values(batch, depth, hidden, denominator=8), values(batch, hidden, denominator=8) backing = values(batch, 8, local, denominator=2) base = backing[:, 1:depth + 1] @@ -65,7 +73,7 @@ def values(*shape, denominator=64): with RecordedPreparationSession(device=device, checkpoint="synthetic-recurrent-head", workload_schema="conditional-proposals", numerical_policy="bf16-checkpoint", autotune_effort="off", compile_workers=2) as session: - head = PreparedRecurrentProposalHead(recurrent, pending, session=session, name="head") + head = PreparedRecurrentProposalHead(recurrent, pending, positions=depth, session=session, name="head") sampler = PreparedVocabularySoftmax(base, q, valid, requests, slots, generations, live, tokens, start=0, runtime=None, coordinator=None, session=session, name="q", pending=pending, seeds=seeds, offsets=offsets, tokens=tokens) @@ -75,9 +83,10 @@ def values(*shape, denominator=64): def forward(): state = head.begin(context) + fixed = head.project_context(features, context) previous = pending for index in range(depth): - state, logits = head.step(state, previous, features[:, index].contiguous(), context, base[:, index]) + state, logits = head.step(state, previous, fixed[:, index], base[:, index]) observed_states[:, index].copy_(state) scores[:, index].copy_(logits) sampler.run_step(index, scores, tokens, pending=pending, seeds=seeds, offsets=offsets, @@ -112,9 +121,20 @@ def forward(): torch.testing.assert_close(raw.double(), concatenated, rtol=2e-7, atol=2e-7) state, latent = recurrent_gate(raw, state) assert torch.equal(observed_states[:active, index], state[:active]) - correction = (latent.double() @ recurrent.head.double().T + recurrent.head_bias.double()).bfloat16() - expected_scores = corrected_logits(base[:, index], correction, 30.) - assert torch.equal(scores[:active, index], expected_scores[:active]) + if row_scaled: + # The E4M3 product is FP32; the BF16 bias joins it before the BF16 rounding. + correction = ((latent.double() @ correction_head.double().T).float() + + recurrent.head_bias.float()).bfloat16() + expected_scores = corrected_logits(base[:, index], correction, 30.) + # FP32 accumulation order can move a correction by one BF16 step. + torch.testing.assert_close(scores[:active, index].float(), expected_scores[:active].float(), + rtol=2**-7, atol=2**-9) + expected_scores = scores[:, index].clone() + else: + correction = (latent.double() @ correction_head.double().T + + recurrent.head_bias.double()).bfloat16() + expected_scores = corrected_logits(base[:, index], correction, 30.) + assert torch.equal(scores[:active, index], expected_scores[:active]) expected_q = expected_scores[:, :vocabulary].float().softmax(-1) torch.testing.assert_close(q[:active, index, :vocabulary], expected_q[:active], rtol=3e-6, atol=1e-9) assert not q[:, index, vocabulary:].count_nonzero() @@ -241,14 +261,20 @@ def values(*shape): operation = DraftAttention(layer, weights, config, scratch, m, pool, shard=TensorParallelShard(0, 1), runtime=None, coordinator=None, session=session, name="attention", workspace=arena) session.tune(show_progress=False) - actual = operation(source, m) + inverse = inverse_frequencies(d, device) + + def attend(): + plan = operation.staging[0](m, *operation.staging[1:]) + return operation(source, m, plan, rotary_table(m.positions, inverse)) + + actual = attend() qkv = (source[:8].double() @ weights.qkv.double().T).bfloat16() q, k, v = qkv.split((heads * dimension, kv_heads * dimension, kv_heads * dimension), -1) def normalize(x, count): x = x.view(8, count, dimension).float() return (x * torch.rsqrt(x.square().mean(-1, keepdim=True) + 1e-6)).bfloat16() - q = rotary(normalize(q, heads), m.positions[:8], operation.inverse) - k = rotary(normalize(k, kv_heads), m.positions[:8], operation.inverse) + q = rotary(normalize(q, heads), m.positions[:8], inverse) + k = rotary(normalize(k, kv_heads), m.positions[:8], inverse) v = v.reshape(8, kv_heads, dimension) if layer == 0: positions = torch.arange(max(0, start - d.window), start, device=device) % d.window @@ -276,7 +302,7 @@ def normalize(x, count): replayed = torch.empty_like(actual) graph = torch.cuda.CUDAGraph() with session.capture(), torch.cuda.graph(graph): - replayed.copy_(operation(source, m)) + replayed.copy_(attend()) allocated = torch.cuda.memory_allocated() graph.replay() torch.cuda.synchronize() @@ -300,8 +326,9 @@ def normalize(x, count): graph.reset() +@pytest.mark.parametrize("draft_head", [None, "nvfp4"]) @torch.no_grad() -def test_five_layer_block_uses_learned_masks_and_replays_without_allocating(): +def test_five_layer_block_uses_learned_masks_and_replays_without_allocating(draft_head): device, hidden, heads, kv_heads, dimension, vocabulary, rank = torch.device("cuda:0"), 128, 12, 2, 128, 576, 256 generator = torch.Generator().manual_seed(341) def values(*shape): @@ -319,7 +346,10 @@ def ones(width): embedding_norm=ones(hidden), head=values(vocabulary, hidden), draft=SimpleNamespace(layers=layers, mask_embedding=values(hidden), norm=ones(hidden), recurrent=SimpleNamespace(embedding=values(vocabulary, rank), context_weight=values(3 * rank, 2 * hidden), state_weight=values(3 * rank, 2 * rank), - bias=values(3 * rank).float(), head=values(vocabulary, rank), head_bias=values(vocabulary), softcap=30.))) + bias=values(3 * rank).float(), head=values(vocabulary, rank), head_bias=values(vocabulary), softcap=30.), + draft_head=None)) + if draft_head is not None: + weights.draft.draft_head = nvfp4_draft_head(weights.head) regions = {f"draft{index}.{kind}": values(3, 1024, kv_heads, dimension) for index in (0, 1, 3, 4) for kind in ("key", "value")} regions["draft.rnn_context"] = values(3, hidden) @@ -347,6 +377,12 @@ def forward(): return features features = forward() assert features["hidden"].shape == (8, hidden) + if draft_head is not None: + # The proposal head reads its NVFP4 copy; four-bit weights keep the logits' direction. + reference = features["hidden"].double() @ weights.head.double().T + similarity = torch.nn.functional.cosine_similarity(output.double(), reference, dim=-1) + assert similarity.min() > .95 + assert not torch.equal(output, reference.bfloat16()) assert torch.equal(features["recurrent_context"], regions["draft.rnn_context"][1:2]) torch.cuda.synchronize() expected = output.clone() diff --git a/tests/components/test_ring_commit_cuda.py b/tests/components/test_ring_commit_cuda.py index aa89b793b..3cb4b4851 100644 --- a/tests/components/test_ring_commit_cuda.py +++ b/tests/components/test_ring_commit_cuda.py @@ -181,3 +181,13 @@ def forward(): worker.close() if graph is not None: graph.reset() + + +@pytest.mark.parametrize("candidate_offset", [-1, 1.5]) +def test_reject_candidates_before_the_staging(candidate_offset): + device = torch.device("cuda", 0) + backing = torch.zeros((3, 4096), dtype=torch.uint8, device=device) + rows, starts = (torch.ones(1, dtype=torch.int64, device=device) for _ in range(2)) + with pytest.raises(ValueError, match="nonnegative record index"): + PreparedRingCommit(backing, (0,), rows, starts, token_capacity=4, window_tokens=8, record_bytes=16, + candidate_offset=candidate_offset) diff --git a/tests/components/test_window_staging_cuda.py b/tests/components/test_window_staging_cuda.py index 4ace3f129..f9f73c692 100644 --- a/tests/components/test_window_staging_cuda.py +++ b/tests/components/test_window_staging_cuda.py @@ -104,3 +104,10 @@ def test_reject_unsupported_staging_views(failure): values = values[0].float(), values[1] with pytest.raises(ValueError): PreparedWindowStaging(*history, *values, *outputs, m, session=None, name='invalid') + + +@pytest.mark.parametrize('lookback', [0, 2049, 1023.]) +def test_reject_a_lookback_outside_the_history(lookback): + history, values, outputs, m, _ = _fixture(8, 128, 1) + with pytest.raises(ValueError, match='looks back'): + PreparedWindowStaging(*history, *values, *outputs, m, lookback=lookback, session=None, name='invalid') diff --git a/tests/recipes/test_inkling2_target.py b/tests/recipes/test_inkling2_target.py index fb0d9fee9..33a2fb0f1 100644 --- a/tests/recipes/test_inkling2_target.py +++ b/tests/recipes/test_inkling2_target.py @@ -162,48 +162,6 @@ def forward(): assert (((partial[:n].double() - exact).abs() - gamma * accumulated).max() <= 0).item() -@pytest.mark.skipif(os.environ.get('FLARE_RUN_CUDA_TESTS') != '1', reason='requires an assigned SM120 GPU') -def test_accepted_window_prefix_commits_replay_without_candidate_mutation(): - from ignition.recipes.inkling2.attention import retain_batch, stage_batch - - device = torch.device('cuda', 0) - m = _metadata([8, 8, 8], [0, 1150, 3499], device) - m.state_rows.copy_(torch.tensor([3, 1, 2], device=device)) - initial = torch.randn(5, 1152, 2, 128, device=device).to(torch.float8_e4m3fn) - rings = initial.clone().view(torch.uint8).view(5, -1) - values = torch.randn(24, 2, 128, dtype=torch.bfloat16, device=device) - staged, lengths = stage_batch(rings, values, m, window=1024, pages=9) - torch.testing.assert_close(rings, initial.view(torch.uint8).view(5, -1), rtol=0, atol=0) - assert lengths.tolist() == [8, 1031, 1031] - for lane, start in enumerate(m.starts.tolist()): - first = max(start - 1023, 0) - expected = torch.cat((initial[m.state_rows[lane], first % 1152:].bfloat16(), initial[m.state_rows[lane], :first % 1152].bfloat16())) - previous = expected[:start - first] - retained = torch.cat((previous, values[lane * 8:(lane + 1) * 8])).to(torch.float8_e4m3fn) - actual = staged.view(3, 1152, 2, 128)[lane] - torch.testing.assert_close(actual[:retained.shape[0]].view(torch.uint8), retained.view(torch.uint8), rtol=0, atol=0) - assert not actual[retained.shape[0]:].view(torch.uint8).any() - counts = torch.zeros(3, dtype=torch.int32, device=device) - retain_batch(rings, values, counts, m) - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - retain_batch(rings, values, counts, m) - for accepted in range(9): - rings.copy_(initial.view(torch.uint8).view(5, -1)) - selected = [accepted, (accepted + 1) % 9, 8 - accepted] - counts.copy_(torch.tensor(selected, dtype=torch.int32, device=device)) - before = torch.cuda.memory_stats()['allocation.all.allocated'] - graph.replay() - torch.cuda.synchronize() - assert torch.cuda.memory_stats()['allocation.all.allocated'] == before - expected = initial.clone() - for lane, count in enumerate(selected): - for index in range(count): - position = (int(m.starts[lane]) + index) % 1152 - expected[m.state_rows[lane], position] = values[lane * 8 + index].to(torch.float8_e4m3fn) - torch.testing.assert_close(rings, expected.view(torch.uint8).view(5, -1), rtol=0, atol=0) - - @pytest.mark.skipif(os.environ.get('FLARE_RUN_CUDA_TESTS') != '1', reason='requires an assigned SM120 GPU') @pytest.mark.parametrize('tokens,streams,sources,add', [(1, streams, sources, add) for streams in (1, 3) for sources in range(1, 10) for add in (False, True)] diff --git a/tests/recipes/test_inkling2_window.py b/tests/recipes/test_inkling2_window.py new file mode 100644 index 000000000..ccf1dfac4 --- /dev/null +++ b/tests/recipes/test_inkling2_window.py @@ -0,0 +1,231 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling 2 verification stages sliding-window rings and commits accepted rows byte for byte. + +The references gather each request's whole ring, select in BF16 and rewrite the ring, +which states the staged pages and committed ring bytes independently of the kernels. +""" + +import os + +import pytest +import torch + +from ignition.components.paged_batch import Metadata +from ignition.recipes.inkling2.attention import accepted_records, staged_lengths + +KV, PAGE, WINDOW, RING, HEADS, DIM, WIDTH = torch.float8_e4m3fn, 128, 1024, 1152, 2, 128, 8 +PAGES = -(-(WINDOW - 1 + WIDTH) // PAGE) +RECORD = HEADS * DIM +cuda = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="requires an assigned SM120 GPU") + + +def reference_stage(rings, values, m): + """FP8 pages `[requests * PAGES, PAGE, heads, dim]` of each request's window and rows, and key counts.""" + rows, capacity = m.starts.numel(), PAGES * PAGE + ring = rings[m.state_rows].view(KV).view(rows, RING, *values.shape[1:]) + first = (m.starts - WINDOW + 1).clamp_min(0) + positions = first[:, None] + torch.arange(capacity, device=values.device) + previous = ring[torch.arange(rows, device=values.device)[:, None], positions.remainder(RING)].to(values.dtype) + index = (m.query_start_loc[:-1, None] + positions - m.starts[:, None]).clamp(0, values.shape[0] - 1) + staged = torch.where((positions < m.starts[:, None])[:, :, None, None], previous, values[index]) + lengths = torch.where(m.lengths > 0, m.starts - first + m.lengths, 0).int() + staged = torch.where((positions < (m.starts + m.lengths)[:, None])[:, :, None, None], staged, 0) + return staged.clamp(-448, 448).to(KV).view(rows * PAGES, PAGE, *values.shape[1:]), lengths + + +def reference_retain(rings, values, counts, m): + """Rewrite the ring of every request that accepted rows, in place.""" + rows = m.starts.numel() + ring = rings[m.state_rows].view(KV).view(rows, RING, *values.shape[1:]) + first = m.starts + counts - RING + positions = first[:, None] + (torch.arange(RING, device=values.device) - first[:, None]).remainder(RING) + indices = (m.query_start_loc[:-1, None] + positions - m.starts[:, None]).clamp(0, values.shape[0] - 1) + current = values[indices].clamp(-448, 448) + keep = ((positions < m.starts[:, None]) | (positions < 0))[:, :, None, None] + retained = torch.where(keep, ring.to(values.dtype), current).to(KV).view(torch.uint8).view(rows, -1) + selected = counts > 0 + rings[m.state_rows[selected]] = retained[selected] + + +def metadata(lengths, starts, rows, device="cpu"): + m = Metadata.allocate(len(lengths) * WIDTH, len(lengths), 1, device, max_query_tokens=WIDTH) + update(m, lengths, starts, rows) + return m + + +def update(m, lengths, starts, rows): + device, count = m.starts.device, m.starts.numel() + m.set(torch.as_tensor(starts, device=device), torch.as_tensor(lengths, dtype=torch.int32, device=device), + torch.as_tensor(rows, device=device), torch.zeros(count, 1, dtype=torch.int32, device=device), + torch.zeros(count, WIDTH, dtype=torch.int64, device=device), torch.tensor([count], device=device)) + + +def candidates(tokens, generator, device="cpu"): + values = torch.randn(tokens, HEADS, DIM, generator=generator) * 4 + values.view(-1)[:6].copy_(torch.tensor([449., -449., 0., -0., 448., 1.0625])) + return values.bfloat16().to(device) + + +def test_staged_lengths_count_the_preceding_window_and_the_request_rows(): + m = metadata([8, 3, 0, 8, 1], [0, 5, 77, 1023, 5000], [1, 2, 0, 3, 4]) + assert staged_lengths(m, WINDOW).tolist() == [8, 8, 0, 1031, 1024] + values = candidates(m.positions.numel(), torch.Generator().manual_seed(1)) + rings = torch.zeros(5, RING * RECORD, dtype=torch.uint8) + assert torch.equal(staged_lengths(m, WINDOW), reference_stage(rings, values, m)[1]) + + +@pytest.mark.parametrize("starts", [[0, 1, 1144], [1151, 1152, 1153], [1016, 1023, 1024], [3499, 2297, 1048568]]) +def test_accepted_records_commit_to_the_bytes_of_a_rewritten_ring(starts): + generator = torch.Generator().manual_seed(sum(starts)) + lengths, rows = [8, 5, 8], [3, 1, 2] + m = metadata(lengths, starts, rows) + values = (candidates(m.positions.numel(), generator), candidates(m.positions.numel(), generator)) + initial = torch.randn(2, 5, RING, HEADS, DIM, generator=generator).to(KV).view(torch.uint8).view(2, 5, -1) + records = accepted_records(*values, m) + assert records.shape == (2, 3, WIDTH * RECORD) and records.dtype == torch.uint8 + for accepted in range(9): + counts = torch.tensor([min(accepted, 8), min((accepted + 1) % 9, 5), 8 - accepted], dtype=torch.int32) + for region in range(2): + expected = initial[region].clone() + reference_retain(expected, values[region], counts, m) + actual = initial[region].clone().view(5, RING, RECORD) + # The commit stores record `t` of a request at slot `(start + t) mod ring` for `t` below its count. + for request, count in enumerate(counts.tolist()): + for token in range(count): + actual[rows[request], (starts[request] + token) % RING] = records[region, request].view( + WIDTH, RECORD)[token] + assert torch.equal(actual.view(5, -1), expected) + + +def _layer(batch, device, generator): + """Continuation rows with K and V rings at distinct offsets, and the layer's prepared operations.""" + from ignition.components.ring_commit import PreparedRingCommit + from ignition.components.window_staging import PreparedWindowStaging + + offsets = (256, 256 + RING * RECORD + 768) + row_bytes = offsets[1] + RING * RECORD + 256 + backing = torch.randint(0, 256, (batch + 2, row_bytes), dtype=torch.uint8, generator=generator).to(device) + for offset in offsets: + ring = torch.randn(batch + 2, RING, HEADS, DIM, generator=generator).to(KV).view(torch.uint8) + backing[:, offset:offset + RING * RECORD].copy_(ring.view(batch + 2, -1).to(device)) + rings = tuple(backing[:, offset:offset + RING * RECORD] for offset in offsets) + m = metadata([WIDTH] * batch, [0] * batch, list(range(1, batch + 1)), device) + tokens = batch * WIDTH + key, value = (torch.zeros(tokens, HEADS, DIM, dtype=torch.bfloat16, device=device) for _ in range(2)) + staged = tuple(torch.zeros(batch * PAGES, PAGE, HEADS, DIM, dtype=KV, device=device) for _ in range(2)) + + def build(session): + shape = (-1, RING, HEADS, DIM) + staging = PreparedWindowStaging(rings[0].view(KV).view(shape), rings[1].view(KV).view(shape), key, value, + *staged, m, lookback=WINDOW - 1, session=session, name="staging").functional(session=session) + commit = PreparedRingCommit(backing, offsets, m.state_rows, m.starts, token_capacity=WIDTH, + window_tokens=RING, record_bytes=RECORD, candidate_offset=0).functional() + return staging, commit + + return backing, rings, m, key, value, build + + +def _cases(batch, generator): + """Request starts, row counts and state rows at sequence start, window and ring boundaries.""" + boundaries = [0, 1, 7, 1015, 1016, 1023, 1024, 1025, 1143, 1144, 1151, 1152, 1153, 2297, 3499, 1048568] + for shift in range(4): + starts = [boundaries[(shift * 5 + 3 * lane) % len(boundaries)] for lane in range(batch)] + lengths = [int(torch.randint(0 if shift else 1, WIDTH + 1, (1,), generator=generator)) for _ in range(batch)] + if shift == 0: + lengths = [WIDTH] * batch + rows = torch.randperm(batch, generator=generator).add(1).tolist() + yield starts, lengths, rows + + +@cuda +@pytest.mark.parametrize("batch", [1, 8, 32]) +@torch.no_grad() +def test_verification_staging_and_commit_match_the_whole_ring_references(batch): + from ignition.preparation.tuning import RecordedPreparationSession + + device, generator = torch.device("cuda", 0), torch.Generator().manual_seed(600 + batch) + backing, rings, m, key, value, build = _layer(batch, device, generator) + counts = torch.zeros(batch, dtype=torch.int32, device=device) + observed = tuple(torch.zeros(batch * PAGES, PAGE, HEADS, DIM, dtype=KV, device=device) for _ in range(2)) + with RecordedPreparationSession(device=device, checkpoint="inkling2-window-verification", + workload_schema="window-verification", numerical_policy="exact", compile_workers=1) as session: + staging, commit = build(session) + session.tune(show_progress=False) + + def forward(): + staged = staging(key, value, metadata=m) + for output, pages in zip(observed, staged): + output.copy_(pages) + commit(counts, staging=accepted_records(key, value, m), rows=m.state_rows, starts=m.starts) + + forward() + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + forward() + for starts, lengths, rows in _cases(batch, generator): + for accepted in ("none", "all", "depth", "random"): + update(m, lengths, starts, rows) + key.copy_(candidates(batch * WIDTH, generator, device)) + value.copy_(candidates(batch * WIDTH, generator, device)) + limit = torch.tensor(lengths, dtype=torch.int32) + selected = {"none": torch.zeros_like(limit), "all": limit, + "depth": torch.minimum(limit, torch.arange(batch, dtype=torch.int32) % (WIDTH + 1)), + "random": (torch.rand(batch, generator=generator) * (limit + 1)).int()}[accepted] + counts.copy_(selected.to(device)) + before, expected = backing.clone(), backing.clone() + references = [] + for offset, values in zip((256, 256 + RING * RECORD + 768), (key, value)): + region = expected[:, offset:offset + RING * RECORD] + references.append(reference_stage(region, values, m)) + reference_retain(region, values, counts, m) + allocated = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocated + live = (m.lengths > 0).repeat_interleave(PAGES) + for output, (pages, counted) in zip(observed, references): + assert torch.equal(output.view(torch.uint8)[live], pages.view(torch.uint8)[live]) + # A request without rows stages no keys; attention reads none of its pages. + assert not output.view(torch.uint8)[~live].any() + assert torch.equal(staged_lengths(m, WINDOW), counted) + assert torch.equal(backing, expected) + if accepted == "none": + assert torch.equal(backing, before) + graph.reset() + + +@cuda +@torch.no_grad() +def test_successive_rounds_keep_rings_identical_across_ring_wraps(): + from ignition.preparation.tuning import RecordedPreparationSession + + batch = 4 + device, generator = torch.device("cuda", 0), torch.Generator().manual_seed(77) + backing, rings, m, key, value, build = _layer(batch, device, generator) + counts = torch.zeros(batch, dtype=torch.int32, device=device) + with RecordedPreparationSession(device=device, checkpoint="inkling2-window-rounds", + workload_schema="window-verification", numerical_policy="exact", compile_workers=1) as session: + staging, commit = build(session) + session.tune(show_progress=False) + expected = backing.clone() + starts, rows = [0, 1000, 1140, 2300], [4, 2, 1, 3] + for _ in range(500): + lengths = torch.randint(1, WIDTH + 1, (batch,), generator=generator).tolist() + update(m, lengths, starts, rows) + key.copy_(candidates(batch * WIDTH, generator, device)) + value.copy_(candidates(batch * WIDTH, generator, device)) + accepted = [int(torch.randint(0, length + 1, (1,), generator=generator)) for length in lengths] + counts.copy_(torch.tensor(accepted, dtype=torch.int32)) + staged = staging(key, value, metadata=m) + for offset, values, pages in zip((256, 256 + RING * RECORD + 768), (key, value), staged): + region = expected[:, offset:offset + RING * RECORD] + assert torch.equal(pages.view(torch.uint8), reference_stage(region, values, m)[0].view(torch.uint8)) + reference_retain(region, values, counts, m) + commit(counts, staging=accepted_records(key, value, m), rows=m.state_rows, starts=m.starts) + assert torch.equal(backing, expected) + starts = [start + count for start, count in zip(starts, accepted)] + # Every request has crossed its window; three have wrapped their rings. + assert starts[0] > WINDOW and min(starts[1:]) > RING From c49ae59bf501062c9d3349fe325c6c842a30c558 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sun, 15 Nov 2026 11:58:21 -0500 Subject: [PATCH 06/11] Shard the row-local stages of Inkling 2 prefill across hosts Between two cross-host reductions, an Inkling 2 decoder layer computes stages whose result for a row depends on that row or on the three rows before it: the attention-residual mixtures with their norms, the output convolutions, the expert router and the residual additions. In tensor- parallel prefill every rank computed them for every row of the chunk. On one GB10 they take 773 ms of an 8,192-row chunk, and four ranks produce four identical copies. RoCEnante's pipelined all-reduce is a reduce- scatter followed by a shard gather, so a rank can keep its quarter of the rows after the first half, compute these stages for those rows only, and gather where every rank needs every row, at the wire bytes of the all-reduce it replaces. Prefill graphs of at least 2,048 rows on ranks that reduce over RoCEnante shard their rows (SHARDED_PREFILL_ROWS in the Inkling 2 decoder). PreparedReduceScatter and PreparedShardGather in ignition/components/collectives.py prepare the two halves of the pipelined all-reduce as separate captured operations. ignition/components/ row_shards.py holds row ownership, each rank's view of the batch metadata, a column gather that exchanges the three rows before each rank's rows and each request's last three rows after every reduce-scatter (the output convolutions and their replicated histories read them), and PreparedRouteGather, which carries each row's int32 expert IDs and FP32 route weights as bytes in BF16 lanes. The decoder's layer loop and final mixture move into PreparedStack; in a sharded graph the residual state holds a rank's rows, and shard gathers supply the attention input streams, the expert input, the drafter taps and the final normalized rows. Row ownership follows graph capacity, so a rank whose rows are padding computes inactive rows. Smaller prefill graphs, decode, verification and ranks on one host are unchanged. Helios and the package contract are unchanged; a core gains sharded prefill when it is exported again. A sharded 8,192-row chunk computes the row-local stages once across the four ranks and runs 361 collectives where the replicated chunk runs 97. Every row-local value, route, gathered row and convolution history equals the replicated forward bit for bit. Evidence: on one GB10 with the checkpoint, the row-local stages of 48 layers take 175.7 ms for a rank's shard against 773.4 ms for 8,192 rows, and 37.5 ms against 173.3 ms at 2,048 rows, with no differing element. tests/components/test_row_shards.py (41 tests) covers ownership, halo and tail selection and capacity checks; tests/recipes/ test_inkling2_row_shards_cuda.py (6 tests) compares four ranks' sharded forwards of a five-layer stack with the replicated stack through an in-process exchange, eagerly and through a compiled, captured and replayed forward, on an RTX PRO 6000 and a GB10; tests/recipes/ test_inkling2_target.py passes 87 tests on a GB10. One core exported from this tree with FlashInfer 4fd836dc plus the FlashInfer changes this branch's parents require served at TP4 on four DGX Sparks with 8,192-row chunks: tests/server/test_inkling2.py -k default-effort passes 7 of 7 and 32 concurrent requests complete. Over three service launches, time to first token was 2.07 to 2.34 s at 7,668 prompt tokens, 18.4 to 20.1 s at 67,145 and 40.7 to 43.1 s at 131,990, three repeats each; one launch of the core exported from the parent commit measured 2.59 to 2.69 s, 22.4 to 23.0 s and 48.8 to 49.8 s. In kernel traces of rank 0, a 7,168-row chunk spans 1,809 ms sharded against 2,034 ms replicated: collectives 586 ms against 508 ms, mixtures and norms 70 ms against about 216 ms. Limitations: a fourth launch of the sharded core ran every graph, decode included, about 10% slower (2.85 to 2.96 s and 48.8 to 53.8 s) for a cause that was not identified, and the replicated core was measured on one launch, so the serving comparison does not exclude a launch effect of that size. Capacities between 2,048 and 8,192 rows are not measured in serving; the threshold is an estimate. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/TODO.txt | 5 + docs/model-preparation.md | 31 +- ignition/components/collectives.py | 142 +++++++ ignition/components/row_shards.py | 203 ++++++++++ ignition/recipes/inkling2/decoder.py | 151 ++++++-- tests/components/test_row_shards.py | 181 +++++++++ .../recipes/test_inkling2_row_shards_cuda.py | 362 ++++++++++++++++++ 7 files changed, 1048 insertions(+), 27 deletions(-) create mode 100644 ignition/components/row_shards.py create mode 100644 tests/components/test_row_shards.py create mode 100644 tests/recipes/test_inkling2_row_shards_cuda.py diff --git a/docs/TODO.txt b/docs/TODO.txt index fab2560af..fea39324f 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -15,6 +15,11 @@ KV pages per rank where native loading allocates 12.4 GiB; correct the declared rank costs from a measured GB10 memory report. +[ ] Measure the smallest prefill capacity at which Inkling 2 row sharding + shortens a chunk on four DGX Sparks. SHARDED_PREFILL_ROWS (2048) in + ignition/recipes/inkling2/decoder.py is an estimate; only 8192-row chunks + are measured in serving. A sharded chunk runs 361 collectives against 97. + [ ] Fix native TP4 shutdown reporting "free(): double free detected in tcache 2" after server drain with Inkling 2 cores. Reproduces with compiled and uncompiled graphs; preserve the successful request drain and GPU release. diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 1457b42d1..5c31ff1fe 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1377,7 +1377,36 @@ ConnectX-7 ports. Ranks on one host reduce FP32 partial sums; ranks on separate hosts round each partial sum to BF16 before the reduction, because RoCEnante reduces BF16. One runtime carries the hidden reductions, the vocabulary gathers of FP32 logits as BF16 column pairs, the sampling and log-probability gathers, -and the sampling broadcasts. Multi-host export requires the checkpoint +and the sampling broadcasts. + +Across hosts, prefill graphs of at least 2048 rows shard their row-local stages +by rows. Each rank owns an equal contiguous share of the chunk's rows, receives +those rows of every attention and expert sum through a RoCEnante +reduce-scatter, and computes the attention-residual mixtures with their norms, +the output convolutions, the expert routing and the residual additions for +those rows only. Shard gathers return every row to every rank where attention +heads and experts, which are sharded by column, the drafter taps and the final +normalized rows need them; the routes travel as one small message. After each +reduce-scatter a column gather exchanges the three rows that precede each +rank's rows and each request's last three rows, which the output convolutions +and their replicated histories read. A reduce-scatter and a shard gather are +the halves of the pipelined all-reduce they replace and reproduce its bits, and +the gathers copy bytes, so the row-local values equal those of a forward that +computes them on every rank. Row ownership follows the graph's capacity: a +rank whose rows are padding computes inactive rows. Smaller prefill graphs, +decode, verification, and ranks on one host compute these stages on every +rank. Qualification: on one RTX PRO 6000, with the transport replaced by an +in-process exchange between four ranks' forwards, every row-local value, +route, gathered row and convolution history of a five-layer stack equals the +replicated stack bit for bit, eagerly and through a compiled, captured and +replayed forward (`tests/recipes/test_inkling2_row_shards_cuda.py`); the same +test passes on a GB10. On four DGX Sparks at TP4 with 8192-row chunks, time to +first token over three service launches is 2.07 to 2.34 s for a 7,668-token +prompt, 18.4 to 20.1 s for 67,145 tokens and 40.7 to 43.1 s for 131,990 tokens. +One launch of a core that computes these stages on every rank measured 2.59 to +2.69 s, 22.4 to 23.0 s and 48.8 to 49.8 s. + +Multi-host export requires the checkpoint directory on rank zero only; peers read their tensor ranges from it. The recipe accepts up to 32 concurrent requests. On rank zero, whose preparation address is `10.200.0.13`, with `[memory] reserve = "4G"`: diff --git a/ignition/components/collectives.py b/ignition/components/collectives.py index 387043623..4bcbdb3f1 100644 --- a/ignition/components/collectives.py +++ b/ignition/components/collectives.py @@ -288,6 +288,148 @@ def __call__(self, source): return output +@torch.library.custom_op("flare::roce_reduce_scatter", mutates_args=("output",)) +def _reduce_scatter(source: torch.Tensor, output: torch.Tensor, handle: int) -> None: + owner = _OWNERS[handle] + owner.runtime.reduce_scatter(source, out=output, plan=owner.plan) + + +@_reduce_scatter.register_fake +def _fake_reduce_scatter(source, output, handle): + pass + + +@torch.library.custom_op("flare::roce_gather_shards", mutates_args=("output",)) +def _gather_shards(source: torch.Tensor, output: torch.Tensor, handle: int) -> None: + owner = _OWNERS[handle] + owner.runtime.gather_shards(source, out=output, plan=owner.plan) + + +@_gather_shards.register_fake +def _fake_gather_shards(source, output, handle): + pass + + +class _RowShardCollective: + """Shared output binding of the row-shard collectives: a fixed destination, or one per call.""" + + def functional(self, *, session): + """Allocate the destination inside the traced forward unless the call supplies one.""" + del session + if self.output is not None: + self.output_layout = (tuple(self.output.shape), self.output.stride(), self.output.dtype) + self.output = None + return self + + def _destination(self, source, output): + if output is None: + output = self.output + if output is None: + shape, stride, dtype = self.output_layout + output = torch.empty_strided(shape, stride, dtype=dtype, device=source.device) + return output + + +class PreparedReduceScatter(_RowShardCollective): + """Reduce every rank's [rows, columns] partial sums and keep this rank's contiguous row shard. + + Rank r's output holds rows [r * rows / world, (r + 1) * rows / world) of the + sum with the arithmetic of the runtime's two-shot all-reduce, so a + PreparedShardGather of every rank's output reproduces that all-reduce's + bits. Ranks on separate hosts reduce through RoCEnante's pipelined path, + whose eligibility `fits` reports. A component given no runtime serves one + rank: the output is the source, copied. + """ + + @staticmethod + def fits(runtime, source): + """True when every rank can reduce-scatter `source` through `runtime` (rank-uniform).""" + return runtime is None or (_roce(runtime) and runtime.should_reduce_scatter(source)) + + def __init__(self, source, output, *, runtime, session, coordinator, name): + import torch.distributed as dist + + self.runtime, self.output = runtime, output + # Traced forwards test this flag, never the runtime, which compile workers see as a placeholder. + self.single = runtime is None + if runtime is None: + if source.shape != output.shape or source.dtype != output.dtype: + raise ValueError("a single-rank reduce-scatter copies its source into a matching output") + return + if not _roce(runtime): + raise ValueError("reduce-scatter runs over RoCEnante") + if (source.ndim != 2 or source.dtype != torch.bfloat16 or not runtime.should_reduce_scatter(source) + or output.shape != (source.shape[0] // runtime.world_size, source.shape[1]) + or output.dtype != source.dtype or not output.is_contiguous()): + raise ValueError("RoCE reduce-scatter requires a contiguous BF16 [rows, columns] source whose rows divide " + "by the world size within the pipelined capacity, and a matching row-shard output") + self.plan = _roce_plan(runtime, coordinator, "AllReduce.reduce_scatter") + ranks = tuple(dist.get_process_group_ranks(runtime._group)) + declare(session, (self.plan.request(name=name, + prepare_call=lambda state: PreparedCall( + run=lambda: runtime._run_prepared_reduce_scatter(source, prepared=state, out=output), + output=output, owners=(runtime,)), + collective=CollectiveRequirement(key=name, ranks=ranks)),), coordinator=coordinator) + self.handle = next(_HANDLES) + _OWNERS[self.handle] = self + + def __call__(self, source, output=None): + output = self._destination(source, output) + if self.single: + output.copy_(source) + else: + _reduce_scatter(source, output, self.handle) + return output + + +class PreparedShardGather(_RowShardCollective): + """Gather every rank's [rows / world, columns] row shard into [rows, columns] in rank order. + + The inverse of PreparedReduceScatter over the same pipelined RoCEnante path; + the bytes are copied. A component given no runtime serves one rank: the + output is the source, copied. + """ + + @staticmethod + def fits(runtime, source): + """True when every rank can gather its shard `source` through `runtime` (rank-uniform).""" + return runtime is None or (_roce(runtime) and runtime.should_gather_shards(source)) + + def __init__(self, source, output, *, runtime, session, coordinator, name): + import torch.distributed as dist + + self.runtime, self.output = runtime, output + self.single = runtime is None + if runtime is None: + if source.shape != output.shape or source.dtype != output.dtype: + raise ValueError("a single-rank shard gather copies its source into a matching output") + return + if not _roce(runtime): + raise ValueError("shard gathers run over RoCEnante") + if (source.ndim != 2 or source.dtype != torch.bfloat16 or not runtime.should_gather_shards(source) + or output.shape != (source.shape[0] * runtime.world_size, source.shape[1]) + or output.dtype != source.dtype or not output.is_contiguous()): + raise ValueError("RoCE shard gathers require a contiguous BF16 [rows, columns] shard within the pipelined " + "capacity and a matching world-fold output") + self.plan = _roce_plan(runtime, coordinator, "AllReduce.gather_shards") + ranks = tuple(dist.get_process_group_ranks(runtime._group)) + declare(session, (self.plan.request(name=name, + prepare_call=lambda state: PreparedCall( + run=lambda: runtime._run_prepared_gather_shards(source, prepared=state, out=output), + output=output, owners=(runtime,)), + collective=CollectiveRequirement(key=name, ranks=ranks)),), coordinator=coordinator) + self.handle = next(_HANDLES) + _OWNERS[self.handle] = self + + def __call__(self, source, output=None): + output = self._destination(source, output) + if self.single: + output.copy_(source) + else: + _gather_shards(source, output, self.handle) + return output + + @dataclass(frozen=True) class WeightedGroupSource: """Ordered weighted groups with physical [rows, groups, hidden] storage. diff --git a/ignition/components/row_shards.py b/ignition/components/row_shards.py new file mode 100644 index 000000000..f8ffe1761 --- /dev/null +++ b/ignition/components/row_shards.py @@ -0,0 +1,203 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Row shards of a prefill chunk: each rank runs row-local stages on the rows it owns. + +Between two cross-rank reductions of a `[tokens, columns]` chunk, a tensor-parallel rank computes +stages whose result for a row depends on that row alone (normalization, mixtures, routing, residual +additions) or on a few preceding rows (causal convolutions). Replicated, every rank computes them for +every row. Sharded, rank `r` owns rows `[r * tokens / world, (r + 1) * tokens / world)`: a +reduce-scatter delivers it those rows of the sum, it computes the row-local stages for them, and a +shard gather reassembles all rows where a consumer needs them on every rank. The reduce-scatter and +the shard gather are the two halves of the pipelined all-reduce, whose bits they reproduce, and the +gathers copy bytes, so every rank's rows equal the replicated computation's. + +A causal convolution reads `halo` rows before each row and commits each request's last `halo` raw +rows to replicated history. Ranks exchange those rows by one small column gather after each +reduce-scatter: every rank contributes the last `halo` rows it owns and its copy of each request's +last rows, takes its predecessor's rows as the halo before its own, and takes each request's last +rows from their owners. + +Row ownership follows the chunk's capacity, not its live rows: a rank whose rows are padding +computes inactive rows, which stay zero and mutate no state. A rank's row offset reaches traced +forwards only through device tensors, so every rank compiles the same forward. +""" + +from dataclasses import dataclass + +import torch + +from ignition.components.collectives import PreparedAllGather, PreparedReduceScatter, PreparedShardGather, _roce +from ignition.preparation.examples import declaration_tensor + + +@dataclass(frozen=True) +class ConvolutionRows: + """Batch metadata of a causal convolution over the halo rows followed by this rank's rows.""" + + requests: torch.Tensor + positions: torch.Tensor + query_start_loc: torch.Tensor + state_rows: torch.Tensor + + +@dataclass(frozen=True) +class TailRows: + """Batch metadata of a history commit from `[requests * halo, columns]` rows: each request's last rows.""" + + starts: torch.Tensor + lengths: torch.Tensor + query_start_loc: torch.Tensor + state_rows: torch.Tensor + + +@dataclass(frozen=True) +class ShardMetadata: + """One rank's view of a chunk's batch metadata. + + `tail_rows` indexes the halo-extended rows this rank contributes for each request's last rows; + `tail_select` picks each of those rows from its owner in the exchanged `[requests * halo * world]` rows. + """ + + convolution: ConvolutionRows + tail: TailRows + live_count: torch.Tensor + tail_rows: torch.Tensor + tail_select: torch.Tensor + + +@dataclass(frozen=True) +class RowShards: + """Equal contiguous row shards of a `tokens`-row chunk across `world` ranks, and this rank's rows.""" + + world: int + tokens: int + halo: int + own_rows: torch.Tensor + offset: torch.Tensor + predecessor: torch.Tensor + + @classmethod + def of(cls, rank, world, tokens, device, *, halo): + if (any(type(value) is not int for value in (rank, world, tokens, halo)) or world < 2 + or not 0 <= rank < world or halo < 1 or tokens % world or tokens // world < halo): + raise ValueError("row shards require at least two ranks, a rank among them, and a chunk that divides " + "into shards of at least the halo's rows") + rows = tokens // world + return cls(world, tokens, halo, + own_rows=torch.arange(rank * rows, (rank + 1) * rows, dtype=torch.int64, device=device), + offset=torch.full((1,), rank * rows, dtype=torch.int64, device=device), + # Rank zero has no predecessor and names itself: no row reads a halo before the chunk's first row. + predecessor=torch.full((1,), max(rank - 1, 0), dtype=torch.int64, device=device)) + + @property + def rows(self): + return self.tokens // self.world + + def metadata(self, m): + """This rank's view of the batch metadata `m` of the whole chunk.""" + halo, rows = self.halo, self.rows + device = self.own_rows.device + offset = self.offset + + def extended(values): + # Halo rows carry no position: the convolution reads them and computes nothing for them. + return torch.cat((torch.full((halo,), -1, dtype=values.dtype, device=device), + values.index_select(0, self.own_rows))) + + starts = m.query_start_loc + convolution = ConvolutionRows(extended(m.requests).clamp_min(0), extended(m.positions), + (starts - offset + halo).to(starts.dtype), m.state_rows) + requests = m.lengths.shape[0] + steps = torch.arange(halo, dtype=torch.int64, device=device) + # A request's last rows, or its first `halo` rows when it has fewer: the rows a commit reads. + first = starts[:-1].long() + (m.lengths.long() - halo).clamp_min(0) + last = (first[:, None] + steps).reshape(-1).clamp(0, self.tokens - 1) + tail = TailRows(m.starts, m.lengths.clamp(max=halo), + (torch.arange(requests + 1, dtype=torch.int64, device=device) * halo).to(starts.dtype), m.state_rows) + return ShardMetadata(convolution, tail, + live_count=(m.live_counts[:1] - offset).clamp(0, rows).to(m.live_counts.dtype), + tail_rows=(last - offset).clamp(0, rows - 1) + halo, + tail_select=torch.arange(requests * halo, dtype=torch.int64, device=device) * self.world + + torch.div(last, rows, rounding_mode="floor")) + + def edges(self, extended, shard): + """The rows this rank contributes to the exchange: its last `halo` rows, then each request's last rows.""" + return torch.cat((extended[self.rows:], extended.index_select(0, shard.tail_rows))) + + def place_edges(self, extended, exchanged, shard): + """Write the predecessor's rows before this rank's rows; return each request's last rows. + + `exchanged` holds every rank's `edges` as `[rows, world * columns]` in rank order. + """ + columns = extended.shape[1] + exchanged = exchanged.view(-1, self.world, columns) + extended[:self.halo] = exchanged[:self.halo].index_select(1, self.predecessor).squeeze(1) + return exchanged[self.halo:].reshape(-1, columns).index_select(0, shard.tail_select) + + +def row_sharding_fits(runtime, partial, *, halo, minimum_rows): + """True when every rank can shard `partial`'s rows through `runtime` (rank-uniform).""" + if runtime is None or not _roce(runtime): + return False + rows, world = partial.shape[0], runtime.world_size + return (rows >= minimum_rows and rows % world == 0 and rows // world >= halo + and PreparedReduceScatter.fits(runtime, partial) + and PreparedShardGather.fits(runtime, partial[:rows // world])) + + +class RowShardCollectives: + """The reduce-scatter, shard gather and edge exchange of one chunk capacity's `[tokens, columns]` BF16 rows.""" + + def __init__(self, shards, columns, *, requests, runtime, session, coordinator, name, examples=None): + device = shards.own_rows.device + + def example(role, rows, width=columns): + return declaration_tensor(examples, "row_shards." + role, (rows, width), torch.bfloat16, device) + + self.shards, self.columns = shards, columns + collectives = dict(runtime=runtime, session=session, coordinator=coordinator) + self.reduce_scatter = PreparedReduceScatter(example("partial", shards.tokens), example("reduced", shards.rows), + name=name + ".reduce_scatter", **collectives).functional(session=session) + self.shard_gather = PreparedShardGather(example("shard", shards.rows), example("gathered", shards.tokens), + name=name + ".shard_gather", **collectives).functional(session=session) + edges = (1 + requests) * shards.halo + self.exchange = PreparedAllGather(example("edges", edges), example("exchanged", edges, shards.world * columns), + name=name + ".edge_exchange", **collectives).functional(session=session) + + def reduce(self, partial, shard): + """This rank's rows of the reduced `partial` after their halo rows, and each request's last reduced rows.""" + shards = self.shards + extended = torch.empty((shards.halo + shards.rows, self.columns), dtype=partial.dtype, device=partial.device) + self.reduce_scatter(partial, extended[shards.halo:]) + return extended, shards.place_edges(extended, self.exchange(shards.edges(extended, shard)), shard) + + def gather(self, rows): + """Every rank's `rows` in rank order.""" + return self.shard_gather(rows) + + +class PreparedRouteGather: + """Gather every rank's top-k expert IDs and FP32 route weights of its rows as one message. + + Each row travels as the bytes of its int32 IDs followed by its FP32 weights, in BF16 lanes. + """ + + def __init__(self, shards, top_k, *, runtime, session, coordinator, name, examples=None): + if type(top_k) is not int or top_k < 1 or top_k % 2: + raise ValueError("gathered routes require an even expert count per row: whole 16-byte packs") + device = shards.own_rows.device + self.lanes = 2 * top_k + + def example(role, rows): + return declaration_tensor(examples, "row_shards." + role, (rows, 2 * self.lanes), torch.bfloat16, device) + + self.shard_gather = PreparedShardGather(example("routes", shards.rows), example("gathered_routes", shards.tokens), + runtime=runtime, session=session, coordinator=coordinator, name=name).functional(session=session) + + def __call__(self, ids, weights): + if ids.dtype != torch.int32 or weights.dtype != torch.float32 or ids.shape != weights.shape: + raise ValueError("gathered routes are matching int32 expert IDs and FP32 weights") + gathered = self.shard_gather(torch.cat((ids.view(torch.bfloat16), weights.view(torch.bfloat16)), dim=1)) + return (gathered[:, :self.lanes].contiguous().view(torch.int32), + gathered[:, self.lanes:].contiguous().view(torch.float32)) diff --git a/ignition/recipes/inkling2/decoder.py b/ignition/recipes/inkling2/decoder.py index d86763cd4..1558e3a6e 100644 --- a/ignition/recipes/inkling2/decoder.py +++ b/ignition/recipes/inkling2/decoder.py @@ -5,6 +5,15 @@ Ranks on one host reduce FP32 partial sums. Ranks on separate hosts reduce through RoCEnante, which carries BF16: each rank rounds its partial sum to BF16 before the reduction. + +Between reductions a layer's stages are row-local: the attention-residual mixtures with their norms, +the output convolutions, the expert router and the residual additions. Every rank computes them for +every row, except in prefill chunks of at least `SHARDED_PREFILL_ROWS` rows over RoCEnante, whose +rows are sharded across ranks (`ignition.components.row_shards`). There each reduction is a +reduce-scatter, a rank keeps its own rows of the residual state, and shard gathers supply every rank +what attention heads and experts, which are sharded by column, read for every row: the attention +input streams, the expert input with its routes, the drafter taps and the final normalized rows. +The first layer normalizes the replicated embedding rows, so its attention needs no gather. """ from dataclasses import dataclass @@ -17,6 +26,7 @@ from ignition.components.linear import UnquantizedProjection from ignition.components.rms_norm import PreparedTorchRMSNorm from ignition.components.moe import PreparedRouter, PreparedRoutedExperts, RouterScratch +from ignition.components.row_shards import PreparedRouteGather, RowShardCollectives, RowShards, row_sharding_fits from ignition.preparation.examples import declaration_tensor from .attention import LayerCache, PreparedAttention @@ -40,6 +50,13 @@ def rows(self, tokens, samples): return type(self)(self.logits[:samples], self.local_logits[:samples], tokens) +# The smallest prefill capacity whose rows are sharded. A sharded layer adds three small collectives +# (two edge exchanges and the route gather) to the wire bytes of its two reductions, and a global +# layer two more row gathers; below this capacity the row-local stages they save are shorter than +# those collectives are estimated to take. +SHARDED_PREFILL_ROWS = 2048 + + def reduction_dtype(runtime): """Element type of cross-rank hidden reductions: BF16 over RoCEnante, FP32 on one host.""" return torch.bfloat16 if runtime is not None and _roce(runtime) else torch.float32 @@ -52,11 +69,16 @@ class ResidualState: class PreparedLayer(torch.nn.Module): + """One decoder layer. With `rows`, its row-local stages run on this rank's row shard of the chunk.""" + def __init__(self, layer, weights, text, pool, metadata, reduction, reduction_dtype, *, mode, tokens, - session, workspace, name, examples=None): + session, workspace, name, examples=None, rows=None, route_gather=None): super().__init__() self.layer, self.weights, self.text, self.mode = layer, weights, text, mode self.reduction, self.reduction_dtype = reduction, reduction_dtype + self.rows, self.route_gather = rows, route_gather + # Rows of the row-local stages: the whole chunk, or this rank's shard of it. + local = tokens if rows is None else rows.shards.rows self.attention = PreparedAttention(layer, weights.attention, text, LayerCache.of(pool, layer), metadata, mode=mode, tokens=tokens, session=session, workspace=workspace, name=name + ".attention", examples=examples, # Prefill writes the attention partial sum in the reduction's element type. At prefill row counts the @@ -68,14 +90,15 @@ def __init__(self, layer, weights, text, pool, metadata, reduction, reduction_dt def example(role, shape, dtype=torch.bfloat16): return declaration_tensor(examples, "inkling.mlp." + role, shape, dtype, device) source = example("source", (tokens, text.hidden)) - logits = example("router_logits", (tokens, text.experts), torch.float32) + local_source = example("source", (local, text.hidden)) + logits = example("router_logits", (local, text.experts), torch.float32) # BF16 operands with the sum carried in FP32: each product of two BF16 values is exact in FP32. - self.router_projection = UnquantizedProjection(source, weights.router, logits, session=session, + self.router_projection = UnquantizedProjection(local_source, weights.router, logits, session=session, name=name + ".router", accumulation="fp32").functional(session=session) routes = RouterScratch.allocate(tokens, device, experts=text.experts, top_k=text.experts_per_token) - self.router = PreparedRouter(logits, routes, session=session, name=name + ".routing", score_func="sigmoid", - renormalize=True, routed_scaling_factor=text.route_scale, correction_bias=weights.correction, - num_valid_tokens=metadata.live_counts[:1]).functional(session=session) + self.router = PreparedRouter(logits, routes.rows(local), session=session, name=name + ".routing", + score_func="sigmoid", renormalize=True, routed_scaling_factor=text.route_scale, + correction_bias=weights.correction, num_valid_tokens=metadata.live_counts[:1]).functional(session=session) self.experts = PreparedRoutedExperts(source, weights.experts, routes.ids, routes.weights, example("partial", source.shape), session=session, name=name + ".experts", workspace=workspace, activation_mode="a4" if mode == "prefill" else "a16").functional(session=session) @@ -83,17 +106,19 @@ def example(role, shape, dtype=torch.bfloat16): pool.history(layer, "attention_convolution")) self.mlp_convolution = PreparedCausalConvolution(weights.mlp_convolution, pool.history(layer, "mlp_convolution")) blocks = (layer + text.residual_block - 1) // text.residual_block - self.input_mix = (None if weights.attention_query is None else PreparedResidualMix(source, + self.input_mix = (None if weights.attention_query is None else PreparedResidualMix(local_source, weights.attention_query, weights.input_norms, sources=blocks + 1, eps=text.eps, session=session, name=name + ".attention_input", examples=examples)) self.input_norms = (() if self.input_mix is not None else tuple(PreparedTorchRMSNorm(source, norm, example(f"input_norm{index}", source.shape), eps=text.eps, session=session, name=f"{name}.input_norm{index}").functional(session=session) for index, norm in enumerate(weights.input_norms))) - self.mlp_mix = PreparedResidualMix(source, weights.mlp_query, (weights.mlp_norm,), + self.mlp_mix = PreparedResidualMix(local_source, weights.mlp_query, (weights.mlp_norm,), sources=blocks + (2 if layer % text.residual_block == 0 else 1), eps=text.eps, session=session, name=name + ".mlp_input", addend=layer % text.residual_block != 0, examples=examples) - def forward(self, state, metadata): + def forward(self, state, metadata, shard=None, replicated=None): + if self.rows is not None: + return self._forward_rows(state, metadata, shard, replicated) w, t, m = self.weights, self.text, metadata streams = (tuple(norm(state.partial) for norm in self.input_norms) if self.input_mix is None else self.input_mix((*state.blocks, state.partial))) @@ -118,6 +143,39 @@ def forward(self, state, metadata): state = ResidualState(state.blocks, (state.partial.float() + attention.float() + mlp.float()).to(torch.bfloat16)) return state, records + def _forward_rows(self, state, m, shard, replicated): + """The prefill layer over this rank's rows of the residual state. + + `shard` is this rank's view of the metadata `m`. `replicated` holds every row of the state's + partial before any mixture exists, where the layer normalizes the rows themselves. + """ + t, rows = self.text, self.rows + halo = rows.shards.halo + if self.input_mix is None: + streams = tuple(norm(replicated) for norm in self.input_norms) + else: + streams = tuple(rows.gather(stream) for stream in self.input_mix((*state.blocks, state.partial))) + _, attention_partial, _ = self.attention.attend(streams, m) + attention_raw, attention_tail = rows.reduce(attention_partial.to(self.reduction_dtype), shard) + attention, attention_previous = self.attention_convolution(attention_raw, shard.convolution) + attention = attention[halo:] + if self.layer % t.residual_block == 0: + mlp_input = self.mlp_mix((*state.blocks, state.partial, attention))[0] + else: + mlp_input = self.mlp_mix((*state.blocks, state.partial), addend=attention)[0] + routes = self.router(self.router_projection(mlp_input), num_valid_tokens=shard.live_count) + ids, weights = self.route_gather(routes.ids, routes.weights) + expert_partial = self.experts(rows.gather(mlp_input), ids, weights) + mlp_raw, mlp_tail = rows.reduce(expert_partial.to(self.reduction_dtype), shard) + mlp, mlp_previous = self.mlp_convolution(mlp_raw, shard.convolution) + mlp = mlp[halo:] + # Each request's last raw rows reach every rank through the edge exchange, so history stays replicated. + self.attention_convolution.commit(attention_previous, attention_tail, shard.tail) + self.mlp_convolution.commit(mlp_previous, mlp_tail, shard.tail) + if self.layer % t.residual_block == 0: + return ResidualState((*state.blocks, state.partial), (attention.float() + mlp.float()).to(torch.bfloat16)), () + return ResidualState(state.blocks, (state.partial.float() + attention.float() + mlp.float()).to(torch.bfloat16)), () + def commit(self, records, counts, metadata): values, attention_previous, attention_raw, mlp_previous, mlp_raw = records self.attention.commit(values, counts, metadata) @@ -125,6 +183,52 @@ def commit(self, records, counts, metadata): self.mlp_convolution.commit(mlp_previous, mlp_raw, metadata, counts=counts) +class PreparedStack: + """The decoder layers and the final mixture: normalized embedding rows to final normalized rows and drafter taps. + + With `rows`, the residual state holds this rank's row shard of the chunk; the taps and the final + rows are gathered, so callers receive every row either way. + """ + + def __init__(self, weights, pool, metadata, reduction, reduction_dtype, *, mode, tokens, session, workspace, + name, examples=None, rows=None, route_gather=None): + text = weights.config.text + self.mode, self.rows = mode, rows + self.taps = weights.config.draft.taps if weights.draft is not None else () + self.layers = [PreparedLayer(index, layer, text, pool, metadata, reduction, reduction_dtype, mode=mode, + tokens=tokens, session=session, workspace=workspace, name=f"{name}.layer{index}", examples=examples, + rows=rows, route_gather=route_gather) + for index, layer in enumerate(weights.layers)] + source = declaration_tensor(examples, "inkling.decoder.embedded", + (tokens if rows is None else rows.shards.rows, text.hidden), torch.bfloat16, weights.final_norm.device) + self.output_mix = PreparedResidualMix(source, weights.output_query, (weights.final_norm,), + sources=(len(weights.layers) + text.residual_block - 1) // text.residual_block + 1, + eps=text.eps, session=session, name=name + ".output_mix", examples=examples) + + def __call__(self, hidden, metadata): + rows, shard = self.rows, None + state, records, taps = ResidualState((), hidden), [], [] + if rows is not None: + shard = rows.shards.metadata(metadata) + state = ResidualState((), hidden.index_select(0, rows.shards.own_rows)) + for index, layer in enumerate(self.layers): + if index in self.taps: + taps.append(state.partial if rows is None else rows.gather(state.partial)) + if rows is None: + state, record = layer(state, metadata) + else: + state, record = layer(state, metadata, shard, hidden if index == 0 else None) + if self.mode == "verify": + records.append(record) + del record + normalized = self.output_mix((*state.blocks, state.partial))[0] + if rows is not None: + normalized = rows.gather(normalized) + if self.taps: + taps.append(normalized) + return normalized, taps, records + + class PreparedDecoder: def __init__(self, weights, tables, scratch, metadata, pool, *, mode, session, name, workspace, runtime, vocabulary_runtime, coordinator, examples=None, vision_state=None, @@ -142,9 +246,17 @@ def example(role, shape, dtype=torch.bfloat16): partial = example("partial", (tokens, text.hidden), self.reduction_dtype) self.reduce = PreparedChunkedAllReduce(partial, example("reduced", partial.shape, self.reduction_dtype), runtime=runtime, coordinator=coordinator, session=session, name=name + ".reduction").functional(session=session) - self.layers = [PreparedLayer(index, layer, text, pool, metadata, self.reduce, self.reduction_dtype, mode=mode, tokens=tokens, - session=session, workspace=workspace, name=f"{name}.layer{index}", examples=examples) - for index, layer in enumerate(weights.layers)] + rows = route_gather = None + halo = text.convolution_width - 1 + if mode == "prefill" and row_sharding_fits(runtime, partial, halo=halo, minimum_rows=SHARDED_PREFILL_ROWS): + shards = RowShards.of(weights.rank, weights.world, tokens, device, halo=halo) + collectives = dict(runtime=runtime, session=session, coordinator=coordinator, examples=examples) + rows = RowShardCollectives(shards, text.hidden, requests=metadata.lengths.numel(), + name=name + ".rows", **collectives) + route_gather = PreparedRouteGather(shards, text.experts_per_token, name=name + ".route_gather", **collectives) + self.stack = PreparedStack(weights, pool, metadata, self.reduce, self.reduction_dtype, mode=mode, tokens=tokens, + session=session, workspace=workspace, name=name, examples=examples, rows=rows, route_gather=route_gather) + self.layers = self.stack.layers self.logits = PreparedLogits(weights.head, text, weights.rank, tokens=samples, session=session, name=name + ".logits", examples=examples) local = example("local_logits", (samples, weights.head.shape[0]), torch.float32) @@ -160,9 +272,6 @@ def example(role, shape, dtype=torch.bfloat16): embedded = example("embedded", (tokens, text.hidden)) self.embedding_norm = PreparedTorchRMSNorm(embedded, weights.embedding_norm, example("normalized_embedding", embedded.shape), eps=text.eps, session=session, name=name + ".embedding_norm").functional(session=session) - self.output_mix = PreparedResidualMix(embedded, weights.output_query, (weights.final_norm,), - sources=(len(weights.layers) + text.residual_block - 1) // text.residual_block + 1, - eps=text.eps, session=session, name=name + ".output_mix", examples=examples) def release_outputs(self): self.scratch = self.local_logits = self.auxiliary = None @@ -175,17 +284,7 @@ def __call__(self, metadata): if self.vision_state is not None and self.mode == "prefill": self.vision_state.inject(m, hidden) hidden = torch.where((m.positions >= 0)[:, None], hidden, 0) - state, records, taps = ResidualState((), hidden), [], [] - for index, layer in enumerate(self.layers): - if w.draft is not None and index in w.config.draft.taps: - taps.append(state.partial) - state, record = layer(state, m) - if self.mode == "verify": - records.append(record) - del record - normalized = self.output_mix((*state.blocks, state.partial))[0] - if w.draft is not None: - taps.append(normalized) + normalized, taps, records = self.stack(hidden, m) sampled_hidden = normalized[m.sample_indices] local = self.logits(sampled_hidden) logits = local if self.vocabulary_parallel else self.gather(local.view(torch.bfloat16)).view(torch.float32)[:, :t.valid_vocabulary].contiguous() diff --git a/tests/components/test_row_shards.py b/tests/components/test_row_shards.py new file mode 100644 index 000000000..854c3b2e1 --- /dev/null +++ b/tests/components/test_row_shards.py @@ -0,0 +1,181 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Row shards of a prefill chunk: ownership, per-rank metadata, convolution halos and history tails. + +The convolution and commit references are the recipe's Torch arithmetic. Each rank computes them on +its halo-extended rows with its view of the metadata, exchanging edge rows as the column gather +does; the results must equal the whole chunk's bit for bit. +""" + +from types import SimpleNamespace + +import pytest +import torch + +from ignition.components import collectives, row_shards +from ignition.components.paged_batch import Metadata +from ignition.components.row_shards import PreparedRouteGather, RowShards, row_sharding_fits +from ignition.recipes.inkling2.arithmetic import commit_history, short_convolution, stored_history + +HALO, CHANNELS = 3, 8 + + +def _metadata(capacity, lengths, starts): + rows = len(lengths) + m = Metadata.allocate(capacity, rows, 1, "cpu", max_query_tokens=capacity) + m.set(torch.tensor(starts), torch.tensor(lengths, dtype=torch.int32), torch.arange(1, rows + 1), + torch.zeros(rows, 1, dtype=torch.int32), torch.zeros(rows, capacity, dtype=torch.int64), + torch.tensor([rows])) + return m + + +def _shards(world, capacity): + return [RowShards.of(rank, world, capacity, "cpu", halo=HALO) for rank in range(world)] + + +@pytest.mark.parametrize("world,capacity", [(2, 16), (4, 16), (4, 2048), (3, 9)]) +def test_shards_partition_the_capacity_and_the_live_rows(world, capacity): + shards = _shards(world, capacity) + assert torch.equal(torch.cat([s.own_rows for s in shards]), torch.arange(capacity)) + assert [int(s.offset) for s in shards] == [rank * capacity // world for rank in range(world)] + assert [int(s.predecessor) for s in shards] == [max(rank - 1, 0) for rank in range(world)] + for live in (0, 1, capacity // world, capacity // world + 1, capacity - 1, capacity): + m = _metadata(capacity, [live], [5]) + counts = [s.metadata(m).live_count for s in shards] + assert all(count.dtype == m.live_counts.dtype and count.shape == (1,) for count in counts) + assert [int(count) for count in counts] == [min(max(live - int(s.offset), 0), s.rows) for s in shards] + assert sum(int(count) for count in counts) == live + + +@pytest.mark.parametrize("arguments", [(0, 1, 16), (4, 4, 16), (0, 4, 18), (0, 4, 8), (-1, 4, 16)]) +def test_shards_reject_geometry_without_equal_shards_holding_a_halo(arguments): + with pytest.raises(ValueError, match="row shards require"): + RowShards.of(*arguments, "cpu", halo=HALO) + + +def _exchange(shards, extended, views): + """Every rank's edge rows as the column gather delivers them, and each rank's placed history tail.""" + exchanged = torch.cat([s.edges(e, v) for s, e, v in zip(shards, extended, views, strict=True)], dim=1) + return [s.place_edges(e, exchanged.clone(), v) for s, e, v in zip(shards, extended, views, strict=True)] + + +# One request per chunk, as prefill graphs hold, and packed requests, whose boundaries fall inside shards. +@pytest.mark.parametrize("world", [2, 4]) +@pytest.mark.parametrize("lengths,starts", [ + ([16], [0]), ([16], [40]), ([13], [7]), ([5], [0]), ([4], [3]), ([9], [0]), ([2], [0]), ([1], [6]), ([0], [0]), + ([5, 9], [0, 12]), ([3, 2, 7], [4, 0, 1]), ([8, 8], [0, 0]), ([0, 6], [0, 2]), ([7, 0, 2], [1, 0, 9])]) +def test_sharded_convolution_and_history_commit_match_the_whole_chunk(world, lengths, starts): + capacity = 16 + generator = torch.Generator().manual_seed(1115 + world + sum(lengths)) + m = _metadata(capacity, lengths, starts) + x = (torch.randint(-64, 65, (capacity, CHANNELS), generator=generator).float() / 16).bfloat16() + weight = torch.randint(-8, 9, (CHANNELS, 1, HALO + 1), generator=generator).float() / 8 + history = (torch.randint(-64, 65, (len(lengths) + 1, HALO, CHANNELS), generator=generator).float() / 16).bfloat16() + previous = stored_history(history, m) + expected = short_convolution(x, weight, previous, m) + expected_history = history.clone() + commit_history(expected_history, previous, x, m) + + shards = _shards(world, capacity) + views = [s.metadata(m) for s in shards] + # The reduce-scatter delivers each rank its rows after the unwritten halo rows. + extended = [torch.cat((torch.full((HALO, CHANNELS), float("nan"), dtype=x.dtype), x[s.own_rows])) for s in shards] + tails = _exchange(shards, extended, views) + for rank, (s, e, view, tail) in enumerate(zip(shards, extended, views, tails, strict=True)): + if rank: + assert torch.equal(e[:HALO], x[int(s.offset) - HALO:int(s.offset)]) + actual = short_convolution(e, weight, previous, view.convolution) + assert torch.equal(actual[:HALO], torch.zeros_like(actual[:HALO])) + assert torch.equal(actual[HALO:], expected[s.own_rows]) + assert tail.shape == (len(lengths) * HALO, CHANNELS) and tail.is_contiguous() + committed = history.clone() + commit_history(committed, previous, tail, view.tail) + assert torch.equal(committed, expected_history) + # Padding rows stay zero and requests without rows keep their history bytes. + assert torch.equal(expected[sum(lengths):], torch.zeros_like(expected[sum(lengths):])) + + +def test_convolution_metadata_keeps_the_chunk_metadata_types(): + m = _metadata(16, [11], [3]) + view = RowShards.of(2, 4, 16, "cpu", halo=HALO).metadata(m) + assert view.convolution.requests.dtype == m.requests.dtype and view.convolution.positions.dtype == m.positions.dtype + assert view.convolution.query_start_loc.dtype == m.query_start_loc.dtype + assert view.tail.query_start_loc.dtype == m.query_start_loc.dtype and view.tail.lengths.dtype == m.lengths.dtype + assert view.convolution.positions.tolist() == [-1, -1, -1, 11, 12, 13, -1] + assert view.convolution.query_start_loc.tolist() == [-5, 6] + assert view.tail.lengths.tolist() == [3] and view.tail_rows.tolist() == [3, 4, 5] + # Rows 8, 9 and 10 of the chunk belong to rank 2. + assert view.tail_select.tolist() == [2, 6, 10] + + +class _Group: + """Four ranks' gathers on one process: peers contribute a marked copy of this rank's shard.""" + + world_size = 4 + + def __init__(self, rank): + self.rank = rank + + def gather_shards(self, source, *, out, plan): + rows = source.shape[0] + for peer in range(self.world_size): + out[peer * rows:(peer + 1) * rows].copy_(source if peer == self.rank else source.flip(0)) + return out + + +class _ShardGather(collectives.PreparedShardGather): + def __init__(self, source, output, *, runtime, session, coordinator, name): + assert output.shape == (source.shape[0] * runtime.world_size, source.shape[1]) + assert source.dtype == output.dtype == torch.bfloat16 and source.shape[1] * 2 % 16 == 0 + self.runtime, self.output, self.single, self.plan = runtime, output, False, None + self.handle = next(collectives._HANDLES) + collectives._OWNERS[self.handle] = self + + +def test_route_gather_carries_ids_and_weights_bit_for_bit(monkeypatch): + monkeypatch.setattr(row_shards, "PreparedShardGather", _ShardGather) + shards = RowShards.of(1, 4, 32, "cpu", halo=HALO) + gather = PreparedRouteGather(shards, 8, runtime=_Group(1), session=None, coordinator=None, name="routes") + generator = torch.Generator().manual_seed(5) + ids = torch.randint(-1, 384, (8, 8), generator=generator, dtype=torch.int32) + weights = torch.rand((8, 8), generator=generator) + weights[3, 2] = float("nan") + gathered_ids, gathered_weights = gather(ids, weights) + assert gathered_ids.shape == gathered_weights.shape == (32, 8) + assert gathered_ids.dtype == torch.int32 and gathered_weights.dtype == torch.float32 + assert gathered_ids.is_contiguous() and gathered_weights.is_contiguous() + assert torch.equal(gathered_ids[8:16], ids) and torch.equal(gathered_ids[:8], ids.flip(0)) + assert torch.equal(gathered_weights[8:16].view(torch.int32), weights.view(torch.int32)) + with pytest.raises(ValueError, match="even expert count"): + PreparedRouteGather(shards, 7, runtime=_Group(1), session=None, coordinator=None, name="routes") + + +def test_single_rank_row_collectives_copy_their_source(): + source = torch.arange(24, dtype=torch.float32).view(6, 4).bfloat16() + for component in (collectives.PreparedReduceScatter, collectives.PreparedShardGather): + prepared = component(source, torch.zeros_like(source), runtime=None, session=None, coordinator=None, name="rows") + assert torch.equal(prepared.functional(session=None)(source), source) + with pytest.raises(ValueError, match="single-rank"): + component(source, torch.zeros_like(source[:3]), runtime=None, session=None, coordinator=None, name="rows") + + +def test_sharding_requires_a_pipelined_roce_message_of_enough_rows(monkeypatch): + accepted = [] + runtime = SimpleNamespace(world_size=4, + should_reduce_scatter=lambda source: accepted.append(tuple(source.shape)) or True, + should_gather_shards=lambda source: accepted.append(tuple(source.shape)) or True) + partial = torch.zeros((2048, 16), dtype=torch.bfloat16) + def fits(value, **changes): + return row_sharding_fits(runtime, value, **{"halo": HALO, "minimum_rows": 2048, **changes}) + + monkeypatch.setattr(row_shards, "_roce", lambda runtime: False) + monkeypatch.setattr(collectives, "_roce", lambda runtime: False) + assert not fits(partial) and not row_sharding_fits(None, partial, halo=HALO, minimum_rows=2048) + monkeypatch.setattr(row_shards, "_roce", lambda runtime: True) + monkeypatch.setattr(collectives, "_roce", lambda runtime: True) + assert fits(partial) and accepted == [(2048, 16), (512, 16)] + assert not fits(partial[:1024]) and not fits(partial[:2046], minimum_rows=1024) + assert not fits(partial[:8], minimum_rows=8) + runtime.should_reduce_scatter = lambda source: False + assert not fits(partial) diff --git a/tests/recipes/test_inkling2_row_shards_cuda.py b/tests/recipes/test_inkling2_row_shards_cuda.py new file mode 100644 index 000000000..c28a349cb --- /dev/null +++ b/tests/recipes/test_inkling2_row_shards_cuda.py @@ -0,0 +1,362 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Row-sharded Inkling 2 prefill layers equal the replicated layers bit for bit, without a checkpoint. + +One GPU runs every rank of a tensor-parallel group in turn, twice: with the row-local stages +replicated on every rank, and with them sharded by rows. The RoCEnante transport is replaced by a +group whose collectives exchange the ranks' actual operands: reductions sum them in FP32 in rank +order, gathers copy them. Attention and the routed experts, which are sharded by column and not by +row, are replaced by rank-dependent functions that read every row of their inputs, so a row that a +gather misplaced changes the following reduction. The layers, the stack, the row-shard collectives, +the mixtures, convolutions, router projection and router are the production ones with synthetic +weights. One case also compiles one rank's sharded forward, captures it in a CUDA graph and replays +it against the operands its peers exchanged. +""" + +import os +import threading +from types import SimpleNamespace + +import pytest +import torch + +from ignition.components import collectives, row_shards +from ignition.components.paged_batch import Metadata + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an explicitly assigned CUDA device and FLARE_RUN_CUDA_TESTS=1") + +LAYERS, RESIDUAL_BLOCK, GLOBAL_LAYERS, TAPS, HALO, TOP_K = 5, 2, (1, 4), (2, 4, 5), 3, 8 + + +class Group: + """Ranks of one group taking turns on one GPU; a collective completes when every rank has entered it. + + Every exchange is logged. `replay` then runs one rank alone: each of its collectives combines + its live operand with the operands its peers contributed to the logged exchange of that kind + whose operand from this rank has the same bits. A compiled forward may order independent + collectives differently from the eager forward, identically on every rank, so exchanges are + matched by content and not by ordinal. `replay_order` repeats the matched order without reading + operands, as CUDA graph capture requires. + """ + + def __init__(self, world): + self.world = world + self.turn = threading.Lock() + self.barrier = threading.Barrier(world) + self.operands = [None] * world + self.kinds = [[] for _ in range(world)] + self.log = [[] for _ in range(world)] + self.replayed = self.ordered = None + self.order = [] + + def replay(self, rank): + self.replayed, self.ordered, self.order = list(self.log[rank]), None, [] + + def replay_order(self): + self.replayed, self.ordered = None, iter(self.order) + + def exchange(self, rank, kind, operand): + if self.ordered is not None: + logged_kind, operands = next(self.ordered) + assert logged_kind == kind + return [operand if peer == rank else value for peer, value in enumerate(operands)] + if self.replayed is not None: + for index, (logged_kind, operands) in enumerate(self.replayed): + if (logged_kind == kind and operands[rank].shape == operand.shape + and torch.equal(operands[rank].view(torch.int16), operand.view(torch.int16))): + self.order.append(self.replayed.pop(index)) + return [operand if peer == rank else value for peer, value in enumerate(operands)] + raise AssertionError(f"rank {rank} launched a {kind} whose operand no logged exchange holds") + self.kinds[rank].append(kind) + self.operands[rank] = operand + self.turn.release() + try: + self.barrier.wait() + operands = list(self.operands) + self.barrier.wait() + finally: + self.turn.acquire() + self.log[rank].append((kind, operands)) + return operands + + def reduce(self, rank, kind, source): + total = None + for operand in self.exchange(rank, kind, source): + total = operand.float() if total is None else total + operand.float() + return total.to(source.dtype) + + def run(self, forwards): + results, errors = [None] * self.world, [] + + def rank_main(rank): + with self.turn: + try: + with torch.no_grad(): + results[rank] = forwards[rank]() + torch.cuda.synchronize() + except BaseException as error: + errors.append(error) + self.barrier.abort() + + threads = [threading.Thread(target=rank_main, args=(rank,)) for rank in range(self.world)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + if errors: + raise errors[0] + assert all(kinds == self.kinds[0] for kinds in self.kinds) + return results + + +class RankRuntime: + """One rank's transport: the operations the prepared collectives launch, over the group's exchange.""" + + def __init__(self, group, rank): + self.group, self.rank, self.world_size = group, rank, group.world + + def reduce_scatter(self, source, *, out, plan): + rows = out.shape[0] + out.copy_(self.group.reduce(self.rank, "reduce_scatter", source)[self.rank * rows:(self.rank + 1) * rows]) + + def gather_shards(self, source, *, out, plan): + out.copy_(torch.cat(self.group.exchange(self.rank, f"gather_shards{source.shape[1]}", source))) + + def all_gather(self, source, *, dim, out, plan): + out.copy_(torch.cat(self.group.exchange(self.rank, "all_gather", source), dim=dim)) + + def all_reduce(self, source): + return self.group.reduce(self.rank, "all_reduce", source) + + +def _bind(component, runtime, output): + component.runtime, component.output, component.single, component.plan = runtime, output, False, None + component.handle = next(collectives._HANDLES) + collectives._OWNERS[component.handle] = component + + +class ReduceScatter(collectives.PreparedReduceScatter): + def __init__(self, source, output, *, runtime, session, coordinator, name): + assert source.dtype == torch.bfloat16 and output.is_contiguous() + assert output.shape == (source.shape[0] // runtime.world_size, source.shape[1]) + _bind(self, runtime, output) + + +class ShardGather(collectives.PreparedShardGather): + def __init__(self, source, output, *, runtime, session, coordinator, name): + assert source.dtype == torch.bfloat16 and source.shape[1] * 2 % 16 == 0 and output.is_contiguous() + assert output.shape == (source.shape[0] * runtime.world_size, source.shape[1]) + _bind(self, runtime, output) + + +class EdgeGather(collectives.PreparedAllGather): + def __init__(self, source, output, *, runtime, session, coordinator, name, dependencies=()): + assert source.dtype == torch.bfloat16 and source.shape[1] * 2 % 16 == 0 + assert output.shape == (source.shape[0], source.shape[1] * runtime.world_size) + _bind(self, runtime, output) + self.roce, self.dependencies = True, [] + + +class Attention: + """A rank's attention partial sums as a function of every row of every input stream.""" + + def __init__(self, layer, weights, text, cache, metadata, **kwargs): + self.layer, self.rank, self.marker = layer, weights.rank, weights + + def attend(self, streams, metadata): + if self.marker.seen is not None: + self.marker.seen[self.layer, "streams"] = streams + mixed = sum(stream.float() for stream in streams) + partial = mixed * (.25 + .125 * self.rank) + mixed.roll(1 + self.rank, 0) * .0625 + return None, partial.to(torch.bfloat16), None + + +class Experts: + """A rank's expert partial sums as a function of every row's input, expert IDs and weights.""" + + def __init__(self, source, weights, ids, route_weights, partial, *, name, **kwargs): + self.name, self.rank, self.marker = name.split(".", 2)[2], weights.rank, weights + + def functional(self, *, session): + return self + + def __call__(self, source, ids, weights): + if self.marker.seen is not None: + self.marker.seen[self.name] = (source, ids, weights) + value = source.float() + partial = (value * weights.sum(1, keepdim=True) * (.5 + .25 * self.rank) + + ids.float().sum(1, keepdim=True) * 2 ** -12 + value.roll(2, 0) * .03125) + return partial.to(torch.bfloat16) + + +def _stack_weights(hidden, experts, device, generator): + def random(*shape, scale=1., dtype=torch.float32): + return (torch.randn(shape, generator=generator) * scale).to(device=device, dtype=dtype) + + layers = [] + for layer in range(LAYERS): + streams = 3 if layer in GLOBAL_LAYERS else 1 + layers.append(dict(router=random(experts, hidden, scale=hidden ** -.5, dtype=torch.bfloat16), + correction=random(experts, scale=.1), + attention_convolution=random(hidden, 1, HALO + 1, scale=.3), + mlp_convolution=random(hidden, 1, HALO + 1, scale=.3), + input_norms=tuple(1 + random(hidden, scale=.1, dtype=torch.bfloat16) for _ in range(streams)), + mlp_norm=1 + random(hidden, scale=.1, dtype=torch.bfloat16), + attention_query=None if layer == 0 else random(streams, hidden, scale=hidden ** -.5).contiguous(), + mlp_query=random(1, hidden, scale=hidden ** -.5))) + return dict(layers=layers, output_query=random(1, hidden, scale=hidden ** -.5), + final_norm=1 + random(hidden, scale=.1, dtype=torch.bfloat16)) + + +def _rank_stack(shared, text, history, metadata, rank, group, *, sharded, tokens, session, arena, examples, device): + from ignition.recipes.inkling2.decoder import PreparedStack + + seen, runtime = {}, RankRuntime(group, rank) + marker = SimpleNamespace(rank=rank, seen=seen) + weights = SimpleNamespace(config=SimpleNamespace(text=text, draft=SimpleNamespace(taps=TAPS)), draft=marker, + layers=[SimpleNamespace(attention=marker, experts=marker, **layer) for layer in shared["layers"]], + output_query=shared["output_query"], final_norm=shared["final_norm"]) + histories = {} + pool = SimpleNamespace(memory_capacity=torch.tensor([2, 8]), ring_row_pages=1, geometry=SimpleNamespace(ring=128), + history=lambda layer, name: histories.setdefault((layer, name), history[layer, name].clone())) + rows = route_gather = None + if sharded: + shards = row_shards.RowShards.of(rank, group.world, tokens, device, halo=HALO) + collective = dict(runtime=runtime, session=session, coordinator=None, examples=examples) + rows = row_shards.RowShardCollectives(shards, text.hidden, requests=1, name=f"rank{rank}.rows", **collective) + route_gather = row_shards.PreparedRouteGather(shards, TOP_K, name=f"rank{rank}.routes", **collective) + stack = PreparedStack(weights, pool, metadata, runtime.all_reduce, torch.bfloat16, mode="prefill", tokens=tokens, + session=session, workspace=arena, name=f"rank{rank}.stack{int(sharded)}", examples=examples, rows=rows, + route_gather=route_gather) + stack.marker = marker + return stack, seen, histories + + +def _compiled_replay(stack, histories, history, expected, expected_histories, source, m, group, rank, session): + """One rank's sharded forward, compiled and captured, equals its eager result on every replay.""" + from ignition.preparation.compilation import compile_forward + + def restore(): + for key, value in histories.items(): + value.copy_(history[key]) + + def check(result): + normalized, taps, _ = result + assert torch.equal(normalized, expected[0]) + assert all(torch.equal(got, want) for got, want in zip(taps, expected[1], strict=True)) + assert all(torch.equal(value, expected_histories[key]) for key, value in histories.items()) + + stack.marker.seen = None + restore() + group.replay(rank) + compiled = compile_forward(lambda: stack(source, m)) + restore() + group.replay(rank) + check(compiled()) + assert not group.replayed + restore() + group.replay_order() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + result = compiled() + for _ in range(3): + for value in (result[0], *result[1]): + value.fill_(float("nan")) + restore() + before = torch.cuda.memory_stats()["allocation.all.allocated"] + graph.replay() + torch.cuda.synchronize() + assert torch.cuda.memory_stats()["allocation.all.allocated"] == before + check(result) + graph.reset() + + +# World size, chunk capacity, hidden width, experts, live rows and the chunk's first position: the +# model's geometry with a full and a padded chunk at a nonzero start, then smaller chunks whose +# live rows end one row past a shard boundary, inside the first shard's first rows, and nowhere. +# The last argument selects a rank whose sharded forward is also compiled and replayed. +@pytest.mark.parametrize("world,tokens,hidden,experts,live,start,compiled_rank", [ + (4, 2048, 4608, 384, 2048, 0, None), (4, 2048, 4608, 384, 1500, 8192, None), (4, 256, 512, 64, 65, 3, 1), + (2, 256, 512, 64, 2, 0, None), (4, 256, 512, 64, 130, 0, None), (4, 256, 512, 64, 0, 0, None)]) +@torch.no_grad() +def test_row_sharded_layers_match_replicated_layers(world, tokens, hidden, experts, live, start, compiled_rank, + monkeypatch): + from ignition.preparation.scratch import ScratchArena + from ignition.preparation.tuning import RecordedPreparationSession + from ignition.recipes.inkling2 import decoder + + assert os.environ.get("CUDA_VISIBLE_DEVICES"), "assign a CUDA device explicitly" + monkeypatch.setattr(decoder, "PreparedAttention", Attention) + monkeypatch.setattr(decoder, "PreparedRoutedExperts", Experts) + monkeypatch.setattr(decoder, "LayerCache", SimpleNamespace(of=lambda pool, layer: None)) + monkeypatch.setattr(row_shards, "PreparedReduceScatter", ReduceScatter) + monkeypatch.setattr(row_shards, "PreparedShardGather", ShardGather) + monkeypatch.setattr(row_shards, "PreparedAllGather", EdgeGather) + device = torch.device("cuda", 0) + generator = torch.Generator().manual_seed(1115) + text = SimpleNamespace(hidden=hidden, experts=experts, experts_per_token=TOP_K, route_scale=2.5, + residual_block=RESIDUAL_BLOCK, eps=1e-6, local=lambda layer: layer not in GLOBAL_LAYERS) + shared = _stack_weights(hidden, experts, device, generator) + history = {(layer, name): torch.randn((3, HALO, hidden), generator=generator).to(device, torch.bfloat16) + for layer in range(LAYERS) for name in ("attention_convolution", "mlp_convolution")} + m = Metadata.allocate(tokens, 1, 1, device) + hidden_rows = torch.randn((tokens, hidden), generator=generator).to(device, torch.bfloat16) + group = Group(world) + with RecordedPreparationSession(device=device, checkpoint="inkling2-row-shards", + workload_schema="inkling2-row-shards", numerical_policy="default", autotune_effort="off") as session: + arena = ScratchArena(device) + session.register_scratch(arena) + examples = {} + variants = {sharded: [_rank_stack(shared, text, history, m, rank, group, sharded=sharded, tokens=tokens, + session=session, arena=arena, examples=examples, device=device) + for rank in range(world)] for sharded in (False, True)} + session.tune() + m.set(torch.tensor([start], device=device), torch.tensor([live], dtype=torch.int32, device=device), + torch.tensor([1], device=device), torch.zeros((1, 1), dtype=torch.int32, device=device), + torch.zeros((1, tokens), dtype=torch.int64, device=device), torch.tensor([1], device=device)) + source = torch.where((m.positions >= 0)[:, None], hidden_rows, 0) + results = {} + for sharded, ranks in variants.items(): + group.kinds, group.log = [[] for _ in range(world)], [[] for _ in range(world)] + results[sharded] = group.run([lambda stack=stack: stack(source, m) for stack, _, _ in ranks]) + kinds = group.kinds[0] + if sharded: + # Per layer: one row gather per attention stream after the first layer, two + # reduce-scatters each followed by an edge exchange, the route gather and the expert + # input gather; then one gather per tap before a layer and the final gather. + assert kinds.count("reduce_scatter") == kinds.count("all_gather") == 2 * LAYERS + assert kinds.count(f"gather_shards{4 * TOP_K}") == LAYERS + streams = sum(3 if layer in GLOBAL_LAYERS else 1 for layer in range(1, LAYERS)) + assert kinds.count(f"gather_shards{hidden}") == streams + LAYERS + len(TAPS) + assert "all_reduce" not in kinds + else: + assert kinds == ["all_reduce"] * (2 * LAYERS) + if compiled_rank is not None: + stack, _, histories = variants[True][compiled_rank] + expected_histories = {key: value.clone() for key, value in histories.items()} + _compiled_replay(stack, histories, history, results[True][compiled_rank], expected_histories, source, m, + group, compiled_rank, session) + + reference, reference_seen, reference_histories = results[False][0], variants[False][0][1], variants[False][0][2] + normalized, taps, _ = reference + assert len(taps) == len(TAPS) and torch.isfinite(normalized).all() + assert bool(normalized[:live].any()) == (live > 0) and not normalized[live:].any() + for sharded, ranks in variants.items(): + for rank, (_, seen, histories) in enumerate(ranks): + actual, actual_taps, _ = results[sharded][rank] + assert torch.equal(actual, normalized), (sharded, rank) + for index, (got, want) in enumerate(zip(actual_taps, taps, strict=True)): + assert torch.equal(got, want), (sharded, rank, index) + assert seen.keys() == reference_seen.keys() + for key, values in seen.items(): + for got, want in zip(values, reference_seen[key], strict=True): + # NaN-free integers and floats: IDs, route weights, attention streams and expert inputs. + assert got.dtype == want.dtype and torch.equal(got, want), (sharded, rank, key) + for key, value in histories.items(): + assert torch.equal(value, reference_histories[key]), (sharded, rank, key) + assert torch.equal(value[0], history[key][0]) and torch.equal(value[2], history[key][2]) + assert (live > 0) or torch.equal(value, history[key]) + routes = reference_seen["layer0.experts"] + assert bool((routes[1][:live] >= 0).all()) and bool((routes[1][live:] == -1).all()) From e455aa100eb903c2ecf393709c7c4f2902b6f0b4 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sun, 15 Nov 2026 14:35:15 -0500 Subject: [PATCH 07/11] Store Inkling 2 attention projections as MXFP8 with --online-mxfp8 An Inkling 2 decoder layer projects its input by a fused BF16 weight (query, output gate, key, value, relative-bias factors and sink logits) and its attention result by a BF16 output weight. At TP4 a rank reads 2.36 GB of these weights in every decode step whatever the row count, and on a GB10 the 48 layers' projections take 9.6 ms of a one-row step. Decode with one to four requests is bound by those reads. Kimi K3, Kimi K3.1 and Qwen3.8 already store such projections as MXFP8 under --online-mxfp8, which halves the bytes read. The Inkling 2 recipe declares online MXFP8 conversion. With the flag, attention_weights in ignition/recipes/inkling2/attention.py converts every fused input projection and the output projection of every decoder layer, key and value rows included, with quantize_bf16_linear_as_mxfp8, and PreparedAttention projects through QuantizedProjection with BF16 activations in prefill, decode and verification. The output projection then writes BF16 partial sums in every mode. The weight loader allocates the BF16 sources as temporaries, the flag enters the tuning identity, and PreparationConfig carries it from the plan. Routers, vocabulary shards, convolutions, norms, clip scales, the relative-logit projection, experts, DSpark and the vision encoder keep checkpoint precision. Without the flag preparation is unchanged. Helios and the package contract are unchanged. A rank reads 1.22 GB of attention projection weights per decode step and holds 1.14 GB less. The stored weights differ from the checkpoint's by 2.7% in relative norm, so generated text differs from a BF16-projection core's. An 8,192-row prefill projection is about 5% slower than with BF16 weights. Evidence: on one GB10 with the checkpoint, the 48 layers' projections of one rank take 5.62 ms against 9.57 ms at one row, 5.58 against 9.81 at four rows, and 221.9 ms against 211.4 ms at 8,192 rows. With the Transformers reference layers over 1,536 positions of prose and source code, next-token accuracy is 65.6% with MXFP8 projections and 65.8% without, and the most likely token agrees at 97.3% of positions. tests/recipes/test_inkling2_target.py checks that the decode, verification and prefill kernels of a window and a global layer multiply by the stored values, and tests/cli/test_inkling2.py covers the flag. One core exported with the flag served at TP4 on four DGX Sparks with 32 requests and 8,192-token chunks: tests/server/test_inkling2.py -k default-effort passes 7 of 7, lookups at 18,832, 67,151 and 131,996 prompt tokens return the expected value in 26 of 26 requests, and each rank holds 3,604,480 KV tokens against 3,416,064. Over three repeats on one launch of each core, a one-token round takes 31.5 to 32.7 ms of GPU time with two requests against 35.4 to 36.7 ms, and 49.8 to 50.0 ms with four against 52.0 to 53.2 ms; time to first token at 131,990 prompt tokens is 43.5 to 43.7 s against 40.7 to 43.1 s. Limitations: one-request round time and decode throughput at one to four requests do not separate from the BF16 core within three repeats. Completions of 60 seeded lookups had a median of 472 tokens against 356, one sample set per core. On a GB10, one of eight runs of test_inkling2_target.py -k checkpoint_attention reported one failing case of 20, which was not identified. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/cli-design.md | 2 +- docs/model-preparation.md | 33 ++++++++++ ignition/recipes/inkling2/attention.py | 69 +++++++++++++++----- ignition/recipes/inkling2/bootstrap.py | 12 +++- ignition/recipes/inkling2/decoder.py | 1 + ignition/recipes/inkling2/recipe.py | 4 +- ignition/recipes/inkling2/weights.py | 44 +++++++------ tests/cli/test_inkling2.py | 37 +++++++++++ tests/recipes/test_inkling2_target.py | 87 ++++++++++++++++++++++++++ 9 files changed, 249 insertions(+), 40 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index 23b3e74cf..902737f63 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -469,7 +469,7 @@ explicit flags take precedence. | `--no-compile` | Development only: capture graphs without compiling forwards. A recipe never sets it. | off | | `--force-moe-decode-a16` / `--no-force-moe-decode-a16` | Prepare Qwen3.8 Flash NVFP4 target routed experts as one packed weight owner: decode and speculative verification use W4A16 at every token-row count, and separate prefill graphs use calibrated A4. Requires SM120/121, checkpoint activation scales, and rank-local expert intermediate width divisible by 64 (TP1/2). Mixed prefill and other recipes/precisions reject the flag. Shared experts and stored A16 MTP experts retain their precision. Overrides `[preparation] force_moe_decode_a16`; the resolved value is recorded in the plan and core rebuild metadata. | off | | `--native-dense-activations` | Replace dense projection `auto` precision with b12x `quantized`: A8 for FP8 weights and A4 for FP4 weights. Explicit recipe precision and routed MoE precision are retained. NVFP4 requires a checkpoint activation global scale; unsupported native paths fail preparation. | Recipe precision | -| `--online-mxfp8` | Store eligible BF16 projections as MXFP8 while loading. Kimi K3.1 converts fused target KDA inputs by default; `--online-mxfp8-scope all` also converts eligible attention output/latent projections, shared experts, MoE latent projections, and DFlash2 draft projections. Kimi K3 converts KDA projections, MLA latent/gate, query and output projections, shared experts, MoE latent down/up projections, and DSpark context, outputs and MLPs; batched MLA key/value projections retain BF16. Qwen3.8 dense converts target attention/MLP projections and DFlash2 context, attention and MLP projections. Flash Next with `--speculative-method dflash2` converts only DFlash2 projections; target precision is retained. Existing packed weights, normalization, convolutions, selectors and target vocabulary weights retain their precision. Recipes that name no such projections reject it. | Checkpoint precision | +| `--online-mxfp8` | Store eligible BF16 projections as MXFP8 while loading. Kimi K3.1 converts fused target KDA inputs by default; `--online-mxfp8-scope all` also converts eligible attention output/latent projections, shared experts, MoE latent projections, and DFlash2 draft projections. Kimi K3 converts KDA projections, MLA latent/gate, query and output projections, shared experts, MoE latent down/up projections, and DSpark context, outputs and MLPs; batched MLA key/value projections retain BF16. Qwen3.8 dense converts target attention/MLP projections and DFlash2 context, attention and MLP projections. Flash Next with `--speculative-method dflash2` converts only DFlash2 projections; target precision is retained. Inkling 2 converts every decoder layer's fused attention input projections and its attention output projection, with BF16 activations in prefill, decoding and verification; routers, experts, DSpark and the vision encoder retain their precision. Existing packed weights, normalization, convolutions, selectors and target vocabulary weights retain their precision. Recipes that name no such projections reject it. | Checkpoint precision | | `--online-mxfp8-scope SCOPE` | Select a conversion group declared by the recipe. Kimi K3.1 supports `kda-input` and `all`; the broader group changes target as well as DFlash2 draft projection storage. Other recipes retain their declared conversion set. Command line only; requires `--online-mxfp8` for a non-default group. | Recipe scope | | `--language-model-only` | Prepare no vision encoder and serve text only, as vLLM's flag of the same name; requests with images are rejected and the encoder's weights, scratch, and graphs become KV pages. Recipes without a separable encoder reject it. | The recipe's image support | diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 5c31ff1fe..844e70406 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1337,6 +1337,39 @@ checkpoint values; target verification keeps the BF16 head, so a quantized proposal head changes which tokens are proposed and how often they are accepted, never the output distribution. The default omits both flags. +`--online-mxfp8` stores every decoder layer's attention projections as MXFP8 +while loading: the fused input projections (query, output gate, key, value, +relative-bias factors, and sink logits, plus the dynamic convolution taps of +global layers) and the output projection. Each output row keeps E4M3 values +with one power-of-two scale per 32 input columns, so the stored values of a row +do not depend on the rows fused with it. Activations stay BF16 in prefill, +decoding, and verification, which therefore project with the same weight +values, and the output projection writes BF16 partial sums. A TP4 rank then +reads 1.22 GB of attention projection weights per decode step where BF16 reads +2.36 GB, and holds 1.14 GB less. Routers, vocabulary shards, convolutions, +norms, clip scales, the relative-logit projection, experts, DSpark, and the +vision encoder keep checkpoint precision. The default omits the flag. + +The stored weights differ from the checkpoint's by 2.7% in relative norm. With +the Transformers reference layers and checkpoint weights over 1,536 positions +of prose and source code, MXFP8 projections change an attention layer's output +by a median 4.2% across layers (2.7% to 6.8%), next to the 2.6% that E4M3 +key/value history already contributes. Next-token accuracy on those positions +is 65.6% with MXFP8 projections and 65.8% without, and the two agree on the +most likely token at 97.3% of positions; rounding the four ranks' partial sums +to BF16, which cross-host reductions do, moves that agreement to 97.8% by +itself. `tests/recipes/test_inkling2_target.py` checks on SM120 that the +decode, verification, and prefill kernels of a window and a global layer +multiply by the stored values. + +On four DGX Sparks at TP4 with 32 requests and 8,192-token chunks, a core +exported with the flag holds 3,604,480 KV tokens per rank where the BF16 core +holds 3,416,064. A one-token round takes 31.5 to 32.7 ms of GPU time with two +requests and 49.8 to 50.0 ms with four, against 35.4 to 36.7 ms and 52.0 to +53.2 ms. Time to first token at 131,990 prompt tokens is 43.5 to 43.7 s +against 40.7 to 43.1 s: MXFP8 weights with BF16 activations project an +8,192-row chunk more slowly than BF16 weights. + Export with default tuning and Torch compilation: ```sh diff --git a/ignition/recipes/inkling2/attention.py b/ignition/recipes/inkling2/attention.py index 819ea633b..016e2a2a6 100644 --- a/ignition/recipes/inkling2/attention.py +++ b/ignition/recipes/inkling2/attention.py @@ -11,6 +11,12 @@ BF16 result projects to partial sums of the cross-rank reduction's element type (FP32 on one host, BF16 over RoCEnante, where the projection rounds its FP32 accumulation once) before the replicated BF16 output convolution. + +The fused input projections and the output projection keep the checkpoint's BF16 +weights, or hold them as MXFP8 (`attention_weights` with `online_mxfp8`). +MXFP8 weights multiply BF16 activations in every mode, so prefill, decode and +verification project with the same weight values, and the output projection +writes BF16 partial sums: its FP32 accumulation rounded once. """ from __future__ import annotations @@ -21,7 +27,7 @@ from ignition.components.causal_convolution import PreparedCausalConvolution from ignition.components.head_gate import PreparedHeadGate -from ignition.components.linear import UnquantizedProjection +from ignition.components.linear import QuantizedProjection, UnquantizedProjection from ignition.components.paged_attention import PreparedPagedAttention, PreparedPagedKVWriter from ignition.components.ring_commit import PreparedRingCommit from ignition.components.rms_norm import PreparedRMSNorm @@ -68,33 +74,40 @@ def split(self, outputs): class AttentionWeights: """One rank's attention tensors of one layer in serving layouts. - `projections` hold one fused BF16 weight per input stream with the rows of - `Columns`. Local layers carry static `[channels, 1, W]` K/V convolution taps; + `projections` hold one fused weight per input stream with the rows of + `Columns`, and `output` the output projection's columns of this rank's heads: + BF16 tensors, or b12x MXFP8 weights under online conversion. Local layers + carry static `[channels, 1, W]` K/V convolution taps; global layers carry `[W, channels]` static lag taps. `relative_projection` is the checkpoint's `[16, extent]` relative-logit projection and `relative_rows` its contiguous `[extent, 16]` transpose. """ - projections: tuple[torch.Tensor, ...] + projections: tuple query_clip_scale: torch.Tensor relative_clip_scale: torch.Tensor relative_projection: torch.Tensor relative_rows: torch.Tensor key_convolution: torch.Tensor value_convolution: torch.Tensor - output: torch.Tensor + output: object + +def fuse_projections(placed, columns: Columns, *, local, temporary=False): + """Concatenate a rank's projection rows in `Columns` order; padding rows are zero. -def fuse_projections(placed, columns: Columns, *, local): - """Concatenate a rank's projection rows in `Columns` order; padding rows are zero.""" + `temporary` allocates the fused weights outside persistent storage, for a caller that converts them. + """ from ignition.preparation.persistent import persistent_zeros + allocate = torch.zeros if temporary else persistent_zeros + names = {"query": "query", "gate": "output_gate", "key": "key", "value": "value", "relative": "relative_query", "sink": "sink", "key_lags": "key_convolution_dynamic", "value_lags": "value_convolution_dynamic"} fused = [] for stream, width in zip(columns.streams, columns.widths(), strict=True): hidden = placed["query"].shape[1] - weight = persistent_zeros((width, hidden), dtype=torch.bfloat16, device=placed["query"].device) + weight = allocate((width, hidden), dtype=torch.bfloat16, device=placed["query"].device) offset = 0 for name, rows in stream: source = placed[names[name]] @@ -106,8 +119,15 @@ def fuse_projections(placed, columns: Columns, *, local): return tuple(fused) -def attention_weights(placed, *, local, heads, kv_heads, dim, width): - """Serving attention tensors from one rank's placed checkpoint roles (`weights.checkpoint_layout`).""" +def attention_weights(placed, *, local, heads, kv_heads, dim, width, online_mxfp8=False): + """Serving attention tensors from one rank's placed checkpoint roles (`weights.checkpoint_layout`). + + `online_mxfp8` stores every fused input projection and the output projection as MXFP8: E4M3 values + with one power-of-two scale per 32 input columns of each output row. A row's stored values depend on + that row alone, so fusing the column groups into one weight leaves each group's values as a separate + conversion would. `placed["output"]` and the fused weights are then temporaries. + """ + from ignition.components.weights import quantize_bf16_linear_as_mxfp8 from ignition.preparation.persistent import persistent_copy columns = Columns.of(local, heads, kv_heads, dim, width) @@ -116,9 +136,21 @@ def attention_weights(placed, *, local, heads, kv_heads, dim, width): key, value = placed["key_convolution"], placed["value_convolution"] else: key, value = placed["key_convolution_static"], placed["value_convolution_static"] - return AttentionWeights(fuse_projections(placed, columns, local=local), placed["query_clip_scale"], + fused, output = fuse_projections(placed, columns, local=local, temporary=online_mxfp8), placed["output"] + if online_mxfp8: + fused = tuple(quantize_bf16_linear_as_mxfp8(weight, retain_scale_rows=False) for weight in fused) + output = quantize_bf16_linear_as_mxfp8(output, retain_scale_rows=False) + return AttentionWeights(fused, placed["query_clip_scale"], placed["relative_clip_scale"], projection, persistent_copy(projection.t().contiguous()), key, value, - placed["output"]) + output) + + +def prepare_projection(source, weight, output, *, session, name, workspace): + """Declare a projection of BF16 activations by a BF16 weight or by an MXFP8 weight.""" + if isinstance(weight, torch.Tensor): + return UnquantizedProjection(source, weight, output, session=session, name=name) + return QuantizedProjection(source, weight, output, session=session, name=name, activation_mode="a16", + workspace=workspace) @dataclass(frozen=True) @@ -196,7 +228,7 @@ def __init__(self, layer, weights: AttentionWeights, text, cache: LayerCache, me dynamic_heads=0 if self.local else self.kv_heads) self.value_convolution = PreparedCausalConvolution(weights.value_convolution, cache.value_history, dynamic_heads=0 if self.local else self.kv_heads) - device = weights.output.device + device = weights.query_clip_scale.device examples = {} if examples is None else examples def example(role, shape, dtype=torch.bfloat16): @@ -204,14 +236,17 @@ def example(role, shape, dtype=torch.bfloat16): return declaration_tensor(examples, role, shape, dtype, device) source = example("inkling.attention.source", (tokens, text.hidden)) - self.projections = tuple(UnquantizedProjection(source, weight, + self.projections = tuple(prepare_projection(source, weight, example(f"inkling.attention.projection{index}", (tokens, width)), session=session, - name=f"{name}.projection{index}").functional(session=session) + name=f"{name}.projection{index}", workspace=workspace).functional(session=session) for index, (weight, width) in enumerate(zip(weights.projections, self.columns.widths(), strict=True))) attended = example("inkling.attention.attended", (tokens, self.heads * self.dim)) - self.output_projection = UnquantizedProjection(attended, weights.output, + if not isinstance(weights.output, torch.Tensor): + # b12x's MXFP8 projection writes BF16, the FP32 accumulation rounded once. + partial_dtype = torch.bfloat16 + self.output_projection = prepare_projection(attended, weights.output, example("inkling.attention.partial", (tokens, text.hidden), partial_dtype), - session=session, name=f"{name}.output").functional(session=session) + session=session, name=f"{name}.output", workspace=workspace).functional(session=session) query = example("inkling.attention.query", (tokens, self.heads, self.dim)) output = example("inkling.attention.output", (tokens, self.heads, self.dim)) sink = example("inkling.attention.sink", (tokens, self.heads), torch.float32) diff --git a/ignition/recipes/inkling2/bootstrap.py b/ignition/recipes/inkling2/bootstrap.py index cb7f6ca7d..a85182197 100644 --- a/ignition/recipes/inkling2/bootstrap.py +++ b/ignition/recipes/inkling2/bootstrap.py @@ -78,6 +78,8 @@ class PreparationConfig: # Proposal-only quantized copies derived from checkpoint values at load; None keeps BF16. draft_head_quantization: str | None = None markov_head_quantization: str | None = None + # Stores the attention input and output projections as MXFP8 at load; False keeps the checkpoint's BF16. + online_mxfp8: bool = False benchmark_selection: object | None = None def __post_init__(self): @@ -117,6 +119,8 @@ def __post_init__(self): if (self.draft_head_quantization is not None or self.markov_head_quantization is not None) and ( not self.drafting or self.draft_tokens < 1): raise ValueError("proposal head quantization requires learned speculation with positive draft depth") + if type(self.online_mxfp8) is not bool: + raise ValueError("Inkling 2 online MXFP8 conversion must be a boolean") if self.snapshot_budget_bytes <= 0 or self.headroom_bytes < 0: raise ValueError("snapshot budget must be positive and headroom nonnegative") object.__setattr__(self, "image_concurrency", image_capacity(self.max_active, self.image_concurrency) if self.vision else 0) @@ -229,7 +233,8 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): weights = ModelWeights.load(manifest, device, shard=shard, layers=config.decoder_layers, progress=progress, drafting=config.drafting, vision=config.vision, draft_head_quantization=config.draft_head_quantization, - markov_head_quantization=config.markov_head_quantization) + markov_head_quantization=config.markov_head_quantization, + online_mxfp8=config.online_mxfp8) weights_bytes = torch.cuda.memory_allocated(device) if torch.cuda.get_device_properties(device).is_integrated: from ignition.preparation.host_memory import release_page_cache @@ -272,7 +277,8 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): draft_block=model.draft.block) identity = hashlib.sha256(json.dumps({"text": model.text.__dict__ | {"local_layers": sorted(model.text.local_layers)}, "quantization": model.quantization, "headers": headers, "world_size": world, - "decoder_layers": len(weights.layers), "contract": "inkling2.paged-text.v1"}, + "decoder_layers": len(weights.layers), "contract": "inkling2.paged-text.v1"} + | ({"online_mxfp8": True} if config.online_mxfp8 else {}), sort_keys=True, default=str).encode()).hexdigest() session = RecordedPreparationSession(compile_workers=config.compile_workers, native_dense_activations=config.native_dense_activations, lock_gpu_clocks=config.lock_gpu_clocks, @@ -420,7 +426,7 @@ def add(name, forward, kind, rows, tokens, fields, enabled=None, packed=0): reserved_tensor_bytes=torch.cuda.memory_reserved(device), headroom_bytes=config.headroom_bytes, tuning=tuning, compiled_decoder=config.compile_decoder, draft_head_quantization=config.draft_head_quantization, - markov_head_quantization=config.markov_head_quantization) + markov_head_quantization=config.markov_head_quantization, online_mxfp8=config.online_mxfp8) # Each decoder layer's weights form one stable payload; vocabulary shards, norms and the output query share misc. rebuild_weights = declare_weights(weights, components=("embedding", "embedding_norm", "final_norm", "output_query", "unembedding", "draft", "vision")) diff --git a/ignition/recipes/inkling2/decoder.py b/ignition/recipes/inkling2/decoder.py index 1558e3a6e..a2cc70c4f 100644 --- a/ignition/recipes/inkling2/decoder.py +++ b/ignition/recipes/inkling2/decoder.py @@ -83,6 +83,7 @@ def __init__(self, layer, weights, text, pool, metadata, reduction, reduction_dt mode=mode, tokens=tokens, session=session, workspace=workspace, name=name + ".attention", examples=examples, # Prefill writes the attention partial sum in the reduction's element type. At prefill row counts the # BF16 projection equals the FP32 projection rounded once; decode and verification keep FP32. + # An MXFP8 output weight writes BF16 in every mode. partial_dtype=reduction_dtype if mode == "prefill" else torch.float32, tuning_page_count=((int(pool.memory_capacity[0].item()) - 1) * pool.ring_row_pages + pool.geometry.ring // 128 if text.local(layer) else int(pool.memory_capacity[1].item()))) diff --git a/ignition/recipes/inkling2/recipe.py b/ignition/recipes/inkling2/recipe.py index 29e3b9c01..fdbd8bf88 100644 --- a/ignition/recipes/inkling2/recipe.py +++ b/ignition/recipes/inkling2/recipe.py @@ -40,7 +40,7 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ headroom_bytes=plan.headroom_bytes + plan.reserve_bytes, compile_decoder=compile_forwards, retain_graphs=retain_graphs, kernel_cache=kernel_cache, drafting=speculation is not None, vision=not plan.language_model_only, - mtp_only=speculation is not None and speculation.mtp_only, + mtp_only=speculation is not None and speculation.mtp_only, online_mxfp8=plan.online_mxfp8, benchmark_selection=plan.benchmark_selection, **drafting) return prepare_group(snapshot, config, prepare_rank, progress=progress, core_storage=core_storage, ranks=ranks, checkpoint=plan.checkpoint) @@ -55,6 +55,8 @@ def usage(prepared): sampling_defaults=SAMPLING_DEFAULTS, # Proposal-only copies: the block's vocabulary head, and the recurrent correction head as row-scaled E4M3. draft_head_quantizations=("nvfp4", "mxfp8"), markov_head_quantizations=("fp8",), + # The attention input and output projections of every decoder layer. + online_mxfp8=True, checkpoints=(Checkpoint(alias="inkling-2-small-nvfp4", repository="/data/models/Inkling-2-Small-NVFP4", revision="local", architecture="Inkling2ForConditionalGeneration", stored_bytes=344_366_116_864, device_bytes=344_366_116_864, expansion_bytes=5_673_717_760, draft_bytes=2_684_203_392),), diff --git a/ignition/recipes/inkling2/weights.py b/ignition/recipes/inkling2/weights.py index 72731dba7..e39e4e5bb 100644 --- a/ignition/recipes/inkling2/weights.py +++ b/ignition/recipes/inkling2/weights.py @@ -73,9 +73,11 @@ def embed_norm(self): @classmethod def load(cls, manifest, device, *, shard, progress=None, drafting=True, vision=True, layers=None, - draft_head_quantization=None, markov_head_quantization=None): + draft_head_quantization=None, markov_head_quantization=None, online_mxfp8=False): + """`online_mxfp8` stores each layer's attention input and output projections as MXFP8.""" before = torch.cuda.memory_allocated(device) - with InklingWeightLoader(manifest, device, shard=shard, progress=progress, vision=vision) as loader: + with InklingWeightLoader(manifest, device, shard=shard, progress=progress, vision=vision, + online_mxfp8=online_mxfp8) as loader: c = loader.config count = c.text.layers if layers is None else layers if type(count) is not int or not 1 <= count <= c.text.layers: @@ -113,8 +115,9 @@ def vocabulary_rows(name): class InklingWeightLoader(DirectWeightLoader): - def __init__(self, manifest, device, *, shard, progress=None, vision=True): + def __init__(self, manifest, device, *, shard, progress=None, vision=True, online_mxfp8=False): super().__init__(manifest, device, progress=progress) + self.online_mxfp8 = online_mxfp8 self.config = ModelConfig.load(manifest.snapshot) self.config.validate_shard(shard) self.shard, self.vision = shard, vision @@ -129,12 +132,10 @@ def _selected_names(self): return {name for name in super()._selected_names() if self.vision or not name.startswith("model.vision_tower.")} - def load_layer(self, index): - from .experts import load_experts - + def load_attention(self, index): + """This rank's attention tensors of one layer (`attention.attention_weights`).""" c, s = self.config.text, self.shard - prefix = f"{TEXT_PREFIX}.layers.{index}" - a = prefix + ".self_attn" + a = f"{TEXT_PREFIX}.layers.{index}.self_attn" q0, q1 = s.partition(c.heads) k0, k1 = s.partition(c.kv_heads) query_rows = (q0 * c.head_dim, q1 * c.head_dim) @@ -145,28 +146,35 @@ def load_layer(self, index): ("relative_query", "r_proj", (q0 * c.relative_width, q1 * c.relative_width)), ("sink", "sink_proj", (q0, q1))): placed[role] = self.load_linear(a + "." + name, rows=extent, temporary=True) - placed["output"] = self.load_linear(a + ".o_proj", columns=query_rows) + placed["output"] = self.load_linear(a + ".o_proj", columns=query_rows, temporary=self.online_mxfp8) for role, name in (("query_clip_scale", "q_l2_clip.scale"), ("relative_clip_scale", "rel_l2_clip.scale")): placed[role] = self.load_tensor(a + "." + name, extent=slice(q0, q1)) placed["relative_projection"] = self.load_tensor(a + ".rel_logits_proj.proj") - if c.local(index): - for kind in ("key", "value"): - n = "k" if kind == "key" else "v" + for kind in ("key", "value"): + n = "k" if kind == "key" else "v" + if c.local(index): placed[kind + "_convolution"] = self.load_tensor( a + f".{n}_sconv.conv1d.weight", extent=slice(*key_rows)) - norms = (self.load_tensor(prefix + ".input_layernorm.weight"),) - else: - for kind in ("key", "value"): - n = "k" if kind == "key" else "v" + else: placed[kind + "_convolution_static"] = self.load_tensor( a + f".{n}_sconv.static_weight", extent=(slice(None), slice(*key_rows))) placed[kind + "_convolution_dynamic"] = self.load_tensor( a + f".{n}_sconv.weight_proj", extent=slice(k0 * c.convolution_width, k1 * c.convolution_width), temporary=True) + return attention_weights(placed, local=c.local(index), heads=q1 - q0, kv_heads=k1 - k0, + dim=c.head_dim, width=c.convolution_width, online_mxfp8=self.online_mxfp8) + + def load_layer(self, index): + from .experts import load_experts + + c, s = self.config.text, self.shard + prefix = f"{TEXT_PREFIX}.layers.{index}" + attention = self.load_attention(index) + if c.local(index): + norms = (self.load_tensor(prefix + ".input_layernorm.weight"),) + else: norms = tuple(self.load_tensor(prefix + f".{n}_input_layernorm.weight") for n in ("q", "k", "v")) - attention = attention_weights(placed, local=c.local(index), heads=q1 - q0, kv_heads=k1 - k0, - dim=c.head_dim, width=c.convolution_width) attention_query = None if index == 0 else scaled_query( self.load_tensor(prefix + ".attention_input.query"), c.hidden) return LayerWeights(attention, load_experts(self, index, shard=s), diff --git a/tests/cli/test_inkling2.py b/tests/cli/test_inkling2.py index 8d3472320..3e7e160f5 100644 --- a/tests/cli/test_inkling2.py +++ b/tests/cli/test_inkling2.py @@ -7,6 +7,7 @@ import pytest +from ignition import planning from ignition.cli import _parser, preparation from ignition.recipes import ResolvedModel from ignition.recipes.inkling2.recipe import RECIPE @@ -115,3 +116,39 @@ def test_inkling_preparation_config_validates_proposal_head_formats(arguments, m with pytest.raises(ValueError, match=message): PreparationConfig(**arguments) + + +@pytest.mark.parametrize("online", [False, True]) +def test_inkling_online_mxfp8_flag_reaches_plan_metadata_and_preparation(monkeypatch, tmp_path, online): + from ignition.recipes.inkling2 import bootstrap + + assert RECIPE.online_mxfp8 + assert (RECIPE.online_mxfp8_scope, RECIPE.online_mxfp8_scopes) == ("all", ("all",)) + model = ResolvedModel(RECIPE, RECIPE.checkpoints[0]) + args = _parser().parse_args(["export", model.checkpoint.alias, *(["--online-mxfp8"] if online else [])]) + devices = tuple(gpu(i, 95) for i in range(4)) + plan = planning.plan(RECIPE, model.checkpoint, devices, selected=(0, 1, 2, 3), concurrency=8, reserve_bytes=0, + speculation=RECIPE.speculation, online_mxfp8=args.online_mxfp8) + assert plan.online_mxfp8 is online + assert plan.to_dict()["online_mxfp8"] is online + captured = [] + configuration = bootstrap.PreparationConfig + + class ConfigurationCaptured(Exception): + pass + + def capture_config(**kwargs): + captured.append(configuration(**kwargs)) + raise ConfigurationCaptured + + monkeypatch.setattr(bootstrap, "PreparationConfig", capture_config) + with pytest.raises(ConfigurationCaptured): + RECIPE.prepare(tmp_path, plan, compile_forwards=False, kernel_cache=None, progress=None) + assert captured.pop().online_mxfp8 is online + + +def test_inkling_preparation_config_rejects_a_non_boolean_online_mxfp8(): + from ignition.recipes.inkling2.bootstrap import PreparationConfig + + with pytest.raises(ValueError, match="online MXFP8"): + PreparationConfig(online_mxfp8="all") diff --git a/tests/recipes/test_inkling2_target.py b/tests/recipes/test_inkling2_target.py index 33a2fb0f1..dfde200c0 100644 --- a/tests/recipes/test_inkling2_target.py +++ b/tests/recipes/test_inkling2_target.py @@ -162,6 +162,93 @@ def forward(): assert (((partial[:n].double() - exact).abs() - gamma * accumulated).max() <= 0).item() +def _expanded(weight): + """The BF16 matrix an MXFP8 weight stores, in FP64.""" + from b12x.gemm._shared.wo_mxfp8 import dequantize_mxfp8_rows_torch, materialize_mxfp8_scale_rows + + rows = weight.weight + return dequantize_mxfp8_rows_torch(rows.values, materialize_mxfp8_scale_rows(rows))[:, :weight.in_features].double() + + +@pytest.mark.skipif(os.environ.get('FLARE_RUN_CUDA_TESTS') != '1', reason='requires an assigned SM120 GPU') +@pytest.mark.parametrize('layer', [0, 5]) +@pytest.mark.parametrize('mode,tokens,compiled', [('decode', 1, False), ('decode', 4, True), ('verify', 8, False), + ('prefill', 128, True)]) +def test_checkpoint_attention_projects_with_stored_mxfp8_weights(configuration, layer, mode, tokens, compiled): + """Online MXFP8 stores every fused input projection and the output projection; each kernel multiplies + BF16 activations by the stored values, and the tensors outside those projections keep checkpoint bits.""" + from b12x.gemm.blockscaled._linear import MXFP8LinearWeight + from ignition.preparation.checkpoint import inspect_indexed_checkpoint + from ignition.preparation.scratch import ScratchArena + from ignition.preparation.tuning import RecordedPreparationSession + from ignition.recipes.inkling2.attention import Columns, LayerCache, PreparedAttention + from ignition.recipes.inkling2.pool import ContinuationPool + from ignition.recipes.inkling2.weights import InklingWeightLoader + + snapshot = Path(os.environ.get('FLARE_INKLING2_SNAPSHOT', '/data/models/Inkling-2-Small-NVFP4')) + device = torch.device('cuda', 0) + config = ModelConfig.from_dict(configuration) + loaded = [] + for online in (False, True): + with InklingWeightLoader(inspect_indexed_checkpoint(snapshot), device, shard=TensorParallelShard(0, 4), + vision=False, online_mxfp8=online) as loader: + loaded.append(loader.load_attention(layer)) + checkpoint, weights = loaded + for stored, original in zip((*weights.projections, weights.output), (*checkpoint.projections, checkpoint.output), + strict=True): + assert isinstance(stored, MXFP8LinearWeight) and stored.weight.scale_rows is None + expanded = _expanded(stored) + assert expanded.shape == original.shape + assert ((expanded - original.double()).norm() / original.double().norm()).item() < .035 + for field in ('query_clip_scale', 'relative_clip_scale', 'relative_projection', 'relative_rows', + 'key_convolution', 'value_convolution'): + torch.testing.assert_close(getattr(weights, field), getattr(checkpoint, field), rtol=0, atol=0) + + text = config.text.prefix(6) + pool = ContinuationPool.allocate(text, RankGeometry.of(text, 4), 3, 4, device) + m = Metadata.allocate(tokens, 1, 4, device) + with RecordedPreparationSession(device=device, checkpoint='inkling2-checkpoint-attention-mxfp8', + workload_schema='inkling2-checkpoint-attention', numerical_policy='default', autotune_effort='off') as session: + arena = ScratchArena(device) + session.register_scratch(arena) + operation = PreparedAttention(layer, weights, text, LayerCache.of(pool, layer), m, + mode=mode, tokens=tokens, session=session, workspace=arena, name='attention', tuning_page_count=4) + session.tune() + torch.manual_seed(layer) + streams = tuple(torch.randn(tokens, text.hidden, device=device).bfloat16() for _ in weights.projections) + m.set(torch.tensor([0], device=device), torch.tensor([tokens], dtype=torch.int32, device=device), + torch.tensor([1], device=device), torch.tensor([[0, 1, 2, 3]], dtype=torch.int32, device=device), + torch.zeros(1, tokens, dtype=torch.int64, device=device), torch.tensor([1], device=device)) + def forward(): + return operation.attend(streams, m) + if compiled: + from ignition.preparation.compilation import compile_forward + forward = compile_forward(forward) + attended, partial, values = forward() + + def within_accumulation(actual, source, weight): + # FP32 accumulation of the products, then one rounding to BF16. + exact, magnitude = source.double() @ weight.T, source.double().abs() @ weight.abs().T + terms = source.shape[1] + gamma = terms * 2 ** -24 / (1 - terms * 2 ** -24) + return (((actual.double() - exact).abs() - gamma * magnitude - 2 ** -8 * exact.abs()).max() <= 0).item() + + columns = Columns.of(text.local(layer), 12, 2, 128, text.convolution_width) + raw = {'gate': values['gate'].flatten(1), 'sink': values['sink'], 'key': values['key_raw'], + 'value': values['value_raw']} + checked = set() + for stream, source, stored in zip(columns.streams, streams, weights.projections, strict=True): + expanded, offset = _expanded(stored), 0 + for name, width in stream: + if name in raw: + assert within_accumulation(raw[name], source, expanded[offset:offset + width]), name + checked.add(name) + offset += width + assert checked == set(raw) + assert partial.dtype == torch.bfloat16 + assert within_accumulation(partial, attended, _expanded(weights.output)) + + @pytest.mark.skipif(os.environ.get('FLARE_RUN_CUDA_TESTS') != '1', reason='requires an assigned SM120 GPU') @pytest.mark.parametrize('tokens,streams,sources,add', [(1, streams, sources, add) for streams in (1, 3) for sources in range(1, 10) for add in (False, True)] From a043011e65b41558f9d5804f2131ce735d0bd642 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sun, 15 Nov 2026 16:14:31 -0500 Subject: [PATCH 08/11] Document switch-only RoCE routing for row-sharded Inkling 2 prefill on Sparks Row-sharded Inkling 2 prefill on four DGX Sparks loses 110 ms of a 2,072 ms chunk to a few collectives that take 7 to 72 ms against a 2 ms median. With the default routing a rank reaches one peer over a direct cable and two through the switch, and both ConnectX-7 ports share the host's PCIe links. The switch marks ECN on the congested flows and the senders' DCQCN rate control throttles them; flows over the cables are never throttled. The serving guide gave no routing advice for this configuration. docs/model-preparation.md states, in the Inkling 2 row-sharding section, that such a core is served with --roce-switch-only on every rank, with the mechanism and the measured effect. No code changes. A reader serving Inkling 2 at TP4 on cabled and switched Sparks is told the flag that removes the stalled collectives. Evidence: all four ranks of one core traced with node-level CUDA graph tracing over 67,000- and 132,000-token prompts. With the default routing, 90 collectives stalled in 32 chunks of 5,120 rows or more, hosts received 213,000 to 722,000 ECN-marked RoCE packets per 67,000-token prefill, and no CNP was counted on a cable port. With --roce-switch-only, no collective stalled in 36 such chunks and ECN, CNP and pause counters stayed at zero; chunks at the same position of the prompt were 92 ms (5.0%) shorter at 5,120 rows or more and 1.3% longer below, and a decode round was 0.08 to 0.09 ms longer. On untraced launches, time to first token at 131,990 tokens was 40.4 to 42.0 s against 43.5 to 43.7 s, three repeats each. Limitations: the two routings were measured on separate launches. The share of the stall caused by the shared PCIe links is inferred from pause and buffer-threshold counters; receive rate was not measured. Disabling ECN marking on the switch or DCQCN on the adapters was not tested. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/model-preparation.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 844e70406..34497e0df 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1439,6 +1439,20 @@ prompt, 18.4 to 20.1 s for 67,145 tokens and 40.7 to 43.1 s for 131,990 tokens. One launch of a core that computes these stages on every rank measured 2.59 to 2.69 s, 22.4 to 23.0 s and 48.8 to 49.8 s. +Serve a row-sharded core on four DGX Sparks with `--roce-switch-only` on every +rank when the hosts are joined by a switch and pairs are also cabled directly. +With the default routing a rank reaches one peer over its cable and two through +the switch, and both ConnectX-7 ports share the host's PCIe links. In +row-sharded chunks of 5,120 rows or more the switch then marks ECN, the +senders' DCQCN rate control throttles the switch flows, and a mean of 2.8 +collectives per chunk take 7 to 72 ms against a 2 ms median: 110 ms of a +2,072 ms chunk. With `--roce-switch-only`, 36 such chunks had no stalled +collective and no host counted an ECN mark, CNP or pause frame; chunks at the +same position of a 67,000-token prompt are 92 ms shorter, smaller chunks are +1.3% longer, and a decode round is under 0.1 ms longer. Time to first token +for 131,990 tokens is 40.4 to 42.0 s against 43.5 to 43.7 s with the default +routing. + Multi-host export requires the checkpoint directory on rank zero only; peers read their tensor ranges from it. The recipe accepts up to 32 concurrent requests. On rank zero, whose preparation address From 20579f0b2b2357fbc0b60cf5f987d2049aed8a95 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Sun, 15 Nov 2026 19:21:21 -0500 Subject: [PATCH 09/11] Store Inkling 2 DSpark attention projections as MXFP8 with --online-mxfp8 An Inkling 2 drafting round reads the drafter's BF16 projections once whatever the number of drafts verified: the five draft layers' fused query/key/value and attention output projections and the recurrent head's context projection, 179 MB per TP4 rank. On a GB10 these kernels run at the memory rate (207 to 221 GB/s) and take about 0.85 ms of the 4.4 ms a round spends in the drafter and its proposal sampling. --online-mxfp8 already stores the target's attention projections as MXFP8; the drafter only proposes tokens, so its projections can take the same form without changing the output distribution. With --online-mxfp8, DraftWeights.load converts each draft layer's fused query/key/value projection and attention output projection and the recurrent head's context projection with quantize_bf16_linear_as_mxfp8, and the drafter declares them through prepare_projection with BF16 activations. ignition/components/recurrent_proposal.py accepts an MXFP8 context weight; its projection is then rounded to BF16 before the FP32 bias and the previous draw's part are added. Each draft layer's key/value projection of accepted target taps keeps BF16 because it also runs on every prefill row, where MXFP8 weights with BF16 activations are slower. The recurrent state projection, embeddings, norms, the checkpoint's MXFP8 feed-forward weights and both proposal heads keep their precision. Without the flag preparation is unchanged. Helios and the package contract are unchanged. A drafting round reads 92 MB of these weights per rank. Proposals and their acceptance rate may differ from a BF16 drafter's; target verification decides every emitted token. Evidence: on a GB10 with the checkpoint, tests/components/ test_inkling2_dspark_cuda.py and test_inkling2_dspark.py pass 45 of 45, including a check that the converted projections of a window and a global draft layer multiply by the stored values, eagerly and compiled; test_inkling2_target.py -k checkpoint_attention passes 20 of 20 and test_inkling2_row_shards_cuda.py 6 of 6. One core exported with --online-mxfp8, --draft-head-quantization nvfp4 and --markov-head-quantization fp8 served at TP4 on four DGX Sparks with 32 requests: tests/server/test_inkling2.py -k default-effort passes 7 of 7 and 32 concurrent requests return the expected values. Over three repeats each, acceptance of the first and second draft was 78% and 62% on ordinary prompts against 79% and 61% for the core with a BF16 drafter and BF16 correction head, and 58% and 34% against 58% and 33% on an article continuation; three decode benchmark passes completed without errors with single-request decode of 48.0 to 51.3 tokens/s at an 8,192-token context against 41.8 to 43.0. Limitations: the drafter's kernel time was not traced on this core, and its one launch also ran one-token rounds and prefill faster than the earlier core's launches (22.5 ms against 24.2 to 28.8 ms at one request), so the throughput difference is not attributed to this change. The served core also used the FP8 correction head, so the acceptance comparison covers both together. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/cli-design.md | 2 +- docs/model-preparation.md | 26 +++- ignition/components/recurrent_proposal.py | 18 ++- ignition/recipes/inkling2/bootstrap.py | 3 +- ignition/recipes/inkling2/dspark.py | 19 ++- ignition/recipes/inkling2/dspark_weights.py | 43 +++++-- ignition/recipes/inkling2/recipe.py | 3 +- ignition/recipes/inkling2/weights.py | 7 +- tests/components/test_inkling2_dspark.py | 20 +++ tests/components/test_inkling2_dspark_cuda.py | 114 ++++++++++++++++++ 10 files changed, 225 insertions(+), 30 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index 902737f63..0af4c3f31 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -469,7 +469,7 @@ explicit flags take precedence. | `--no-compile` | Development only: capture graphs without compiling forwards. A recipe never sets it. | off | | `--force-moe-decode-a16` / `--no-force-moe-decode-a16` | Prepare Qwen3.8 Flash NVFP4 target routed experts as one packed weight owner: decode and speculative verification use W4A16 at every token-row count, and separate prefill graphs use calibrated A4. Requires SM120/121, checkpoint activation scales, and rank-local expert intermediate width divisible by 64 (TP1/2). Mixed prefill and other recipes/precisions reject the flag. Shared experts and stored A16 MTP experts retain their precision. Overrides `[preparation] force_moe_decode_a16`; the resolved value is recorded in the plan and core rebuild metadata. | off | | `--native-dense-activations` | Replace dense projection `auto` precision with b12x `quantized`: A8 for FP8 weights and A4 for FP4 weights. Explicit recipe precision and routed MoE precision are retained. NVFP4 requires a checkpoint activation global scale; unsupported native paths fail preparation. | Recipe precision | -| `--online-mxfp8` | Store eligible BF16 projections as MXFP8 while loading. Kimi K3.1 converts fused target KDA inputs by default; `--online-mxfp8-scope all` also converts eligible attention output/latent projections, shared experts, MoE latent projections, and DFlash2 draft projections. Kimi K3 converts KDA projections, MLA latent/gate, query and output projections, shared experts, MoE latent down/up projections, and DSpark context, outputs and MLPs; batched MLA key/value projections retain BF16. Qwen3.8 dense converts target attention/MLP projections and DFlash2 context, attention and MLP projections. Flash Next with `--speculative-method dflash2` converts only DFlash2 projections; target precision is retained. Inkling 2 converts every decoder layer's fused attention input projections and its attention output projection, with BF16 activations in prefill, decoding and verification; routers, experts, DSpark and the vision encoder retain their precision. Existing packed weights, normalization, convolutions, selectors and target vocabulary weights retain their precision. Recipes that name no such projections reject it. | Checkpoint precision | +| `--online-mxfp8` | Store eligible BF16 projections as MXFP8 while loading. Kimi K3.1 converts fused target KDA inputs by default; `--online-mxfp8-scope all` also converts eligible attention output/latent projections, shared experts, MoE latent projections, and DFlash2 draft projections. Kimi K3 converts KDA projections, MLA latent/gate, query and output projections, shared experts, MoE latent down/up projections, and DSpark context, outputs and MLPs; batched MLA key/value projections retain BF16. Qwen3.8 dense converts target attention/MLP projections and DFlash2 context, attention and MLP projections. Flash Next with `--speculative-method dflash2` converts only DFlash2 projections; target precision is retained. Inkling 2 converts every decoder layer's fused attention input projections and its attention output projection, with BF16 activations in prefill, decoding and verification, and DSpark's query/key/value and attention output projections and its recurrent head's context projection; routers, experts, DSpark's key/value projections of accepted target taps, its feed-forward weights and proposal heads, and the vision encoder retain their precision. Existing packed weights, normalization, convolutions, selectors and target vocabulary weights retain their precision. Recipes that name no such projections reject it. | Checkpoint precision | | `--online-mxfp8-scope SCOPE` | Select a conversion group declared by the recipe. Kimi K3.1 supports `kda-input` and `all`; the broader group changes target as well as DFlash2 draft projection storage. Other recipes retain their declared conversion set. Command line only; requires `--online-mxfp8` for a non-default group. | Recipe scope | | `--language-model-only` | Prepare no vision encoder and serve text only, as vLLM's flag of the same name; requests with images are rejected and the encoder's weights, scratch, and graphs become KV pages. Recipes without a separable encoder reject it. | The recipe's image support | diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 34497e0df..d38ac2d69 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1347,8 +1347,26 @@ decoding, and verification, which therefore project with the same weight values, and the output projection writes BF16 partial sums. A TP4 rank then reads 1.22 GB of attention projection weights per decode step where BF16 reads 2.36 GB, and holds 1.14 GB less. Routers, vocabulary shards, convolutions, -norms, clip scales, the relative-logit projection, experts, DSpark, and the -vision encoder keep checkpoint precision. The default omits the flag. +norms, clip scales, the relative-logit projection, experts, and the vision +encoder keep checkpoint precision. The default omits the flag. + +The flag also stores three of DSpark's BF16 projections in the same MXFP8 +form, with BF16 activations: each of the five draft layers' fused +query/key/value projection and attention output projection, and the recurrent +head's projection of the draft hidden state and target context. Per TP4 rank +these are 2048 by 4608, 4608 by 1536, and 768 by 9216 values. One drafting +round reads each once: 179 MB as BF16 and 92 MB as MXFP8. The recurrent head's +MXFP8 projection is rounded to BF16 before its FP32 bias and the previous +draw's part are added; with BF16 weights that sum stays FP32. Each draft +layer's key/value projection of accepted target taps, 512 by 4608 values per +rank, keeps BF16: it also runs on every prefill row, where MXFP8 weights with +BF16 activations are slower, and it is 24 MB of a drafting round's reads. The +recurrent state projection, embeddings, norms, the sidecar's MXFP8 +feed-forward weights, and both proposal heads keep their precision; +`--draft-head-quantization` and `--markov-head-quantization` select the heads' +formats independently. Target verification decides the output, so MXFP8 draft +projections change which tokens are proposed and how often they are accepted, +never the output distribution. The stored weights differ from the checkpoint's by 2.7% in relative norm. With the Transformers reference layers and checkpoint weights over 1,536 positions @@ -1360,7 +1378,9 @@ most likely token at 97.3% of positions; rounding the four ranks' partial sums to BF16, which cross-host reductions do, moves that agreement to 97.8% by itself. `tests/recipes/test_inkling2_target.py` checks on SM120 that the decode, verification, and prefill kernels of a window and a global layer -multiply by the stored values. +multiply by the stored values, and +`tests/components/test_inkling2_dspark_cuda.py` checks the same of the three +converted DSpark projections for a window and a global draft layer. On four DGX Sparks at TP4 with 32 requests and 8,192-token chunks, a core exported with the flag holds 3,604,480 KV tokens per rank where the BF16 core diff --git a/ignition/components/recurrent_proposal.py b/ignition/components/recurrent_proposal.py index 8c21b4465..d17601c1b 100644 --- a/ignition/components/recurrent_proposal.py +++ b/ignition/components/recurrent_proposal.py @@ -6,7 +6,7 @@ import torch from .embedding import PreparedEmbedding -from .linear import UnquantizedProjection +from .linear import UnquantizedProjection, prepare_projection from .markov_sampling import PreparedRowScaledFP8MarkovProjection, RowScaledFP8MarkovWeight @@ -35,12 +35,17 @@ class PreparedRecurrentProposalHead: computes the second part for every position of the block in one projection; `step` adds the first. `weights.head` maps the recurrent output to vocabulary corrections as BF16 rows, or as row-scaled E4M3 rows whose FP32 product takes the BF16 bias before rounding to BF16. + + `weights.context_weight` is a BF16 matrix, whose projection stays FP32 until the gate, or a b12x + MXFP8 weight, whose projection of the BF16 activations is rounded to BF16 before the FP32 bias + and the previous draw's part are added. `workspace` supplies the MXFP8 projection's scratch. """ - def __init__(self, weights, tokens, *, positions, session, name): + def __init__(self, weights, tokens, *, positions, session, name, workspace=None): rows, device = tokens.numel(), tokens.device rank = weights.embedding.shape[1] - hidden = weights.context_weight.shape[1] // 2 + bf16 = isinstance(weights.context_weight, torch.Tensor) + hidden = (weights.context_weight.shape[1] if bf16 else weights.context_weight.in_features) // 2 if type(positions) is not int or positions < 1: raise ValueError("a recurrent proposal head corrects at least one position per row") self.rank, self.softcap, self.positions = rank, weights.softcap, positions @@ -48,12 +53,13 @@ def __init__(self, weights, tokens, *, positions, session, name): embedding = torch.empty((rows, rank), dtype=torch.bfloat16, device=device) dynamic = torch.empty((rows, 2 * rank), dtype=torch.bfloat16, device=device) context = torch.empty((rows * positions, 2 * hidden), dtype=torch.bfloat16, device=device) - fixed = torch.empty((rows * positions, 3 * rank), dtype=torch.float32, device=device) + fixed = torch.empty((rows * positions, 3 * rank), dtype=torch.float32 if bf16 else torch.bfloat16, + device=device) raw = torch.empty((rows, 3 * rank), dtype=torch.float32, device=device) self.embed = PreparedEmbedding(weights.embedding, tokens, embedding, session=session, name=name + ".embedding").functional(session=session, dynamic_inputs=True) - self.context = UnquantizedProjection(context, weights.context_weight, fixed, - session=session, name=name + ".context").functional(session=session) + self.context = prepare_projection(context, weights.context_weight, fixed, session=session, + name=name + ".context", workspace=workspace, activation_mode="a16").functional(session=session) self.dynamic = UnquantizedProjection(dynamic, weights.state_weight, raw, session=session, name=name + ".dynamic").functional(session=session) self.output_bias = None diff --git a/ignition/recipes/inkling2/bootstrap.py b/ignition/recipes/inkling2/bootstrap.py index a85182197..090f96052 100644 --- a/ignition/recipes/inkling2/bootstrap.py +++ b/ignition/recipes/inkling2/bootstrap.py @@ -78,7 +78,8 @@ class PreparationConfig: # Proposal-only quantized copies derived from checkpoint values at load; None keeps BF16. draft_head_quantization: str | None = None markov_head_quantization: str | None = None - # Stores the attention input and output projections as MXFP8 at load; False keeps the checkpoint's BF16. + # Stores the target's attention input and output projections, and the drafter's query/key/value, attention + # output and recurrent context projections, as MXFP8 at load; False keeps the checkpoint's BF16. online_mxfp8: bool = False benchmark_selection: object | None = None diff --git a/ignition/recipes/inkling2/dspark.py b/ignition/recipes/inkling2/dspark.py index 83095c9e6..18c9bf41d 100644 --- a/ignition/recipes/inkling2/dspark.py +++ b/ignition/recipes/inkling2/dspark.py @@ -1,7 +1,13 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Inkling2 noncausal DSpark blocks and accepted target-feature context storage.""" +"""Inkling2 noncausal DSpark blocks and accepted target-feature context storage. + +The query/key/value and attention output projections and the recurrent head's context projection +multiply BF16 activations by the sidecar's BF16 weights or by MXFP8 weights (`DraftWeights.load` with +`online_mxfp8`). The key/value projection of accepted target taps, which also runs on every prefill +row, always multiplies by BF16 weights. +""" from dataclasses import dataclass @@ -18,6 +24,7 @@ from ignition.components.state import gather_rows, save_hidden from ignition.preparation.persistent import persistent_copy, persistent_zeros +from .attention import prepare_projection from .dspark_state import (block_inputs, context_slots, mix_features, rotary_table, rotate, stage, tail_plan, window_plan) @@ -128,8 +135,8 @@ def __init__(self, index, weights, config, scratch, metadata, pool, *, shard, ru d = config.draft self.query_shape, self.key_shape = tuple(scratch.query.shape), tuple(scratch.key.shape) self.window, self.local = d.window, index in d.local_layers - self.qkv = UnquantizedProjection(scratch.hidden, weights.qkv, scratch.qkv, - session=session, name=name + ".qkv").functional(session=session) + self.qkv = prepare_projection(scratch.hidden, weights.qkv, scratch.qkv, + session=session, name=name + ".qkv", workspace=workspace).functional(session=session) self.query_norm = norm(scratch.query.flatten(0, 1), weights.query_norm, scratch.query.flatten(0, 1), eps=d.text["rms_norm_eps"], session=session, name=name + ".q_norm") self.key_norm = norm(scratch.key.flatten(0, 1), weights.key_norm, scratch.key.flatten(0, 1), @@ -161,8 +168,8 @@ def __init__(self, index, weights, config, scratch, metadata, pool, *, shard, ru session=session, k_cache=None, v_cache=None, cache_seqlens=None, cu_seqlens_q=None, **({} if self.local else {"page_table": None, "tail_key": None, "tail_value": None})) heads = scratch.attended.flatten(1) - self.output = UnquantizedProjection(heads, weights.output, scratch.partial, - session=session, name=name + ".output").functional(session=session) + self.output = prepare_projection(heads, weights.output, scratch.partial, + session=session, name=name + ".output", workspace=workspace).functional(session=session) self.reduce = PreparedAllReduce(scratch.partial, scratch.hidden, runtime=runtime, coordinator=coordinator, session=session, name=name + ".reduce").functional(session=session) @@ -257,7 +264,7 @@ def __init__(self, weights, scratch, metadata, pool, *, runtime, coordinator, se workspace=workspace).functional(session=session) self.recurrent = PreparedRecurrentProposalHead(weights.draft.recurrent, torch.zeros(metadata.lengths.numel(), dtype=torch.int64, device=device), - positions=self.block - 1, session=session, name=name + ".recurrent") + positions=self.block - 1, session=session, name=name + ".recurrent", workspace=workspace) def release_outputs(self): return self diff --git a/ignition/recipes/inkling2/dspark_weights.py b/ignition/recipes/inkling2/dspark_weights.py index 8d7652ac3..99eb2aaa4 100644 --- a/ignition/recipes/inkling2/dspark_weights.py +++ b/ignition/recipes/inkling2/dspark_weights.py @@ -1,7 +1,12 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Tensor partitions for Inkling2's dense DSpark decoder and its optional quantized proposal heads.""" +"""Tensor partitions for Inkling2's dense DSpark decoder and its optional quantized proposal heads. + +The query/key/value and attention output projections and the recurrent head's context projection keep +the sidecar's BF16 weights, or hold them as MXFP8 (`DraftWeights.load` with `online_mxfp8`). The +key/value projection of accepted target taps keeps BF16. +""" from dataclasses import dataclass from functools import cached_property @@ -12,7 +17,7 @@ from ignition.components.markov_sampling import fp8_markov_head from ignition.components.vocabulary import mxfp8_draft_head, nvfp4_draft_head -from ignition.components.weights import DirectWeightLoader, MLPWeights +from ignition.components.weights import DirectWeightLoader, MLPWeights, quantize_bf16_linear_as_mxfp8 from ignition.preparation.checkpoint import IndexedCheckpoint, _read_header from ignition.preparation.persistent import persistent_copy, persistent_empty @@ -64,9 +69,16 @@ def index_path(self): @dataclass(frozen=True) class DraftLayerWeights: - qkv: torch.Tensor + """One rank's tensors of one draft layer. + + `qkv` fuses this rank's query, key and value rows and `output` holds the columns of this rank's + heads: BF16 tensors, or b12x MXFP8 weights under online conversion. `context_kv` holds this rank's + key and value rows for accepted target taps as BF16. + """ + + qkv: object context_kv: torch.Tensor - output: torch.Tensor + output: object query_norm: torch.Tensor key_norm: torch.Tensor context_key_norm: torch.Tensor @@ -87,7 +99,8 @@ def _transient(shape, dtype, device): class RecurrentWeights: embedding: torch.Tensor state_weight: torch.Tensor - context_weight: torch.Tensor + # Columns for the draft hidden state and the target context: BF16, or MXFP8 under online conversion. + context_weight: object bias: torch.Tensor # Vocabulary rows by recurrent rank: BF16, or row-scaled E4M3 when the correction head is quantized. head: object @@ -128,12 +141,17 @@ class DraftWeights: @classmethod def load(cls, snapshot, config, device, shard, *, target_head, progress=None, - draft_head_quantization=None, markov_head_quantization=None): + draft_head_quantization=None, markov_head_quantization=None, online_mxfp8=False): """Load one rank's drafter and derive its proposal heads from checkpoint values. `draft_head_quantization` (`nvfp4` or `mxfp8`) adds a quantized copy of `target_head` for the block's vocabulary logits. `markov_head_quantization` (`fp8`) stores the recurrent correction head, the output map folded through `target_head`, as row-scaled E4M3. The target head keeps BF16. + `online_mxfp8` stores each layer's fused query/key/value projection and attention output + projection, and the recurrent head's context projection, as MXFP8: E4M3 values with one + power-of-two scale per 32 input columns of each output row. Each layer's key/value projection of + accepted target taps, the recurrent state projection, embeddings, norms, the checkpoint's MXFP8 + feed-forward weights and both proposal heads keep their precision. """ if draft_head_quantization not in (None, *DRAFT_HEAD_FORMATS): raise ValueError("Inkling2 draft head quantization must be omitted, nvfp4 or mxfp8") @@ -147,6 +165,10 @@ def load(cls, snapshot, config, device, shard, *, target_head, progress=None, q_rows = shard.partition(d.heads * d.head_dim, alignment=d.head_dim) kv_rows = shard.partition(d.kv_heads * d.head_dim, alignment=d.head_dim) intermediate = shard.partition(d.text["intermediate_size"], alignment=32) + + def stored(weight): + return quantize_bf16_linear_as_mxfp8(weight, retain_scale_rows=False) if online_mxfp8 else weight + with DraftWeightLoader(manifest, device, progress=progress, progress_label="Load DSpark weights") as loader: loader.quantization @@ -160,11 +182,11 @@ def vector(name, width): for index in range(d.layers): prefix = f"layers.{index}" attention = prefix + ".self_attn." - qkv = loader.load_linear_group(tuple(attention + role + "_proj" for role in ("q", "k", "v")), - row_ranges=(q_rows, kv_rows, kv_rows)) + qkv = stored(loader.load_linear_group(tuple(attention + role + "_proj" for role in ("q", "k", "v")), + row_ranges=(q_rows, kv_rows, kv_rows), temporary=online_mxfp8)) context = loader.load_linear_group(tuple(attention + role + "_proj_ctx" for role in ("k", "v")), row_ranges=(kv_rows, kv_rows)) - output = loader.load_linear(attention + "o_proj", columns=q_rows) + output = stored(loader.load_linear(attention + "o_proj", columns=q_rows, temporary=online_mxfp8)) mlp = MLPWeights(loader.load_linear_group(tuple(prefix + ".mlp." + role + "_proj" for role in ("gate", "up")), row_ranges=(intermediate, intermediate)), loader.load_linear(prefix + ".mlp.down_proj", columns=intermediate)) @@ -192,8 +214,9 @@ def vector(name, width): folded, head_bias = fold_recurrent_head(target_head, hidden_out, hidden_bias, allocate=_transient) head = fp8_markov_head(folded) del folded + context_weight = state[:, 2 * rank:].contiguous() recurrent = RecurrentWeights(embedding, persistent_copy(state[:, :2 * rank].contiguous()), - persistent_copy(state[:, 2 * rank:].contiguous()), persistent_copy(vector("markov_head.rnn_proj.bias", 3 * rank).float()), + stored(context_weight) if online_mxfp8 else persistent_copy(context_weight), persistent_copy(vector("markov_head.rnn_proj.bias", 3 * rank).float()), head, head_bias, vector("markov_head.dflare_norm.weight", hidden)) draft_head = (None if draft_head_quantization is None else DRAFT_HEAD_FORMATS[draft_head_quantization](target_head)) diff --git a/ignition/recipes/inkling2/recipe.py b/ignition/recipes/inkling2/recipe.py index fdbd8bf88..c1c3825e4 100644 --- a/ignition/recipes/inkling2/recipe.py +++ b/ignition/recipes/inkling2/recipe.py @@ -55,7 +55,8 @@ def usage(prepared): sampling_defaults=SAMPLING_DEFAULTS, # Proposal-only copies: the block's vocabulary head, and the recurrent correction head as row-scaled E4M3. draft_head_quantizations=("nvfp4", "mxfp8"), markov_head_quantizations=("fp8",), - # The attention input and output projections of every decoder layer. + # The attention input and output projections of every decoder layer, and the drafter's query/key/value, + # attention output and recurrent context projections. online_mxfp8=True, checkpoints=(Checkpoint(alias="inkling-2-small-nvfp4", repository="/data/models/Inkling-2-Small-NVFP4", revision="local", architecture="Inkling2ForConditionalGeneration", stored_bytes=344_366_116_864, diff --git a/ignition/recipes/inkling2/weights.py b/ignition/recipes/inkling2/weights.py index e39e4e5bb..11310e9d7 100644 --- a/ignition/recipes/inkling2/weights.py +++ b/ignition/recipes/inkling2/weights.py @@ -74,7 +74,9 @@ def embed_norm(self): @classmethod def load(cls, manifest, device, *, shard, progress=None, drafting=True, vision=True, layers=None, draft_head_quantization=None, markov_head_quantization=None, online_mxfp8=False): - """`online_mxfp8` stores each layer's attention input and output projections as MXFP8.""" + """`online_mxfp8` stores each decoder layer's attention input and output projections, and the + drafter's query/key/value, attention output and recurrent context projections + (`DraftWeights.load`), as MXFP8.""" before = torch.cuda.memory_allocated(device) with InklingWeightLoader(manifest, device, shard=shard, progress=progress, vision=vision, online_mxfp8=online_mxfp8) as loader: @@ -109,7 +111,8 @@ def vocabulary_rows(name): if drafting: from .dspark_weights import DraftWeights draft = DraftWeights.load(manifest.snapshot, c, device, shard, target_head=head, progress=progress, - draft_head_quantization=draft_head_quantization, markov_head_quantization=markov_head_quantization) + draft_head_quantization=draft_head_quantization, markov_head_quantization=markov_head_quantization, + online_mxfp8=online_mxfp8) return cls(c, shard, loaded, embedding, embed_norm, norm, query, head, torch.cuda.memory_allocated(device) - before, draft, tower) diff --git a/tests/components/test_inkling2_dspark.py b/tests/components/test_inkling2_dspark.py index c2f727db5..7cd9efddc 100644 --- a/tests/components/test_inkling2_dspark.py +++ b/tests/components/test_inkling2_dspark.py @@ -247,6 +247,26 @@ def test_block_context_projection_matches_one_projection_per_position(): operation.project_context(states[:, :3], context) +def test_block_context_projection_adds_the_fp32_bias_to_a_bf16_projection(): + """An MXFP8 context weight projects to BF16; the recurrence input is that rounding plus the FP32 bias.""" + generator = torch.Generator().manual_seed(19) + rows, positions, hidden, rank, vocabulary = 3, 7, 16, 8, 24 + weight = (torch.randn(3 * rank, 2 * rank + 2 * hidden, generator=generator) / 8).bfloat16() + bias = torch.randn(3 * rank, generator=generator) / 8 + head = (torch.randn(vocabulary, rank, generator=generator) / 4).bfloat16() + head_bias = (torch.randn(vocabulary, generator=generator) / 4).bfloat16() + states = torch.randn(rows, positions, hidden, generator=generator).bfloat16() + context = torch.randn(rows, hidden, generator=generator).bfloat16() + operation = _recurrent_head(weight, bias, head, head_bias, positions, row_scaled=False) + exact = operation.context + operation.context = lambda source: exact(source).bfloat16() + fixed = operation.project_context(states, context) + assert fixed.shape == (rows, positions, 3 * rank) and fixed.dtype == torch.float32 + for index in range(positions): + source = torch.cat((states[:, index], context), -1) + assert torch.equal(fixed[:, index], exact(source).bfloat16().float() + bias) + + def test_row_scaled_correction_adds_the_bf16_bias_in_fp32_before_bf16_rounding(): generator = torch.Generator().manual_seed(21) rows, hidden, rank, vocabulary = 2, 16, 8, 24 diff --git a/tests/components/test_inkling2_dspark_cuda.py b/tests/components/test_inkling2_dspark_cuda.py index 4a837f851..8a3099590 100644 --- a/tests/components/test_inkling2_dspark_cuda.py +++ b/tests/components/test_inkling2_dspark_cuda.py @@ -501,6 +501,120 @@ def test_checkpoint_draft_aot_reads_only_selected_mapped_context_rows(tmp_path): graph.reset() +def _stored_matrix(weight): + """The matrix an MXFP8 weight stores, in FP64.""" + from b12x.gemm._shared.wo_mxfp8 import dequantize_mxfp8_rows_torch, materialize_mxfp8_scale_rows + + rows = weight.weight + return dequantize_mxfp8_rows_torch(rows.values, materialize_mxfp8_scale_rows(rows))[:, :weight.in_features].double() + + +@pytest.mark.parametrize("layer", [0, 2]) +@pytest.mark.parametrize("requests,compiled", [(1, False), (4, True)]) +@torch.no_grad() +def test_checkpoint_draft_projects_with_stored_mxfp8_weights(layer, requests, compiled): + """Online MXFP8 stores each draft layer's query/key/value and output projections and the recurrent head's + context projection; each kernel multiplies BF16 activations by the stored values, and the drafter's other + tensors, including the key/value projection of accepted target taps, keep checkpoint bits.""" + from b12x.gemm.blockscaled._linear import MXFP8LinearWeight + from ignition.recipes.inkling2.config import ModelConfig + + snapshot = os.environ.get("FLARE_INKLING2_SNAPSHOT") + if snapshot is None: + pytest.skip("requires FLARE_INKLING2_SNAPSHOT") + device, block = torch.device("cuda:0"), 8 + torch.cuda.set_device(device) + config, shard = ModelConfig.load(snapshot), TensorParallelShard(0, 4) + d, hidden = config.draft, config.text["hidden_size"] + with DirectWeightLoader(inspect_indexed_checkpoint(snapshot), device) as loader: + head = loader.load_tensor("lm_head.weight", extent=(slice(0, 50304), slice(None))) + checkpoint, draft = (DraftWeights.load(snapshot, config, device, shard, target_head=head, online_mxfp8=online) + for online in (False, True)) + + def same_bits(stored, original): + if isinstance(original, MXFP8LinearWeight): + assert torch.equal(stored.weight.values.view(torch.uint8), original.weight.values.view(torch.uint8)) + assert torch.equal(stored.weight.scale_mma.view(torch.uint8), original.weight.scale_mma.view(torch.uint8)) + else: + assert stored.dtype == original.dtype and torch.equal(stored, original) + + converted = [(stored_layer, original_layer, field) + for stored_layer, original_layer in zip(draft.layers, checkpoint.layers, strict=True) + for field in ("qkv", "output")] + converted.append((draft.recurrent, checkpoint.recurrent, "context_weight")) + for stored_owner, original_owner, field in converted: + stored, original = getattr(stored_owner, field), getattr(original_owner, field) + assert isinstance(stored, MXFP8LinearWeight) and stored.weight.scale_rows is None + assert original.dtype == torch.bfloat16 + expanded = _stored_matrix(stored) + assert expanded.shape == original.shape + assert ((expanded - original.double()).norm() / original.double().norm()).item() < .035, field + for stored_layer, original_layer in zip(draft.layers, checkpoint.layers, strict=True): + for field in ("context_kv", "query_norm", "key_norm", "context_key_norm", "context_norm", "input_norm", + "post_attention_norm"): + same_bits(getattr(stored_layer, field), getattr(original_layer, field)) + same_bits(stored_layer.mlp.gate_up, original_layer.mlp.gate_up) + same_bits(stored_layer.mlp.down, original_layer.mlp.down) + for field in ("alpha", "mask_embedding", "norm"): + same_bits(getattr(draft, field), getattr(checkpoint, field)) + for field in ("embedding", "state_weight", "bias", "head", "head_bias", "context_norm"): + same_bits(getattr(draft.recurrent, field), getattr(checkpoint.recurrent, field)) + assert draft.draft_head is None and checkpoint.draft_head is None + del checkpoint + + tokens = requests * block + kv_heads = d.kv_heads // shard.world_size + def zeros(*shape): + return torch.zeros(shape, dtype=torch.bfloat16, device=device) + regions = {f"draft{index}.{kind}": zeros(requests + 1, d.window, kv_heads, d.head_dim) + for index in sorted(d.local_layers) for kind in ("key", "value")} + regions["draft.rnn_context"] = zeros(requests + 1, hidden) + key, value = zeros(2 * requests, 128, kv_heads, d.head_dim), zeros(2 * requests, 128, kv_heads, d.head_dim) + pool = SimpleNamespace(reserved_region=regions.__getitem__, key=lambda *args, **kwargs: key, + value=lambda *args, **kwargs: value) + m = Metadata.pack(torch.full((requests,), 127, device=device), torch.full((requests,), block, device=device), + torch.arange(1, requests + 1, device=device), + torch.arange(2 * requests, dtype=torch.int32, device=device).view(requests, 2), + torch.zeros(requests, block, dtype=torch.int64, device=device), + torch.tensor([requests], dtype=torch.int32, device=device), token_capacity=tokens, sample_count=tokens) + scratch = DraftScratch.allocate(config, shard, tokens, block, device) + pending = torch.zeros(requests, dtype=torch.int64, device=device) + with RecordedPreparationSession(device=device, checkpoint="inkling2-checkpoint-draft-mxfp8", + workload_schema="inkling2-checkpoint-draft", numerical_policy="default", autotune_effort="off") as session: + arena = ScratchArena(device) + session.register_scratch(arena) + attention = DraftAttention(layer, draft.layers[layer], config, scratch, m, pool, shard=shard, + runtime=None, coordinator=None, session=session, name="attention", workspace=arena) + recurrent = PreparedRecurrentProposalHead(draft.recurrent, pending, positions=block - 1, + session=session, name="recurrent", workspace=arena) + session.tune() + torch.manual_seed(layer) + def activations(rows, width): + return torch.randn(rows, width, device=device).bfloat16() + sources = (activations(tokens, hidden), activations(tokens, attention.query_shape[1] * d.head_dim), + activations(requests * (block - 1), 2 * hidden)) + def forward(): + return attention.qkv(sources[0]), attention.output(sources[1]), recurrent.context(sources[2]) + if compiled: + from ignition.preparation.compilation import compile_forward + forward = compile_forward(forward) + outputs = forward() + torch.cuda.synchronize() + + def within_accumulation(actual, source, weight): + # FP32 accumulation of the products, then one rounding to BF16. + exact, magnitude = source.double() @ weight.T, source.double().abs() @ weight.abs().T + terms = source.shape[1] + gamma = terms * 2 ** -24 / (1 - terms * 2 ** -24) + return (((actual.double() - exact).abs() - gamma * magnitude - 2 ** -8 * exact.abs()).max() <= 0).item() + + stored = (draft.layers[layer].qkv, draft.layers[layer].output, draft.recurrent.context_weight) + for name, actual, source, weight in zip(("qkv", "output", "recurrent_context"), outputs, sources, stored, + strict=True): + assert actual.dtype == torch.bfloat16 and actual.shape == (source.shape[0], weight.out_features), name + assert within_accumulation(actual, source, _stored_matrix(weight)), name + + @torch.no_grad() def test_checkpoint_sidecar_preserves_fp8_values_scales_and_feature_coefficients(): from b12x.gemm._shared.wo_mxfp8 import materialize_mxfp8_scale_rows From 34fa07e2777346722b79bb133a7753a586faa277 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Mon, 16 Nov 2026 11:09:55 -0500 Subject: [PATCH 10/11] Store the Inkling 2 vocabulary head as MXFP8 with --online-mxfp8-scope with-vocabulary-head Every Inkling 2 decode and verification round multiplies the final hidden rows by the rank's BF16 unembedding shard, 463 MB per TP4 rank. On a GB10 that projection runs at the memory rate and takes 1.89 ms of a 23.2 ms one-token round with one request, and it is paid once per round whatever the number of requests. --online-mxfp8 stores the attention and DSpark projections as MXFP8 and leaves this shard in BF16. The Inkling 2 recipe declares two --online-mxfp8-scope groups. `all`, the default, is the existing conversion set, and a core exported with --online-mxfp8 alone records it. `with-vocabulary-head` also converts each rank's unembedding shard with mxfp8_draft_head and releases the BF16 rows after the drafter's proposal heads are derived from them. PreparedLogits and PreparedVocabularyProjection bind the packed shard through WidenedQuantizedProjection in ignition/components/vocabulary.py: b12x's A16 packed-weight kernel stores BF16, and the result is widened to FP32, so the softcap, the valid-vocabulary mask, the cross-rank gather, sampling, log-probabilities, resumed sampling and DSpark verification receive FP32 values in the layouts they have with a BF16 shard. Proposals read the drafter's quantized copy when it has one and otherwise the target's shard as stored; with --draft-head-quantization mxfp8 no duplicate is held. The scope enters the tuning identity and the rebuild manifest. No kernel, Helios code, Protobuf field or package contract changes. With the group selected, a round reads 239 MB of vocabulary weights per rank and each logit is an FP32 sum rounded to BF16 before the softcap. Unlike a quantized proposal head, this changes the distribution that sampling and verification use. Cores exported without the group are unchanged. Evidence: on a GB10, over the final hidden states of 1,536 positions of prose and source code, the MXFP8 shard's softcapped logits differ from the BF16 shard's by 0.084 on average and 0.93 at most at a softcap of 30; the most likely token agrees at 99.48% of positions, and at the eight others the BF16 shard's two largest logits are within 0.07; the KL divergence at temperature 1 has mean 3.6e-4 and maximum 7.7e-3; next-token accuracy is 60.33% against 60.39%. Rounding the BF16 shard's logits to BF16 alone gives 99.54% agreement and mean divergence 5.3e-5. With the checkpoint, tests/recipes/test_inkling2_target.py and test_inkling2_vocabulary_cuda.py -k checkpoint pass 30 of 30, the Inkling 2 CLI and planning tests pass 214 with the 2 failures the parent commit has, and the DSpark, sampling, commit, packed-speculation and draft-head component tests pass 178 with the parent's 11 failures, all of which need the qualification feature. One core exported with the group served at TP4 on four DGX Sparks with 32 requests and 8,192-token chunks: tests/server/test_inkling2.py -k default-effort passes 7 of 7, 32 concurrent requests return the expected values, and a 67,150-token lookup is correct at three seeds. A rank-0 kernel trace gives 0.94 ms for the vocabulary projection. One-token rounds take 22.2, 30.3 and 41.5 ms of GPU time at one, two and four requests against 22.4, 31.5 and 42.6 ms for the core exported from the parent commit. With a distinct sampling seed per stream, three decode benchmark passes against two give 67.1 to 67.6 tokens/s against 63.4 to 63.7 at two requests, 92.3 to 94.0 against 88.7 at four and 125.8 to 128.6 against 120.1 to 120.8 at eight, at an 8,192-token context, with the same order at 32,768 and 131,072 tokens; single-request decode is 44.9 to 48.0 against 42.5 to 51.6. Coding medians are 63.6, 47.1 and 67.7 tokens/s against 65.5 and 62.7. Limitations: the first export with the group failed when a compile worker could not create its CUDA context on rank 0 and an unchanged second export succeeded; host memory during both followed exports of the parent commit, and the cause is not established. Output quality beyond the logit comparison and the serving checks was not evaluated. Draft acceptance on article text was sampled on 46 offers. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/cli-design.md | 4 +- docs/model-preparation.md | 62 ++++++++- ignition/cli/__init__.py | 4 +- ignition/components/vocabulary.py | 44 ++++++- ignition/recipes/declaration.py | 3 +- ignition/recipes/inkling2/bootstrap.py | 22 +++- ignition/recipes/inkling2/decoder.py | 8 +- ignition/recipes/inkling2/dspark.py | 10 +- ignition/recipes/inkling2/dspark_weights.py | 6 +- ignition/recipes/inkling2/recipe.py | 7 +- ignition/recipes/inkling2/vocabulary.py | 25 +++- ignition/recipes/inkling2/weights.py | 29 ++-- tests/cli/test_inkling2.py | 66 +++++++++- tests/components/test_draft_head_cuda.py | 28 ++++ .../recipes/test_inkling2_vocabulary_cuda.py | 124 ++++++++++++++++++ 15 files changed, 396 insertions(+), 46 deletions(-) create mode 100644 tests/recipes/test_inkling2_vocabulary_cuda.py diff --git a/docs/cli-design.md b/docs/cli-design.md index 0af4c3f31..bfd84b4c8 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -469,8 +469,8 @@ explicit flags take precedence. | `--no-compile` | Development only: capture graphs without compiling forwards. A recipe never sets it. | off | | `--force-moe-decode-a16` / `--no-force-moe-decode-a16` | Prepare Qwen3.8 Flash NVFP4 target routed experts as one packed weight owner: decode and speculative verification use W4A16 at every token-row count, and separate prefill graphs use calibrated A4. Requires SM120/121, checkpoint activation scales, and rank-local expert intermediate width divisible by 64 (TP1/2). Mixed prefill and other recipes/precisions reject the flag. Shared experts and stored A16 MTP experts retain their precision. Overrides `[preparation] force_moe_decode_a16`; the resolved value is recorded in the plan and core rebuild metadata. | off | | `--native-dense-activations` | Replace dense projection `auto` precision with b12x `quantized`: A8 for FP8 weights and A4 for FP4 weights. Explicit recipe precision and routed MoE precision are retained. NVFP4 requires a checkpoint activation global scale; unsupported native paths fail preparation. | Recipe precision | -| `--online-mxfp8` | Store eligible BF16 projections as MXFP8 while loading. Kimi K3.1 converts fused target KDA inputs by default; `--online-mxfp8-scope all` also converts eligible attention output/latent projections, shared experts, MoE latent projections, and DFlash2 draft projections. Kimi K3 converts KDA projections, MLA latent/gate, query and output projections, shared experts, MoE latent down/up projections, and DSpark context, outputs and MLPs; batched MLA key/value projections retain BF16. Qwen3.8 dense converts target attention/MLP projections and DFlash2 context, attention and MLP projections. Flash Next with `--speculative-method dflash2` converts only DFlash2 projections; target precision is retained. Inkling 2 converts every decoder layer's fused attention input projections and its attention output projection, with BF16 activations in prefill, decoding and verification, and DSpark's query/key/value and attention output projections and its recurrent head's context projection; routers, experts, DSpark's key/value projections of accepted target taps, its feed-forward weights and proposal heads, and the vision encoder retain their precision. Existing packed weights, normalization, convolutions, selectors and target vocabulary weights retain their precision. Recipes that name no such projections reject it. | Checkpoint precision | -| `--online-mxfp8-scope SCOPE` | Select a conversion group declared by the recipe. Kimi K3.1 supports `kda-input` and `all`; the broader group changes target as well as DFlash2 draft projection storage. Other recipes retain their declared conversion set. Command line only; requires `--online-mxfp8` for a non-default group. | Recipe scope | +| `--online-mxfp8` | Store eligible BF16 projections as MXFP8 while loading. Kimi K3.1 converts fused target KDA inputs by default; `--online-mxfp8-scope all` also converts eligible attention output/latent projections, shared experts, MoE latent projections, and DFlash2 draft projections. Kimi K3 converts KDA projections, MLA latent/gate, query and output projections, shared experts, MoE latent down/up projections, and DSpark context, outputs and MLPs; batched MLA key/value projections retain BF16. Qwen3.8 dense converts target attention/MLP projections and DFlash2 context, attention and MLP projections. Flash Next with `--speculative-method dflash2` converts only DFlash2 projections; target precision is retained. Inkling 2 converts every decoder layer's fused attention input projections and its attention output projection, with BF16 activations in prefill, decoding and verification, and DSpark's query/key/value and attention output projections and its recurrent head's context projection; routers, experts, DSpark's key/value projections of accepted target taps, its feed-forward weights and proposal heads, and the vision encoder retain their precision. Existing packed weights, normalization, convolutions, selectors and target vocabulary weights retain their precision; Inkling 2's `with-vocabulary-head` group is the exception for vocabulary weights. Recipes that name no such projections reject it. | Checkpoint precision | +| `--online-mxfp8-scope SCOPE` | Select a conversion group declared by the recipe. Kimi K3.1 supports `kda-input` and `all`; the broader group changes target as well as DFlash2 draft projection storage. Inkling 2 supports `all`, its default, and `with-vocabulary-head`, which adds each rank's target vocabulary shard and so changes the logits that sampling and DSpark verification read. Other recipes retain their declared conversion set. Command line only; requires `--online-mxfp8` for a non-default group. | Recipe scope | | `--language-model-only` | Prepare no vision encoder and serve text only, as vLLM's flag of the same name; requests with images are rejected and the encoder's weights, scratch, and graphs become KV pages. Recipes without a separable encoder reject it. | The recipe's image support | Speculative method, token capacity, and packed graph budget also accept diff --git a/docs/model-preparation.md b/docs/model-preparation.md index d38ac2d69..a3d44f20f 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1333,9 +1333,10 @@ per rank. `--draft-head-quantization nvfp4` or `mxfp8` prepares a quantized copy of the target's vocabulary shard that only proposals read, and `--markov-head-quantization fp8` stores the folded correction head as E4M3 values with one FP32 scale per vocabulary row. Both are computed at load from -checkpoint values; target verification keeps the BF16 head, so a quantized -proposal head changes which tokens are proposed and how often they are -accepted, never the output distribution. The default omits both flags. +checkpoint values; target verification reads the target's own vocabulary +shard, so a quantized proposal head changes which tokens are proposed and how +often they are accepted, never the output distribution. The default omits both +flags. `--online-mxfp8` stores every decoder layer's attention projections as MXFP8 while loading: the fused input projections (query, output gate, key, value, @@ -1346,9 +1347,10 @@ do not depend on the rows fused with it. Activations stay BF16 in prefill, decoding, and verification, which therefore project with the same weight values, and the output projection writes BF16 partial sums. A TP4 rank then reads 1.22 GB of attention projection weights per decode step where BF16 reads -2.36 GB, and holds 1.14 GB less. Routers, vocabulary shards, convolutions, -norms, clip scales, the relative-logit projection, experts, and the vision -encoder keep checkpoint precision. The default omits the flag. +2.36 GB, and holds 1.14 GB less. Routers, convolutions, norms, clip scales, +the relative-logit projection, experts, and the vision encoder keep checkpoint +precision, as do the vocabulary shards unless the plan selects the +`with-vocabulary-head` group described below. The default omits the flag. The flag also stores three of DSpark's BF16 projections in the same MXFP8 form, with BF16 activations: each of the five draft layers' fused @@ -1390,6 +1392,54 @@ requests and 49.8 to 50.0 ms with four, against 35.4 to 36.7 ms and 52.0 to against 40.7 to 43.1 s: MXFP8 weights with BF16 activations project an 8,192-row chunk more slowly than BF16 weights. +`--online-mxfp8 --online-mxfp8-scope with-vocabulary-head` selects a larger +conversion group: the projections above and each rank's unembedding shard, +50,256 vocabulary rows by 4,608 values at TP4, in the same MXFP8 form. The +default group, `all`, keeps the shard in BF16, and a core exported with +`--online-mxfp8` alone records `all`. Every decode and verification round +reads the shard once: 239 MB as MXFP8 and 463 MB as BF16. b12x's +packed-weight kernels multiply BF16 activations and store BF16, so each logit +of the MXFP8 shard is an FP32 sum rounded to BF16 before the FP32 softcap, +where the BF16 shard's logit stays FP32. The softcap, the valid-vocabulary +mask, the cross-rank gather, sampling, log-probabilities, resumed sampling, +and DSpark verification receive FP32 values in the same layouts under either +group. Unlike a quantized proposal head, this group changes the distribution +that verification and sampling use. The proposal heads are still derived from +the BF16 rows, which the rank releases after converting them. With +`--draft-head-quantization mxfp8` the proposal head would repeat the target's +stored values, so proposals read the target's shard; without a quantized +proposal head they read it too. + +The MXFP8 shard's stored weights differ from the checkpoint's by 2.7% in +relative norm. On the final hidden states of 1,536 positions of prose and +source code, computed by the Transformers reference layers with MXFP8 +attention projections and E4M3 key/value history, the recipe's logit kernels +on a GB10 give softcapped logits that differ between the two shard formats by +0.084 on average and by at most 0.93, at a softcap of 30. The two formats +agree on the most likely token at 99.48% of positions; at each of the eight +others the BF16 shard's two largest logits are within 0.07 of each other. The +Kullback-Leibler divergence of the MXFP8 shard's distribution from the BF16 +shard's at temperature 1 has mean 3.6e-4, 99th percentile 2.1e-3, and maximum +7.7e-3, and next-token accuracy is 60.33% against 60.39%. The stored weights +account for most of this: with exact products of the stored weights the +agreement is 99.61% and the mean divergence 3.1e-4, while rounding the BF16 +shard's logits to BF16 gives 99.54% and 5.3e-5 and leaves the two largest +logits exactly equal at 0.8% of positions. The BF16 kernel repeats bit for +bit and differs from exact products by at most 1.5e-4. +`tests/recipes/test_inkling2_vocabulary_cuda.py` checks on SM120, with the +checkpoint's shards of ranks 0 and 3, that loading stores the converted +values and shares them with proposals, that the kernels at 1, 4, 8, and 128 +rows multiply by the stored values, and that the softcapped FP32 logits stay +within the stored weights' distance of the BF16 shard's. + +On four DGX Sparks at TP4 with 32 requests and 8,192-token chunks, a core +exported with the `with-vocabulary-head` group fixes 83.52 GiB of device +memory per rank where a core exported with the `all` group fixes 83.73 GiB. +In a rank-0 kernel trace of one-token rounds with one request, the vocabulary +projection takes 0.94 ms against 1.89 ms. Over load at one to four requests, a +one-token round takes a mean 22.2 ms of GPU time with one request, 30.3 ms +with two, and 41.5 ms with four, against 22.4, 31.5, and 42.6 ms. + Export with default tuning and Torch compilation: ```sh diff --git a/ignition/cli/__init__.py b/ignition/cli/__init__.py index 63f60d8f5..4e7b0ca35 100644 --- a/ignition/cli/__init__.py +++ b/ignition/cli/__init__.py @@ -261,7 +261,9 @@ def _preparation_arguments(running, *, model_default="defaults.model"): " default: checkpoint precision)") advanced.add_argument("--online-mxfp8-scope", metavar="SCOPE", help="select the recipe's online MXFP8 conversion group; Kimi K3.1 supports all" - " (every eligible target and DFlash2 projection) or kda-input (default: recipe scope)") + " (every eligible target and DFlash2 projection) or kda-input; Inkling 2 supports all" + " (attention and DSpark projections) or with-vocabulary-head, which also stores the" + " target vocabulary head as MXFP8 (default: recipe scope)") advanced.add_argument("--language-model-only", action="store_true", help="prepare no vision encoder and reject images; its weights and scratch become KV" " pages (recipes with a separable encoder; default: the recipe's image support)") diff --git a/ignition/components/vocabulary.py b/ignition/components/vocabulary.py index 5ceff8fe1..35873af67 100644 --- a/ignition/components/vocabulary.py +++ b/ignition/components/vocabulary.py @@ -12,12 +12,45 @@ from .linear import QuantizedProjection, UnquantizedProjection +class WidenedQuantizedProjection: + """A b12x projection of BF16 rows by a packed weight, delivered as FP32 rows. + + b12x's packed-weight kernels accumulate in FP32 and store BF16. This projection + widens that BF16 result, so a consumer of FP32 logits binds a quantized vocabulary + shard with the output layout it gives an unquantized one. `rounded` is the BF16 + declaration storage of the kernel's output, `[rows, weight.out_features]`. + """ + + def __init__(self, source, weight, output, *, session, name, activation_mode="a16", workspace=None, + rounded=None): + if output.dtype != torch.float32 or output.shape != (source.shape[0], weight.out_features): + raise ValueError("widened projection requires an FP32 [rows, out_features] output") + if rounded is None: + rounded = torch.empty(output.shape, dtype=torch.bfloat16, device=output.device) + elif rounded.shape != output.shape or rounded.dtype != torch.bfloat16 or rounded.device != output.device: + raise ValueError("widened projection requires BF16 kernel output storage of the FP32 output's shape") + self.output = output + self.projection = QuantizedProjection(source, weight, rounded, session=session, name=name, + activation_mode=activation_mode, workspace=workspace) + + def functional(self, *, session): + """Allocate the kernel's BF16 output and the FP32 result inside each forward.""" + self.projection.functional(session=session) + self.output = None + return self + + def __call__(self, source): + projected = self.projection(source) + return projected.float() if self.output is None else self.output.copy_(projected) + + class PreparedVocabularyProjection: """Project replicated hidden rows with a contiguous vocabulary weight shard. Local and full-vocabulary outputs are caller-owned. Every rank participates in the gather; the recipe chooses which rank samples from the full logits. - A quantized shard, such as an NVFP4 draft head, runs as a b12x A16 projection. + A quantized shard, such as an NVFP4 draft head, runs as a b12x A16 projection, + whose BF16 result is widened when the local output is FP32. Unquantized shards honor the output buffer's arithmetic contract; BF16 checkpoint weights can accumulate and produce logits in FP32. Optional row indices expand gathered physical rows into caller-owned sample @@ -41,7 +74,8 @@ def __init__(self, source, weight, local_output, output, *, runtime, session, self.projection = UnquantizedProjection(source, weight, local_output, session=session, name=f"{name}.projection") else: - self.projection = QuantizedProjection(source, weight, local_output, + projection = WidenedQuantizedProjection if local_output.dtype == torch.float32 else QuantizedProjection + self.projection = projection(source, weight, local_output, session=session, name=f"{name}.projection", activation_mode=activation_mode, workspace=workspace) self.local_only = not gather if self.local_only: @@ -146,10 +180,12 @@ def nvfp4_draft_head(weight: torch.Tensor, *, rows_per_chunk: int = 8192): @torch.no_grad() def mxfp8_draft_head(weight: torch.Tensor, *, rows_per_chunk: int = 1024): - """Prepare an MXFP8 proposal head while retaining the BF16 target weights. + """Prepare an MXFP8 copy of a BF16 vocabulary head or shard, leaving the BF16 weights unchanged. Each 32-value input block uses E4M3 values and a power-of-two scale rounded - upward from its maximum magnitude. Chunking bounds conversion storage. + upward from its maximum magnitude. Chunking bounds conversion storage. A proposal + head keeps the BF16 weights for verification; a recipe that stores its target head + as MXFP8 releases them. """ from b12x.gemm._shared.wo_mxfp8 import quantize_mxfp8_rows_torch from b12x.gemm.blockscaled import pack_weight diff --git a/ignition/recipes/declaration.py b/ignition/recipes/declaration.py index c86523f24..51a889153 100644 --- a/ignition/recipes/declaration.py +++ b/ignition/recipes/declaration.py @@ -212,7 +212,8 @@ class Recipe: MXFP8 while loading, trading checkpoint precision for decode bandwidth. `online_mxfp8_scope` selects the conversion group for preparation; `all` selects the complete eligible set. `online_mxfp8_scopes` also accepts groups recorded in - prepared metadata so an explicit precision choice retains its meaning. + prepared metadata so an explicit precision choice retains its meaning. A recipe whose + exported cores record `all` names a group that converts further weights separately. `language_model_only` states that a plan may prepare the recipe without its vision encoder, rejecting images and leaving the encoder's memory to KV pages. `mla_compute_modes` declares the attention arithmetic constraints a plan may select, diff --git a/ignition/recipes/inkling2/bootstrap.py b/ignition/recipes/inkling2/bootstrap.py index 090f96052..70f7869b6 100644 --- a/ignition/recipes/inkling2/bootstrap.py +++ b/ignition/recipes/inkling2/bootstrap.py @@ -81,6 +81,9 @@ class PreparationConfig: # Stores the target's attention input and output projections, and the drafter's query/key/value, attention # output and recurrent context projections, as MXFP8 at load; False keeps the checkpoint's BF16. online_mxfp8: bool = False + # The conversion group `online_mxfp8` selects: `all` is the set above, and `with-vocabulary-head` adds the + # target's unembedding shard, whose logits then come from b12x's BF16-output packed-weight kernels. + online_mxfp8_scope: str = "all" benchmark_selection: object | None = None def __post_init__(self): @@ -122,6 +125,10 @@ def __post_init__(self): raise ValueError("proposal head quantization requires learned speculation with positive draft depth") if type(self.online_mxfp8) is not bool: raise ValueError("Inkling 2 online MXFP8 conversion must be a boolean") + if self.online_mxfp8_scope not in ("all", "with-vocabulary-head"): + raise ValueError("Inkling 2 online MXFP8 scope must be all or with-vocabulary-head") + if self.online_mxfp8_scope != "all" and not self.online_mxfp8: + raise ValueError("Inkling 2 online MXFP8 scope requires online MXFP8 conversion") if self.snapshot_budget_bytes <= 0 or self.headroom_bytes < 0: raise ValueError("snapshot budget must be positive and headroom nonnegative") object.__setattr__(self, "image_concurrency", image_capacity(self.max_active, self.image_concurrency) if self.vision else 0) @@ -135,6 +142,10 @@ def speculative_round_shapes(self): self.speculative_token_capacity, self.speculative_graph_budget, fixed_width=self.speculative_fixed_width) if self.drafting else ()) + @property + def mxfp8_vocabulary_head(self): + return self.online_mxfp8 and self.online_mxfp8_scope == "with-vocabulary-head" + @property def draft_tokens(self): return max(self.speculative_widths) - 1 if self.drafting else 0 @@ -235,7 +246,8 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): progress=progress, drafting=config.drafting, vision=config.vision, draft_head_quantization=config.draft_head_quantization, markov_head_quantization=config.markov_head_quantization, - online_mxfp8=config.online_mxfp8) + online_mxfp8=config.online_mxfp8, + mxfp8_vocabulary_head=config.mxfp8_vocabulary_head) weights_bytes = torch.cuda.memory_allocated(device) if torch.cuda.get_device_properties(device).is_integrated: from ignition.preparation.host_memory import release_page_cache @@ -274,12 +286,13 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): coordinator = CollectivePreparation(group) runtime, vocabulary_runtime, sampling_runtime, logprob_runtime = _collective_runtimes( config, group, device, coordinator=coordinator, core_storage=core_storage, - hidden=text.hidden, local_vocabulary=weights.head.shape[0], + hidden=text.hidden, local_vocabulary=weights.embedding.shape[0], draft_block=model.draft.block) identity = hashlib.sha256(json.dumps({"text": model.text.__dict__ | {"local_layers": sorted(model.text.local_layers)}, "quantization": model.quantization, "headers": headers, "world_size": world, "decoder_layers": len(weights.layers), "contract": "inkling2.paged-text.v1"} - | ({"online_mxfp8": True} if config.online_mxfp8 else {}), + | ({"online_mxfp8": True} if config.online_mxfp8 else {}) + | ({"online_mxfp8_scope": config.online_mxfp8_scope} if config.online_mxfp8_scope != "all" else {}), sort_keys=True, default=str).encode()).hexdigest() session = RecordedPreparationSession(compile_workers=config.compile_workers, native_dense_activations=config.native_dense_activations, lock_gpu_clocks=config.lock_gpu_clocks, @@ -427,7 +440,8 @@ def add(name, forward, kind, rows, tokens, fields, enabled=None, packed=0): reserved_tensor_bytes=torch.cuda.memory_reserved(device), headroom_bytes=config.headroom_bytes, tuning=tuning, compiled_decoder=config.compile_decoder, draft_head_quantization=config.draft_head_quantization, - markov_head_quantization=config.markov_head_quantization, online_mxfp8=config.online_mxfp8) + markov_head_quantization=config.markov_head_quantization, online_mxfp8=config.online_mxfp8, + online_mxfp8_scope=config.online_mxfp8_scope) # Each decoder layer's weights form one stable payload; vocabulary shards, norms and the output query share misc. rebuild_weights = declare_weights(weights, components=("embedding", "embedding_norm", "final_norm", "output_query", "unembedding", "draft", "vision")) diff --git a/ignition/recipes/inkling2/decoder.py b/ignition/recipes/inkling2/decoder.py index a2cc70c4f..a143973b0 100644 --- a/ignition/recipes/inkling2/decoder.py +++ b/ignition/recipes/inkling2/decoder.py @@ -259,9 +259,11 @@ def example(role, shape, dtype=torch.bfloat16): session=session, workspace=workspace, name=name, examples=examples, rows=rows, route_gather=route_gather) self.layers = self.stack.layers self.logits = PreparedLogits(weights.head, text, weights.rank, tokens=samples, - session=session, name=name + ".logits", examples=examples) - local = example("local_logits", (samples, weights.head.shape[0]), torch.float32) - gathered = example("gathered_logits", (samples, weights.head.shape[0] * weights.world), torch.float32) + session=session, name=name + ".logits", examples=examples, workspace=workspace) + # The embedding and unembedding shards hold the same vocabulary rows; the unembedding may be packed. + columns = weights.embedding.shape[0] + local = example("local_logits", (samples, columns), torch.float32) + gathered = example("gathered_logits", (samples, columns * weights.world), torch.float32) self.gather = PreparedAllGather(local.view(torch.bfloat16), gathered.view(torch.bfloat16), runtime=vocabulary_runtime, coordinator=coordinator, session=session, name=name + ".logit_gather").functional(session=session) diff --git a/ignition/recipes/inkling2/dspark.py b/ignition/recipes/inkling2/dspark.py index 18c9bf41d..b3dae5983 100644 --- a/ignition/recipes/inkling2/dspark.py +++ b/ignition/recipes/inkling2/dspark.py @@ -254,12 +254,14 @@ def __init__(self, weights, scratch, metadata, pool, *, runtime, coordinator, se self.layer_plans = tuple(self.staging.index(layer.attention.staging) for layer in self.layers) self.norm = norm(scratch.accumulator, weights.draft.norm, scratch.hidden, eps=d.text["rms_norm_eps"], session=session, name=name + ".norm") - if weights.draft.draft_head is None: - self.head = UnquantizedProjection(scratch.hidden, weights.head, scratch.local_logits, + # Proposals read the drafter's quantized copy of the target's vocabulary shard when it has one, and + # otherwise the target's shard in the form the target stores: BF16 or MXFP8. + head = weights.head if weights.draft.draft_head is None else weights.draft.draft_head + if isinstance(head, torch.Tensor): + self.head = UnquantizedProjection(scratch.hidden, head, scratch.local_logits, session=session, name=name + ".head").functional(session=session) else: - # A quantized copy of the target's vocabulary shard serves proposals; verification keeps the target's. - self.head = QuantizedProjection(scratch.hidden, weights.draft.draft_head, scratch.local_logits, + self.head = QuantizedProjection(scratch.hidden, head, scratch.local_logits, session=session, name=name + ".head", activation_mode="a16", workspace=workspace).functional(session=session) self.recurrent = PreparedRecurrentProposalHead(weights.draft.recurrent, diff --git a/ignition/recipes/inkling2/dspark_weights.py b/ignition/recipes/inkling2/dspark_weights.py index 99eb2aaa4..c238d10d2 100644 --- a/ignition/recipes/inkling2/dspark_weights.py +++ b/ignition/recipes/inkling2/dspark_weights.py @@ -136,7 +136,8 @@ class DraftWeights: norm: torch.Tensor layers: tuple[DraftLayerWeights, ...] recurrent: RecurrentWeights - # Quantized copy of the target vocabulary shard that only proposals read; None projects with the target's. + # Quantized copy of the target vocabulary shard that only proposals read; None projects with the target's + # stored shard. draft_head: object | None = None @classmethod @@ -146,7 +147,8 @@ def load(cls, snapshot, config, device, shard, *, target_head, progress=None, `draft_head_quantization` (`nvfp4` or `mxfp8`) adds a quantized copy of `target_head` for the block's vocabulary logits. `markov_head_quantization` (`fp8`) stores the recurrent correction head, the - output map folded through `target_head`, as row-scaled E4M3. The target head keeps BF16. + output map folded through `target_head`, as row-scaled E4M3. `target_head` is the BF16 shard, which + this function reads and does not retain; `ModelWeights.load` decides how the target stores it. `online_mxfp8` stores each layer's fused query/key/value projection and attention output projection, and the recurrent head's context projection, as MXFP8: E4M3 values with one power-of-two scale per 32 input columns of each output row. Each layer's key/value projection of diff --git a/ignition/recipes/inkling2/recipe.py b/ignition/recipes/inkling2/recipe.py index c1c3825e4..cc5142c4d 100644 --- a/ignition/recipes/inkling2/recipe.py +++ b/ignition/recipes/inkling2/recipe.py @@ -41,6 +41,7 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ retain_graphs=retain_graphs, kernel_cache=kernel_cache, drafting=speculation is not None, vision=not plan.language_model_only, mtp_only=speculation is not None and speculation.mtp_only, online_mxfp8=plan.online_mxfp8, + online_mxfp8_scope=plan.online_mxfp8_scope, benchmark_selection=plan.benchmark_selection, **drafting) return prepare_group(snapshot, config, prepare_rank, progress=progress, core_storage=core_storage, ranks=ranks, checkpoint=plan.checkpoint) @@ -56,8 +57,10 @@ def usage(prepared): # Proposal-only copies: the block's vocabulary head, and the recurrent correction head as row-scaled E4M3. draft_head_quantizations=("nvfp4", "mxfp8"), markov_head_quantizations=("fp8",), # The attention input and output projections of every decoder layer, and the drafter's query/key/value, - # attention output and recurrent context projections. - online_mxfp8=True, + # attention output and recurrent context projections. That set is the group `all`, the default, which a core + # exported with `--online-mxfp8` alone records; `with-vocabulary-head` adds the target's unembedding shard, + # which changes the logits that verification and sampling read. + online_mxfp8=True, online_mxfp8_scopes=("all", "with-vocabulary-head"), checkpoints=(Checkpoint(alias="inkling-2-small-nvfp4", repository="/data/models/Inkling-2-Small-NVFP4", revision="local", architecture="Inkling2ForConditionalGeneration", stored_bytes=344_366_116_864, device_bytes=344_366_116_864, expansion_bytes=5_673_717_760, draft_bytes=2_684_203_392),), diff --git a/ignition/recipes/inkling2/vocabulary.py b/ignition/recipes/inkling2/vocabulary.py index c08082300..c7ffbb366 100644 --- a/ignition/recipes/inkling2/vocabulary.py +++ b/ignition/recipes/inkling2/vocabulary.py @@ -8,7 +8,9 @@ The embedding contributes a token's row on the rank that holds it and zero elsewhere, so the cross-rank sum is the row exactly. Logits project the final normalized hidden state in FP32, apply `softcap * tanh(x / softcap)` and are -`-inf` at IDs from the valid vocabulary size on. +`-inf` at IDs from the valid vocabulary size on. An unembedding shard stored as +MXFP8 projects BF16 activations through b12x's packed-weight kernels, which round +each FP32 sum to BF16; the softcap and every later consumer read that value as FP32. """ from __future__ import annotations @@ -16,6 +18,7 @@ import torch from ignition.components.linear import UnquantizedProjection +from ignition.components.vocabulary import WidenedQuantizedProjection def embedding_rows(table, ids, first): @@ -33,18 +36,26 @@ def embedding_rows(table, ids, first): class PreparedLogits: """FP32 logits of this rank's vocabulary columns with the softcap and the valid-vocabulary mask.""" - def __init__(self, weight, text, rank, *, tokens, session, name, examples=None): + def __init__(self, weight, text, rank, *, tokens, session, name, examples=None, workspace=None): + """`weight` is the rank's BF16 `[columns, hidden]` unembedding shard or its MXFP8 form.""" from ignition.preparation.examples import declaration_tensor examples = {} if examples is None else examples - device = weight.device + packed = not isinstance(weight, torch.Tensor) + device = weight.weight.values.device if packed else weight.device + columns = weight.out_features if packed else weight.shape[0] source = declaration_tensor(examples, "inkling.logits.source", (tokens, text.hidden), torch.bfloat16, device) - output = declaration_tensor(examples, "inkling.logits.local", (tokens, weight.shape[0]), torch.float32, device) - self.projection = UnquantizedProjection(source, weight, output, session=session, - name=f"{name}.projection").functional(session=session) + output = declaration_tensor(examples, "inkling.logits.local", (tokens, columns), torch.float32, device) + if packed: + rounded = declaration_tensor(examples, "inkling.logits.rounded", output.shape, torch.bfloat16, device) + projection = WidenedQuantizedProjection(source, weight, output, session=session, + name=f"{name}.projection", workspace=workspace, rounded=rounded) + else: + projection = UnquantizedProjection(source, weight, output, session=session, name=f"{name}.projection") + self.projection = projection.functional(session=session) self.softcap = text.softcap # Rank-dependent values are device data, so every rank binds the same compiled code. - self.valid_columns = rank * weight.shape[0] + torch.arange(weight.shape[0], device=device) < text.valid_vocabulary + self.valid_columns = rank * columns + torch.arange(columns, device=device) < text.valid_vocabulary def __call__(self, hidden): logits = self.projection(hidden) diff --git a/ignition/recipes/inkling2/weights.py b/ignition/recipes/inkling2/weights.py index 11310e9d7..32bf5b931 100644 --- a/ignition/recipes/inkling2/weights.py +++ b/ignition/recipes/inkling2/weights.py @@ -50,7 +50,8 @@ class ModelWeights: embedding_norm: torch.Tensor final_norm: torch.Tensor output_query: torch.Tensor - unembedding: torch.Tensor + # BF16 rows, or an MXFP8 weight when the plan stores the vocabulary head as MXFP8. + unembedding: object allocated_bytes: int draft: object | None = None vision: object | None = None @@ -73,10 +74,16 @@ def embed_norm(self): @classmethod def load(cls, manifest, device, *, shard, progress=None, drafting=True, vision=True, layers=None, - draft_head_quantization=None, markov_head_quantization=None, online_mxfp8=False): + draft_head_quantization=None, markov_head_quantization=None, online_mxfp8=False, + mxfp8_vocabulary_head=False): """`online_mxfp8` stores each decoder layer's attention input and output projections, and the drafter's query/key/value, attention output and recurrent context projections - (`DraftWeights.load`), as MXFP8.""" + (`DraftWeights.load`), as MXFP8. + + `mxfp8_vocabulary_head` stores this rank's unembedding shard as MXFP8 (E4M3 values with one + power-of-two scale per 32 hidden columns of each vocabulary row) and releases its BF16 rows. The + drafter's proposal heads are derived from the BF16 rows before that. An MXFP8 proposal head would + hold the same values, so proposals then read the target's shard instead of a copy.""" before = torch.cuda.memory_allocated(device) with InklingWeightLoader(manifest, device, shard=shard, progress=progress, vision=vision, online_mxfp8=online_mxfp8) as loader: @@ -85,14 +92,15 @@ def load(cls, manifest, device, *, shard, progress=None, drafting=True, vision=T if type(count) is not int or not 1 <= count <= c.text.layers: raise ValueError("decoder layer count must fit the checkpoint") first, last = shard.padded_partition(c.text.vocabulary, alignment=64) - def vocabulary_rows(name): - value = persistent_zeros((last - first, c.text.hidden), dtype=torch.bfloat16, device=device) + def vocabulary_rows(name, temporary=False): + allocate = torch.zeros if temporary else persistent_zeros + value = allocate((last - first, c.text.hidden), dtype=torch.bfloat16, device=device) stop = min(last, c.text.vocabulary) loader._copy(value[:stop - first], loader._sources[name][first:stop]) loader._session.flush() return value embedding = vocabulary_rows(TEXT_PREFIX + ".embed_tokens.weight") - head = vocabulary_rows("lm_head.weight") + head = vocabulary_rows("lm_head.weight", temporary=mxfp8_vocabulary_head) loaded = tuple(loader.load_layer(index) for index in range(count)) norm = loader.load_tensor(TEXT_PREFIX + ".norm.weight") embed_norm = loader.load_tensor(TEXT_PREFIX + ".embed_norm.weight") @@ -110,9 +118,14 @@ def vocabulary_rows(name): draft = None if drafting: from .dspark_weights import DraftWeights + shared = mxfp8_vocabulary_head and draft_head_quantization == "mxfp8" draft = DraftWeights.load(manifest.snapshot, c, device, shard, target_head=head, progress=progress, - draft_head_quantization=draft_head_quantization, markov_head_quantization=markov_head_quantization, - online_mxfp8=online_mxfp8) + draft_head_quantization=None if shared else draft_head_quantization, + markov_head_quantization=markov_head_quantization, online_mxfp8=online_mxfp8) + if mxfp8_vocabulary_head: + from ignition.components.vocabulary import mxfp8_draft_head + + head = mxfp8_draft_head(head) return cls(c, shard, loaded, embedding, embed_norm, norm, query, head, torch.cuda.memory_allocated(device) - before, draft, tower) diff --git a/tests/cli/test_inkling2.py b/tests/cli/test_inkling2.py index 3e7e160f5..1548f57f0 100644 --- a/tests/cli/test_inkling2.py +++ b/tests/cli/test_inkling2.py @@ -123,7 +123,7 @@ def test_inkling_online_mxfp8_flag_reaches_plan_metadata_and_preparation(monkeyp from ignition.recipes.inkling2 import bootstrap assert RECIPE.online_mxfp8 - assert (RECIPE.online_mxfp8_scope, RECIPE.online_mxfp8_scopes) == ("all", ("all",)) + assert (RECIPE.online_mxfp8_scope, RECIPE.online_mxfp8_scopes) == ("all", ("all", "with-vocabulary-head")) model = ResolvedModel(RECIPE, RECIPE.checkpoints[0]) args = _parser().parse_args(["export", model.checkpoint.alias, *(["--online-mxfp8"] if online else [])]) devices = tuple(gpu(i, 95) for i in range(4)) @@ -144,7 +144,11 @@ def capture_config(**kwargs): monkeypatch.setattr(bootstrap, "PreparationConfig", capture_config) with pytest.raises(ConfigurationCaptured): RECIPE.prepare(tmp_path, plan, compile_forwards=False, kernel_cache=None, progress=None) - assert captured.pop().online_mxfp8 is online + config = captured.pop() + assert config.online_mxfp8 is online + # Without an explicit group, the vocabulary head keeps the checkpoint's BF16. + assert plan.online_mxfp8_scope == config.online_mxfp8_scope == "all" + assert not config.mxfp8_vocabulary_head def test_inkling_preparation_config_rejects_a_non_boolean_online_mxfp8(): @@ -152,3 +156,61 @@ def test_inkling_preparation_config_rejects_a_non_boolean_online_mxfp8(): with pytest.raises(ValueError, match="online MXFP8"): PreparationConfig(online_mxfp8="all") + + +@pytest.mark.parametrize("scope,head", [(None, False), ("all", False), ("with-vocabulary-head", True)]) +def test_inkling_vocabulary_head_group_reaches_plan_rebuild_metadata_and_preparation(monkeypatch, tmp_path, scope, head): + """The MXFP8 vocabulary head is its own conversion group: `all`, which exported cores record, excludes it.""" + from types import SimpleNamespace + + from google.protobuf import json_format + + from ignition.preparation import rebuild_manifest + from ignition.preparation import runtime_core_pb2 as proto + from ignition.recipes.inkling2 import bootstrap + + model = ResolvedModel(RECIPE, RECIPE.checkpoints[0]) + args = _parser().parse_args(["export", model.checkpoint.alias, "--online-mxfp8", + *([] if scope is None else ["--online-mxfp8-scope", scope])]) + assert args.online_mxfp8_scope == scope + devices = tuple(gpu(i, 95) for i in range(4)) + plan = planning.plan(RECIPE, model.checkpoint, devices, selected=(0, 1, 2, 3), concurrency=8, reserve_bytes=0, + speculation=RECIPE.speculation, online_mxfp8=args.online_mxfp8, + online_mxfp8_scope=args.online_mxfp8_scope) + expected = scope or "all" + assert plan.online_mxfp8_scope == plan.to_dict()["online_mxfp8_scope"] == expected + encoded = proto.RebuildManifest() + json_format.ParseDict(rebuild_manifest.from_plan(SimpleNamespace(directory=None), plan, compiled_forwards=True), + encoded) + assert encoded.online_mxfp8 and encoded.online_mxfp8_scope == expected + captured = [] + configuration = bootstrap.PreparationConfig + + class ConfigurationCaptured(Exception): + pass + + def capture_config(**kwargs): + captured.append(configuration(**kwargs)) + raise ConfigurationCaptured + + monkeypatch.setattr(bootstrap, "PreparationConfig", capture_config) + with pytest.raises(ConfigurationCaptured): + RECIPE.prepare(tmp_path, plan, compile_forwards=False, kernel_cache=None, progress=None) + config = captured.pop() + assert config.online_mxfp8 and config.online_mxfp8_scope == expected + assert config.mxfp8_vocabulary_head is head + + +def test_inkling_vocabulary_head_group_requires_online_mxfp8(): + from ignition.errors import UsageError + from ignition.recipes.inkling2.bootstrap import PreparationConfig + + model = ResolvedModel(RECIPE, RECIPE.checkpoints[0]) + devices = tuple(gpu(i, 95) for i in range(4)) + with pytest.raises(UsageError, match="requires --online-mxfp8"): + planning.plan(RECIPE, model.checkpoint, devices, selected=(0, 1, 2, 3), concurrency=8, reserve_bytes=0, + speculation=RECIPE.speculation, online_mxfp8_scope="with-vocabulary-head") + with pytest.raises(ValueError, match="requires online MXFP8 conversion"): + PreparationConfig(online_mxfp8_scope="with-vocabulary-head") + with pytest.raises(ValueError, match="all or with-vocabulary-head"): + PreparationConfig(online_mxfp8=True, online_mxfp8_scope="kda-input") diff --git a/tests/components/test_draft_head_cuda.py b/tests/components/test_draft_head_cuda.py index 5ac93b132..f1d279c97 100644 --- a/tests/components/test_draft_head_cuda.py +++ b/tests/components/test_draft_head_cuda.py @@ -120,6 +120,34 @@ def test_mxfp8_vocabulary_shard_replays_changed_inputs_without_target_mutation(r graph.reset() +@pytest.mark.parametrize("rows,functional", [(1, False), (8, True), (160, True)]) +@torch.no_grad() +def test_mxfp8_vocabulary_shard_fills_fp32_logits_with_its_bf16_products(rows, functional): + """A consumer of FP32 logits binds a packed shard: the kernel's BF16 products arrive widened, unchanged.""" + torch.manual_seed(41019) + target = torch.randn((192, 512), device="cuda", dtype=torch.bfloat16) * .02 + weight = mxfp8_draft_head(target) + scales = weight.weight.scale_rows.view(torch.float8_e8m0fnu).reshape(192, 16) + restored = (weight.weight.values.float().reshape(192, 16, 32) * scales.float()[..., None]).reshape(192, 512) + source = torch.randn((rows, 512), device="cuda", dtype=torch.bfloat16) + local, logits = (torch.full((rows, 192), float("nan"), device="cuda") for _ in range(2)) + with RecordedPreparationSession(device="cuda:0", checkpoint="mxfp8-fp32-logits", + workload_schema="a16-vocabulary", numerical_policy="mxfp8-weight-bf16-source", + autotune_effort="off") as session: + operation = PreparedVocabularyProjection(source, weight, local, logits, + runtime=None, coordinator=None, session=session, name="head") + if functional: + operation.functional(session=session) + session.tune(show_progress=False) + result = compile_forward(lambda: operation(source))() if functional else operation(source) + assert result.dtype == torch.float32 and result.shape == (rows, 192) + assert functional or result.data_ptr() == logits.data_ptr() + assert torch.equal(result, result.bfloat16().float()) + expected = source.double() @ restored.double().T + bound = expected.abs() * 2**-7 + expected.abs().max() * 1e-6 + assert bool(((result.double() - expected).abs() <= bound).all()) + + @torch.no_grad() def test_mxfp8_head_retains_the_actual_bounded_proposal_distribution(): from ignition.components.draft_sampling import PreparedDraftProposal diff --git a/tests/recipes/test_inkling2_vocabulary_cuda.py b/tests/recipes/test_inkling2_vocabulary_cuda.py new file mode 100644 index 000000000..778ca9ab8 --- /dev/null +++ b/tests/recipes/test_inkling2_vocabulary_cuda.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""An Inkling 2 unembedding shard stored as MXFP8 yields FP32 softcapped logits from the stored values.""" + +import os +from pathlib import Path + +import pytest +import torch + +from ignition.components.parallel import TensorParallelShard + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an assigned SM120 GPU") + + +def _expanded(weight): + """The BF16 matrix an MXFP8 weight stores, in FP64.""" + from b12x.gemm._shared.wo_mxfp8 import dequantize_mxfp8_rows_torch, materialize_mxfp8_scale_rows + + rows = weight.weight + return dequantize_mxfp8_rows_torch(rows.values, materialize_mxfp8_scale_rows(rows))[:, :weight.in_features].double() + + +@pytest.fixture(scope="module", params=[0, 3]) +def shards(request): + """One rank's weights with a BF16 and with an MXFP8 unembedding shard; rank 3 holds the padded vocabulary rows.""" + from ignition.preparation.checkpoint import inspect_indexed_checkpoint + from ignition.recipes.inkling2.weights import ModelWeights + + snapshot = os.environ.get("FLARE_INKLING2_SNAPSHOT") + if not snapshot: + pytest.skip("requires FLARE_INKLING2_SNAPSHOT") + device = torch.device("cuda", 0) + + def load(mxfp8_vocabulary_head): + with torch.no_grad(): + return ModelWeights.load(inspect_indexed_checkpoint(Path(snapshot)), device, + shard=TensorParallelShard(request.param, 4), vision=False, layers=1, draft_head_quantization="mxfp8", + mxfp8_vocabulary_head=mxfp8_vocabulary_head) + + return load(False), load(True) + + +@torch.no_grad() +def test_checkpoint_unembedding_loads_as_mxfp8_and_proposals_share_it(shards): + from b12x.gemm.blockscaled._linear import MXFP8LinearWeight + + checkpoint, weights = shards + assert checkpoint.head.dtype == torch.bfloat16 and isinstance(checkpoint.draft.draft_head, MXFP8LinearWeight) + assert isinstance(weights.head, MXFP8LinearWeight) + assert (weights.head.out_features, weights.head.in_features) == tuple(checkpoint.head.shape) + expanded, original = _expanded(weights.head), checkpoint.head.double() + assert ((expanded - original).norm() / original.norm()).item() < .035 + # An MXFP8 proposal head would repeat the target's stored values, so the drafter holds no copy. + assert weights.draft.draft_head is None + assert torch.equal(weights.head.weight.values.view(torch.uint8), + checkpoint.draft.draft_head.weight.values.view(torch.uint8)) + # The embedding shard and the recurrent correction head, folded through the BF16 rows, keep their bits. + assert torch.equal(weights.embedding, checkpoint.embedding) + assert torch.equal(weights.draft.recurrent.head, checkpoint.draft.recurrent.head) + assert torch.equal(weights.draft.recurrent.head_bias, checkpoint.draft.recurrent.head_bias) + + +@pytest.mark.parametrize("tokens,compiled", [(1, False), (4, True), (8, False), (128, True)]) +@torch.no_grad() +def test_checkpoint_mxfp8_unembedding_projects_stored_values_into_fp32_softcapped_logits(shards, tokens, compiled): + """Decode, verification and packed-round row counts: each kernel multiplies BF16 hidden rows by the stored + values and rounds the FP32 sum to BF16; softcap and the valid-vocabulary mask then run in FP32, as they do + for the BF16 shard, whose logits differ by no more than the stored weights' distance allows.""" + from ignition.preparation.scratch import ScratchArena + from ignition.preparation.tuning import RecordedPreparationSession + from ignition.recipes.inkling2.vocabulary import PreparedLogits + + checkpoint, weights = shards + text, device = weights.config.text, weights.embedding.device + torch.manual_seed(tokens) + # Rows in the final hidden state's layout: unit RMS scaled by the checkpoint's final norm weight. + hidden = torch.randn(tokens, text.hidden, device=device) + hidden = (hidden * hidden.square().mean(-1, keepdim=True).rsqrt() * weights.final_norm.float()).bfloat16() + with RecordedPreparationSession(device=device, checkpoint="inkling2-checkpoint-unembedding-mxfp8", + workload_schema="inkling2-checkpoint-unembedding", numerical_policy="default", + autotune_effort="off") as session: + arena = ScratchArena(device) + session.register_scratch(arena) + stored = PreparedLogits(weights.head, text, weights.rank, tokens=tokens, session=session, + name="stored", workspace=arena) + reference = PreparedLogits(checkpoint.head, text, checkpoint.rank, tokens=tokens, session=session, + name="reference", workspace=arena) + session.tune() + + def forward(): + return stored.projection(hidden), stored(hidden), reference(hidden) + + if compiled: + from ignition.preparation.compilation import compile_forward + forward = compile_forward(forward) + raw, logits, expected = forward() + + columns = checkpoint.head.shape[0] + assert raw.dtype == logits.dtype == expected.dtype == torch.float32 + assert raw.shape == logits.shape == expected.shape == (tokens, columns) + # The kernel's result is a BF16 value, widened without change. + assert torch.equal(raw, raw.bfloat16().float()) + source, expanded = hidden.double(), _expanded(weights.head) + exact, magnitude = source @ expanded.T, source.abs() @ expanded.abs().T + gamma = text.hidden * 2 ** -24 / (1 - text.hidden * 2 ** -24) + # FP32 accumulation of the products, then one rounding to BF16. + assert (((raw.double() - exact).abs() - gamma * magnitude - 2 ** -8 * exact.abs()).max() <= 0).item() + valid = weights.rank * columns + torch.arange(columns, device=device) < text.valid_vocabulary + assert valid.any() and bool(valid.all()) == (weights.rank < 3) + assert torch.equal(logits[:, ~valid], torch.full_like(logits[:, ~valid], float("-inf"))) + assert torch.equal(torch.isneginf(logits), torch.isneginf(expected)) + capped = text.softcap * torch.tanh(raw / text.softcap) + torch.testing.assert_close(logits[:, valid], capped[:, valid], rtol=1e-6, atol=1e-6) + # Softcap has slope at most one, so the two heads' logits differ by at most the products of the hidden rows + # with the weight differences, plus each head's accumulation and the stored head's BF16 rounding. + original = checkpoint.head.double() + # Each softcap evaluation is within a few FP32 units in the last place of the softcap. + bound = (source.abs() @ (expanded - original).abs().T + gamma * (magnitude + source.abs() @ original.abs().T) + + 2 ** -8 * exact.abs() + 8 * 2 ** -23 * text.softcap) + assert (((logits.double() - expected.double()).abs() - bound)[:, valid].max() <= 0).item() + assert (logits[:, valid] - expected[:, valid]).abs().max().item() > 0 From c63fda04f5be5b982f6f6ba6e95764584ed42620 Mon Sep 17 00:00:00 2001 From: Jason Cook Date: Mon, 16 Nov 2026 13:21:58 -0500 Subject: [PATCH 11/11] Document serving Inkling 2 on Sparks with --mtp-adaptive-verification-alpha 0.5 With the default exponent of 1.0 on completed prefix-survival scores, the balanced scheduler serving Inkling 2 Small at TP4 on four DGX Sparks leaves drafting after one to three rejected first drafts: a request's estimates start at a weight of two and a rejection zeroes every deeper offered prefix. In one-token rounds nothing is observed, so the request returns only through an acceptance probe, and one request funds a probe about every 6 s. Of twelve sequential 25 s requests on task prompts, three spent 12 to 26 s in one-token rounds at 48 to 51 tokens/s although their first drafts were accepted 63% to 90% of the time once drafting, and single-request coding completions of 400 to 1,000 tokens ran either near 46 tokens/s or at 63 to 80. docs/model-preparation.md recommends --mtp-adaptive-verification-alpha 0.5 for Inkling 2 on DGX Sparks and states what it trades. The flag exists; no code, default, or package changes. With the exponent at 0.5 a request with high draft acceptance keeps drafting, and low-acceptance text is drafted more often than it repays. Evidence: one core exported from the parent commit with --online-mxfp8-scope with-vocabulary-head, served at TP4 on four DGX Sparks with the balanced policy, one launch per exponent. Ten sequential coding completions with 0.5 generated 70.6 to 81.9 tokens/s, with drafts in 99% of rounds; fifteen with 1.0 generated 46.5 to 76.7. On task prompts ending at EOS, three 20 s repeats gave 98.2 tokens/s (97.9 to 100.8) at four requests against 89.2 (88.3 to 90.4), 88.1 (80.4 to 92.4) at two against 80.4 (67.3 to 88.7), and 65.2 (63.2 to 69.2) at one against 71.3 (63.1 to 75.1). On an article continuation the exponent drafted in 100%, 84% and 49% of rounds at one, two and four requests for 46.7, 65.2 and 92.1 tokens/s against 46.3, 68.1 and 95.1. Two decode benchmark passes at an 8,192-token context with a distinct seed per stream gave 48.7 and 46.3 tokens/s at one request, 71.6 and 68.3 at two, 91.8 and 93.9 at four and 128.8 and 129.9 at eight, against 45.1 to 45.6, 67.1 to 67.6, 92.3 to 94.0 and 125.8 to 128.6 over three passes with 1.0. An exponent of 0.75 kept single requests drafting and did not change four requests (89.5). Limitations: launches differ by 3% in one-token round time; the exponent was not measured on other models or at more than eight requests; the probe cadence that makes the default slow to return is unchanged. Design-Signed-Off-By: flare-02; design-review=ed22 --- docs/model-preparation.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/model-preparation.md b/docs/model-preparation.md index a3d44f20f..5f56915ef 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1523,6 +1523,22 @@ same position of a 67,000-token prompt are 92 ms shorter, smaller chunks are for 131,990 tokens is 40.4 to 42.0 s against 43.5 to 43.7 s with the default routing. +Serve Inkling 2 on DGX Sparks with `--mtp-adaptive-verification-alpha 0.5`. +With the default exponent of 1.0 the balanced scheduler leaves drafting after +one to three rejected first drafts and returns only through an acceptance +probe, which one request funds about every 6 s; a request whose drafts are +accepted 80% of the time can spend 12 to 26 s of a 25 s run in one-token +rounds at 48 to 51 tokens/s. An exponent of 0.5 keeps such requests drafting. +On four DGX Sparks at TP4, ten sequential single-request coding completions +generate 70.6 to 81.9 tokens/s with drafts in 99% of rounds, where fifteen +with the default generate 46.5 to 76.7 tokens/s; task prompts ending at EOS +reach 98.2 tokens/s at four requests against 89.2 and 88.1 against 80.4 at +two, and 65.2 against 71.3 at one request with overlapping ranges. On an +article continuation, where the second draft is accepted a third of the time, +the exponent drafts in 49% to 100% of rounds for the same throughput at one +request and 3% to 4% less at two and four. The decode benchmark's 8,192-token +cells are unchanged at one to eight requests. + Multi-host export requires the checkpoint directory on rank zero only; peers read their tensor ranges from it. The recipe accepts up to 32 concurrent requests. On rank zero, whose preparation address