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/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..5c31ff1fe 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 @@ -1365,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/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)] { 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/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/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/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/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 4b430ddfa..819ea633b 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 @@ -22,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 @@ -124,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 @@ -134,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")) @@ -173,7 +182,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 +210,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)) @@ -229,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) @@ -335,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: @@ -354,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/decoder.py b/ignition/recipes/inkling2/decoder.py index 89e6241b5..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,26 +69,36 @@ 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 + # 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 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) + 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(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) @@ -79,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))) @@ -100,7 +129,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) @@ -114,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) @@ -121,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, @@ -138,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) @@ -156,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 @@ -171,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/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/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..72731dba7 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) @@ -64,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 @@ -97,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) @@ -160,7 +170,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/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_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/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_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()) diff --git a/tests/recipes/test_inkling2_target.py b/tests/recipes/test_inkling2_target.py index 1977c63a1..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)] @@ -224,7 +182,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 +191,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 +233,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 +245,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 +339,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) 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