Code correctness report · NVIDIA/hyperflare-inference #732

Raw Markdown for agents: https://autobot.eidonix.com/p/3426eeac-feae-414f-a884-bb320dff991e.md

Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #732 (02ba762)

Scope: 10 files, ~565 changed lines across helios, heliopause, ignition → below the >12-file / >900-line partitioning threshold, so audited directly (no sub-agents).

Verdict: The Rust, protobuf, and export halves are correct and I verified several non-obvious invariants hold. I found one Major defect, in the Python (ignition) dispatch that this PR's new encoding makes newly reachable, plus three Minor observations.


Findings

1. Major — ignition/components/ngram_delivery.py:105-114 and :136-144: non-exhaustive mode dispatch folds unknown modes into the NVFP4 branch and dereferences a None scale plane; no ValueError on unsupported modes

The diff widens scales/scale to Optional (ngram_delivery.py:99-100) and turns scales is None into a normal, expected state for the new FP8_E4M3_GLOBAL encoding — precisely because the Rust decoder now emits scales: None for it (helios/src/runtime_core/engram.rs:159-167 → has_scales = scale_bytes.is_some() = false → :270-273 scales: scale_bytes.map(...) = None → :423 scales: has_scales.then_some(table.scale_buffer) = None, surfaced as table.scales on the Python side). The dispatch that then decides whether scales may be None is a two-literal if/elif with a catch-all else:

105     mode = state.query.quant_mode
106     if mode == "bf16":
107         state.run_lookup(weight.view(torch.bfloat16), None, None, ids, count, out, ...
109     elif mode == "fp8_e4m3_per_tensor":
110         state.run_lookup(weight.view(torch.float8_e4m3fn), scale, None, ids, count, out, ...
112     else:
113         state.run_lookup(weight, scales.view(torch.float8_e4m3fn), scale, ids, count, out, ...

and the identical structure in PreparedPLELookup.__init__:

136         mode = caps.quant_mode
137         if mode == "bf16":
138             lookup_weight, lookup_scale, lookup_scale_2 = self.weights.view(torch.bfloat16), None, None
139         elif mode == "fp8_e4m3_per_tensor":
140             lookup_weight, lookup_scale, lookup_scale_2 = self.weights.view(torch.float8_e4m3fn), table.scale, None
141         else:
142             lookup_weight = self.weights
143             lookup_scale = self.scales.view(torch.float8_e4m3fn)
144             lookup_scale_2 = table.scale

Callee/enum resolution: mode is not an enum — I grepped the whole repository and quant_mode occurs in exactly two places in production code (both lines above) plus the test's SimpleNamespace; there is no central vocabulary, no Literal, no validation, and no raise ValueError anywhere. The three literals ("bf16", "fp8_e4m3_per_tensor", and the implicit "nvfp4_group16" catch-all) exist only as string comparisons. _ple_lookup_planes(mode, ...) — the explicit validator with ValueError on unsupported modes / mismatched planes that the PR description says it "extracts" — does not exist in this diff or in the file; the logic is duplicated inline in two functions instead.

Concrete counterexample (provable by reading): a single-plane FP8_E4M3_GLOBAL table (table.scales is None, line 132 sets self.scales = None) combined with any quant_mode other than the two hardcoded literals — e.g. a recipe emitting "mxfp8", "fp8_e4m3", "fp8", or a capitalization variant "BF16" — takes the else arm at line 113 and raises an unhelpful

AttributeError: 'NoneType' object has no attribute 'view'

instead of a diagnosable ValueError. The same crash exists at line 143 during plan construction, so it fails at build time as well as at run time.

Second, subtler consequence of the same structure: the branch decision is read from two different objects — caps.quant_mode at plan time (line 136) and state.query.quant_mode at run time (line 105). If those ever disagree, the plan is built from one dtype/scale interpretation and the run executes another. The dangerous case is not the crash case but caps="fp8_e4m3_per_tensor" / query="bf16": the plan's invocation_from_tensors(weight=self.weights.view(torch.float8_e4m3fn), ...) binds an E4M3 view, while the run reinterprets the same uint8 buffer as bfloat16 (self.weights.view(torch.bfloat16)) and drops the scale — a silent reinterpretation of 1-byte rows as 2-byte rows, i.e. wrong embeddings with no error. (I could not prove from this repo that the two objects can differ, so I state this as a hazard created by the two-source-of-truth structure, not as a demonstrated failure.)

Also: mode == "bf16" silently discards table.scale (line 138 sets the scale to None unconditionally) rather than validating it is absent. Today helios/src/core/schema.rs:506-509 rejects a BF16 table with a nonzero global_scale, so the core backstops it — but helios/src/runtime_core/engram.rs:151 only requires global_scale.to_bits() == 0 (bf16-only path, not reproduced in the Python layer), so the Python layer is relying on an upstream guard it does not itself enforce.

Concrete fix — make the dispatch total and explicit, in one place, with the contract checks the PR describes:

def _ple_lookup_planes(mode, weight, scales, scale):
    if mode == "nvfp4_group16":
        if scales is None:
            raise ValueError("nvfp4_group16 PLE table requires a scales plane")
        return weight, scales.view(torch.float8_e4m3fn), scale
    if mode == "bf16":
        if scales is not None or scale is not None:
            raise ValueError("bf16 PLE table must not carry scale planes")
        return weight.view(torch.bfloat16), None, None
    if mode == "fp8_e4m3_per_tensor":
        if scales is not None:
            raise ValueError("fp8_e4m3_per_tensor PLE table must not carry a scales plane")
        if scale is None:
            raise ValueError("fp8_e4m3_per_tensor PLE table requires a global scale")
        return weight.view(torch.float8_e4m3fn), scale, None
    raise ValueError(f"unsupported PLE quant mode {mode!r}")

then call it from both _lookup (line 105) and PreparedPLELookup.__init__ (line 136), so caps.quant_mode and state.query.quant_mode are validated by the same code and the None-deref is unreachable.

Supporting evidence that this path is untested: the new test only parametrizes the three supported modes (tests/components/test_ngram_delivery.py:31-35), so every case takes a matched branch; there is no test for an unsupported mode or a mismatched plane, despite the PR description claiming "invalid mode/plane rejection tests."


2. Minor — helios/src/runtime_core/engram.rs:190: the table.embedding_width != width conjunct is unconditionally false for the new arm (dead condition, no harm)

159             wire::engram_table::Encoding::Fp8E4m3Global
160                 if table.embedding_width > 0
161                     && table.global_scale.is_finite()
162                     && table.global_scale > 0.0 =>
163             {
164                 let row_bytes = usize::try_from(table.embedding_width)
165                     .map_err(|_| invalid("FP8 global embedding row width overflow"))?;
166                 (table.embedding_width, 0, row_bytes, None)
...
190             || table.embedding_width != width

The arm binds width = table.embedding_width (line 166), so line 190 compares the field to itself. This is intentional (any width is legal for this encoding, unlike Fp8E4m3E8m0's fixed 256 at line 140) and it is the pre-existing pattern for Nvfp4E4m3Global (line 147), so it is harmless dead code rather than a defect — noted only because it means the width is not range-checked beyond > 0 here; the real bounds come from validate_buffer (:310-327) against the declared buffer, which I confirmed is the enforcing check.


3. Minor — helios/src/runtime_core/engram.rs:157 / helios/src/core/schema.rs:565: inconsistent overflow treatment, cosmetically preserved BF16 message

schema.rs:561-571 guards the BF16 width with checked_mul(2) ("BF16 engram row width overflow") while the new FP8 arm is a plain u64::from(table.embedding_width) with no multiply — correct, since FP8 rows are exactly embedding_width bytes and no overflow is possible. The BF16-specific error string at schema.rs:565 was left un-renamed while its two sibling messages were generalized to "single-plane…" (:582, :584, :626, :628). Purely cosmetic; the arithmetic is sound.


4. Minor — helios/src/core/schema.rs:506-512: the final else is only sound because of the earlier engram_encoding_has_scales call

502         if has_scales {
503             bounded_name(&table.scale_buffer, 64, "engram scale buffer")?;
504         } else if !table.scale_buffer.is_empty() || table.scale_block != 0 {
505             return Err(invalid("single-plane engram table cannot carry scale metadata"));
506         } else if table.encoding == wire::engram_table::Encoding::Bf16 as i32 {
507             if table.global_scale.to_bits() != 0 {
508                 return Err(invalid("single-plane engram table cannot carry scale metadata"));
509             }
510         } else if !(table.global_scale.is_finite() && table.global_scale > 0.0) {
511             return Err(invalid("FP8 global engram table requires a finite positive global scale"));
512         }

I traced the domains: has_scales == false at line 502 can only be reached with encoding ∈ {Bf16, Fp8E4m3Global}, because &?/"unknown" and Unspecified already returned Err at line 497 via engram_encoding_has_scales (:445-457, whose catch-all _ => Err covers Unspecified and out-of-range i32). So the else at 510 provably means Fp8E4m3Global exclusively — the guard is not dead and not contradictory. Recorded as a verified invariant, not a bug. The to_bits() != 0 test correctly rejects -0.0 and NaN for BF16, matching engram.rs:151 and the existing neg_zero assertion (schema.rs:2020-2022).


Checks that came back clean (verified, not assumed)

Regenerated Python descriptor is correct — I verified this arithmetically rather than assuming. My first pass suspected ignition/preparation/runtime_core_pb2.py was regenerated with a newer protoc (7.35.1 → 7.36.2) but a stale enum. It is not. The enum's serialized span grew from 11543..11622 (79 bytes, at main) to 11543..11643 (100 bytes, pr/732, lines 182-183). The added EnumValueDescriptorProto for FP8_E4M3_GLOBAL costs exactly: name (tag 1 + len 1 + 15 chars = 17) + number (tag 2 + varint 1 = 2) + outer repeated tag/len (2) = +21 bytes. 79 + 21 = 100 ✓, and every downstream span shifted by exactly 21 (_ENGRAMTABLE._serialized_end 11622→11643, _ENGRAMHASH 11768→11789, _BUNDLEINDEX 12057→12078, …). The new value is present and the file is internally consistent.

Signed-core schema validation (helios/src/core/schema.rs:445-457, 560-637): single-plane row geometry rows * embedding_width is byte-exact for both shared and partitioned planes; checked_mul guards overflow; scale_block == 0, empty scale_buffer, and absent scales are all enforced; partitioned shards are validated per-shard against shard.rows and the union must equal table.rows (:635-637). No off-by-one, no unsigned underflow.

Runtime decode (helios/src/runtime_core/engram.rs:159-167): finite-positive global_scale, row_bytes == embedding_width, scale_block == 0, and plane() (:257-269) re-checks stored_rows * row_bytes == span.nbytes — double-validated against the schema layer, with no window where one accepts and the other silently disagrees.

Export/combination (heliopause/src/export/core.rs:96-142, 1676-1733): engram_scales returning None correctly yields scales: None / scales_idx: None for both shared (line 1684 scales_idx.map(...)) and partitioned (line 1694) tables, and global_scale is propagated verbatim at line 1729. weight_reuse.rs:472 compares global_scale.to_bits() — the right comparison for -0.0/NaN equality — so cached Engram weights cannot be reused across differing global scales. conversion.rs:2862-2863 includes both encoding and global_scale in combined-core semantic identity.

Modified export test arithmetic (heliopause/src/export/core.rs:4413-4415, 4560-4596, 4633-4643, 4660-4690): installed.len() == 12 is correct (2 + 4 + 1 + 2 + 1 + 2 planes); the even/odd bad_idx convention (bad_idx % 2 == 0 → shared weights, else shards[0].weights) maps correctly onto the fixture's table order (0 shared, 1 partitioned, 2 shared, 3 partitioned, 4 shared, 5 partitioned) for all of [2,3,4,5]; FP8 payload sizes match exactly (rows=2 × width=8 = 16 shared, rows=1 × 8 = 8 per shard).

Hot-path complexity: the changed Rust adds one match arm (engram_encoding_has_scales, O(1) on an i32) and two constant-time predicates in decode. No loop, no per-iteration allocation, no Vec/HashMap clone, and no O(N·span) scan was introduced anywhere in the diff; decode's existing per-table loops are unchanged in shape.

Test file (tests/components/test_ngram_delivery.py): the fixture geometry is self-consistent with the Rust contract — row_bytes=256 for bf16 halves to 128 bf16 columns on .view(torch.bfloat16), row_bytes=128 for fp8 stays 128, row_bytes//8 scales for nvfp4 — and the assertions distinguish is table.scale (identity) from dtype checks correctly. The functional() → __call__ re-entry reuses output_shape/output_dtype and the retained weights/scales consistently. The only gap is the missing negative-mode case called out in Finding 1.


Summary

# Severity Location Defect
1 Major ignition/components/ngram_delivery.py:112-114, :141-144 Non-exhaustive quant_mode dispatch: no validator exists (_ple_lookup_planes is absent), unknown modes fall into the NVFP4 branch and dereference the now-legitimately-None scales (AttributeError instead of ValueError); decision duplicated across two functions reading two different objects, risking plan/run dtype divergence
2 Minor helios/src/runtime_core/engram.rs:190 table.embedding_width != width is self-comparison for the new arm (harmless, pre-existing pattern)
3 Minor helios/src/core/schema.rs:565 vs :582,584,626,628 BF16-specific overflow message left un-generalized during the rename
4 Minor (verified sound, no action) helios/src/core/schema.rs:506-512 Final else is Fp8E4m3Global-only by virtue of the line-497 guard — confirmed not dead, not contradictory

No other correctness, ordering, boundary, or hot-path defect found in the changed code. The docs and manifest.md edits match the implemented semantics; I raise no documentation concerns (separate lens).