diff --git a/docs/TODO.txt b/docs/TODO.txt index 704bb17ce..524adc112 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -8,6 +8,16 @@ populated large vision graphs. Canonical vision comparisons cover at most 256 live patches. +[ ] Compare Inkling 2 output across four DGX Sparks, where cross-host hidden + reductions round partial sums to BF16, against single-host FP32 reductions. + Also run the unverified Inkling 2 combinations: effort-zero cases of + tests/server/test_inkling2.py on Sparks, single-host SM120 preparation + after the multi-host changes and at 32 concurrent requests, and --roce-ring + and --roce-chain routing. Planning at 32 requests and 8192-token chunks + predicts 22.9 GiB of KV pages per rank where native loading allocates + 12.4 GiB; correct the declared rank costs from a measured GB10 memory + report. + [ ] Fix native TP4 shutdown reporting "free(): double free detected in tcache 2" after server drain with Inkling 2 cores. Reproduces with compiled and uncompiled graphs; preserve the successful request drain and GPU release. diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 23a4a5128..063fc1d77 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -1412,18 +1412,21 @@ flare-cli/target/release/flare run /data/flare-runtime/minimax-m3.1-flash-tp4.sa ## Inkling 2 Small NVFP4 The `inkling-2-small-nvfp4` alias selects the local checkpoint -`/data/models/Inkling-2-Small-NVFP4`. Preparation requires four SM120 GPUs and -the bundled DSpark weights in `mtp.safetensors`. Target experts retain the +`/data/models/Inkling-2-Small-NVFP4`. Preparation requires four SM120 GPUs on +one host, or four SM121 GPUs with one rank per host, and the bundled DSpark +weights in `mtp.safetensors`. Target experts retain the checkpoint's static NVFP4 scales, with A4 activations for prefill and A16 activations for decoding and speculative verification. DSpark uses MXFP8 feed-forward projections and BF16 attention and recurrent state. Target and draft attention use b12x. The pinned FlashInfer dependency provides relative bias, private paged-attention tails, and explicit expert activation selection. -The recipe declares a 1048576-token context, eight concurrent requests, -4096-token prefill chunks, and seven draft tokens per round. Adaptive packed -verification has 64 target rows and a 64-graph budget, plus width-one graphs -that preserve DSpark context. The vision encoder accepts padded 20-pixel +The recipe declares a 1048576-token context, a default of eight concurrent +requests (maximum 32), 4096-token prefill chunks, and seven draft tokens per +round. Adaptive packed verification defaults to a 128-token capacity (at most +64 packed target rows at the default eight-request concurrency) and a 64-graph +budget, plus width-one graphs that preserve DSpark context. The vision encoder +accepts padded 20-pixel patches, merges each 2-by-2 group, and supports four images per request and four concurrent image requests. Native TMLv0 encoding and parsing provide reasoning, tool calls, and structured responses. Sampling defaults are @@ -1464,6 +1467,72 @@ FLARE_RUN_CUDA_TESTS=1 FLARE_INKLING2_TEST_URL=http://127.0.0.1:8000 \ .venv/bin/python -m pytest tests/server/test_inkling2.py -k default-effort -q ``` +Each rank holds a quarter of the 344 GB checkpoint, so four-host DGX Spark +serving runs one rank on each of four GB10 (SM121) hosts, reducing through +RoCEnante over their ConnectX-7 ports. Ranks on one host reduce FP32 partial +sums; ranks on separate hosts round each partial sum to BF16 before the +reduction, because RoCEnante reduces BF16. One runtime carries the hidden +reductions, the vocabulary gathers of FP32 logits as BF16 column pairs, the +sampling and log-probability gathers, and the sampling broadcasts. Multi-host +export requires the checkpoint directory on rank zero only; peers read their +tensor ranges from it. + +The 32-request, 8192-token configuration was qualified on four DGX Sparks +(the recipe defaults `--speculative-token-capacity` to 128, matching this +export). On rank zero, whose preparation address is `10.200.0.13`, with +`[memory] reserve = "4G"`: + +```sh +ulimit -Sn 65536 +.venv/bin/ignition export /data/models/Inkling-2-Small-NVFP4 \ + --ranks 4 --rendezvous 10.200.0.13:29630 --gpus 0 \ + --max-concurrency 32 --image-concurrency 4 \ + --prefill-chunk-size 8192 --mtp-draft-tokens 7 \ + --speculative-token-capacity 128 --speculative-graph-budget 64 \ + --autotune-effort default +``` + +On each peer, with its rank from 1 through 3: + +```sh +.venv/bin/ignition join 10.200.0.13:29630 --rank 1 --ranks 4 +``` + +Serve with `flare run CACHE_ENTRY --rank 0 --rendezvous 10.200.0.13:29800 +--gpus 0 --mtp-draft-tokens 7 --no-history-drafts --memory-limit=-0G` on rank +zero and `flare run --rank R --rendezvous 10.200.0.13:29800 --gpus 0` with the +same serving options on each peer. `--memory-limit=-0G` replaces the exported +4 GiB reserve, so the cache takes everything outside the integrated-memory +allowances, which leave about 8 GiB available on each host. Follow the +[multi-host guide](multi-host.md) for preparation authentication, rank +placement, and publisher acceptance. Hosts that share a switch need neither +`--roce-ring` nor `--roce-chain`. + +Disk: rank zero holds the complete core, 351 GB for this configuration. Each +peer needs about 87 GB for the payloads it prepares and another 87 GB for the +rank core it receives when serving; the prepared payloads can be removed after +export. Drop the page cache on every host before export and before serving so +cached checkpoint and peer rank-core files do not exhaust unified memory. + +On four DGX Sparks (GB10, SM121, 121 GiB each) joined by a switch, with one +pair also cabled directly, this configuration compiled and captured all 152 +graphs in 1 h 26 min. The lowest available memory during export was 11.5 GiB on +rank zero and 12.5 to 13.1 GiB on the peers; the captured graph pool uses +2840 MiB per rank. Native loading used 90.1 to 90.2 GiB per rank and, with +`--memory-limit=-0G`, allocated a 16.5 GiB cache: 3,252,224 KV-token slots and +106 shared snapshot slots, limited by memory, leaving 7.8 to 8.3 GiB available +per host after loading and at least 7.6 GiB during 32 concurrent requests. With +the exported 4 GiB reserve the cache is 12.4 GiB, 2,392,064 KV-token slots and +78 snapshot slots, with 12.0 to 12.5 GiB available. The service passed the +seven default-effort tests of `tests/server/test_inkling2.py`, 32 concurrent +requests, streaming, and an 18,832-token prompt with a 2048-token output limit, +with no change in the RoCE loss counters. A core without drafting and vision, +prepared for one request with 512-token chunks, loaded 82.9 GiB per rank and +passed text, streaming, and a 7,150-token prompt. Not run: single-host SM120 +preparation after the multi-host changes or at 32 concurrent requests, +effort-zero tests on Sparks, `--roce-ring`, `--roce-chain`, and a numerical +comparison of BF16 cross-host reductions against single-host FP32 output. + ## Muse Spark Open The `muse-spark-open-nvfp4` alias selects diff --git a/docs/roce-ring.md b/docs/roce-ring.md index 8e0ad8481..810bd03e8 100644 --- a/docs/roce-ring.md +++ b/docs/roce-ring.md @@ -5,7 +5,8 @@ its neighbors in rank order. A native CPU proxy forwards transfers addressed to other ranks through those neighbors. The transport supports 2 through 16 ranks; each model recipe determines which tensor-parallel sizes it can prepare, and the multi-host preparation rendezvous admits two, three, or four ranks. -GLM-5.3 Flash, MiMo V2.6, DeepSeek V4 Flash, and Qwen3.8 Flash prepare multi-host TP2 and TP4 cores. +GLM-5.3 Flash, MiMo V2.6, DeepSeek V4 Flash, and Qwen3.8 Flash prepare multi-host TP2 and TP4 cores; +Inkling 2 Small NVFP4 prepares multi-host TP4 cores. Ring routing applies to RoCEnante's one-shot reductions, two-shot reductions, and variable-length gathers. The collective algorithms and arithmetic belong diff --git a/ignition/recipes/inkling2/bootstrap.py b/ignition/recipes/inkling2/bootstrap.py index 153ddfcb5..9460268d0 100644 --- a/ignition/recipes/inkling2/bootstrap.py +++ b/ignition/recipes/inkling2/bootstrap.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Prepare Inkling 2 text, vision and complete DSpark generation graphs on four local GPUs.""" +"""Prepare Inkling 2 text, vision and complete DSpark generation graphs on four GPUs, on one host or across four hosts.""" import contextlib import hashlib @@ -23,7 +23,8 @@ from ignition.components.state_transfer import StateCommands from ignition.preparation.capture import capture_forwards from ignition.preparation.checkpoint import inspect_indexed_checkpoint -from ignition.preparation.collectives import CollectivePreparation, create_all_reduce_runtime, create_all_gather_runtime +from ignition.preparation.collectives import (CollectivePreparation, create_all_reduce_runtime, create_all_gather_runtime, + create_roce_runtime) from ignition.preparation.execution import GraphSignature from ignition.preparation.fixtures.recurrent import register_benchmark_state from ignition.preparation.host_memory import release_unused @@ -40,7 +41,7 @@ from .decoder import PreparedDecoder, Scratch from .weights import ModelWeights from .pool import PAGE_TOKENS, ContinuationPool, RankGeometry, continuation_layout, page_specs -from ignition.preparation.bootstrap import BasePreparationConfig +from ignition.preparation.bootstrap import BasePreparationConfig, validate_host_topology @dataclass(frozen=True) @@ -49,6 +50,10 @@ class PreparationConfig(BasePreparationConfig): image_concurrency: int | None = None autotune_effort: str = "off" devices: tuple[int, ...] = (0, 1, 2, 3) + # Device ordinals are host-local when each rank runs on its own host. + hosts: tuple[str, ...] | None = None + roce_ring: bool = False + roce_chain: bool = False context: int = 1048576 max_active: int = 8 compile_decoder: bool = False @@ -56,16 +61,21 @@ class PreparationConfig(BasePreparationConfig): drafting: bool = True vision: bool = True speculative_widths: tuple[int, ...] = tuple(range(1, 9)) - speculative_token_capacity: int | None = 64 + speculative_token_capacity: int | None = 128 speculative_graph_budget: int = 64 benchmark_selection: object | None = None def __post_init__(self): - if len(self.devices) != WORLD_SIZE or len(set(self.devices)) != WORLD_SIZE or min(self.devices) < 0: - raise ValueError("Inkling 2 preparation requires four distinct GPUs on one host") + placements = tuple(zip(self.hosts or ("",) * len(self.devices), self.devices)) + if (not isinstance(self.devices, tuple) or len(self.devices) != WORLD_SIZE + or len(set(placements)) != WORLD_SIZE + or self.hosts is not None and (not isinstance(self.hosts, tuple) or len(self.hosts) != WORLD_SIZE) + or any(type(d) is not int or d < 0 for d in self.devices)): + raise ValueError("Inkling 2 preparation requires four distinct GPUs") + validate_host_topology(self.roce_ring, self.roce_chain, self.hosts) request_capacity(self.max_active) - if not 1 <= self.max_active <= 8: - raise ValueError("Inkling 2 request capacity must be in [1, 8]") + if not 1 <= self.max_active <= 32: + raise ValueError("Inkling 2 request capacity must be in [1, 32]") if not PAGE_TOKENS <= self.context <= 1048576 or self.context % PAGE_TOKENS: raise ValueError("Inkling 2 context must be 128-aligned in [128, 1048576]") if not PAGE_TOKENS <= self.prefill_chunk_size <= self.context or self.prefill_chunk_size % PAGE_TOKENS: @@ -112,6 +122,41 @@ def _logit_gather_bytes(rows, width): return rows * width * 4 +def _collective_runtimes(config, group, device, *, coordinator, core_storage, hidden, local_vocabulary, draft_block): + """Allocate the hidden reduction and the vocabulary, sampling and log-probability gather channels. + + `hidden` is the model width, `local_vocabulary` one rank's padded vocabulary columns and `draft_block` + the positions the drafter reduces per request. Ranks on separate hosts run every collective in + rank-serial order over one RoCEnante runtime, which all four roles share; the sampling and + log-probability channels are None without drafting. + """ + slots, world = request_capacity(config.max_active), len(config.devices) + tokens = max(config.prefill_chunk_size, config.decode_tokens) + vocabulary_rows = max(config.decode_samples, slots) + if coordinator.spans_hosts: + # One-shot reductions cover decode and verification rows and the drafter's block of every request; + # prefill chunks reduce through the pipelined two-shot path. The largest gather is each rank's FP32 + # vocabulary partition of every sampled row, carried as BF16 column pairs: 4 * local_vocabulary + # bytes per row. A row of the other gathers is at most 1024 bytes (the FP32 log-probability summary), + # and the packed sampling results of all rows fit in one vocabulary row. + runtime = create_roce_runtime(group, device, + max_tokens=max(config.decode_tokens, slots * draft_block if config.drafting else 0), pipe_tokens=tokens, + hidden_size=hidden, gather_bytes=vocabulary_rows * local_vocabulary * 4, + ring=config.roce_ring, ring_open=config.roce_chain, core_storage=core_storage) + drafting = runtime if config.drafting else None + return runtime, runtime, drafting, drafting + ipc = core_storage.peer_storage + runtime = create_all_reduce_runtime(group, device, max_tokens=min(tokens, 1024), + hidden_size=hidden, element_bytes=4, ipc=ipc, collective_tuning=config.collective_tuning) + vocabulary = create_all_gather_runtime(group, device, max_rows=vocabulary_rows, + columns=2 * local_vocabulary * world, ipc=ipc) + sampling = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, + columns=64 * world, ipc=ipc) if config.drafting else None) + logprob = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, + columns=512 * world, ipc=ipc) if config.drafting else None) + return runtime, vocabulary, sampling, logprob + + class _Softcapped: def __init__(self, projection, softcap): self.projection, self.softcap = projection, softcap @@ -143,8 +188,8 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): shard = TensorParallelShard(rank, world) device = torch.device("cuda", config.devices[rank]) torch.cuda.set_device(device) - if torch.cuda.get_device_capability(device) != (12, 0): - raise ValueError("Inkling 2 preparation requires SM120 GPUs") + if torch.cuda.get_device_capability(device) not in ((12, 0), (12, 1)): + raise ValueError("Inkling 2 preparation requires SM120 or SM121 GPUs") with phase(progress, "Inspect checkpoint"): manifest = inspect_indexed_checkpoint(snapshot) headers = [entry.header_sha256 for entry in manifest.shards] @@ -158,6 +203,11 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): weights = ModelWeights.load(manifest, device, shard=shard, layers=config.decoder_layers, progress=progress, drafting=config.drafting, vision=config.vision) weights_bytes = torch.cuda.memory_allocated(device) + if torch.cuda.get_device_properties(device).is_integrated: + from ignition.preparation.host_memory import release_page_cache + + # Unified memory counts cached checkpoint pages against the GPU; drop them after loading. + release_page_cache(manifest.shard_paths) del manifest release_unused() transient = contextlib.ExitStack() @@ -188,16 +238,10 @@ def prepare_rank(snapshot, config, *, rank, group, progress=None, core_storage): width = max((w for _, w, _ in config.speculative_round_shapes), default=1) completion = CompletionOutputs.allocate((2, slots, VECTOR_TOKENS_FIELD + width), device=device) coordinator = CollectivePreparation(group) - runtime = create_all_reduce_runtime(group, device, max_tokens=min(tokens, 1024), - hidden_size=text.hidden, element_bytes=4, ipc=core_storage.peer_storage, - collective_tuning=config.collective_tuning) - vocabulary_runtime = create_all_gather_runtime(group, device, - max_rows=max(config.decode_samples, slots), columns=2 * weights.head.shape[0] * world, - ipc=core_storage.peer_storage) - sampling_runtime = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, - columns=64 * world, ipc=core_storage.peer_storage) if config.drafting else None) - logprob_runtime = (create_all_gather_runtime(group, device, max_rows=config.decode_samples, - columns=512 * world, ipc=core_storage.peer_storage) if config.drafting else None) + runtime, vocabulary_runtime, sampling_runtime, logprob_runtime = _collective_runtimes( + config, group, device, coordinator=coordinator, core_storage=core_storage, + hidden=text.hidden, local_vocabulary=weights.head.shape[0], + draft_block=model.draft.block) identity = hashlib.sha256(json.dumps({"text": model.text.__dict__ | {"local_layers": sorted(model.text.local_layers)}, "quantization": model.quantization, "headers": headers, "world_size": world, "decoder_layers": len(weights.layers), "contract": "inkling2.paged-text.v1"}, @@ -357,4 +401,6 @@ def add(name, forward, kind, rows, tokens, fields, enabled=None, packed=0): export_zero_ranges=completion.zero_ranges(), resources=(weights, pool, requests, inputs, admission, commands, completion, forwards, arena, session, compiled, stream, graph_pool, coordinator, runtime, vocabulary_runtime, sampling_runtime, logprob_runtime, speculation, vision_state), - close_resources=tuple(r for r in (runtime, vocabulary_runtime, sampling_runtime, logprob_runtime) if r is not None)) + # Ranks on separate hosts share one runtime across these roles; close it once. + close_resources=tuple(dict.fromkeys( + r for r in (runtime, vocabulary_runtime, sampling_runtime, logprob_runtime) if r is not None))) diff --git a/ignition/recipes/inkling2/decoder.py b/ignition/recipes/inkling2/decoder.py index 46337ccac..89e6241b5 100644 --- a/ignition/recipes/inkling2/decoder.py +++ b/ignition/recipes/inkling2/decoder.py @@ -1,7 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Tensor-parallel target execution with complete accepted-state commits.""" +"""Tensor-parallel target execution with complete accepted-state commits. + +Ranks on one host reduce FP32 partial sums. Ranks on separate hosts reduce through RoCEnante, +which carries BF16: each rank rounds its partial sum to BF16 before the reduction. +""" from dataclasses import dataclass from types import SimpleNamespace @@ -9,7 +13,7 @@ import torch from ignition.components.causal_convolution import PreparedCausalConvolution -from ignition.components.collectives import PreparedAllGather, PreparedChunkedAllReduce +from ignition.components.collectives import PreparedAllGather, PreparedChunkedAllReduce, _roce from ignition.components.linear import UnquantizedProjection from ignition.components.rms_norm import PreparedTorchRMSNorm from ignition.components.moe import PreparedRouter, PreparedRoutedExperts, RouterScratch @@ -36,6 +40,11 @@ def rows(self, tokens, samples): return type(self)(self.logits[:samples], self.local_logits[:samples], tokens) +def reduction_dtype(runtime): + """Element type of cross-rank hidden reductions: BF16 over RoCEnante, FP32 on one host.""" + return torch.bfloat16 if runtime is not None and _roce(runtime) else torch.float32 + + @dataclass(frozen=True) class ResidualState: blocks: tuple[torch.Tensor, ...] @@ -43,11 +52,11 @@ class ResidualState: class PreparedLayer(torch.nn.Module): - def __init__(self, layer, weights, text, pool, metadata, reduction, *, mode, tokens, + def __init__(self, layer, weights, text, pool, metadata, reduction, reduction_dtype, *, mode, tokens, session, workspace, name, examples=None): super().__init__() self.layer, self.weights, self.text, self.mode = layer, weights, text, mode - self.reduction = reduction + self.reduction, self.reduction_dtype = reduction, reduction_dtype self.attention = PreparedAttention(layer, weights.attention, text, LayerCache.of(pool, layer), metadata, mode=mode, tokens=tokens, session=session, workspace=workspace, name=name + ".attention", examples=examples, tuning_page_count=((int(pool.memory_capacity[0].item()) - 1) * pool.ring_row_pages + pool.geometry.ring // 128 @@ -85,7 +94,7 @@ def forward(self, state, metadata): streams = (tuple(norm(state.partial) for norm in self.input_norms) if self.input_mix is None else self.input_mix((*state.blocks, state.partial))) _, attention_partial, attention_values = self.attention.attend(streams, m) - attention_raw = self.reduction(attention_partial).to(torch.bfloat16) + attention_raw = self.reduction(attention_partial.to(self.reduction_dtype)).to(torch.bfloat16) attention, attention_previous = self.attention_convolution(attention_raw, m) if self.layer % t.residual_block == 0: mlp_input = self.mlp_mix((*state.blocks, state.partial, attention))[0] @@ -93,7 +102,7 @@ def forward(self, state, metadata): mlp_input = self.mlp_mix((*state.blocks, state.partial), addend=attention)[0] routes = self.router(self.router_projection(mlp_input.float()), num_valid_tokens=m.live_counts[:1]) expert_partial = self.experts(mlp_input, routes.ids, routes.weights) - mlp_raw = self.reduction(expert_partial.float()).to(torch.bfloat16) + mlp_raw = self.reduction(expert_partial.to(self.reduction_dtype)).to(torch.bfloat16) mlp, mlp_previous = self.mlp_convolution(mlp_raw, m) if self.mode != "verify": self.attention_convolution.commit(attention_previous, attention_raw, m) @@ -124,10 +133,12 @@ def __init__(self, weights, tables, scratch, metadata, pool, *, mode, session, n examples = {} if examples is None else examples def example(role, shape, dtype=torch.bfloat16): return declaration_tensor(examples, "inkling.decoder." + role, shape, dtype, device) - partial = example("partial", (tokens, text.hidden), torch.float32) - self.reduce = PreparedChunkedAllReduce(partial, example("reduced", partial.shape, torch.float32), + # Traced forwards read this attribute, never the runtime, which compile workers see as a placeholder. + self.reduction_dtype = reduction_dtype(runtime) + partial = example("partial", (tokens, text.hidden), self.reduction_dtype) + self.reduce = PreparedChunkedAllReduce(partial, example("reduced", partial.shape, self.reduction_dtype), runtime=runtime, coordinator=coordinator, session=session, name=name + ".reduction").functional(session=session) - self.layers = [PreparedLayer(index, layer, text, pool, metadata, self.reduce, mode=mode, tokens=tokens, + self.layers = [PreparedLayer(index, layer, text, pool, metadata, self.reduce, self.reduction_dtype, mode=mode, tokens=tokens, session=session, workspace=workspace, name=f"{name}.layer{index}", examples=examples) for index, layer in enumerate(weights.layers)] self.logits = PreparedLogits(weights.head, text, weights.rank, tokens=samples, @@ -155,7 +166,7 @@ def release_outputs(self): def __call__(self, metadata): w, t, m = self.weights, self.weights.config.text, metadata embedded = embedding_rows(w.embedding, m.token_ids, self.first_token) - hidden = self.reduce(embedded.float()).to(torch.bfloat16) + hidden = self.reduce(embedded.to(self.reduction_dtype)).to(torch.bfloat16) hidden = self.embedding_norm(hidden) if self.vision_state is not None and self.mode == "prefill": self.vision_state.inject(m, hidden) diff --git a/ignition/recipes/inkling2/recipe.py b/ignition/recipes/inkling2/recipe.py index f6d6c3986..b109b22da 100644 --- a/ignition/recipes/inkling2/recipe.py +++ b/ignition/recipes/inkling2/recipe.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors # SPDX-License-Identifier: Apache-2.0 -"""Inkling 2 Small NVFP4 preparation on four GPUs with bundled DSpark and vision.""" +"""Inkling 2 Small NVFP4 preparation on four GPUs, on one host or one per host, with bundled DSpark and vision.""" from types import MappingProxyType @@ -12,11 +12,13 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_graphs=False, core_storage=None, ranks=None): + """Prepare the plan's catalog on process-local GPUs 0 through 3. + + With `ranks`, rank zero's multi-host rendezvous, each rank uses its own host's GPU 0. + """ from ignition.preparation.rank_group import prepare_group from .bootstrap import PreparationConfig, prepare_rank - if ranks is not None: - raise ValueError("Inkling 2 preparation requires four GPUs on one host") if plan.prompt_logprobs: raise ValueError("Inkling 2 preparation does not capture prompt scoring graphs") speculation = plan.speculation @@ -31,7 +33,9 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ native_dense_activations=plan.native_dense_activations, lock_gpu_clocks=plan.lock_gpu_clocks and plan.autotune_effort != "off", autotune_effort=plan.autotune_effort, tuning_replica=plan.tuning_replica, - devices=tuple(range(plan.world_size)), context=plan.recipe.context, prefill_chunk_size=plan.prefill_chunk, + devices=tuple(range(plan.world_size)) if ranks is None else (0,) * plan.world_size, + hosts=None if ranks is None else ranks.hosts, roce_ring=plan.roce_ring, roce_chain=plan.roce_chain, + context=plan.recipe.context, prefill_chunk_size=plan.prefill_chunk, max_active=plan.concurrency, image_concurrency=plan.image_concurrency, snapshot_budget_bytes=plan.snapshots * plan.costs.state_row_bytes, headroom_bytes=plan.headroom_bytes + plan.reserve_bytes, compile_decoder=compile_forwards, @@ -40,7 +44,7 @@ def prepare(snapshot, plan, *, compile_forwards, kernel_cache, progress, retain_ mtp_only=speculation is not None and speculation.mtp_only, benchmark_selection=plan.benchmark_selection, **drafting) return prepare_group(snapshot, config, prepare_rank, progress=progress, core_storage=core_storage, - checkpoint=plan.checkpoint) + ranks=ranks, checkpoint=plan.checkpoint) def usage(prepared): @@ -53,8 +57,8 @@ def usage(prepared): checkpoints=(Checkpoint(alias="inkling-2-small-nvfp4", repository="/data/models/Inkling-2-Small-NVFP4", revision="local", architecture="Inkling2ForConditionalGeneration", stored_bytes=344_366_116_864, device_bytes=344_366_116_864, expansion_bytes=5_673_717_760, draft_bytes=2_684_203_392),), - context=1048576, page_tokens=128, concurrency=8, max_concurrency=8, prefill_chunk=4096, - speculation=Speculation(draft_tokens=7, token_capacity=64, packed_verification=True, graph_budget=64), + context=1048576, page_tokens=128, concurrency=8, max_concurrency=32, prefill_chunk=4096, + speculation=Speculation(draft_tokens=7, token_capacity=128, packed_verification=True, graph_budget=64), max_draft_tokens=7, max_images=4, image_bytes=32 << 20, verification_rows=0, language_model_only=True, ranks=MappingProxyType({4: RankCosts(31_293_440, 655_360, 5 << 30)}), plain_ranks=MappingProxyType({4: RankCosts(26_935_296, 524_288, 5 << 30)})) diff --git a/tests/cli/test_inkling2.py b/tests/cli/test_inkling2.py index 44ebdc706..484bbe6d7 100644 --- a/tests/cli/test_inkling2.py +++ b/tests/cli/test_inkling2.py @@ -16,11 +16,12 @@ def test_inkling_defaults_cover_tp4_seven_drafts_and_vision(): assert RECIPE.tensor_parallel == (4,) assert (RECIPE.context, RECIPE.concurrency, RECIPE.prefill_chunk) == (1048576, 8, 4096) + assert RECIPE.max_concurrency == 32 assert (RECIPE.max_images, RECIPE.image_bytes) == (4, 32 << 20) model = ResolvedModel(RECIPE, RECIPE.checkpoints[0]) args = _parser().parse_args(["export", model.checkpoint.alias]) speculation = preparation.speculation(args, model) - assert (speculation.draft_tokens, speculation.token_capacity, speculation.graph_budget) == (7, 64, 64) + assert (speculation.draft_tokens, speculation.token_capacity, speculation.graph_budget) == (7, 128, 64) assert speculation.packed_verification assert speculation.widths == tuple(range(1, 9)) @@ -52,5 +53,5 @@ def capture_config(**kwargs): assert config.max_active == 8 assert config.drafting and config.vision assert config.speculative_widths == tuple(range(1, 9)) - assert config.speculative_token_capacity == 64 + assert config.speculative_token_capacity == 128 assert config.speculative_graph_budget == 64 diff --git a/tests/cli/test_planning.py b/tests/cli/test_planning.py index bc8a44252..4cb0a179d 100644 --- a/tests/cli/test_planning.py +++ b/tests/cli/test_planning.py @@ -329,7 +329,7 @@ def test_cli_plan_resolves_recipe_configuration_and_flag_defaults(tmp_path, mode if expected is None: expected = ((4, 4096, 6) if model.recipe.name == "gemma4" else (4, 4096, 32) if model.recipe.name == "muse_spark" else - (8, 4096, 64) if model.recipe.name == "inkling2" else (32, 4096, 128)) + (8, 4096, 128) if model.recipe.name == "inkling2" else (32, 4096, 128)) args = _parser().parse_args(["export", model.checkpoint.alias, *flags]) selected = preparation.speculation(args, model, configuration) concurrency = configuration.max_concurrency(model.checkpoint.alias, model.recipe.concurrency, diff --git a/tests/recipes/test_inkling2_hosts.py b/tests/recipes/test_inkling2_hosts.py new file mode 100644 index 000000000..26d594375 --- /dev/null +++ b/tests/recipes/test_inkling2_hosts.py @@ -0,0 +1,185 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Inkling 2 TP4 host placement and channels preserve the local preparation contract.""" + +from types import SimpleNamespace + +import pytest +import torch + +from ignition import planning +from ignition.recipes.inkling2 import bootstrap, decoder, recipe + +HOSTS = ("hertz", "maxwell", "ampere", "faraday") +HIDDEN, LOCAL_VOCABULARY, DRAFT_BLOCK = 4608, 201024 // 4, 8 +GEOMETRY = dict(hidden=HIDDEN, local_vocabulary=LOCAL_VOCABULARY, draft_block=DRAFT_BLOCK) + + +def test_four_hosts_may_each_use_their_own_gpu_zero(): + config = bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS) + assert config.devices == (0,) * 4 + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0,) * 4) + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0,) * 4, hosts=("hertz",) * 4) + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS[:3]) + with pytest.raises(ValueError, match="distinct GPUs"): + bootstrap.PreparationConfig(devices=(0, 1), hosts=HOSTS[:2]) + + +def test_ring_and_chain_need_hosts_in_rank_order(): + with pytest.raises(ValueError, match="--roce-ring"): + bootstrap.PreparationConfig(roce_ring=True) + with pytest.raises(ValueError, match="exclude each other"): + bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, roce_ring=True, roce_chain=True) + assert bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, roce_ring=True).roce_ring + assert bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, roce_chain=True).roce_chain + + +def _gb10(count): + return tuple(planning.Gpu(i, "GB10", f"GPU-{i}", 121 << 30, 115 << 30, (12, 1)) for i in range(count)) + + +@pytest.mark.parametrize("concurrency, chunk", [(8, 4096), (32, 8192)]) +def test_four_gb10_hosts_fit_the_declared_and_the_largest_configuration(concurrency, chunk): + plan = planning.plan(recipe.RECIPE, recipe.RECIPE.checkpoints[0], _gb10(4), selected=(0, 1, 2, 3), + concurrency=concurrency, reserve_bytes=4 << 30, speculation=recipe.RECIPE.speculation, + prefill_chunk=chunk) + assert plan.fits and plan.world_size == 4 + assert (plan.concurrency, plan.prefill_chunk, plan.speculative_token_capacity) == (concurrency, chunk, 128) + assert plan.guaranteed_tokens >= planning.MINIMUM_REQUEST_TOKENS + + +def test_request_capacity_is_bounded_by_thirty_two(): + from ignition.errors import UsageError + + assert bootstrap.PreparationConfig(max_active=32, prefill_chunk_size=8192).max_active == 32 + with pytest.raises(ValueError, match=r"\[1, 32\]"): + bootstrap.PreparationConfig(max_active=33) + with pytest.raises(UsageError, match="must be 1 through 32"): + planning.plan(recipe.RECIPE, recipe.RECIPE.checkpoints[0], _gb10(4), selected=(0, 1, 2, 3), + concurrency=33, reserve_bytes=4 << 30, speculation=recipe.RECIPE.speculation) + + +def test_thirty_two_requests_size_rounds_scratch_rows_and_prefill_graphs(): + default_eight = bootstrap.PreparationConfig(max_active=8) + legacy_eight = bootstrap.PreparationConfig(max_active=8, speculative_token_capacity=64) + # At concurrency 8, 8 * 8 = 64 <= 128, so the 128-token default preserves the exact 8-request graph catalog. + assert default_eight.speculative_round_shapes == legacy_eight.speculative_round_shapes + assert (default_eight.decode_tokens, default_eight.decode_samples) == (64, 64) + + config = bootstrap.PreparationConfig(max_active=32, prefill_chunk_size=8192) + shapes = config.speculative_round_shapes + assert {batch for batch, _, _ in shapes} == {1, 2, 4, 8, 16, 32} + assert all(packed <= 128 for _, _, packed in shapes) and (32, 8, 128) in shapes and (32, 1, 32) in shapes + # Packed verification bounds target rows; every request still samples each of its eight positions. + assert (config.decode_tokens, config.decode_samples) == (128, 256) + assert config.image_concurrency == 4 + assert bootstrap.prefill_capacities(8192)[-1] == 8192 + + +@pytest.mark.parametrize("remote", [False, True]) +@pytest.mark.parametrize("ring", [False, True]) +def test_recipe_dispatches_the_complete_plan_to_the_rank_group(monkeypatch, remote, ring): + from ignition.preparation import rank_group + + ring = ring and remote + plan = planning.fit(recipe.RECIPE, recipe.RECIPE.checkpoints[0], _gb10(4), concurrency=8, + reserve_bytes=4 << 30, speculation=recipe.RECIPE.speculation, roce_ring=ring) + ranks = SimpleNamespace(hosts=HOSTS) if remote else None + calls, result, storage = [], object(), object() + monkeypatch.setattr(rank_group, "prepare_group", lambda *args, **kwargs: calls.append((args, kwargs)) or result) + assert recipe.prepare("checkpoint", plan, compile_forwards=True, kernel_cache=None, progress=None, + core_storage=storage, ranks=ranks) is result + (snapshot, config, forward), kwargs = calls[0] + assert snapshot == "checkpoint" and forward is bootstrap.prepare_rank + assert config.devices == ((0,) * 4 if remote else (0, 1, 2, 3)) + assert config.hosts == (HOSTS if remote else None) + assert config.roce_ring is ring and not config.roce_chain + assert config.context == recipe.RECIPE.context + assert config.max_active == 8 and config.drafting and config.vision and config.draft_tokens == 7 + assert kwargs["ranks"] is ranks and kwargs["checkpoint"] is plan.checkpoint + assert kwargs["core_storage"] is storage + + +def test_remote_capacities_follow_thirty_two_requests_and_8192_token_chunks(monkeypatch): + config = bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, max_active=32, prefill_chunk_size=8192) + calls = [] + monkeypatch.setattr(bootstrap, "create_roce_runtime", lambda group, device, **kwargs: calls.append(kwargs)) + bootstrap._collective_runtimes(config, None, None, coordinator=SimpleNamespace(spans_hosts=True), + core_storage=None, **GEOMETRY) + (call,) = calls + # The drafter reduces an eight-position block of each of 32 requests in one shot. + assert call["max_tokens"] == 32 * DRAFT_BLOCK == 256 and call["pipe_tokens"] == 8192 + assert call["gather_bytes"] == 256 * LOCAL_VOCABULARY * 4 + + +@pytest.mark.parametrize("drafting", [False, True]) +@pytest.mark.parametrize("chain", [False, True]) +def test_remote_channels_share_one_roce_runtime_without_pcie(monkeypatch, drafting, chain): + from ignition.components.collectives import packed_broadcast_layout + from ignition.components.vocabulary_logprobs import _SUMMARY + from ignition.components.vocabulary_sampling import SUMMARY_WORDS + + config = bootstrap.PreparationConfig(devices=(0,) * 4, hosts=HOSTS, max_active=8, drafting=drafting, + roce_chain=chain) + calls, runtime, storage = [], object(), object() + monkeypatch.setattr(bootstrap, "create_roce_runtime", + lambda group, device, **kwargs: calls.append(kwargs) or runtime) + for name in ("create_all_reduce_runtime", "create_all_gather_runtime"): + monkeypatch.setattr(bootstrap, name, lambda *args, **kwargs: pytest.fail("host ranks cannot use CUDA IPC")) + channels = bootstrap._collective_runtimes(config, None, None, + coordinator=SimpleNamespace(spans_hosts=True), core_storage=storage, **GEOMETRY) + assert channels == (runtime, runtime, runtime if drafting else None, runtime if drafting else None) + (call,) = calls + assert call["core_storage"] is storage and call["hidden_size"] == HIDDEN + assert call["ring"] is False and call["ring_open"] is chain + # One reduction covers a whole prefill chunk; decode, verification and draft rows reduce one-shot. + assert call["pipe_tokens"] == max(config.prefill_chunk_size, config.decode_tokens) == 4096 + assert call["max_tokens"] >= config.decode_tokens + assert call["max_tokens"] * HIDDEN * 2 % 16 == 0 and call["pipe_tokens"] * HIDDEN * 2 % 16 == 0 + rows = max(config.decode_samples, 8) + # FP32 vocabulary partitions of every sampled row travel as BF16 column pairs. + assert call["gather_bytes"] == rows * LOCAL_VOCABULARY * 4 and call["gather_bytes"] % 16 == 0 + sampled = [((rows,), torch.int64), ((rows,), torch.bool), ((rows,), torch.float32), ((rows,), torch.float32)] + assert call["gather_bytes"] >= (packed_broadcast_layout(sampled)[1] + 15) // 16 * 16 + if drafting: + assert call["max_tokens"] >= 8 * DRAFT_BLOCK + assert (config.decode_tokens, config.decode_samples) == (64, 64) + # Sampling statistics and log-probability summaries are FP32 rows of 32 and 256 words per rank. + assert call["gather_bytes"] >= rows * max(SUMMARY_WORDS, _SUMMARY) * 4 + else: + assert call["max_tokens"] == config.decode_tokens == 8 + + +@pytest.mark.parametrize("drafting", [False, True]) +def test_local_channels_are_unchanged(monkeypatch, drafting): + config = bootstrap.PreparationConfig(max_active=8, drafting=drafting, collective_tuning="runtime") + gathers, reductions = [], [] + monkeypatch.setattr(bootstrap, "create_all_gather_runtime", + lambda group, device, **kwargs: gathers.append(kwargs) or object()) + monkeypatch.setattr(bootstrap, "create_all_reduce_runtime", + lambda group, device, **kwargs: reductions.append(kwargs) or object()) + monkeypatch.setattr(bootstrap, "create_roce_runtime", + lambda *args, **kwargs: pytest.fail("local ranks share CUDA IPC")) + ipc = object() + channels = bootstrap._collective_runtimes(config, None, None, + coordinator=SimpleNamespace(spans_hosts=False), core_storage=SimpleNamespace(peer_storage=ipc), **GEOMETRY) + present = [channel for channel in channels if channel is not None] + assert len(present) == (4 if drafting else 2) and len({id(channel) for channel in present}) == len(present) + assert reductions == [dict(max_tokens=1024, hidden_size=HIDDEN, element_bytes=4, ipc=ipc, + collective_tuning="runtime")] + samples = config.decode_samples + assert gathers[0] == dict(max_rows=max(samples, 8), columns=2 * 201024, ipc=ipc) + assert gathers[1:] == ([dict(max_rows=samples, columns=64 * 4, ipc=ipc), + dict(max_rows=samples, columns=512 * 4, ipc=ipc)] if drafting else []) + + +def test_hidden_reductions_round_to_bf16_only_over_roce(monkeypatch): + local, remote = object(), object() + monkeypatch.setattr(decoder, "_roce", lambda runtime: runtime is remote) + assert decoder.reduction_dtype(None) == torch.float32 + assert decoder.reduction_dtype(local) == torch.float32 + assert decoder.reduction_dtype(remote) == torch.bfloat16 diff --git a/tests/server/test_inkling2.py b/tests/server/test_inkling2.py index 509e3476b..c7231b69c 100644 --- a/tests/server/test_inkling2.py +++ b/tests/server/test_inkling2.py @@ -4,7 +4,9 @@ """Inkling 2 text, TML tools, images and cached continuations through native TP4 serving. Set FLARE_RUN_CUDA_TESTS=1 and FLARE_INKLING2_TEST_URL to an exported core -running with flare run, concurrency eight, 4096-token prefill and vision. +running with flare run, concurrency of at least eight, 4096- or 8192-token +prefill and vision. Prompts that cross a prefill chunk scale with the chunk +size the service reports. """ from concurrent.futures import ThreadPoolExecutor @@ -30,8 +32,9 @@ def service(request): with urllib.request.urlopen(url + "/v1/models", timeout=10) as response: model = json.load(response)["data"][0] assert "inkling" in model["id"].lower(), model - assert model["flare"]["max_concurrency"] == 8 - assert model["flare"]["prefill_chunk_size"] == 4096 + assert model["flare"]["max_concurrency"] >= 8 + chunk = model["flare"]["prefill_chunk_size"] + assert chunk in (4096, 8192) assert "image" in model["flare"]["input_modalities"] def ask(content, **options): @@ -61,6 +64,7 @@ def ask(content, **options): assert result["usage"]["completion_tokens"] == len(choice["token_ids"]) return result + ask.chunk = chunk return ask @@ -87,14 +91,15 @@ def test_streamed_reasoning_and_answer(service): def test_chunked_prefix_reuse_and_branching(service): - prefix = " ".join(f"Item {i} records code {i * 17 % 997}." for i in range(700)) + chunk = service.chunk + prefix = " ".join(f"Item {i} records code {i * 17 % 997}." for i in range(700 * chunk // 4096)) history = [dict(role="user", content=prefix), dict(role="assistant", content="I have the item records.")] for index in (211, 677, 211): messages = history + [dict(role="user", content=f"What code does item {index} record? Reply with only the integer.")] first, second = service("", messages=messages), service("", messages=messages) - assert first["usage"]["prompt_tokens"] > 4096 - assert second["usage"]["prompt_tokens_details"]["cached_tokens"] > 4096 + assert first["usage"]["prompt_tokens"] > chunk + assert second["usage"]["prompt_tokens_details"]["cached_tokens"] > chunk assert answer(first) == answer(second) == str(index * 17 % 997) @@ -122,11 +127,11 @@ def test_structured_response(service): def test_images_across_a_prefill_chunk(service): - content = [dict(type="text", text="filler " * 4100), + content = [dict(type="text", text="filler " * (service.chunk + 4)), image("red", "FIRST 128"), image("blue", "SECOND 256"), dict(type="text", text="Read both image labels in their original order. Only output the labels.")] response = service(content) - assert response["usage"]["prompt_tokens"] > 4096 + assert response["usage"]["prompt_tokens"] > service.chunk result = answer(response) assert "FIRST 128" in result and "SECOND 256" in result assert result.index("FIRST 128") < result.index("SECOND 256")