Deep Code Correctness Audit — PR #732 (helios,heliopause,ignition: add FP8_E4M3_GLOBAL single-plane engram table support) @ 078b043
Scope note. The PR is 10 files / ~710 changed lines across helios/, heliopause/, ignition/ — under the >12-file / >900-line partition threshold, so I audited directly. The pr_diff base is stale and carries unrelated merged work (external_extents/async_transfers, workflow YAML, AGENTS.md (not opened), THIRD_PARTY_NOTICES.md (not opened), docs/api.md (not opened), flare-winui), so I compared main against head for each of the 10 files and confined findings to the encoding/schema/export/delivery change.
Finding 1 — Major: duplicated quant-mode dispatch in the PLE lookup, with a catch-all else that silently selects the NVFP4 two-plane path and dereferences a possibly-None scales
ignition/components/ngram_delivery.py:98-114 (changed):
@torch.library.custom_op("flare::staged_ple", mutates_args=("out", "timings", "barrier_output"))
def _lookup(source: torch.Tensor, weight: torch.Tensor, scales: torch.Tensor | None,
scale: torch.Tensor | None, ids: torch.Tensor, count: torch.Tensor, out: torch.Tensor,
...
mode = state.query.quant_mode
if mode == "bf16":
state.run_lookup(weight.view(torch.bfloat16), None, None, ids, count, out, token_count=out.shape[0])
elif mode == "fp8_e4m3_per_tensor":
state.run_lookup(weight.view(torch.float8_e4m3fn), scale, None, ids, count, out, token_count=out.shape[0])
else:
state.run_lookup(weight, scales.view(torch.float8_e4m3fn), scale, ids, count, out, token_count=out.shape[0])
and the second, independent decision at ignition/components/ngram_delivery.py:132-155 (changed):
self.scales = None if table.scales is None else table.scales[:tokens * heads]
...
mode = caps.quant_mode
if mode == "bf16":
lookup_weight, lookup_scale, lookup_scale_2 = self.weights.view(torch.bfloat16), None, None
elif mode == "fp8_e4m3_per_tensor":
lookup_weight, lookup_scale, lookup_scale_2 = self.weights.view(torch.float8_e4m3fn), table.scale, None
else:
lookup_weight = self.weights
lookup_scale = self.scales.view(torch.float8_e4m3fn)
lookup_scale_2 = table.scale
Three distinct defects in the same construct:
-
Two sources of truth for one decision.
__init__resolves the mode fromcaps.quant_modeand bakes the resulting tensor views into the captured plan (self.plan = ple_embedding.plan(...)/declare(... run=lambda: state.run_lookup(lookup_weight, ...)), lines 145-157), while__call__(lines 184-193) re-enters_lookup, which re-resolves the mode from a different object —state.query.quant_modeobtained fromrequire_prepared(plan_from_handle(plan), ...)at line 104. Nothing in the file tiesstate.query.quant_modetocaps.quant_mode. If they disagree, the graph-captured path uses the precomputed views while the eager path re-derives from rawuint8/None— same table, different numerics under graph replay vs eager, with no error. -
Non-exhaustive dispatch on a free-form string. Any mode value other than the two literals —
"nvfp4_group16"(the documented NVFP4 mode, seetests/components/test_ngram_delivery.py:32), a new"fp8_e4m3_per_block", a different casing ("FP8_E4M3_PER_TENSOR") — falls into theelsebranch, i.e. is treated as the two-plane NVFP4 layout. No validation error is raised. -
Nonedereference in the fallback. Becauseself.scalesis now legitimatelyNonefor single-plane tables (line 132) and is forwarded unconditionally as thescalesoperand (line 190), theelsebranch at line 113 executesscales.view(torch.float8_e4m3fn)onNone.Concrete counterexample (no hardware needed): a
Qwen4-35B-A3BPLE table declaredFP8_E4M3_GLOBAL(single plane ⇒table.scales is None⇒self.scales is None) served withcaps.quant_mode == "nvfp4_group16"(the model body's mode, since Helios' schema has no field tyingEngramTable.encodingto a quant mode — seehelios/proto/core.proto:266-292, which has no such field).PreparedPLELookup.__init__succeeds (itselsebranch is only reached ifcaps.quant_modeis also"nvfp4_group16", in which case line 143 already raises), but_lookupreaches line 113 withscales is None→AttributeError: 'NoneType' object has no attribute 'view'at the first decode step. The reverse skew (caps.quant_mode == "fp8_e4m3_per_tensor"butstate.query.quant_mode == "nvfp4_group16") silently runs the row data through the group-scale kernel instead.The new test cannot catch this:
tests/components/test_ngram_delivery.py:86only pairsscales=Nonewithmode in {"bf16", "fp8_e4m3_per_tensor"}, never exercising the fallback with a single-plane table.
Fix. Make the dispatch a single exhaustively-checked function returning a mode tag plus the views, use it in both places, and fail loudly:
def _planes(weight, scales, scale, mode, *, view):
if mode == "bf16":
return weight.view(torch.bfloat16), None, None
if mode == "fp8_e4m3_per_tensor":
return weight.view(torch.float8_e4m3fn), scale, None
if mode == "nvfp4_group16":
if scales is None:
raise ValueError("nvfp4_group16 requires a scale plane")
return weight, scales.view(torch.float8_e4m3fn), scale
raise ValueError(f"unsupported PLE quant mode {mode!r}")
and in __init__ assert (scales is None) == (mode != "nvfp4_group16"), then pass the precomputed views (or the resolved tag) into _lookup so the eager and captured paths cannot diverge.
Finding 2 — Minor: spans() accepts encoding == UNSPECIFIED while decode() and engram_encoding_has_scales() reject the same table
helios/src/runtime_core/engram.rs:29-36 (added):
// Legacy pre-encoding `ModelIndex` fixtures leave `encoding == 0` with two planes.
let encoding = if table.encoding == wire::engram_table::Encoding::Unspecified as i32 {
wire::engram_table::Encoding::Fp8E4m3E8m0 as i32
} else {
table.encoding
};
let has_scales = crate::core::schema::engram_encoding_has_scales(encoding)?;
validate_shards(table, world, has_scales)?;
versus helios/src/runtime_core/engram.rs:137-138 (unchanged in this respect):
let encoding = wire::engram_table::Encoding::try_from(table.encoding)
.map_err(|_| invalid("unknown n-gram encoding"))?;
and helios/src/core/schema.rs:445-456, which returns Err(invalid("engram table has no encoding")) for Unspecified.
Counterexample: wire::EngramTable { encoding: 0, weights: Some(w), scales: Some(s), .. } (exactly the "legacy pre-encoding fixture" the new comment describes, e.g. the byte fixture decoded in helios/src/runtime_core/engram.rs:500-524). spans(index, Some(rank)) returns Ok with two planes, but decode(...) on the same value returns Err("unknown n-gram encoding"). spans() is called on the payload-accounting/verification path (helios/src/runtime_core/protection.rs:1254, for (owner, span) in super::engram::spans(index, self.rank)?), so verification admits an index that loading then rejects — a late, misattributed failure ("unknown n-gram encoding" instead of a schema error). The same resolver also makes any future encoding value (≥ 5) fail verification with a stale message.
Fix. Hoist one resolver, e.g.
fn resolve_encoding(encoding: i32) -> Result<wire::engram_table::Encoding> // with the UNSPECIFIED→Fp8E4m3E8m0 legacy arm
and use it in both spans() and decode() (line 137 currently bypasses the legacy arm), or delete the fallback in spans() and let the single engram_encoding_has_scales error stand.
Finding 3 — Minor (hot path): per-call .view() tensor allocations, duplicating views already built once at plan time
ignition/components/ngram_delivery.py:107 and :110 allocate a fresh TensorImpl on every flare::staged_ple invocation — i.e. every PLE lookup, every decode step, on every rank. PreparedPLELookup.__init__ already precomputes exactly these views (lines 137-144) and hands them to the captured plan (line 155), so the per-call construction is redundant as well as cheap-but-nonzero. For a 160M-row, 8960-wide PLE table at decode time this is one extra ATen view per step per rank, plus it re-enters Python attribute lookups (state.query.quant_mode) inside an op that make_fx traces. Passing the precomputed lookup_weight/lookup_scale/lookup_scale_2 (or a small integer mode tag) as op operands removes both the allocation and Finding 1's divergence.
Verified sound (checked, no defect found)
- BF16
-0.0symmetry.helios/src/core/schema.rs:506-509rejects BF16 tables whoseglobal_scale.to_bits() != 0, andhelios/src/runtime_core/engram.rs:150-151requirestable.global_scale.to_bits() == 0in the matching match-arm. The two predicates are exact complements, so-0.0(bits0x8000_0000) is rejected by both rather than admitted by one — no validation/decode disagreement. - NVFP4 generalisation is behaviour-preserving.
helios/src/runtime_core/engram.rs:141-149replaces the hardcoded(160, 16, 80, 10)with(width, 16, width/2, width/16)guarded byembedding_width > 0 && embedding_width % 16 == 0; atwidth = 160this yields exactly(160, 16, 80, 10). The% 16guard prevents a fractionalwidth/16scale row. - New exact-coverage check closes a real hole.
helios/src/core/schema.rs:635-637(if end != table.rows { "engram partitions must cover all table rows" }) is new;mainonly checkedend > table.rows, so under-covering partitions passed schema validation whileruntime_core::engram::validate_shards(helios/src/runtime_core/engram.rs:103-105) already required exact coverage. The shards.length == ranks requirement atschema.rs:599-603is consistent withvalidate_deployment's rank commitments (ranks,tensor_parallel == ranks,schema.rs:423-435) and withvalidate_shards'world, so it does not reject legitimate rank-selective copies. - Optional scale plane is handled by every consumer I traced.
heliopause/src/export/core.rs:96-142(roles),:413-445(validate_ranks),:1534-1611/:1678-1706(core_engramTablePlan),:1474-1504(cached_engram, whichcontinues onNone),:1393-1417(estimated_export_fds, which uses.flatten()), andheliopause/src/export/weight_reuse.rs:397-410all guard the absent plane.helios/src/engram.rs:204-209/reader.rs:83-101/cache.rs:172-257reduce to zero-length slices whenplanes.scalesisNone(row[weights.len()..]is empty,debug_assert_eq!(weights.len() + 0, row_bytes)holds), so the row cache and staging paths do not panic — they simply omit the scale bytes. helios/proto/core.proto:269andhelios/proto/runtime_core.proto:665carry the identical append-only numbering{ UNSPECIFIED=0; FP8_E4M3_E8M0=1; NVFP4_E4M3_GLOBAL=2; BF16=3; FP8_E4M3_GLOBAL=4; }, so no existing wire value was renumbered. (The PR description's "FP8_E4M3_GLOBAL = 3,BF16 = 2" does not match the code's3/4; that is a description discrepancy, not a code defect, and appending is the correct choice.)
One item I could not verify (needs a command, not another read)
ignition/preparation/runtime_core_pb2.py shows +112/−112 with the only textual change being Protobuf Python Version: 7.36.1 → 7.36.2; the enum values live inside the single-line escaped DESCRIPTOR blob, so I could not confirm that the regenerated descriptor actually contains BF16 = 3 / FP8_E4M3_GLOBAL = 4. If it is stale, ignition would silently alias the new encodings. Worth one check: python -c "from ignition.preparation import runtime_core_pb2 as p; print(p.EngramTable.Encoding.items())" — expected [(0,'UNSPECIFIED'),(1,'FP8_E4M3_E8M0'),(2,'NVFP4_E4M3_GLOBAL'),(3,'BF16'),(4,'FP8_E4M3_GLOBAL')].