Skip to content

Add Gemma 4 image preparation, Bracketed patch-width metadata, and atomic spans - #483

Open
rickybrent wants to merge 1 commit into
NVIDIA:mainfrom
rickybrent:core/gemma4-image-frontend
Open

rickybrent wants to merge 1 commit into
NVIDIA:mainfrom
rickybrent:core/gemma4-image-frontend

Conversation

@rickybrent

@rickybrent rickybrent commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Why

Gemma 4 multimodal checkpoints preprocess images into aspect-preserving 16×16 interleaved RGB patches (768 f32 elements per patch), 2D (x, y) patch coordinates, 3×3 spatial pooling (patches_per_feature = 9, up to 1,120 soft tokens per image), and an atomic image envelope (start_token, repeated image_token features, end_token). Previously, Helios had no Gemma 4 image preparation profile, ImageLayoutKind::Bracketed hardcoded 2×2 merge (patches_per_feature = 4) and 1,176 floats/patch, and Bracketed layouts did not emit atomic image spans when declared by ImageTokenLayout.span. Without this, Gemma 4 multimodal cores cannot prepare or load native image processing, Bracketed vision uploads cannot pack 3×3 / 768-float patches, and a span-declaring Bracketed image fails per-request at validate_prompt_data (or hits per-request chunk-size rejections rather than failing at load when the maximum image envelope exceeds prefill_chunk_size or span.max_tokens).

What changed

  • Wire & contract metadata (helios/proto/runtime_core.proto, helios/build.rs, ignition/preparation/runtime_core_pb2.py, ignition/preparation/contract.py, helios/src/model.rs, helios/src/model/contract.rs, helios/src/runtime_core/{describe,protobuf}.rs, docs/runtime-core-design.md, helios/README.md, helios/model-contract.md, docs/TODO.txt):
    • Added additive ImageSettings.profile tag 11 (Gemma4ImageSettings), ImagePreparationKind::Gemma4 (tag 11), VisionCapacity.patch_features (tag 6, #[serde(default)], 0 = legacy Bracketed width 1176), and VisionCapabilities::bracketed_patch_features().
    • Defaulted vision["patch_features"] = 0 in ignition/preparation/contract.py and documented that Bracketed vision recipes with non-1176 patch widths set it.
    • Regenerated ignition/preparation/runtime_core_pb2.py matching origin/main (Protobuf Python Version: 7.36.1, pure descriptor-only diff).
    • Updated VisionCapabilities::validate() to allow 0 (legacy default) and reject nonzero widths that are not positive multiples of 3, and added a protobuf round-trip test verifying serialized Gemma 4 settings select only image preparation.
  • Native image preparation, orthogonal Bracketed packing, and load-time validation (helios/src/frontend/images/{gemma4,mod,conditioned,packing,patch_merge}.rs, helios/src/model/packing.rs, helios/src/server/config.rs):
    • Implemented helios/src/frontend/images/gemma4.rs (area-bounded uint8 antialiased bicubic resize matching PyTorch/torchvision, 1/255 scaling, interleaved (y, x, channel) 16×16 patches, (x, y) patch coordinates, shared patch_merge::Envelope expansion, and per-condition load errors naming failing fields and bounds).
    • Removed the patches_per_feature -> width lookup table in packing.rs: Bracketed now reads per-patch float width via VisionCapabilities::bracketed_patch_features() (0 defaults to legacy MiniMax temporal-merge width 3 * 2 * 14² = 1176, which cannot be derived from 3 * patch_size² alone because MiniMax duplicates frames temporally) and derives merge stride from any positive square patches_per_feature.
    • Unified per-profile patch widths behind ImageProcessor::patch_features() (fixing conditioned.rs cache validation across all profiles, including PaddedGrid = 1200 and PatchMerge = 1176) and added cross-profile consistency test coverage.
    • Enforced load-time consistency split cleanly across layers: gemma4::Processor::load verifies pooling_kernel_size² == limits.patches_per_feature and max_soft_tokens * pooling_kernel_size² <= limits.max_patches_per_image, and server::config::validate_loaded_image_processor checks processor.patch_features() against vision.bracketed_patch_features() (single actionable re-export error for any Bracketed mismatch) or nonzero vision.patch_features for other layouts, plus max_image_envelope_tokens <= prefill_chunk_size and <= image_tokens.span.max_tokens.
  • Layout-owned atomic spans (helios/src/frontend/images/layouts/bracketed.rs, helios/src/model/prompt.rs):
    • Moved atomic span emission into layouts::bracketed::prepare_input (matching layouts::deepseek), gated on image_tokens.span.is_some() and validating prompt bounds on both ends; deleted the fallback block in model/prompt.rs.
  • Checkpoint validation & deterministic test fixtures (ignition/preparation/frontend.py, tests/frontend/generate_gemma4_image_fixtures.py, tests/frontend/gemma4_images.json, tests/preparation/test_frontend_gemma4.py, helios/src/model/tests.rs):
    • Tightened ignition/preparation/frontend.py to accept any model_type: "gemma4" / vision_config.model_type: "gemma4_vision" checkpoint (E2B, E4B, 26B-A4B, 31B) while rejecting gemma4_unified (12B), and to validate image_token, boi_token, and eoi_token from tokenizer_config.json against tokenizer.json and optional config.json token IDs (failing closed if tokenizer_config or snapshot is omitted).
    • Checked in tests/frontend/generate_gemma4_image_fixtures.py and tests/frontend/gemma4_images.json (8 bit-exact SHA-256 cases across max_soft_tokens = 280 and 1120) verified unconditionally under plain cargo test (with its processor and model provenance blocks verified in tests/preparation/test_frontend_gemma4.py), added unconditional pure-Rust Envelope::expand, Bracketed span-bearing contract, and legacy Bracketed Inputs::new core-load tests, and kept the live-tokenizer envelope test #[ignore] with explicit assertions.

Claimed result

Helios natively decodes, resizes, normalizes, packs, and validates Gemma 4 images with bit-exact SHA-256 pixel, resize, and (x, y) position parity against Hugging Face's Gemma4ImageProcessor, enforces patch-width and atomic-span invariants at load time, and emits atomic spans from the Bracketed layout.

Load-path impact on existing cores: MiniMax (Bracketed + PatchMerge) and all non-Bracketed upstream cores remain loadable and unchanged (missing patch_features decodes as 0, which preserves the legacy 1176 width for Bracketed — covered by legacy_bracketed_core_omitting_patch_features_loads_and_stages_1176_wide_pixels through Inputs::new; the envelope bound check applies only to profiles exposing max_image_envelope_tokens, i.e., Gemma 4; among existing span-declaring layouts in-tree, Deepseek / DeepseekRowMajor continue emitting their own data.spans). Narrowings: Bracketed now requires a positive-square patches_per_feature, and any Gemma 4 core prepared before this change (with patch_features == 0) is rejected at load with an actionable error (bracketed image layout patch width (1176) differs from image processor (768); re-export the core with vision.patch_features).

Supporting evidence and limitations

Verified on origin/main (v0.5.0 0a8c20f4, commit 445c6658):

  • cargo test --offline --locked --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --lib frontend::images: 48 passed, 0 failed, 1 ignored (includes unconditional 8-case HF SHA-256 fixture parity across max_soft_tokens=280 and 1120, S1/S3 load rejections, 11-profile width consistency, Bracketed behavioral packing, pure-Rust Envelope::expand, and upstream 70e0f4a8's patch_merge_materializes_and_caches_with_exact_pixel_width).
  • Live-checkpoint test (not part of CI; requires a local snapshot directory containing tokenizer.json and tokenizer_config.json from google/gemma-4-31B-it at 842da3794eaa0b77d5f08bae87a17459d91ff475): FLARE_GEMMA4_TEST_SNAPSHOT=/path/to/gemma-4-31B-it-snapshot cargo test --offline --locked --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --lib -- --ignored --exact frontend::images::gemma4::tests::checkpoint_tokens_expand_the_image_envelope: 1 passed, 0 failed.
  • cargo test --offline --locked --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --lib model::: 57 passed, 0 failed (including legacy_bracketed_core_omitting_patch_features_loads_and_stages_1176_wide_pixels through Inputs::new and span/chunk-size rejections).
  • cargo test --offline --locked --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --lib runtime_core::protobuf: 29 passed, 0 failed (including Gemma 4 profile round-trip).
  • cargo test --offline --locked --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --lib server::config: 3 passed, 0 failed (bootstrap patch_features, 64-aligned prefill_chunk_size, and span.max_tokens boundary checks).
  • cargo test --offline --locked --manifest-path flare-cli/Cargo.toml --test unverified_payload: 7 passed, 0 failed.
  • cargo test --offline --locked --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --tests --no-run and cargo check --offline --locked --manifest-path flare-cli/Cargo.toml --tests: passed.
  • Rebuilt flare-heliopause (uv pip install --offline --python .venv/bin/python --no-deps --reinstall ./heliopause) and ran HF_HUB_CACHE=... CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/preparation/test_core_boundary.py tests/preparation/test_source_identity.py tests/preparation/test_frontend_gemma4.py: 23 passed, 0 skipped in 2.89s (validating synthetic E2B-sized towers, gemma4_unified 12B rejection, bad envelope tokens, checked-in gemma4_images.json provenance blocks, plus local cached checkpoints; cached checkpoint cases are not part of CI).
  • External compatibility check in hyperflare-recipes (recipes/gemma4-vision-wiring d15e059, HF_HUB_CACHE=... .venv/bin/pytest -v tests/frontend/test_gemma4_images.py): 3 passed, 0 skipped.
  • Limitations: no serving-path timing or memory was measured; evidence here is unit-, fixture-parity-, and preparation-level. Because recipes were extracted to local-inference-lab/hyperflare-recipes, this core profile lands ahead of its companion Gemma 4 vision recipe PR (recipes/gemma4-vision-wiring, which declares vision.patch_features = 768), tracked in docs/TODO.txt alongside E2B/E4B/26B-A4B serving qualification and partial-span prefix-cache audit.

Branch logistics

  • Repository: NVIDIA/hyperflare-inference
  • Branch / commit: rickybrent:core/gemma4-image-frontend (445c6658) targeting main (0a8c20f4, v0.5.0).

Discord: ran.cossack

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 483
Case File Intake Report

To opt out, include #autobot:ignore in the PR or any comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Full Review

Changes Requested

The bones are good — the proto/contract additions are properly additive, the patch_merge::Envelope extraction is real de-duplication, and the Gemma 4 geometry is overflow-guarded. What blocks merge is that three behaviours do more than the description says, and one headline claim has no reproducible evidence.

Blockers:

  • packing.rs:16-22 maps patches_per_feature → patch width (4 => 1176, 9 => 768): patch width is 3·patch_size², and DeepSeek already runs 9 patches/feature at 588 floats, so this is model identity inside shared packing — the opposite of the description's "orthogonal, no model-identity branching" claim. → Put the width in prepared metadata (VisionCapabilities.patch_size) and derive merge_side = ppf.isqrt(), width = 3·patch_size².
  • The Hugging Face parity tests silently return when FLARE_GEMMA4_TEST_SNAPSHOT or ../.venv/bin/python is absent (gemma4.rs:236-256, 281-283, 336-339), so "45 passed" is identical whether the comparison ran. → Check in a tests/frontend/gemma4_images.json (not opened) fixture + generator like glm.rs:147-199, or #[ignore] both tests and report them as unrun.
  • Atomic spans are populated in shared code (prompt.rs:137-151) for any layout declaring an ImageSpan, changing validate_prompt_data and set_prefill_spans semantics, with no test (gemma4_frontend.json:38 has "image_tokens": null) and no stated blast radius. → Emit the span in layouts/bracketed.rs beside the envelope (deepseek.rs:149 pattern), delete the shared block, add a span-bearing fixture and test.

Should fix:

  • gemma4::Processor::load (gemma4.rs:23-31) accepts patch_size ≤ 64 / pooling ≤ 16, so a profile can load that the packer and cache validator cannot represent. → Require pooling² == limits.patches_per_feature and the patch width to match at load.
  • Patch width authored three times (packing.rs:19, conditioned.rs:192, gemma4.rs:116) with no compile-time link; conditioned.rs:191 shows the right pattern. → One shared constant/helper.
  • max_soft_tokens: 1120 → a 1,122-token envelope that model.rs:421-423 / scheduler.rs:1922-1930 reject on a small prefill_chunk_size, and nothing checks it at load. → Reject or clamp at load, plus a boundary test.
  • Ignition pins one vision tower (frontend.py:126-129: 27 layers/1152 hidden/16 heads/72 dim/4304 FFN) and literal image tokens; the charter asks for more than one checkpoint (qwen38: support compressed-tensors NVFP4 expert-only checkpoints such as ThinkingCap-Qwen3.8-Flash-Next-NVFP4 #74). → Assert only consumed fields, take the tokens from the tokenizer, show a second checkpoint.
  • Docs left stale: helios/README.md:702-704, docs/runtime-core-design.md:226-233, helios/model-contract.md:251-254 all enumerate profiles and omit Gemma 4; the recipe dependency belongs in docs/TODO.txt.
    ... 2 more (description corrections; runtime_core_pb2.py regenerated at 7.36.1 under a >=7.36.2 pin)

Nits:

7 nits (churn in the staging.put rewrite, a table-only test, missing protobuf round-trip test, duplicated soft-token allowlist, and four prose items)

To opt out of future reviews, put #autobot:ignore in your response.

@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from f2340e4 to 792522d Compare November 25, 2026 07:43
@rickybrent rickybrent changed the title Add Gemma 4 image prep profile, bracketed 3x3 packing & atomic spans Add Gemma 4 image preparation, Bracketed patch-width metadata, and atomic spans Nov 25, 2026
@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from 792522d to 2b4a31e Compare November 25, 2026 08:08
@rickybrent

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review! The branch has been rebased onto main (27716185) and updated to address each blocker, should-fix item, and nit:

  • B1 (Bracketed patch width & merge stride — note on patch_features vs 3 * patch_size²): MiniMax (PatchMerge), the existing ImageLayoutKind::Bracketed user, duplicates frames temporally (3 * 2 * 14² = 1176 floats/patch in helios/src/frontend/images/patches.rs:84), so deriving width from 3 * patch_size² alone would yield 588 and break existing MiniMax cores. To keep packing.rs free of any model-identity table while preserving every existing upstream core, we added additive uint64 patch_features = 6 to VisionCapacity (#[serde(default)], with 0 preserving the legacy 1176 width for Bracketed and Gemma 4 recipes declaring 768). Bracketed now derives its merge stride from any positive square patches_per_feature with checked arithmetic and reads per-patch width solely from prepared VisionCapabilities.
  • B2 (Unconditional HF parity & envelope coverage): Added tests/frontend/generate_gemma4_image_fixtures.py and checked in tests/frontend/gemma4_images.json (8 bit-exact SHA-256 cases across max_soft_tokens = 280 and 1120, covering pixels, (x, y) positions, and resized RGB bytes) verified unconditionally under cargo test. Added unconditional pure-Rust synthetic-tokenizer Envelope::expand tests in patch_merge.rs, removed the Python subprocess from checkpoint_tokens_expand_the_image_envelope (using an inline Jinja template), and marked the live-snapshot parity tests #[ignore] with explicit assertions instead of silent early returns.
  • B3 (Layout-owned atomic spans): Moved atomic span emission into layouts::bracketed::prepare_input (matching layouts::deepseek), validating both start/end envelope markers and gating on image_tokens.span.is_some(). Deleted the fallback in model/prompt.rs and added span-bearing, chunk-too-small (64-aligned), and no-span (MiniMax) contract tests.
  • S1 & S3 (Load-time validation): Split cleanly across layers: gemma4::Processor::load verifies pooling_kernel_size² == limits.patches_per_feature and max_soft_tokens * pooling_kernel_size² <= limits.max_patches_per_image; server::config::validate_loaded_image_processor checks processor.patch_features() against vision.patch_features (with an actionable re-export error on Bracketed mismatch) and enforces max_image_envelope_tokens <= prefill_chunk_size and <= image_tokens.span.max_tokens.
  • S2 (Unified per-profile patch width): Added ImageProcessor::patch_features() covering all profiles (including PaddedGrid = 1200, PatchMerge = 1176, Gemma4 = 768), wired conditioned.rs to use it, and added an 11-pair cross-profile consistency test in packing.rs.
  • S4 (ignition/preparation/frontend.py): Dropped the 31B-only encoder dimension checks so any model_type: "gemma4" / vision_config.model_type: "gemma4_vision" checkpoint (E2B, E4B, 26B-A4B, 31B) is accepted while 12B (gemma4_unified) is rejected; validated image_token, boi_token, and eoi_token from tokenizer_config.json against tokenizer.json and optional config.json IDs (failing closed if tokenizer_config or snapshot is omitted). Added tests/preparation/test_frontend_gemma4.py covering synthetic variants, negative cases, and cached google/gemma-4-31B-it, nvidia/Gemma-4-31B-IT-NVFP4, and google/gemma-4-E2B-it checkpoints.
  • S5, S6, S7 & N1–N7: Updated helios/README.md, docs/runtime-core-design.md, helios/model-contract.md, docs/TODO.txt (tracking companion recipe wiring, E2B/E4B/26B-A4B serving qualification, and partial-span prefix-cache audit), and refreshed the PR description (removing the stray Execution.persistent_workers reference). Regenerated ignition/preparation/runtime_core_pb2.py with libprotoc 36.1 matching main (descriptor-only diff). Applied N1–N6 cleanups (staging.put formatting, behavioral bracketed() tests, image_processor.max_soft_tokens budget comment, protobuf Gemma 4 round-trip test, Envelope doc comment, consistent error wording; keeping check_input_extent + geometry() explicit-error ordering per N3).

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents.

Recommendation: Changes Requested

Blockers:

None. Nothing on the served path is incorrect; the remaining items are one scope question, one authoring gap on the Python side, and cleanup.

Should fix:

  • Profile lands ahead of its exporter, and no test mounts a Bracketed core. Serving waits on an unlanded hyperflare-recipes PR (docs/TODO.txt:331-337) and no contract fixture under helios/tests/support/contracts/ uses the profile, while tensor_layout now runs at core load. → Confirm a maintainer approved landing it ahead of the recipe (or split the shared half out), and add one core-load test with a Bracketed contract that omits patch_features.
  • Nothing on the Python side authors patch_features. ignition/preparation/contract.py:112 defaults vision to the four historical keys, so a recipe filling them exports patch_features = 0 and its core is rejected at flare run (server/config.rs:456-463) — though Ignition already validated patch_size=16/pooling=3 (frontend.py:124-127). → Derive the width in Ignition and document the key.
  • One error message for seven load rejections. gemma4.rs:30-38 returns "invalid Gemma 4 image settings" for the pooling mismatch and patch-budget overflow too, where the capacity comes from the export, not the checkpoint. → Split by condition, naming the field and both values, as server/config.rs:449-463 does.
  • Dead wire knobs and constants spelled several ways. patch_size/pooling_kernel_size are proto/serde/Python fields no exporter can vary (frontend.py:124-127,169-170), making three validation arms unreachable; 768 is spelled four ways and gemma4.rs:132 re-inlines it; the soft-token allowlist lives in two languages. → const PATCH/POOLING/FEATURES like glm.rs:13 (not opened), reserve proto tags 1-2, keep one allowlist.
  • Superseded tests and unread fixture data. native_pixels_and_positions_match_the_checkpoint_processor (gemma4.rs:451-533) duplicates fixture cases already pinned by hash unconditionally; gemma4.rs:394-413 hashes a chat template it never renders (and leaks it on early return); tests/frontend/gemma4_images.json:2-125 is 124 lines nothing reads, including the image_token_id/boi_token_id/eoi_token_id that would make the envelope claim testable. → Delete the first two; consume the model block or trim it.

Nits:

5 nits


PR #483 — Add Gemma 4 image preparation, Bracketed patch-width metadata, and atomic spans

Head 2b4a31e, base main 27716185, 36 files, +2269/−240. Third review round; line-level detail and prior rounds are in the linked case file.

Key findings

No blockers. Every blocker and should-fix from the previous round is fixed and verified in code at this head: patch width comes from prepared metadata instead of a patches_per_feature lookup table, the Hugging Face parity fixture runs unconditionally under cargo test, atomic spans are emitted by the Bracketed layout rather than shared prompt code, patch width has one authority across all 11 profiles (which also fixes a real main bug for PatchMerge 1176 / PaddedGrid 1200), load-time bounds cover pooling, patch budget and envelope size, and the Ignition tower pins are gone. Genuinely good work.

What remains: five should-fix items — one scope question needing an answer before merge, one authoring gap that hands the first Gemma 4 recipe author a serve-time error, one opaque load error, dead configuration knobs, and superseded test scaffolding — plus five nits, mostly documentation and duplicated test rows.

Note on diff scope: the head diff also shows large unrelated base-branch churn (banner removal, flare doctor, parallax, download rewrites, RebuildManifest → PreparationManifest). Those commits landed on main between the old base and now, are not this PR's files, and are not attributed to the author.

Verified resolved this round — not re-litigated

  • The patches_per_feature → width model-identity table is gone: packing.rs:16-24 (bracketed_patch_features, 0 → legacy 1176) and packing.rs:26-32 (isqrt plus square check for the merge stride).
  • Parity evidence runs unconditionally: tests/frontend/gemma4_images.json (8 cases, max_soft_tokens 280/1120) is consumed by gemma4.rs:267-333 under plain cargo test; the live-checkpoint tests are #[ignore]d with hard assertions (gemma4.rs:375-385, :449-457) instead of silent returns.
  • Atomic spans moved into the layout that builds the envelope (layouts/bracketed.rs:52-70); the shared prompt.rs fallback is deleted; markers are validated at both ends.
  • gemma4::Processor::load enforces the packing contract (gemma4.rs:25-39): pooling_area == Some(limits.patches_per_feature), patch budget, checked_mul so overflow fails closed.
  • Patch width has one authority (mod.rs:459-471, used at conditioned.rs:187 (not opened)).
  • The maximum envelope is bounded at bootstrap against prefill_chunk_size and span.max_tokens (server/config.rs:465-488), with 64-aligned boundary tests.
  • Ignition no longer pins one vision tower; envelope tokens come from tokenizer_config.json (not opened), are validated to encode as single tokens, and cross-checked against config.json (not opened) (frontend.py:114-173); gemma4_unified is rejected on all three surfaces and three cached checkpoints are covered in tests/preparation/test_frontend_gemma4.py.
  • Docs updated (helios/README.md:709,713-719, docs/runtime-core-design.md:181-197, helios/model-contract.md:82, docs/TODO.txt:331-337).
  • The earlier runtime_core_pb2.py version concern is withdrawn: the header reads 7.36.1 identically on main and on this head; pyproject.toml:34 (not opened)'s protobuf>=7.36.2 bounds the runtime, not the generator header. The diff is descriptor-only plus the new fields.

Blockers

None.

Should Fix

S1 — The profile lands ahead of the exporter that can use it, and no test mounts an existing Bracketed core

Finding: the description defers end-to-end serving to an unlanded companion PR in local-inference-lab/hyperflare-recipes, and docs/TODO.txt:331-337 records qualification (E2B/E4B/26B-A4B/31B export and serving) as open. No core fixture uses the profile: helios/tests/support/contracts/gemma4_frontend.json:16-17,38 has image_preparation: null, image_layout: null, image_tokens: null, and no contract JSON under helios/tests/support/contracts/ declares a Bracketed layout (values used: 1, 2, 3, 5, 6, 10). The charter asks a new model format to "prove they export and serve cleanly from the PR branch, and support more than a single checkpoint (#74)" and separately to "verify that existing data, artifacts, and exported cores still load". The legacy staging arithmetic is tested — packing.rs:660-670 asserts patch_features == 0 yields 16 × 1176, and :671-680 asserts a non-square patches_per_feature errors — but the load path is not: tensor_layout runs from Inputs::new (model/packing.rs), so an existing Bracketed core now passes through square_merge_side (packing.rs:26-32) at core load, and nothing in the tree mounts such a core.

Request: state in the description whether a maintainer approved landing the profile ahead of its recipe, or split the shared half (patch_features field, contract-driven Bracketed packing, Bracketed spans, envelope bounds) onto its own PR, since it stands alone and fixes a main defect. Either way, add one core-load test with a Bracketed contract JSON that omits patch_features, asserting the core loads and stages 1176-wide pixels.

Why: the charter makes export-and-serve the bar for a new profile and requires existing cores be shown to still load. Both claims are currently prose only.

S2 — Nothing on the Python side authors patch_features

Finding: ignition/preparation/contract.py:112 defaults vision to the four historical keys (features_per_request, max_images, patches_per_feature, patch_capacities) plus feature_slots: 0, and never mentions patch_features; a search for the name across ignition/ returns only the generated runtime_core_pb2.py. A recipe that fills the historical four keys therefore exports patch_features = 0, bracketed_patch_features reads that as 1176 (packing.rs:18-24), and server/config.rs:456-463 rejects the core at flare run with "bracketed image layout patch width (1176) differs from image processor (768); re-export the core with vision.patch_features". Meanwhile Ignition has already validated patch_size = 16 and pooling_kernel_size = 3 from the checkpoint (frontend.py:124-127, :140-141) and writes them literally at :168-170, so the width is derivable as 3 · patch_size² = 768.

Request: derive patch_features in Ignition from the settings it already validated and emit it in the vision block, and add patch_features=0 to the default dict at contract.py:112 with a docstring note that Bracketed vision cores must set it.

Why: right problem, wrong layer. The width is preparation metadata; the first feedback a recipe author gets should not be a serve-time rejection whose only other hint is a docs/TODO.txt line.

S3 — Seven distinct load rejections share one message

Finding: gemma4.rs:30-38 returns "invalid Gemma 4 image settings" for zero/oversized patch_size, zero/oversized pooling_kernel_size, an unsupported max_soft_tokens, pooling_area != Some(limits.patches_per_feature) (:35), and the patch budget max_soft_tokens · pooling² > limits.max_patches_per_image (:36). The last two compare settings against captured capacity, and that capacity comes from the export's vision.patch_capacities (server/config.rs:497-502), not from the checkpoint — so an operator cannot tell a mis-exported core from a mis-declared checkpoint. server/config.rs:449-463 in this same PR shows the actionable style, and the neighbouring Envelope::load (gemma4.rs:40-44) names the offending token.

Request: split the condition into named errors naming the failing field and both values; add a comment naming the source of the patch_size > 64 / pooling > 16 bounds.

Why: a load path that only says "invalid settings" moves the diagnosis onto the operator, and this is the error most likely to be hit because the capacity comes from export, not the checkpoint.

S4 — Dead wire knobs and constants spelled several ways

Finding: Gemma4ImageSettings.patch_size / pooling_kernel_size (helios/proto/runtime_core.proto:599-600, mod.rs:335-336, gemma4.rs:18-19) travel through proto, serde and the Python producer, but no exporter can emit anything but 16/3: frontend.py:124-127 and :140-141 reject any other pair and :169-170 writes the literals — which makes the patch_size > 64 / pooling > 16 arms at gemma4.rs:32-33 unreachable. The width 768 is spelled four ways: computed at gemma4.rs:55, via patch_features() at conditioned.rs:187 (not opened), the legacy 1176 at packing.rs:16, and a 3 * 16 * 16 literal in a test. gemma4.rs:132 re-inlines 3 * self.patch_size * self.patch_size instead of calling self.patch_features(), so the value validated at server/config.rs:448 and the value sizing the buffer are two expressions. conditioned.rs:367 (not opened) recomputes pooling_kernel_size * pooling_kernel_size outside gemma4.rs. The soft-token allowlist exists twice in two languages (gemma4.rs:13, frontend.py:132) with no test tying them.

Request: replace with const PATCH: usize = 16; const POOLING: usize = 3; const FEATURES: usize = 3 * PATCH * PATCH; as helios/src/frontend/images/glm.rs:13 (not opened) does; reserve proto tags 1-2 (append-only rule); drop the struct fields, serde keys, validation arms and the two Python literals; make gemma4.rs:132 call self.patch_features(); keep the Python soft-token gate (preparation is the right place) and let Rust accept any positive budget, or the reverse — not both.

Why: AGENTS.md:188-193 (not opened) forbids configuration switches without a concrete requirement, and these tags become permanent once a core ships. Doing this now costs ~25 lines; later it costs a reserved-tag migration.

S5 — Superseded test scaffolding and 124 unread fixture lines

Finding:

  • native_pixels_and_positions_match_the_checkpoint_processor (gemma4.rs:451-533, #[ignore]d, ~85 lines) uses exactly fixture seeds 1/5/6 — (91,37), (10,3000), (3000,10) — which gemma4.rs:267-333 already pins by SHA-256 for grid, tokens, patches, resized RGB, pixels and positions, unconditionally. It also carries a bespoke struct.pack('<qqqq') IPC with a hand-computed pixel_offset = 32.
  • gemma4.rs:394-413 writes and hashes a Jinja chat template the test never renders (frontend.encode at :425 is not a render), then removes it after several unwraps, so a panic leaks it and the early-return path skips the removal.
  • tests/frontend/gemma4_images.json:2-125 — 124 of 257 lines — is a processor snapshot plus a trimmed model block nothing reads: the sole consumer iterates fixture["cases"] (gemma4.rs:269-273), and the generator writes both at generate_gemma4_image_fixtures.py:81-86. The model block is exactly where image_token_id/boi_token_id/eoi_token_id live — the recorded ids that would make the envelope claim testable in CI.

Request: delete the ignored Python-comparison test and the chat-template plumbing; for the fixture, either consume the model block in Rust (assert the configured envelope strings map to the recorded ids and that processor round-trips into Gemma4ImageSettings) or trim both blocks to a small provenance object. Also state in the description that the live-checkpoint runs are not part of CI.

Why: AGENTS.md:194-199 (not opened) — "Do not present scaffolding or partially wired features as supported." An ignored test that duplicates an unconditional one is a liability, and a 124-line block nothing reads invites the next reader to assume it is validated somewhere.

Nits

  1. Duplicate patch-width check in bootstrap. server/config.rs:449-455 and :456-464 fire on the same condition for a Bracketed core, because bracketed_patch_features returns vision.patch_features verbatim when nonzero (packing.rs:18-24); the second has the strictly better message (layout, expected width, remedy). Keep the Bracketed check (it also covers 0 → 1176) and fold the != 0 case into it — one error per defect. Related: server/config.rs:457 reaches into packing::bracketed_patch_features while its neighbours use ImageProcessor/VisionCapabilities accessors; expose an accessor instead.
  2. Two documentation contradictions. helios/README.md:721-728 states, unqualified, that process produces pixel_values[N,1536] float32, orders patch features by "channel, temporal copy, pixel row, and pixel column", and orders patches by "2×2 spatial merge blocks" — all three false for the Gemma 4 paragraph three lines above (:713-719: 768 floats, no temporal copy, 3×3). Scope it to Qwen/MiMo and point per-profile width at ImageProcessor::patch_features(). docs/runtime-core-design.md:233-240 enumerates what each image-settings kind consumes and omits the new Gemma 4 kind (and the pooling → merge-stride relationship), in the one place a reader looks; patch_features itself is documented at :181-197, so the gap is local to this enumeration.
  3. New fixtures undocumented; reproduction command is a placeholder. helios/README.md:772-789 pins only tests/frontend/qwen38_images.json (not opened) and its generator; gemma4_images.json and generate_gemma4_image_fixtures.py appear in no document (the only reference in the tree is the include_str! at gemma4.rs:270), yet the generator depends on a Transformers release shipping Gemma4ImageProcessor and on the snapshot's processor_config.json (not opened)/config.json (not opened), none of it pinned where a reader can find it. Add the fixture set, its pinned Transformers/Torch/Torchvision versions, the snapshot, and the regeneration command. In the description, FLARE_GEMMA4_TEST_SNAPSHOT=<gemma-4-31B-it@842da379> is a placeholder where the code needs a directory holding tokenizer.json (not opened) and tokenizer_config.json (not opened) (gemma4.rs:377-385) plus .venv/bin/python with transformers/torch (:452-457); AGENTS.md:110-112 (not opened) requires the inputs be identified. Also: "libprotoc 36.1" does not match the artifact's Protobuf Python Version: 7.36.1 — name the generator release or drop the version.
  4. Four tests restate the fixture. geometry_matches_the_hugging_face_processor (gemma4.rs:336-354) repeats seven of nine rows from the fixture — only (100,3000) and (3000,100) are unique; keep those plus the tokens * 9 == patches invariant. pixels_interleave_rgb_and_positions_are_xy (:357-372) restates what the 91×37 fixture case pins by hash. The cross-profile table (packing.rs:695-825, ~130 lines) repeats patch_features: 0 ten times; three rows (PatchMerge 1176, PaddedGrid 1200, Gemma4 768) cover every distinct outcome. packing.rs:501's grid-divisibility guard is implied by :503 (tokens * patches_per_feature == patches) and by every producer's rounding, leaving merge_side unused there.
  5. Small shape and wording. Keep atomic_spans: bool (bracketed.rs:23, computed at prompt.rs:53-65) — emitting unconditionally would make model.rs:457-458 reject every existing Bracketed core that declares no span — but passing Option<&ImageSpan> (the prepared layout field, as class_token receives its token) puts the derivation next to its use. bracketed.rs:60 says "missing envelope markers" but tests bounds (start == 0 || end >= len); marker identity is enforced at model.rs:444-445, so reword to "bracketed image span run is outside the expanded prompt". Envelope is now a general frontend construct homed in patch_merge (patch_merge.rs:10-17 (not opened)); move it to frontend/images/envelope.rs (not opened). For the record: scheduler/policy.rs:343-350 truncates end to span.start for a straddling span, so a captured capacity below the envelope length contributes no work for span-bearing requests; the bootstrap bound makes that unreachable today, but no test advertises a sub-envelope capacity.

Verified clean (so the report is honest about what was not flagged)

  • Additive wire format. ImagePreparationKind::Gemma4 = 11 appended (model/contract.rs (not opened)), ImageSettings.profile tag 11, VisionCapacity.patch_features tag 6 with #[serde(default)] (helios/build.rs:54-56), describe.rs:466-468 (not opened) omits 0 so legacy describe JSON is byte-identical, and a round-trip test covers the new tag (protobuf.rs:813 (not opened)).
  • Envelope extraction (patch_merge.rs:10-136 (not opened)) is real de-duplication with no MiniMax behaviour change: token-uniqueness validation moved verbatim, expand_prompt delegates.
  • Gemma 4 arithmetic is overflow-guarded: checked_add/checked_mul/try_fold, check_batch before and after geometry, and the shared resize::resize uint8 antialiased bicubic instead of a new kernel.
  • Contract validation accepts patch_features == 0 and rejects non-multiples of 3 (model.rs:72-92); zero patches_per_feature is already rejected for any enabled vision core (model.rs:78 via contract.rs:376 (not opened), before tensor_layout), so the new positive-square load narrowing covers only non-square nonzero values.
  • Ignition accepts any gemma4/gemma4_vision tower, checks processor flags and max_soft_tokens, and rejects gemma4_unified.
  • Resource bounds on the new path: resize inputs go through check_input_extent/check_image_patches, and layouts/bracketed.rs cross-checks image/feature counters against the processed geometry so a malformed expansion errors rather than under-populating vision_token_indices.

Open questions and what could not be established

  • Was landing the profile ahead of its recipe approved by a maintainer? If yes, S1 shrinks to the load-test request; if no, splitting the shared half out is the smaller change and the profile moves to the recipe PR that can export and serve it.
  • Does any published Bracketed core declare a non-square patches_per_feature? Zero is already rejected earlier in validation, so only a non-square nonzero value would newly fail to load. The manifests live in local-inference-lab/hyperflare-recipes, outside this repository; a sweep there is the only thing that settles the blast radius.
  • Should a prefix-cache endpoint restored mid-envelope fail the request or back off to the envelope boundary? docs/TODO.txt:336-337 records the audit; no test pins the behaviour, and scheduler/checkpoints.rs (not opened) keeps published endpoints span-aligned, so the in-process path is safe today.
  • Verification limits. This review was read-only: no cargo test, cargo check or pytest was run, so behavioural claims come from reading code and callers. The PR's reported test counts are the author's own evidence and nothing here depends on them. The live-checkpoint runs (FLARE_GEMMA4_TEST_SNAPSHOT, .venv) are not part of CI in any case. Serving-path timing and memory were not measured by the author and the description says so, so no performance claim is at issue.

What to do next, in order

  1. Answer S1 (maintainer sign-off or split) — it decides whether S4/S5 are worth doing now.
  2. S2 (Ignition derives patch_features) — otherwise the first recipe author cannot serve a Gemma 4 core.
  3. S3 (split the load error) — small, and it is the error operators will hit.
  4. S4 and S5 — line-count reductions with no behaviour change.
  5. Nits 1-5 — documentation and duplicated test rows, batchable in one pass.

To opt out, include #autobot:ignore in your post or comment.

@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from 2b4a31e to ab9a432 Compare November 25, 2026 12:18
@rickybrent

Copy link
Copy Markdown
Contributor Author

I updated core/gemma4-image-frontend (ab9a432b) with the actionable polish items, and added notes on the few items we kept as-is:

  • S1 (legacy Bracketed core-load test & PR scope): Added legacy_bracketed_core_omitting_patch_features_loads_and_stages_1176_wide_pixels in helios/src/model/tests.rs deserializing a Bracketed contract JSON without patch_features, loading it through Inputs::new(&config, &manifest), verifying 1176-wide pixel staging, and checking negative load rejections (undersized 768 buffer and non-square patches_per_feature). On landing ahead of the recipe: because recipes were extracted to local-inference-lab/hyperflare-recipes, the core image profile must land in this repository first so the companion recipe PR can reference ImagePreparationKind::Gemma4 / image_profile="gemma4".
  • S2 (ignition/preparation/contract.py): Added "patch_features": 0 to model_contract()'s vision default dict and documented that Bracketed vision recipes with non-1176 widths set vision["patch_features"]. Left explicit width authoring to the recipe alongside patches_per_feature / patch_capacities rather than inferring width from ImagePreparationKind inside contract.py.
  • S3 & S4 (gemma4.rs load errors & width helper): Split gemma4::Processor::load into per-condition error messages naming the failing field and both values (with a comment explaining the defensive 1..=64 / 1..=16 wire caps), and replaced the inline 3 * self.patch_size * self.patch_size at gemma4.rs with self.patch_features(). On keeping patch_size / pooling_kernel_size as wire fields and keeping the Rust soft-token check: conceded that Ignition fixes them to 16 and 3 today, but retaining them matches PatchMergeImageSettings.patch_size (likewise fixed to 14 in patch_merge.rs:92), avoids breaking existing downstream hyperflare-recipes tests, and preserves wire-level defense-in-depth (and if fields were ever removed pre-merge, unmerged proto tags wouldn't need reserving).
  • S5 (tests & fixture provenance): Deleted the redundant 83-line #[ignore] native_pixels_and_positions_match_the_checkpoint_processor test (all three shapes are already pinned bit-exact in gemma4_images.json). Added test_checked_in_gemma4_fixture_provenance_matches_image_settings in tests/preparation/test_frontend_gemma4.py so gemma4_images.json's processor and model blocks (including recorded image_token_id / boi_token_id / eoi_token_id) are actively verified in CI. In checkpoint_tokens_expand_the_image_envelope, wrapped the temp Jinja template in a Drop guard so failures cannot leak it; the template itself must stay because Frontend::load requires Some(chat_template) for PromptEncoder::Jinja (helios/src/frontend/mod.rs:1041).
  • Nits 1–5: Exposed VisionCapabilities::bracketed_patch_features() and folded the duplicate width check in server/config.rs so every Bracketed mismatch emits the single actionable re-export error. Scoped helios/README.md's Qwen process paragraph, documented tests/frontend/gemma4_images.json with pinned transformers 5.23.0 / torch 2.14.1+cu132 / torchvision 0.29.1+cu132 and snapshot revision, added Gemma 4 to docs/runtime-core-design.md's FrontendSettings enumeration, reworded layouts/bracketed.rs's bounds error to "bracketed image feature run is outside the expanded prompt", and noted in the PR description that live-checkpoint tests are not part of CI. Kept packing.rs's h % merge_side != 0 || w % merge_side != 0 guard because it is not implied by tokens * patches_per_feature == patches (e.g., h = 2, w = 9 at patches_per_feature = 9 satisfies h·w = 18 = tokens·ppf, yet h % 3 ≠ 0).

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents.

Recommendation: Changes Requested

Blockers:

None.

Should fix:

  • Profile lands ahead of its exporter; nothing mounts it end to end. No contract fixture uses layout 9 / preparation 11 (helios/tests/support/contracts/gemma4_frontend.json:16-17 (not opened),38 is null), so nothing goes Bootstrap::load → served image request, and the head runs no CI. → Confirm the stack order in one line (or split the shared half out) and add one Bracketed+Gemma 4 contract fixture loaded through the existing helper.
  • prepare_frontend(snapshot, image_profile="gemma4") cannot find the processor. The default path is preprocessor_config.json (not opened) (frontend.py:310) but Gemma 4 ships processor_config.json (not opened) — every test passes it explicitly, so the documented default raises FileNotFoundError with no test to catch it. → Resolve the filename per profile (or accept either) and test the default argument.
  • Only 2 of the 5 allowlisted budgets are ever loaded. Fixture specs cover 280 and 1120 only (generate_gemma4_image_fixtures.py:31-40), yet max_soft_tokens drives geometry, the clamp branches (gemma4.rs:118-123) and the envelope bound. → Add 70/140/560 cases (regenerate) or a table test over SUPPORTED_SOFT_TOKENS.
  • The new legacy-core test hand-builds a manifest. tests.rs:1304-1411 duplicates testing.rs:307-337/:368-377 because testing::manifest cannot emit a Vision graph (testing.rs:354), and tests.rs:1450 rebuilds a manifest it already holds. → One arm in testing.rs:344-355 plus a width override removes ~110 lines.

Nits:

10 nits


Full report — no blockers; every round-3 should-fix is fixed and verified in code at ab9a432b (per-condition load errors naming both values, a single patch_features() authority, patch_features authored in the Ignition contract default, fixture provenance consumed by a CI test, the legacy Bracketed core-load test, the folded bootstrap width check, the deleted superseded #[ignore] test with a Drop-guarded template, and corrected README/docs). Nothing is wrong on the served path. The four remaining should-fix items are one scope confirmation plus one test that would catch a real FileNotFoundError, one budget-coverage gap, and one test-plumbing reduction. Ten nits cover patch width authored over two enums, duplicated test rows, a doubled max_patches, an over-broad % 3 rule, Envelope's home, the atomic_spans shape, an untested sub-envelope prefill path, and two doc/wording fixes. Two debates are recorded as accepted as-is (patch_size/pooling_kernel_size on the wire, recipe-side width authoring); round-3 nits on the duplicate bootstrap check and bracketed_patch_features() are resolved, and the packing.rs divisibility nit is withdrawn as wrong. Verification was read-only: no cargo test/pytest, and no CI checks on the head commit, so all behavioural claims come from code and callers.

To opt out, include #autobot:ignore in your post or comment.

@rickybrent

rickybrent commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

This is ready for maintainer review (ab9a432b, 0 blockers).

Two quick notes on the remaining bot items:

  • Stack order: Because model recipes were extracted to local-inference-lab/hyperflare-recipes, this core PR lands first so the companion Gemma 4 vision recipe PR can target ImagePreparationKind::Gemma4 / image_profile="gemma4" and vision.patch_features = 768.
  • preprocessor= filename: Passing preprocessor=snapshot / "processor_config.json" explicitly matches the existing convention used by the other processor_config.json-based profiles (glm and padded_grid) in hyperflare-recipes.

The other two items are pure bot errors/looping:

  • Only 2 of 5 SUPPORTED_SOFT_TOKENS (280, 1120) are tested: Pure coverage nit — 70, 140, and 560 run the exact same max_soft_tokens * 9 formula.
  • The egacy-core test duplicates testing.rs helpers: Literally complaining about the style of the test it told us to add in Round 3, asking us to modify shared helios/src/model/testing.rs to shrink it. We can do either, but cycling in a loop between both is annoying.

#autobot:ignore

@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from ab9a432 to c3f3311 Compare November 27, 2026 23:02
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Nov 27, 2026
Gemma 4 sliding-window layers allow each image token to attend over
`window ∩ (causal ∪ same-image-block)` (`sliding_window = 1024`), while
global layers remain causal. Paged causal prefill attention alone cannot
express bidirectional same-image attention, whereas a dense chunk-local
SDPA overlay adds O(T^2) overhead to text-only chunks and breaks
multi-turn prefix-cache boundaries. Because sliding prefill layers stage
the active circular window + current chunk into a contiguous buffer via
`PreparedWindowStaging` (or `stage_circular_kv` for BF16 KV), a sparse
Triton overlay reading that staged buffer (shifting `positions` and
`image_span_end` by each request's first staged position
`max(0, start - window)`) handles arbitrary cached prefixes, wraparound,
and KV-shared sliding layers, exits immediately on query tiles
containing no image tokens, and stays a recipe-side `native_contract`
Triton operator captured inside existing `prefill` graphs (introducing
no Helios `GraphOperation` family or runtime operation contract).

This PR stacks on `local-inference-lab#16` (`recipes/gemma4-sliding-window-kv`) and `local-inference-lab#14`
(`recipes/gemma4-vision-encoder`) and requires companion core PR
`NVIDIA/hyperflare-inference#483` (`core/gemma4-image-frontend`) for
native Gemma 4 image preprocessing, 3x3 bracketed packing
(`patch_features = 768`), and atomic image spans.

Changes:
- hyperflare_recipes/components/image_sliding_attention.py: add
  `compute_image_sliding_spans` (O(T) pure-tensor reverse-cummin span
  calculation shared across all sliding layers) and
  `PreparedImageSlidingAttention` (`flare.image_sliding_attention`
  recipe-side `native_contract` Triton operator accepting both FP8 E4M3
  and BF16 paged/staged K/V caches, optional unbound `k_cache`/`v_cache`,
  overwriting only image rows in place and exiting early on text-only
  tiles).
- hyperflare_recipes/recipes/gemma4/{vision_state,config,weights,
  contract,attention,decoder,bootstrap,recipe}.py: wire `VisionInputs`,
  `PreparedVisionGeneration` (5 vision graphs for capacities
  630..10080), `VisionParameters(separable_encoder=True)` on
  `Gemma4Parameters`, `VISION["patch_features"] = 768` matching `#483`,
  BF16 vision tower loading (with `--language-model-only` and
  `--image-concurrency` opt-out), vision feature injection after text
  embedding scaling, per-prefill staged span offset calculation in
  `PreparedDecoder`, and `PreparedImageSlidingAttention` over the staged
  output in `PreparedAttention`. Include `"vision"` in the compilation
  identity hash.
- tests/components/test_image_sliding_attention_cuda.py: add 8 SM120
  CUDA tests covering FP8 and BF16 paged/staged circular-window parity
  across early, pre-wrap, 1,500-token wraparound, 1,120-token
  window-clipped images, poisoned 0x7F ring slots, multi-request
  heterogeneous starts, and CUDA graph capture/replay with text-only
  early exit.
- tests/frontend/test_gemma4_images.py: add 3 frontend metadata and
  atomic-token validation tests against `ignition.preparation.frontend`.

Claimed result:
Exported Gemma 4 31B NVFP4 TP1 cores serve single-image, multi-image
(up to 4 images), long-prefix (>2K wraparound) image, multi-turn
prefix-cached image, and concurrent 2-request image workloads accurately
on a single 96 GiB SM120 GPU with 1,540,096 KV tokens and 148
VMM-aliased GPU shared snapshot slots (`--max-concurrency 4
--image-concurrency 2`, 62 graphs). Existing exported cores embed their
compiled graphs and remain wire-compatible (not re-served in this
validation).

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 1, base
  `60411f1` + `local-inference-lab#16` + `local-inference-lab#14`, paired with Core PR `#483` `c3f3311f`):
  - `tests/components/test_image_sliding_attention_cuda.py`: 8 passed
    (including BF16 cache parity).
  - `tests/frontend/test_gemma4_images.py`: 3 passed.
  - `tests/recipes/test_gemma4.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    46 passed, 5 skipped.
- End-to-end multimodal serving evidence from pre-split combined
  `gemma-4-31b-nvfp4` TP1 package `gb202-tp1-202611230337` (`feb712de`,
  combining `local-inference-lab#14` + `local-inference-lab#15` + `local-inference-lab#16` + PR 4): 7/7 multimodal checks passed,
  60.7 GiB KV / 1,540,096 KV tokens / 148 shared snapshot slots.

Design-Signed-Off-By: Antigravity (Gemini); design-review=8fdd
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-inference that referenced this pull request Nov 28, 2026
PreparedStateTransfer.prepare() launches `_copy_rows` with grid
`(capacity, cdiv(row_bytes, 4096), 1)`. On CUDA devices, `gridDim.y` is
capped at 65,535, so continuation rows larger than 256 MiB - 4 KiB
(for example, circular sliding-window KV rows of ~405 MiB / 103,683
tiles in FP8 KV or ~810 MiB / 207,363 tiles in BF16 KV on 60-layer
Gemma 4 31B TP1 models in companion PR
`local-inference-lab/hyperflare-recipes#16`) fail kernel launch with
`RuntimeError: Triton Error [CUDA]: invalid argument` during graph
warmup and maintenance transfers.

Changes:
- ignition/components/state_transfer.py:
  - define named constants `_COPY_BLOCK = 4096`, `_PAGE_BLOCK = 1024`,
    and `_MAX_GRID_Y = 65_535` (with a single authoritative comment
    documenting CUDA's 65,535 `gridDim.y` ceiling and 256 MiB - 4 KiB
    striding threshold), removing duplicated inline block literals;
  - keep `row = tl.program_id(0)` in `_copy_rows` and stride byte tiles
    across `tl.program_id(1)` by `tl.num_programs(1) * BLOCK` up to
    `ROW_BYTES`, preserving direct `_copy_rows[(rows, tiles)](*args)`
    callers (such as
    `local-inference-lab/hyperflare-recipes@60411f1:tests/components/test_state_transfer.py`);
  - cap `PreparedStateTransfer.prepare()`'s `gridDim.y` at
    `min(tiles, _MAX_GRID_Y)`, so rows up to 256 MiB - 4 KiB (including
    128 MiB through 256 MiB - 4 KiB rows such as Gemma 4 31B TP2's
    202.5 MiB rows) keep identical single-iteration launch geometry;
  - reject `pool.layout.row_bytes > (1 << 31) - 1 - _MAX_GRID_Y * _COPY_BLOCK`
    (1,879,052,287 B, ~1.75 GiB) in `PreparedStateTransfer.__init__` so
    Triton's signed 32-bit `offset += step` loop induction cannot wrap
    around `INT32_MAX` (verified in Triton TTIR `scf.for ... : i32` and
    generated PTX `add.s32` / `setp.lt.s32`);
  - note on `_copy_pages` that `args[12]` is per-page byte size (one
    physical KV page), not `row_bytes`.
- docs/TODO.txt: record a follow-up item for the 65,535 * 1024
  (~64 MiB/uint8 row) `gridDim.y` ceiling in `ignition/components/state.py`
  row kernels.
- tests/components/test_state_transfer.py: add ungated `FakeTensorMode`
  unit test verifying `PreparedStateTransfer` rejects the first
  256-aligned `row_bytes` above `INT32_MAX - 65_535 * 4096`
  (`1,879,052,288` B) without requiring a CUDA device or
  `FLARE_RUN_CUDA_TESTS=1`.
- tests/components/test_state_transfer_copy_rows_cuda.py: add CUDA-gated
  tests (using production `_COPY_BLOCK = 4096`, a shared expected-row
  oracle, and a shared `_replay_and_verify` helper that snapshots the
  source row before replay and asserts it remains unchanged) covering
  direct `(row, tile)` launches (`grid_y` in `[8, 3]`, with a
  deliberately non-tile-aligned excluded span) and parametrized
  `PreparedStateTransfer.prepare()` + `validate()` + `apply()` across
  `("total_tiles", "expected_y")` in `[(8, 8), (65_535, 65_535),
  (_MAX_GRID_Y + 2, 65_535)]` (`32 KiB`, exact `256 MiB - 4 KiB`
  boundary, and `256 MiB + 4 KiB / 268.4 MB`) with hard-coded
  independent excluded byte spans and 3 freshly dirtied CUDA graph
  replays.

Claimed result:
Continuation rows larger than 256 MiB - 4 KiB copy, reset, and replay
inside CUDA graphs without exceeding CUDA's 65,535 `gridDim.y` ceiling
— verified at 256 MiB + 4 KiB (65,537 tiles) in unit tests, ~405 MiB
(103,683 tiles) in packaged FP8-KV downstream runtimes, and ~810 MiB
(207,363 tiles) in end-to-end BF16-KV serving; larger rows between
~810 MiB and the ~1.75 GiB (`1,879,052,287` B) strided-copy offset
guard follow from the same capped launch geometry (reasoning, not
executed). All continuation rows up to 256 MiB - 4 KiB keep identical
launch geometry and behavior; direct `(row, tile)` callers that launch
one program per tile keep identical behavior, while callers that launch
fewer Y programs than tiles now copy the whole row instead of only the
first `grid_y * 4,096` bytes. Existing exported cores are unaffected by
construction (reasoning, not an export/reload measurement): this change
touches only preparation-time launch geometry in
`PreparedStateTransfer.prepare()`, a preparation-time `row_bytes` bound
in `PreparedStateTransfer.__init__`, and the `_copy_rows` Triton kernel
body, not Helios runtime loading, core wire format, or already-exported
graph binaries.

Supporting evidence and limitations:
- Pre-fix failure on both SM120 (RTX PRO 6000 Blackwell) and SM121
  (NVIDIA GB10, aarch64 DGX Spark): launching `_copy_rows[(1, 65_537)]`
  on a 256 MiB + 4 KiB (268.4 MB) row raises
  `RuntimeError: Triton Error [CUDA]: invalid argument`.
- SM120 (RTX PRO 6000 Blackwell, x86-64 Linux, on `v0.4.0` `5adb27f2`,
  this commit):
  - Ungated CPU-only (`CUDA_VISIBLE_DEVICES=0 pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py`):
    5 passed (strided-copy offset guard + 4 boundary checks), 5 skipped
    (GPU cases) in 2.85s.
  - Gated full (`CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py tests/preparation/test_source_identity.py`,
    after rebuilding `flare-heliopause` on `v0.4.0` `5adb27f2`):
    21 passed in 4.73s.
  - External backward-compatibility check (`CUDA_VISIBLE_DEVICES=1 FLARE_RUN_CUDA_TESTS=1 pytest -v tests/components/test_state_transfer.py`
    against untouched `local-inference-lab/hyperflare-recipes@60411f1`):
    7 passed in 3.18s.
- SM121 (NVIDIA GB10, aarch64 DGX Spark, PyTorch `2.14.1+cu132`, on
  `v0.4.0` `5adb27f2`, this commit):
  - Ungated CPU-only (`pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py`):
    5 passed, 5 skipped in 4.63s.
  - Gated (`CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py`):
    10 passed in 21.23s (1 ungated offset guard + 5 CUDA cases + 4
    boundary checks).
  - External (`CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 pytest -v hyperflare-recipes/tests/components/test_state_transfer.py`):
    7 passed in 3.79s.
- End-to-end ~810 MiB BF16-KV serving (SM120x1 RTX PRO 6000 Blackwell,
  x86-64 Linux, `google/gemma-4-31B-it@842da379` BF16 TP1,
  `--max-concurrency 4`, 57 graphs, `--kv-cache-dtype bf16`, MTP
  enabled): exported and served with core stack
  `NVIDIA/hyperflare-inference@v0.4.0` (`5adb27f2`) + this PR NVIDIA#484
  (`rickybrent/hyperflare-inference@core/state-transfer-large-rows`
  `6463aa58`, whose `_copy_rows` kernel and launch geometry are
  unchanged by this commit's tightened 1.75 GiB preparation guard) +
  `rickybrent/hyperflare-inference@core/gemma4-image-frontend`
  (`c3f3311f`, PR NVIDIA#483 image frontend, unused during text-only checks)
  and recipe stack `local-inference-lab/hyperflare-recipes@main`
  (`60411f1`) + `rickybrent/hyperflare-recipes@recipes/gemma4-sliding-window-kv`
  (`eb7ac17`, PR NVIDIA#16 circular sliding-window KV) +
  `rickybrent/hyperflare-recipes@recipes/gemma4-bf16-kv` (`39a61a7`,
  adds `--kv-cache-dtype bf16`, ~810 MiB / 207,363-tile continuation
  rows). Passed 4,082-token wraparound snapshot/restore
  (`cached_tokens=4050`) and 53K / 163.8K needle checks (401,408 KV
  tokens / 38 snapshot slots).
- Packaged FP8-KV downstream runtimes: both packaged cores were
  exported from `rickybrent/hyperflare-inference@gemma4-export`
  (`53eabcad`, 32,768-tile cap — four iterations per program at
  ~405 MiB; the shipped 65,535 cap is covered by the 65,537-tile test
  case) + `rickybrent/hyperflare-recipes@recipes/gemma4-integration`
  (`08bf07a`), with ~405 MiB (103,683-tile) circular sliding-window
  continuation rows:
  - `rickybrent/Gemma-4-31B-IT-NVFP4-HYPERFLARE-TP1-gb202` (SM120,
    core `gb202-tp1-202611240119`, ~405 MiB continuation rows).
  - `rickybrent/Gemma-4-31B-IT-NVFP4-HYPERFLARE-TP1-gb10` (SM121,
    core `gb10-tp1-202611240340`, ~405 MiB continuation rows; 68.5 GiB
    cache, 1,742,848 KV tokens, 168 snapshot slots; 7/7 vision and
    42.8K / 128.4K / 171.1K exact needle checks).
- Limitations: SM103 and Windows were not executed on hardware; rows
  between ~810 MiB and the ~1.75 GiB strided-copy offset guard were not
  executed; `test_source_identity.py` ran on SM120 only (where
  `flare-heliopause` was rebuilt for `v0.4.0` `5adb27f2`); and no
  base-export/branch-reload test was run for existing exported cores.

Design-Signed-Off-By: Antigravity (Gemini); design-review=15f3
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
@flare-autobot flare-autobot added area:preparation Ignition checkpoint loading, tuning, compilation, capture, and export. enhancement New feature or request model:gemma4 Affected recipe or documented reproducer: gemma4. Impact may be broader. triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 29, 2026
yatesdr pushed a commit that referenced this pull request Nov 29, 2026
…484)

PreparedStateTransfer.prepare() launches `_copy_rows` with grid
`(capacity, cdiv(row_bytes, 4096), 1)`. On CUDA devices, `gridDim.y` is
capped at 65,535, so continuation rows larger than 256 MiB - 4 KiB
(for example, circular sliding-window KV rows of ~405 MiB / 103,683
tiles in FP8 KV or ~810 MiB / 207,363 tiles in BF16 KV on 60-layer
Gemma 4 31B TP1 models in companion PR
`local-inference-lab/hyperflare-recipes#16`) fail kernel launch with
`RuntimeError: Triton Error [CUDA]: invalid argument` during graph
warmup and maintenance transfers.

Changes:
- ignition/components/state_transfer.py:
  - define named constants `_COPY_BLOCK = 4096`, `_PAGE_BLOCK = 1024`,
    and `_MAX_GRID_Y = 65_535` (with a single authoritative comment
    documenting CUDA's 65,535 `gridDim.y` ceiling and 256 MiB - 4 KiB
    striding threshold), removing duplicated inline block literals;
  - keep `row = tl.program_id(0)` in `_copy_rows` and stride byte tiles
    across `tl.program_id(1)` by `tl.num_programs(1) * BLOCK` up to
    `ROW_BYTES`, preserving direct `_copy_rows[(rows, tiles)](*args)`
    callers (such as
    `local-inference-lab/hyperflare-recipes@60411f1:tests/components/test_state_transfer.py`);
  - cap `PreparedStateTransfer.prepare()`'s `gridDim.y` at
    `min(tiles, _MAX_GRID_Y)`, so rows up to 256 MiB - 4 KiB (including
    128 MiB through 256 MiB - 4 KiB rows such as Gemma 4 31B TP2's
    202.5 MiB rows) keep identical single-iteration launch geometry;
  - reject `pool.layout.row_bytes > (1 << 31) - 1 - _MAX_GRID_Y * _COPY_BLOCK`
    (1,879,052,287 B, ~1.75 GiB) in `PreparedStateTransfer.__init__` so
    Triton's signed 32-bit `offset += step` loop induction cannot wrap
    around `INT32_MAX` (verified in Triton TTIR `scf.for ... : i32` and
    generated PTX `add.s32` / `setp.lt.s32`);
  - note on `_copy_pages` that `args[12]` is per-page byte size (one
    physical KV page), not `row_bytes`.
- docs/TODO.txt: record a follow-up item for the 65,535 * 1024
  (~64 MiB/uint8 row) `gridDim.y` ceiling in `ignition/components/state.py`
  row kernels.
- tests/components/test_state_transfer.py: add ungated `FakeTensorMode`
  unit test verifying `PreparedStateTransfer` rejects the first
  256-aligned `row_bytes` above `INT32_MAX - 65_535 * 4096`
  (`1,879,052,288` B) without requiring a CUDA device or
  `FLARE_RUN_CUDA_TESTS=1`.
- tests/components/test_state_transfer_copy_rows_cuda.py: add CUDA-gated
  tests (using production `_COPY_BLOCK = 4096`, a shared expected-row
  oracle, and a shared `_replay_and_verify` helper that snapshots the
  source row before replay and asserts it remains unchanged) covering
  direct `(row, tile)` launches (`grid_y` in `[8, 3]`, with a
  deliberately non-tile-aligned excluded span) and parametrized
  `PreparedStateTransfer.prepare()` + `validate()` + `apply()` across
  `("total_tiles", "expected_y")` in `[(8, 8), (65_535, 65_535),
  (_MAX_GRID_Y + 2, 65_535)]` (`32 KiB`, exact `256 MiB - 4 KiB`
  boundary, and `256 MiB + 4 KiB / 268.4 MB`) with hard-coded
  independent excluded byte spans and 3 freshly dirtied CUDA graph
  replays.

Claimed result:
Continuation rows larger than 256 MiB - 4 KiB copy, reset, and replay
inside CUDA graphs without exceeding CUDA's 65,535 `gridDim.y` ceiling
— verified at 256 MiB + 4 KiB (65,537 tiles) in unit tests, ~405 MiB
(103,683 tiles) in packaged FP8-KV downstream runtimes, and ~810 MiB
(207,363 tiles) in end-to-end BF16-KV serving; larger rows between
~810 MiB and the ~1.75 GiB (`1,879,052,287` B) strided-copy offset
guard follow from the same capped launch geometry (reasoning, not
executed). All continuation rows up to 256 MiB - 4 KiB keep identical
launch geometry and behavior; direct `(row, tile)` callers that launch
one program per tile keep identical behavior, while callers that launch
fewer Y programs than tiles now copy the whole row instead of only the
first `grid_y * 4,096` bytes. Existing exported cores are unaffected by
construction (reasoning, not an export/reload measurement): this change
touches only preparation-time launch geometry in
`PreparedStateTransfer.prepare()`, a preparation-time `row_bytes` bound
in `PreparedStateTransfer.__init__`, and the `_copy_rows` Triton kernel
body, not Helios runtime loading, core wire format, or already-exported
graph binaries.

Supporting evidence and limitations:
- Pre-fix failure on both SM120 (RTX PRO 6000 Blackwell) and SM121
  (NVIDIA GB10, aarch64 DGX Spark): launching `_copy_rows[(1, 65_537)]`
  on a 256 MiB + 4 KiB (268.4 MB) row raises
  `RuntimeError: Triton Error [CUDA]: invalid argument`.
- SM120 (RTX PRO 6000 Blackwell, x86-64 Linux, on `v0.4.0` `5adb27f2`,
  this commit):
  - Ungated CPU-only (`CUDA_VISIBLE_DEVICES=0 pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py`):
    5 passed (strided-copy offset guard + 4 boundary checks), 5 skipped
    (GPU cases) in 2.85s.
  - Gated full (`CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py tests/preparation/test_source_identity.py`,
    after rebuilding `flare-heliopause` on `v0.4.0` `5adb27f2`):
    21 passed in 4.73s.
  - External backward-compatibility check (`CUDA_VISIBLE_DEVICES=1 FLARE_RUN_CUDA_TESTS=1 pytest -v tests/components/test_state_transfer.py`
    against untouched `local-inference-lab/hyperflare-recipes@60411f1`):
    7 passed in 3.18s.
- SM121 (NVIDIA GB10, aarch64 DGX Spark, PyTorch `2.14.1+cu132`, on
  `v0.4.0` `5adb27f2`, this commit):
  - Ungated CPU-only (`pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py`):
    5 passed, 5 skipped in 4.63s.
  - Gated (`CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 pytest -v tests/components/test_state_transfer.py tests/components/test_state_transfer_copy_rows_cuda.py tests/preparation/test_core_boundary.py`):
    10 passed in 21.23s (1 ungated offset guard + 5 CUDA cases + 4
    boundary checks).
  - External (`CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 pytest -v hyperflare-recipes/tests/components/test_state_transfer.py`):
    7 passed in 3.79s.
- End-to-end ~810 MiB BF16-KV serving (SM120x1 RTX PRO 6000 Blackwell,
  x86-64 Linux, `google/gemma-4-31B-it@842da379` BF16 TP1,
  `--max-concurrency 4`, 57 graphs, `--kv-cache-dtype bf16`, MTP
  enabled): exported and served with core stack
  `NVIDIA/hyperflare-inference@v0.4.0` (`5adb27f2`) + this PR #484
  (`rickybrent/hyperflare-inference@core/state-transfer-large-rows`
  `6463aa58`, whose `_copy_rows` kernel and launch geometry are
  unchanged by this commit's tightened 1.75 GiB preparation guard) +
  `rickybrent/hyperflare-inference@core/gemma4-image-frontend`
  (`c3f3311f`, PR #483 image frontend, unused during text-only checks)
  and recipe stack `local-inference-lab/hyperflare-recipes@main`
  (`60411f1`) + `rickybrent/hyperflare-recipes@recipes/gemma4-sliding-window-kv`
  (`eb7ac17`, PR #16 circular sliding-window KV) +
  `rickybrent/hyperflare-recipes@recipes/gemma4-bf16-kv` (`39a61a7`,
  adds `--kv-cache-dtype bf16`, ~810 MiB / 207,363-tile continuation
  rows). Passed 4,082-token wraparound snapshot/restore
  (`cached_tokens=4050`) and 53K / 163.8K needle checks (401,408 KV
  tokens / 38 snapshot slots).
- Packaged FP8-KV downstream runtimes: both packaged cores were
  exported from `rickybrent/hyperflare-inference@gemma4-export`
  (`53eabcad`, 32,768-tile cap — four iterations per program at
  ~405 MiB; the shipped 65,535 cap is covered by the 65,537-tile test
  case) + `rickybrent/hyperflare-recipes@recipes/gemma4-integration`
  (`08bf07a`), with ~405 MiB (103,683-tile) circular sliding-window
  continuation rows:
  - `rickybrent/Gemma-4-31B-IT-NVFP4-HYPERFLARE-TP1-gb202` (SM120,
    core `gb202-tp1-202611240119`, ~405 MiB continuation rows).
  - `rickybrent/Gemma-4-31B-IT-NVFP4-HYPERFLARE-TP1-gb10` (SM121,
    core `gb10-tp1-202611240340`, ~405 MiB continuation rows; 68.5 GiB
    cache, 1,742,848 KV tokens, 168 snapshot slots; 7/7 vision and
    42.8K / 128.4K / 171.1K exact needle checks).
- Limitations: SM103 and Windows were not executed on hardware; rows
  between ~810 MiB and the ~1.75 GiB strided-copy offset guard were not
  executed; `test_source_identity.py` ran on SM120 only (where
  `flare-heliopause` was rebuilt for `v0.4.0` `5adb27f2`); and no
  base-export/branch-reload test was run for existing exported cores.

Design-Signed-Off-By: Antigravity (Gemini); design-review=15f3

Signed-off-by: Ricky Brent <ricky@rickybrent.com>
@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from c3f3311 to 4f42d94 Compare November 29, 2026 05:11
…omic spans

Gemma 4 multimodal checkpoints preprocess images into aspect-preserving 16x16
interleaved RGB patches (768 f32 elements/patch), 2D (x, y) patch coordinates,
3x3 spatial pooling (patches_per_feature = 9, up to 1120 soft tokens), and an
atomic image envelope (start_token, repeated image_token features, end_token).
Previously, Helios had no Gemma 4 image preparation profile,
ImageLayoutKind::Bracketed hardcoded 2x2 merge and 1176 floats/patch, and
Bracketed layouts did not emit atomic image spans.

Changes:
- Wire & contract metadata:
  - Add additive ImageSettings.profile tag 11 (Gemma4ImageSettings) and
    ImagePreparationKind::Gemma4 (tag 11), plus VisionCapacity.patch_features
    (tag 6, serde default 0) and VisionCapabilities::bracketed_patch_features()
    to declare per-patch float width in prepared metadata rather than
    hardcoding a model-identity table in shared packing.
  - Default vision["patch_features"] = 0 in ignition/preparation/contract.py
    and document that Bracketed vision recipes with non-1176 widths set it.
  - Regenerate ignition/preparation/runtime_core_pb2.py matching main
    (Protobuf Python Version: 7.36.1, descriptor-only diff).
  - Document the new profile, fixture provenance, patch_features field, and
    Bracketed atomic spans in helios/README.md, docs/runtime-core-design.md,
    helios/model-contract.md, and docs/TODO.txt.
- Native image preparation & packing:
  - Implement helios/src/frontend/images/gemma4.rs (area-bounded uint8
    antialiased bicubic resize matching torchvision, 1/255 scaling, interleaved
    (y, x, channel) patches, (x, y) positions, shared patch_merge::Envelope,
    and per-condition load errors naming failing fields and bounds).
  - Derive Bracketed merge stride from square patches_per_feature and patch
    width from vision.bracketed_patch_features() (0 defaults to legacy MiniMax
    width 1176, which uses 2x temporal duplication: 3 * 2 * 14^2 = 1176).
  - Unify per-profile patch widths via ImageProcessor::patch_features()
    (delegating Qwen/MiMo/PatchMerge to their dynamic pixel_width() helpers),
    fixing conditioned.rs cache validation across all profiles, and add
    load-time consistency checks in gemma4::Processor::load and server::config
    (single actionable Bracketed patch-width check, patches_per_feature,
    per-image patch budget, and max envelope <= prefill_chunk_size and
    span.max_tokens).
  - Move atomic span emission into layouts/bracketed.rs when image_tokens.span
    is declared, removing the fallback in model/prompt.rs.
- Preparation & tests:
  - Tighten ignition/preparation/frontend.py to accept any gemma4/gemma4_vision
    checkpoint (E2B/E4B/26B-A4B/31B while rejecting gemma4_unified 12B) and
    validate envelope tokens from tokenizer_config.json against tokenizer.json
    and optional config.json IDs.
  - Add checked-in HF reference fixture generator and
    tests/frontend/gemma4_images.json (8 bit-exact SHA-256 cases across
    max_soft_tokens=280 and 1120), unconditional Rust Envelope::expand /
    Bracketed span / legacy Bracketed Inputs::new core-load / cross-profile
    width / bootstrap validation tests, #[ignore] checkpoint envelope test, and
    tests/preparation/test_frontend_gemma4.py (including fixture provenance
    validation).

Verified on origin/main (v0.5.0, 0a8c20f):
- helios frontend::images: 48 passed, 0 failed, 1 ignored
- helios ignored checkpoint envelope test (google/gemma-4-31B-it@842da379): 1 passed
- helios model:: (57 passed, 0 failed), runtime_core::protobuf (29 passed),
  server::config (3 passed), flare-cli --test unverified_payload (7 passed)
- helios integration tests --no-run & flare-cli --tests check: passed
- upstream-core pytest (after rebuilding flare-heliopause; core_boundary,
  source_identity, frontend_gemma4 incl. fixture provenance and cached
  gemma-4-31B-it, Gemma-4-31B-IT-NVFP4, and gemma-4-E2B-it): 23 passed, 0 skipped
- external hyperflare-recipes tests/frontend/test_gemma4_images.py: 3 passed, 0 skipped

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from 4f42d94 to 445c665 Compare November 30, 2026 10:27
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Nov 30, 2026
Gemma 4 sliding-window layers allow each image token to attend over
`window ∩ (causal ∪ same-image-block)` (`sliding_window = 1024`), while
global layers remain causal. Paged causal prefill attention alone cannot
express bidirectional same-image attention, whereas a dense chunk-local
SDPA overlay adds O(T^2) overhead to text-only chunks and breaks
multi-turn prefix-cache boundaries. Because sliding prefill layers stage
the active circular window + current chunk into a contiguous buffer via
`PreparedWindowStaging` (or `stage_circular_kv` for BF16 KV), a sparse
Triton overlay reading that staged buffer (shifting `positions` and
`image_span_end` by each request's first staged position
`max(0, start - window)`) handles arbitrary cached prefixes, wraparound,
and KV-shared sliding layers, exits immediately on query tiles
containing no image tokens, and stays a recipe-side `native_contract`
Triton operator captured inside existing `prefill` graphs (introducing
no Helios `GraphOperation` family or runtime operation contract).

This PR stacks on `local-inference-lab#16` (`recipes/gemma4-sliding-window-kv`) and `local-inference-lab#14`
(`recipes/gemma4-vision-encoder`) and requires companion core PR
`NVIDIA/hyperflare-inference#483` (`core/gemma4-image-frontend`) for
native Gemma 4 image preprocessing, 3x3 bracketed packing
(`patch_features = 768`), and atomic image spans.

Changes:
- hyperflare_recipes/components/image_sliding_attention.py: add
  `compute_image_sliding_spans` (O(T) pure-tensor reverse-cummin span
  calculation shared across all sliding layers) and
  `PreparedImageSlidingAttention` (`flare.image_sliding_attention`
  recipe-side `native_contract` Triton operator accepting both FP8 E4M3
  and BF16 paged/staged K/V caches, optional unbound `k_cache`/`v_cache`,
  overwriting only image rows in place and exiting early on text-only
  tiles).
- hyperflare_recipes/recipes/gemma4/{vision_state,config,weights,
  contract,attention,decoder,bootstrap,recipe}.py: wire `VisionInputs`,
  `PreparedVisionGeneration` (5 vision graphs for capacities
  630..10080), `VisionParameters(separable_encoder=True)` on
  `Gemma4Parameters`, `VISION["patch_features"] = 768` matching `#483`,
  BF16 vision tower loading (with `--language-model-only` and
  `--image-concurrency` opt-out), vision feature injection after text
  embedding scaling, per-prefill staged span offset calculation in
  `PreparedDecoder`, and `PreparedImageSlidingAttention` over the staged
  output in `PreparedAttention`. Include `"vision"` in the compilation
  identity hash.
- tests/components/test_image_sliding_attention_cuda.py: add 8 SM120
  CUDA tests covering FP8 and BF16 paged/staged circular-window parity
  across early, pre-wrap, 1,500-token wraparound, 1,120-token
  window-clipped images, poisoned 0x7F ring slots, multi-request
  heterogeneous starts, and CUDA graph capture/replay with text-only
  early exit.
- tests/frontend/test_gemma4_images.py: add 3 frontend metadata and
  atomic-token validation tests against `ignition.preparation.frontend`.

Claimed result:
Exported Gemma 4 31B NVFP4 TP1 cores serve single-image, multi-image
(up to 4 images), long-prefix (>2K wraparound) image, multi-turn
prefix-cached image, and concurrent 2-request image workloads accurately
on a single 96 GiB SM120 GPU with 1,540,096 KV tokens and 148
VMM-aliased GPU shared snapshot slots (`--max-concurrency 4
--image-concurrency 2`, 62 graphs). Existing exported cores embed their
compiled graphs and remain wire-compatible (not re-served in this
validation).

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 1, base
  `60411f1` + `local-inference-lab#16` + `local-inference-lab#14`, paired with Core PR `#483` `c3f3311f`):
  - `tests/components/test_image_sliding_attention_cuda.py`: 8 passed
    (including BF16 cache parity).
  - `tests/frontend/test_gemma4_images.py`: 3 passed.
  - `tests/recipes/test_gemma4.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    46 passed, 5 skipped.
- End-to-end multimodal serving evidence from pre-split combined
  `gemma-4-31b-nvfp4` TP1 package `gb202-tp1-202611230337` (`feb712de`,
  combining `local-inference-lab#14` + `local-inference-lab#15` + `local-inference-lab#16` + PR 4): 7/7 multimodal checks passed,
  60.7 GiB KV / 1,540,096 KV tokens / 148 shared snapshot slots.

Design-Signed-Off-By: Antigravity (Gemini); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:preparation Ignition checkpoint loading, tuning, compilation, capture, and export. enhancement New feature or request model:gemma4 Affected recipe or documented reproducer: gemma4. Impact may be broader. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants