Subtractive scratchpad · NVIDIA/hyperflare-inference #483

Raw Markdown for agents: https://autobot.eidonix.com/p/d60f0ef5-a94c-4e2f-9b6d-ce4492c58b30.md

#1 [high] PR 483 overview: scope and size

PR #483 (open, author rickybrent, head 2b4a31e, base main 27716185): "Add Gemma 4 image preparation, Bracketed patch-width metadata, and atomic spans". 36 files, +2269/-240.

Parts:

  1. Wire/contract: VisionCapacity.patch_features (proto tag 6, serde default 0 = legacy 1176), ImagePreparationKind::Gemma4 (tag 11), Gemma4ImageSettings (tag 11). helios/build.rs +4 (buffer override list).
  2. New helios/src/frontend/images/gemma4.rs (+534, of which ~300 test lines).
  3. packing.rs +285 (of which ~250 lines are a new #[cfg(test)] mod).
  4. load-time validation: server/config.rs validate_loaded_image_processor (+143, ~90 test).
  5. Bracketed atomic spans in layouts/bracketed.rs (+22) and model/prompt.rs (+126 mostly test).
  6. ignition/preparation/frontend.py +70/-6; tests/preparation/test_frontend_gemma4.py +216; tests/frontend/gemma4_images.json +256; generate_gemma4_image_fixtures.py +94.

Charter hooks (read_charter): line "Keep the runtime small and model-agnostic... Helios shouldn't accumulate per-model branches (#267, #334)"; "Solve the right problem in the right place... smallest footprint in shared code"; "Be explicit and pin everything. No magic defaults". Note: gemma4.rs SUPPORTED_SOFT_TOKENS magic list and patch_features=0 legacy default are tension points.

Baseline pre-existing code: packing.rs already hardcoded widths for every layout (Qwen/Mimo 1536, Deepseek* 588, Radio 768, Glm 1176, ClassToken 1200); conditioned.rs duplicated the same table via a _ => 588 fallback (bug: PatchMerge/ClassToken wrong). PR unifies behind ImageProcessor::patch_features().

#2 [high] Candidate subtractions list (v1)

Candidate subtractions found so far (to verify):

  1. tests/frontend/gemma4_images.json lines 2-125: processor (~74 lines: whole processor_config including audio/video/mel blocks) and model (~48 lines: full vision_config) are written by generate_gemma4_image_fixtures.py:28-29,81-86 but NO test reads them. The only consumer is helios/src/frontend/images/gemma4.rs:270-273, which uses fixture["cases"] only (width,height,seed,max_soft_tokens,grid,tokens,patches,pixels,positions,resized). => ~123 JSON lines + ~15 generator lines dead.

  2. helios/src/frontend/images/gemma4.rs:469-540ish native_pixels_and_positions_match_the_checkpoint_processor (#[ignore], needs .venv+transformers) duplicates exactly what the checked-in fixture test (canonical_processor_pixels_positions_and_resize + generate_gemma4_image_fixtures.py) proves; and checkpoint_tokens_expand_the_image_envelope (#[ignore], needs FLARE_GEMMA4_TEST_SNAPSHOT) duplicates the pure-Rust Envelope::expand test added in patch_merge.rs:218-305. ~160 lines total.

  3. gemma4.rs geometry_matches_the_hugging_face_processor (~25 lines) hardcodes grid/tokens for the same sizes (1x1, 672x672, 1008x672, 1920x1080, 10x3000, 3000x10) that gemma4_images.json cases already assert with HF-derived values; pixels_interleave_rgb_and_positions_are_xy (~18 lines) restates pixel count/position order that the fixture's pixels+positions SHA-256 cover.

  4. helios/src/frontend/images/packing.rs:16-24 LEGACY_BRACKETED_PATCH_FEATURES + bracketed_patch_features() legacy 0->1176 default: violates charter "No magic defaults"; the only producer of the contract is ignition (_expected/pipeline), and the PR's own docs say re-export is needed. Also compare #[serde(default)] on VisionCapabilities.patch_features (helios/src/model.rs:52) and proto comment (runtime_core.proto:281). Removes the special case in server/config.rs:456-464 and describe.rs:457-469 conditional insertion.

  5. helios/src/server/config.rs:456-464 second (Bracketed) mismatch block only fires when patch_features==0 (legacy) — dies with (4).

  6. helios/src/model/prompt.rs:58-64 & bracketed.rs:23 atomic_spans bool threaded from config; instead the layout could derive it. (weak)

  7. helios/src/frontend/images/layouts/bracketed.rs:55-88 run_start+flush_span closure + trailing flush + unreachable "missing envelope markers" error: at run start the code can push position-1..position+geometry.tokens+1 directly (Envelope::expand always wraps runs in start/end), ~10 lines.

  8. helios/src/frontend/images/gemma4.rs:13-15 SUPPORTED_SOFT_TOKENS magic list + contains + patch_size > 64/pooling_kernel_size > 16 bounds duplicate ignition's _expected gate (frontend.py: max_soft_tokens not in (70,140,280,560,1120), patch_size 16, pooling 3); PR itself calls it "defense-in-depth alongside Ignition's checkpoint gate".

  9. helios/src/frontend/images/packing.rs:26-32 square_merge_side gating tensor_layout + bracketed(): Bracketed's own geometry validation (tokens*patches_per_feature == patches, h % side) already rejects non-square; h % 2 == 0 also rejects odd values for pf=4.

  10. Gemma4ImageSettings.patch_size/pooling_kernel_size are pinned to 16/3 by ignition _expected; repo convention for fixed geometry profiles is unit variants (ImageSettings::Glm {}, Radio {}, PaddedGrid {}, Moonvit {}, Step {}, Deepseek4 {}). Dropping the two fields saves proto (2), mod.rs struct (2), protobuf.rs (2), describe.rs (2), gemma4 load/consts (~8) and ignition dict entries.

Still to check: patches.rs PatchProcessor reuse; model/prompt.rs image_frontend() helper reuse by patch_merge test; describe.rs vision_json consumers; conditioned.rs dedup done by PR; packing.rs test mod size (190 lines) vs conditioned.rs existing all-profile enumeration test.

#3 [high] Blocking: Gemma 4 profile has no qualified in-tree consumer (~560 lines)

The PR mixes two things: (a) shared fixes with a demonstrated defect, and (b) an entire new Gemma 4 image profile that nothing in the repository consumes.

(b) evidence that it is not needed yet:

Lines that serve only this unproven profile (~560 of +2269):

The rest of the PR is defensible and should land on its own: per-profile ImageProcessor::patch_features() (fixes conditioned.rs:184-194's _ => 588 fallback, which was wrong for PatchMerge=1176 and PaddedGrid=1200), Bracketed packing that reads width/merge stride from the contract instead of hardcoded 1176/4 (packing.rs:49-56, 493-518), and Bracketed atomic spans (layouts/bracketed.rs). Recommendation: split; land the metadata+span fix, defer the profile to the recipe PR that can prove export and serving.

#4 [high] Should fix: gemma4_images.json ships 124 lines no test reads

tests/frontend/gemma4_images.json lines 2-125 contain a full processor block (audio feature extractor, image_processor, video_processor, 74 lines) and a full model block (vision_config + model_type + image/video token ids, 48 lines).

Only consumer: helios/src/frontend/images/gemma4.rs:269-273 serde_json::from_str(include_str!("../../../../tests/frontend/gemma4_images.json")) then fixture["cases"].as_array(). Nothing reads ["processor"] or ["model"] (search_code "gemma4_images" → 1 hit; helios/tests/tools/test_images.rs expects an "assets" key and isn't pointed at this fixture).

Generator also builds them: tests/frontend/generate_gemma4_image_fixtures.py:28-29 reads processor_config.json/config.json, 81-85 builds profile, 86 writes dict(processor=raw, model=profile, cases=cases) — ~10 lines with no reader.

Smaller version: emit only {"cases": cases}; delete lines 28-29 and 81-85 of the generator, and JSON lines 2-125. Saves ~124 JSON lines + ~10 Python lines.

Caveat to state honestly in the report: tests/frontend/glm53_images.json (lines 2-87) and generate_glm_image_fixtures.py:29-30,43-44 do the same thing, so this follows an existing (already dead) convention; for the newly added file it is still 134 lines that no code reads.

#5 [high] Should fix: two #[ignore] tests duplicate the checked-in fixture (~160 lines)

helios/src/frontend/images/gemma4.rs:

  1. lines 449-533 (85 lines) native_pixels_and_positions_match_the_checkpoint_processor, #[ignore = "requires .venv with transformers Gemma4ImageProcessor"]: runs a Python heredoc that calls Gemma4ImageProcessor over (91,37),(10,3000),(3000,10) and compares pixels/positions. tests/frontend/generate_gemma4_image_fixtures.py:27-80 runs the same canonical processor over the same and more sizes and stores SHA-256s that canonical_processor_pixels_positions_and_resize (gemma4.rs:266-333) checks unconditionally under plain cargo test. Nothing is added by re-running the reference by hand; it is the same assertion with a weaker (tolerance-free but unordered) form.

  2. lines 374-447 (74 lines) checkpoint_tokens_expand_the_image_envelope, #[ignore = "requires FLARE_GEMMA4_TEST_SNAPSHOT"]: asserts a 262-token start/feature/end envelope from a real tokenizer. The same Envelope::expand behaviour is already asserted unconditionally by the new pure-Rust test patch_merge.rs:218-305 (envelope_expands_image_placeholders_and_rejects_mismatches, which checks exactly 2 start ids, 2 end ids, 5 feature ids, mm_token_type_ids, and mismatch rejection) and again by model/prompt.rs:1170-1283 bracketed_layout_emits_atomic_spans_only_when_contract_declares_them (span.len() == 262, markers at both ends).

Both also deviate from the repository's existing pattern for optional-snapshot tests, which skip by early return (layouts/bracketed.rs:126, helios/src/frontend/images/decoding_tests.rs, helios/tests/tools/test_images.rs); the PR description says this was deliberate ("explicit assertions rather than silent early returns"), which makes them fail-only-if-you-set-a-variable tests that CI never runs.

Delete both functions and the now-unused imports (use crate::frontend::{Asset, FrontendAssets, images::ImageSettings}, sha2, std::path::PathBuf) at gemma4.rs:189-191. Saves ~160 lines; every assertion remains covered unconditionally.

#7 [high] Should fix: packing.rs 11-profile table test duplicates conditioned.rs (~132 lines)

helios/src/frontend/images/packing.rs:579-826 is a new 247-line #[cfg(test)] mod tests.

processor_patch_features_match_tensor_layout_for_every_profile (lines 694-826, ~132 lines) builds an 11-row table of ImageSettings + ImageLimits + layout + patches_per_feature + patch_features and asserts processor.patch_features() == tensor_layout(...).1.

What already enforces that equality:

So the new table is a third copy of the profile list plus the same assertion. Keep the 60-line bracketed_packs_3x3_metadata_widths_and_rejects_invalid_extents (603-694), which is the only new behavior (3x3 stride, 768 width, truncation/odd-grid rejection); drop the 11-profile table: ~132 lines saved, and delete the 11 ImageSettings imports it needs.

If some direct table coverage is wanted, three representative rows (PatchMerge=1176, PaddedGrid=1200, Bracketed/Gemma4=768) do the same job in ~12 lines.

#11 [high] Final ranking and totals

Final ranking by lines saved (see entries 3-9 for detail):

  1. Blocking ~1,200 lines (53% of +2269): Gemma 4 profile is scaffolding — no in-tree recipe/contract declares it, PR says serving needs an unlanded recipe PR, docs/TODO.txt adds qualification TODOs, charter #74 requires proof it exports and serves. Defer: gemma4.rs 534, gemma4_images.json 256, test_frontend_gemma4.py 216, generate_gemma4_image_fixtures.py 94, frontend.py 60, proto/mod/protobuf/describe/conditioned/config/docs 40.
  2. Should fix 160: gemma4.rs ignored tests 374-533 (if the profile is kept).
  3. Should fix 134: fixture processor/model blocks (gemma4_images.json 2-125) + generator 28-29,81-85.
  4. Should fix 132: packing.rs:694-826 all-profile table (conditioned.rs + model/packing.rs already enforce it).
  5. Should fix 24: gemma4.rs:335-372.
  6. Nit 20: config.rs:449-464 duplicate width check (10) + square_merge_side → VisionCapabilities::validate (10).
  7. Nit 14: layouts/bracketed.rs:52-88 run_start/flush_span closure (10) + atomic_spans bool → Option<&ImageSpan> (4).

If the profile is deferred: ~1,200 of +2,269 removable → the PR shrinks to ~1,070 lines carrying only the shared Bracketed width/stride/span fix. If the profile is kept: ~484 removable → ~1,785.

#12 [high] Research summary

I reviewed all 36 changed files under the subtraction lens, against the charter, AGENTS.md contribution-scope rules, and docs/design-review.md. The change is not minimal: about 1,200 of its 2,269 added lines (over half) exist for a Gemma 4 image profile that no recipe, contract, or serving path in the repository consumes, and a further ~350 added lines are tests/fixtures that either duplicate each other or are read by nothing.

Findings, ranked by lines saved:

  1. Blocking (~1,200 lines) — the Gemma 4 profile is scaffolding. The PR itself states end-to-end serving needs an unlanded recipe PR, docs/TODO.txt gains qualification TODOs, no in-tree core declares image_layout for it (helios/tests/support/contracts/*.json only use 1,2,3,5,6,10), and image_profile="gemma4" has no non-test caller. That contradicts charter "#74 … prove they export and serve cleanly from the PR branch" and AGENTS.md "do not present scaffolding or partially wired features as supported". Defer gemma4.rs (534), gemma4_images.json (256), test_frontend_gemma4.py (216), generate_gemma4_image_fixtures.py (94), and the gemma4 block in frontend.py/proto/enums (~40); the remaining ~1,070 lines — per-profile patch_features(), contract-driven Bracketed width/stride, and Bracketed atomic spans — land on their own and fix a real defect (conditioned.rs's _ => 588 fallback was wrong for 1176/1200).

  2. Should fix (160) — gemma4.rs:374-533, two #[ignore] tests requiring a checkpoint snapshot or .venv re-prove what the checked-in hash fixture and the new unconditional Envelope::expand test already assert.

  3. Should fix (134) — gemma4_images.json:2-125 (full processor and model blocks) plus the generator code at lines 28-29 and 81-85 that builds them; the only reader uses ["cases"].

  4. Should fix (132) — packing.rs:694-826, an 11-profile table asserting patch_features() == tensor_layout(...); conditioned.rs:428-504 already runs all 11 profiles through valid_processed, and model/packing.rs:92-102 enforces the buffer side at load.

  5. Should fix (24) — gemma4.rs:335-372 restates grid/tokens/pixel/position facts the fixture cases already pin.

6-7. Nits (~34) — server/config.rs:449-464 compares the same width twice with two error strings; square_merge_side belongs in VisionCapabilities::validate; layouts/bracketed.rs:52-88 uses a run-tracking closure and trailing flush where the span is known at run start, and threads an atomic_spans bool that could be Option<&ImageSpan>.

I also recorded eight candidates I verified and rejected, so they are not mistaken for omissions: the patch_features = 0 → 1176 legacy default is required by design-review principle 13 and AGENTS.md core-compatibility (existing MiniMax cores have no such field), and the patch_features: 0 churn across ~20 test literals is the unavoidable cost of the new contract field. Details, line references, and the smaller code for each finding are in the scratchpad.

#13 [high] Counting basis: diff totals, production/test splits (corrects entry 3)

Corrected line counts and the arithmetic the report should quote.

Diff totals (pr_files / orientation packet), 36 files, +2269/-240:

Production vs test split (correction to entry 3: use these figures).

Totals per scenario (ranked findings 1-7 in entry 11):

Point to make once, not twice: removing the profile also removes the #[ignore] pair (finding 2) and the fixture's dead blocks (finding 3), so the report should present finding 1 as the umbrella and 2-3 as "only if the profile stays".

#6 [medium] Should fix: repeated geometry/pixel tests restate the fixture (~24 lines)

helios/src/frontend/images/gemma4.rs:

Total ~24 lines, no loss: every assertion is either in the fixture test or new-case coverage that can be folded into the fixture table.

#8 [medium] Nit: duplicated width check and square-merge helper (~20 lines)

helios/src/server/config.rs:443-490 validate_loaded_image_processor compares the processor width to the contract twice:

if vision.patch_features != 0 && width != vision.patch_features { return Err("... differs from prepared vision.patch_features ...") }
if image_layout == Some(Bracketed) {
    let expected = packing::bracketed_patch_features(vision);
    if width != expected { return Err("... re-export the core with vision.patch_features") }
}

The second block is unreachable after the first whenever patch_features != 0 (both compare width with the same value). So the two blocks are one condition:

let expected = (vision.patch_features != 0 || model.contract.frontend.image_layout == Some(ImageLayoutKind::Bracketed))
    .then(|| packing::bracketed_patch_features(vision));
if let Some(expected) = expected.filter(|expected| width != *expected) {
    return Err(format!("image preparation patch width ({width}) differs from the prepared layout width ({expected}); re-export the core with vision.patch_features").into());
}

Saves ~10 lines and one duplicated error string; every rejection the test at config.rs:937-1024 covers still fires (legacy 0 → 1176 mismatch, explicit mismatch, matching case).

Related: square_merge_side (helios/src/frontend/images/packing.rs:26-32) exists only so tensor_layout can reject a non-square ratio at load. Every profile in-tree has a square patches_per_feature (Qwen 4, Mimo 4, Deepseek 9, DeepseekRowMajor 9, Moonvit 4, Step 4, Radio 4, Glm 4, PatchMerge 4, PaddedGrid 4, Gemma4 9), so it is a contract invariant, not a Bracketed rule. Moving it into VisionCapabilities::validate() (helios/src/model.rs:72-92) as || !self.patches_per_feature.isqrt().checked_pow(2).is_some_and(|n| n == self.patches_per_feature) removes the helper, the extra vision parameter now threaded through tensor_layout (packing.rs:34-39, model/packing.rs:92-97, 4 test call sites) and the duplicate check in bracketed() (packing.rs:495). ~8-12 lines plus a smaller signature.

#9 [medium] Should fix: bracketed span run-tracking closure (~14 lines)

helios/src/frontend/images/layouts/bracketed.rs:52-88 adds run_start state, a flush_span closure with two error branches, and a trailing flush:

let mut run_start = None;
let mut flush_span = |start, end| { if atomic_spans { if start == 0 || end >= len { return Err("bracketed image span is missing envelope markers".into()) } spans.push(start-1..end+1) } Ok(()) };
for (position, kind) in ... {
    if *kind == 0 { if let Some(start) = run_start.take() { flush_span(start, position)?; } indices.push(-1); continue; }
    if position == 0 || mm[position-1] == 0 { ...conditioning.push...; run_start = Some(position); image += 1; }
    ...
}
if let Some(start) = run_start.take() { flush_span(start, len)?; }

The run's extent is already known where the run starts (processed.geometry[image].tokens), so the run-tracking state and the trailing flush disappear:

if position == 0 || expanded.mm_token_type_ids[position - 1] == 0 {
    let source = images.get(image).ok_or("unexpected image token span")?;
    conditioning.push(ConditioningEvent { position: position as u64, identity: source.identity });
    if let Some(span) = span {
        let end = position + processed.geometry[image].tokens + 1;
        spans.push(position.checked_sub(1).filter(|_| end <= expanded.token_ids.len())
            .ok_or("bracketed image span is missing envelope markers")?..end);
    }
    image += 1;
}

~10 lines saved and no closure. The two flush_span error branches are also redundant with validate_prompt_data (helios/src/model.rs:425-428 requires s.start < s.end <= tokens.len(); 441-456 requires tokens[s.start] == span.start_token and tokens[s.end-1] == span.end_token), so a mis-placed boundary is already rejected before admission.

Separately, the atomic_spans: bool parameter (bracketed.rs:23) is derived in one place from the contract at helios/src/model/prompt.rs:58-64:

config.contract.frontend.image_tokens.as_ref().and_then(|layout| layout.span.as_ref()).is_some()

Passing config.contract.frontend.image_tokens.as_ref().and_then(|l| l.span.as_ref()) as Option<&ImageSpan> instead removes the boolean and the .is_some(), and matches how class_token::prepare_input already receives a prepared layout field (helios/src/model/prompt.rs:69-73). ~4 lines.

#10 [medium] Rejected candidates (do not report as subtractions)

Items examined and deliberately NOT reported as subtractions (verified in code, would lose something the project needs):

  1. VisionCapabilities.patch_features with 0 = legacy 1176 (helios/src/model.rs:51-53, helios/src/frontend/images/packing.rs:16-24) is NOT gratuitous magic defaults. docs/design-review.md principle 13 and AGENTS.md "Model core compatibility" require protobuf additions to preserve existing core behavior through compatible defaults, and existing MiniMax Bracketed cores have no width field. Keep. (Charter's "No magic defaults" does not override the compatibility rule, and docs/runtime-core-design.md:181-190 documents the 0 case.)

  2. tensor_layout(kind, vision, ...) gaining the contract argument is required to size vision_pixel_values from the declared width (helios/src/model/packing.rs:92-102); the alternative is a second width source, which is what the PR removes.

  3. ImageProcessor::patch_features() (helios/src/frontend/images/mod.rs:459-469) replaces a duplicated per-profile table in conditioned.rs:184-194 whose _ => 588 fallback was wrong for PatchMerge (1176) and PaddedGrid (1200). Net -7 lines there and removes a real defect; keep.

  4. ImagePreparationKind::Gemma4 / gemma4 enum and proto tags: additive and consistent with the repo's contract_enum! pattern (helios/src/model/contract.rs:68). Only relevant if the profile lands at all (see blocking note).

  5. Ignition's tokenizer_config/snapshot keyword args (ignition/preparation/frontend.py:92-93, 293-313) exist because envelope tokens must be validated against tokenizer.json; Path/Tokenizer are imported where used, no new module-level import. Failing closed is defensible; not a removal.

  6. Per-field validation in gemma4::Processor::load (pooling_kernel_size² == limits.patches_per_feature, max_soft_tokens*area <= max_patches_per_image) mirrors the repo's existing load-time re-validation convention in patch_merge/mimo/etc.; only the patch_size > 64 and pooling_kernel_size > 16 caps and the SUPPORTED_SOFT_TOKENS list are redundant with Ignition's exact pins (frontend.py:124-133 pins 16, 3 and 70/140/280/560/1120), so they are dead weight inside a file the blocking finding removes anyway.

  7. crate::frontend::images::ProcessedImages default-building in layouts/bracketed.rs:27-34 is pre-existing, not this PR.

  8. The +1 patch_features: 0 lines across ~20 test struct literals (scheduler/tests.rs, server/runtime/phase_tests.rs, flare-cli/tests/unverified_payload.rs, helios/tests/deepseek_requests.rs, ...) are the unavoidable cost of the new contract field; no smaller form exists without a Default impl that would hide required capacities.

  9. docs/runtime-core-design.md +7, helios/README.md +7, model-contract.md 1 line, docs/TODO.txt +8: prose matches the code and follows AGENTS.md requirements; the TODO entry is required by "Record unresolved defects, unrun checks, and pending measurements in docs/TODO.txt". No duplication worth cutting (TODO's Gemma paragraph repeats the PR description's limitation sentence, but that is the required home for it).