Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/TODO.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions docs/cli-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
43 changes: 42 additions & 1 deletion docs/model-preparation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"`:
Expand Down
1 change: 1 addition & 0 deletions flare-cli/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions flare-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
82 changes: 80 additions & 2 deletions flare-cli/src/distribution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Arc<File>>]) {
for file in files.iter().skip(1).flatten() {
flare_eos::release_page_cache(file);
}
}

struct Source {
port: u16,
stopping: Arc<AtomicBool>,
Expand All @@ -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;
Expand Down Expand Up @@ -1066,7 +1077,9 @@ impl Source {
}
}
error.map_or(Ok(()), Err)
})
});
release_served_pages(&files);
result
});
Ok(Self {
port,
Expand Down Expand Up @@ -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)] {
Expand Down
142 changes: 142 additions & 0 deletions ignition/components/collectives.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading