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 float32 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). Before this change, Helios had no Gemma 4 image preparation profile, ImageLayoutKind::Bracketed hardcoded 2×2 merge (patches_per_feature = 4) and 1,176 floats per patch, and Bracketed layouts did not emit atomic image spans when declared by ImageTokenLayout.span. Without these changes, 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 closed at bootstrap 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):
    • Before: VisionCapacity had no patch-width field, ImageSettings / ImagePreparationKind ended at tag 10 (PaddedGrid), and model_contract() omitted patch_features from its default vision map.
    • After: 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 with a docstring note for non-1176 Bracketed recipes, 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 and reject non-zero widths that are not positive multiples of 3, added a protobuf round-trip test for Gemma 4 settings, and documented the Gemma 4 profile, fixture provenance, patch_features, and Bracketed atomic spans. Updated docs/TODO.txt to record that 31B NVFP4 and BF16 multimodal serving are verified on the combined Gemma 4 recipe stack while 26B-A4B multimodal serving, E2B/E4B recipe vision-tower parameterization, and partial-span prefix-cache audit remain open.
  • Native image preparation, 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):
    • Before: No Gemma 4 preprocessor existed; ImageLayoutKind::Bracketed hardcoded 2×2 merge and width 1176 in a lookup branch; server bootstrap did not check patch width or maximum image envelope against prefill_chunk_size / span.max_tokens.
    • After: 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, single ProcessedImages::reserve_outputs allocation with checked_mul overflow checks and reserve_exact matching glm.rs, and per-condition load errors naming failing fields and bounds). Updated Bracketed packing to derive merge stride from any positive square patches_per_feature and read pixel 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). Unified per-profile patch widths behind ImageProcessor::patch_features() (via PatchProcessor::pixel_width() for Qwen/PatchMerge and in conditioned.rs) and enforced load-time consistency across gemma4::Processor::load and server::config::validate_loaded_image_processor (single actionable re-export error for any Bracketed mismatch, non-zero vision.patch_features check for other layouts, and 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):
    • Before: Bracketed emitted no atomic spans.
    • After: Added atomic_spans handling in layouts::bracketed::prepare_input (matching layouts::deepseek), gated on image_tokens.span.is_some() and validating prompt bounds on both ends.
  • Core wire validation & deterministic test fixtures (ignition/preparation/frontend.py, tests/frontend/generate_gemma4_image_fixtures.py, tests/frontend/gemma4_images.json, tests/preparation/{test_frontend_spec.py,test_frontend_gemma4.py}, helios/src/model/tests.rs):
    • Before: Core ignition/preparation/frontend.py accepted only the 8 existing IMAGE_PROFILES under recipe-owned ImageProcessorSpec contracts.
    • After: Registered "gemma4" in IMAGE_PROFILES and added wire-schema validation in _validate_image_payload (patch_size in 1..=64, pooling_kernel_size in 1..=16, max_soft_tokens in {70, 140, 280, 560, 1120}, and three distinct nonempty envelope token strings), keeping all checkpoint-specific metadata in recipe-owned ImageProcessorSpec definitions. 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), added unconditional Rust Envelope::expand, Bracketed span-bearing contract, cross-profile width, bootstrap validation, and legacy Bracketed Inputs::new core-load tests, kept the live-tokenizer envelope test #[ignore], updated test_frontend_spec.py's IMAGE_PROFILES check, and kept tests/preparation/test_frontend_gemma4.py strictly recipe-free (covering _validate_image_payload, default_preprocessor, checked-in gemma4_images.json validation, and runtime_core_pb2.ImageSettings round-trip).

Claimed result

Helios natively decodes, resizes, rescales and 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 & fail-closed narrowings: MiniMax (Bracketed + PatchMerge) and all non-Bracketed upstream cores remain loadable and unchanged (missing patch_features decodes as 0, preserving legacy width 1176 for Bracketed — exercised by legacy_bracketed_core_omitting_patch_features_loads_and_stages_1176_wide_pixels through Inputs::new; envelope bound checks apply 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 legacy Gemma 4 core prepared before this change (with patch_features == 0) fails load with an actionable re-export 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 (3d1614cc):

  • Full --release Rust test suites (--locked --release):
    • cargo test --offline --locked --release --manifest-path eos/Cargo.toml --target-dir flare-cli/target: 12 passed, 0 failed
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --target-dir flare-cli/target: 553 passed, 0 failed (552 lib + 1 mixed_codec_root)
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --features test-support --target-dir flare-cli/target: 425 passed, 0 failed, 1 ignored (187 lib + 238 across 12 integration suites)
    • FLARE_TEST_TEMPLATE_DIR=/tmp/flare-test-templates cargo test --offline --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target: 1,913 passed, 0 failed, 85 ignored (1,851 unit + 62 across 15 integration targets; prepared un-gated templates excluding gated muse_spark, matching .github/workflows/native-serving.yml)
    • cargo test --offline --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --lib frontend::images --target-dir flare-cli/target: 48 passed, 0 failed, 1 ignored (plus model:: 58 passed, runtime_core::protobuf 29 passed, and server::config 3 passed)
    • Live-snapshot envelope test (not in CI; requires cached tokenizer.json and tokenizer_config.json): FLARE_GEMMA4_TEST_SNAPSHOT=/opt/textllm/cache/huggingface/hub/models--nvidia--Gemma-4-31B-IT-NVFP4/snapshots/4135a98a9b728a548947683219633b25682223ac cargo test --offline --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server,test-tools --lib --target-dir flare-cli/target -- --ignored --exact frontend::images::gemma4::tests::checkpoint_tokens_expand_the_image_envelope: 1 passed, 0 failed
    • cargo test --offline --locked --release --manifest-path flare-cli/Cargo.toml --target-dir flare-cli/target: 246 passed, 0 failed, 3 ignored (including cargo test --offline --locked --release --manifest-path flare-cli/Cargo.toml --test unverified_payload: 7 passed, 0 failed)
    • cargo test --offline --locked --release --manifest-path flare/Cargo.toml --target-dir flare-cli/target: 255 passed, 0 failed, 4 ignored
    • cargo test --offline --locked --release --manifest-path heliopause/Cargo.toml --target-dir flare-cli/target: 229 passed, 0 failed, 6 ignored
  • Rebuilt flare binary (cargo build --offline --locked --release --manifest-path flare-cli/Cargo.toml) and flare-heliopause (uv pip install --offline --python .venv/bin/python --no-deps ./heliopause), synced Core .venv (flashinfer-python 5a8ceed8), and ran CI CPU Python suite (CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest tests/ -q): 2,504 passed, 459 skipped, 0 failed (including 21 passed, 0 skipped across tests/preparation/{test_core_boundary,test_source_identity,test_frontend_spec,test_frontend_gemma4}.py).
  • Combined-stack E2E multimodal serving (evaluated on the companion 5-PR Gemma 4 recipe stack in local-inference-lab/hyperflare-recipes paired with this PR, RTX PRO 6000 Blackwell SM120 GPU 0, TP1, --max-concurrency 4 --image-concurrency 2, MTP enabled):
    • nvidia/Gemma-4-31B-IT-NVFP4 (FP8 KV): 11/11 checks passed (short_math '391', 5,703-tok needle 'NEEDLE-7492-FALCON', 1/2/4-image, 2,564-tok wraparound+image, 810/810 Turn-1 multimodal prefix-cache replay, 2-concurrent images, 122.56 tok/s decode / 122.31 tok/s total, TTFT 0.0041s on a 37-tok prefix-cached prompt).
    • google/gemma-4-31B-it (BF16 KV): 11/11 checks passed (810/810 Turn-1 multimodal replay, 2-concurrent images, 70.73 tok/s decode / 70.64 tok/s total, TTFT 0.0045s on cached prompt).
    • Legacy fail-closed & backward-compat checks with rebuilt release flare: pre-#483 Gemma 4 core gb202-tp1-202611240119 fails load with bracketed image layout patch width (1176) differs from image processor (768); re-export the core with vision.patch_features; existing GLM-5.3-Flash core gb202-tp2-202611090656 passes flare inspect (signatures verified).
  • Limitations: End-to-end multimodal serving requires the companion Gemma 4 recipe stack (local-inference-lab/hyperflare-recipes). On that combined stack, 31B NVFP4 (FP8 KV) and 31B BF16 (BF16 KV) serving are verified on SM120 TP1, whereas TP2/TP4, 26B-A4B vision serving, E2B/E4B (16-layer 768-dim clipped-linear vision tower not yet parameterized in the recipe), SM103/SM121 hardware, and partial-span prefix-cache hits remain unverified (tracked in docs/TODO.txt).

Branch logistics

  • Repository: NVIDIA/hyperflare-inference
  • Branch / commit: rickybrent:core/gemma4-image-frontend (4f777ec0) targeting main (3d1614cc).

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

Context on the remaining automated review items at ab9a432b:

  • Stack order: Because model recipes live in 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" matches the existing processor_config.json-based profiles (glm and padded_grid) in hyperflare-recipes (subsequently moved to recipe-owned ImageProcessorSpec.default_preprocessor after #683).
  • SUPPORTED_SOFT_TOKENS fixture coverage: The checked-in Hugging Face parity fixtures exercise 280 (default) and 1120 (maximum); 70, 140, and 560 follow the same max_soft_tokens * 9 sizing path, and wire validation covers all five values.
  • Legacy-core test helpers: The Bracketed legacy-core load test keeps its minimal builders local to helios/src/model/tests.rs to avoid modifying shared helios/src/model/testing.rs. Happy to move them into testing.rs if maintainers prefer.

@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 2 times, most recently 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>
@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from 445c665 to 7054676 Compare December 3, 2026 05:04
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 multimodal checkpoints include a 27-block BF16 vision tower
(1152 hidden size, 16 heads of dim 72, unit-scale attention with
`softmax_scale=1.0`, 2D rotary embeddings over `(x, y)` coordinates,
3x3 average spatial pooling, and a multimodal embedder projecting into
the text hidden dimension). Previously, `hyperflare_recipes` had no
prepared Gemma 4 vision encoder, and `PreparedVarlenAttention` hardcoded
`softmax_scale = q.shape[-1] ** -0.5`.

Changes:
- hyperflare_recipes/components/varlen_attention.py: add an optional
  `softmax_scale: float | None = None` parameter to
  `PreparedVarlenAttention`, defaulting to `q.shape[-1] ** -0.5` both
  at initialization and via `getattr(self, "softmax_scale", None)` in
  `__call__` so existing callers and `object.__new__` test fixtures
  remain unchanged while Gemma 4 passes `1.0`.
- hyperflare_recipes/recipes/gemma4/vision.py: add `PreparedVision`,
  `VisionMetadata`, and `VisionScratch` implementing the 27-block BF16
  vision tower, 3x3 patch pooling, and multimodal embedder parameterized
  by `text_hidden`, using `PreparedVarlenAttention(softmax_scale=1.0)`
  and `UnquantizedProjection` for CUDA-graph capture.
- tests/components/test_functional_attention_operands.py,
  tests/recipes/test_gemma4_vision.py: add an SM120 CUDA numerical parity
  test comparing `PreparedVision` against Hugging Face's
  `Gemma4VisionModel` + `Gemma4MultimodalEmbedder` on the cached
  `google/gemma-4-31B-it` checkpoint, and verify default and explicit
  `softmax_scale=1.0` forwarding in `PreparedVarlenAttention.__call__`.

Claimed result:
The Gemma 4 vision tower prepares and executes in CUDA graphs with
numerical parity against Hugging Face Transformers, ready to be wired
into `gemma4` multimodal preparation without modifying existing text
recipes or exported cores.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -v tests/recipes/test_gemma4_vision.py`:
    1 passed in 7.13s.
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/components/test_functional_attention_operands.py -k varlen`:
    2 passed, 11 deselected in 1.29s
    (`test_varlen_releases_templates_and_preserves_strided_output` and
    `test_varlen_gather_source_alias_is_explicit`).
- Post-rebase `v0.5.3` combined E2E serving (`recipes/gemma4-integration-v053`
  stack combining all 5 Gemma 4 recipe PRs + `NVIDIA/hyperflare-inference#483`
  `70546769`, SM120 GPU 0, `--max-concurrency 4 --image-concurrency 2`, 80
  graphs each, `seed=42`): both `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8
  KV) and `google/gemma-4-31B-it` TP1 (`--kv-cache-dtype bf16`) passed
  11/11 live `/v1/chat/completions` checks including 1-image, 2-image,
  4-image, >1.5K wraparound+image (`2,564` tokens), `810/810`
  prefix-cached multimodal replay, and 2-concurrent image requests.
- Limitations: E2E serving ran on the combined 5-PR stack (not this PR
  in isolation); standalone vision parity was tested on SM120
  `google/gemma-4-31B-it`, and E2B/E4B/12B/26B-A4B and SM103/SM121
  hardware were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
…ged global KV

Gemma 4 models apply RMSNorm to Q/K/V and attend with unit scale
(`softmax_scale = 1.0`), making them unusually sensitive to FP8 E4M3 KV
quantization. Because circular sliding-window KV (`local-inference-lab#16`) shrinks paged KV
storage by 11x on 31B and 21x on 12B, full lossless BF16 KV becomes
practical on a single 96 GiB GPU (`401,408` KV tokens and `38` snapshot
slots on standalone 31B BF16 TP1 with MTP, or `377,856` KV tokens and `36`
snapshot slots on the full multimodal + wide-decode 31B BF16 TP1 stack)
with zero core `NVIDIA/hyperflare-inference` or `b12x` changes.

This PR stacks directly on `local-inference-lab#16` (`recipes/gemma4-sliding-window-kv`,
`c15b6fe`) and keeps `fp8` as the default `--kv-cache-dtype`.

Changes:
- hyperflare_recipes/recipes/gemma4/recipe.py: add
  `KvCachePrecisionParameters` (`--kv-cache-dtype {fp8,bf16}`, default
  `fp8`) to `Gemma4Parameters` with `adjust_rank_costs` returning exact
  BF16 `RankCosts` for all five Gemma 4 sizes across TP1/TP2/TP4.
- hyperflare_recipes/components/window_attention.py: add batched Triton
  `stage_circular_kv` (`torch.library.wrap_triton`) to stage BF16
  circular sliding history and current candidates into contiguous BF16
  paged buffers without modifying `b12x`'s FP8-only `WindowStageKernel`.
- hyperflare_recipes/recipes/gemma4/{pool,attention,bootstrap}.py:
  parameterize `page_specs`, `page_bytes`, `continuation_layout`, and
  `ContinuationPool` by `kv_dtype`; route BF16 sliding prefill staging
  through `stage_circular_kv`, pre-scale queries by `sqrt(dim)` before
  BF16 `PreparedPagedAttention` (since `b12x` ignores `k_descale` for
  BF16 caches), keep `PreparedWindowAttention(softmax_scale=1.0)` and
  `commit_circular_kv` in native BF16 without FP8 clamping, preserve
  `TERMINAL_PREFILL` variants, and include `"kv_dtype"` in the compilation
  identity hash.
- tests/recipes/test_gemma4.py,
  tests/recipes/test_gemma4_sliding_window_cuda.py: add planner/cost
  tests across all 5 variants x TP1/TP2/TP4 and SM120 CUDA parity tests
  for BF16 sliding prefill/staging/commit/wraparound decode and BF16
  512-dim global KV write + unit-scale prefill attention.

Claimed result:
Exporting Gemma 4 checkpoints with `--kv-cache-dtype bf16` stores both
circular sliding-window and paged global KV caches in lossless BF16,
cutting live-server top-20 KL divergence against Hugging Face BF16 by
4.8x-5.0x on 1.6K and 4.6K contexts while keeping 377,856-401,408 KV
tokens and 36-38 snapshot slots on a single 96 GiB SM120 GPU (31B BF16
TP1 + MTP) and leaving `--kv-cache-dtype fp8` unchanged by default.

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 0, base
  `20e360b` + `local-inference-lab#16` `c15b6fe`, `ignition` `c513e46a`, `flashinfer-python`
  `5a8ceed8`):
  - `CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/recipes/test_gemma4_sliding_window_cuda.py tests/components/test_window_attention_cuda.py`:
    72 passed in 223.69s (covering all FP8 + BF16 sliding/global parity
    and circular window attention tests).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    64 passed, 5 skipped, 9 deselected in 4.57s (exact BF16 `RankCosts`
    across E2B, E4B, 12B, 26B-A4B, 31B x TP1/TP2/TP4 plus
    `TERMINAL_PREFILL` rollout checks; the 9 deselected template tests
    require `FLARE_TEST_TEMPLATE_DIR`).
- Post-rebase `v0.5.3` combined E2E serving (`recipes/gemma4-integration-v053`
  stack combining all 5 Gemma 4 recipe PRs + `NVIDIA/hyperflare-inference#483`
  `70546769`, `google/gemma-4-31B-it@842da379` BF16 TP1, SM120 GPU 0,
  `--kv-cache-dtype bf16 --max-concurrency 4 --image-concurrency 2`, 80
  graphs, `seed=42`, MTP enabled):
  - Runtime capacity: `32.8 GiB` · `377,856` KV tokens (`2,952` pages) ·
    `36` shared snapshots · `11.2 GiB` host prefix slab (`1,142` slots);
    11/11 checks passed (`short_math` `'391'`, `multi_turn_prefix`
    `583/614`, >4K wraparound snapshot/restore `p1=5536` `cached=5529`
    `'COBALT-88'`, `5,703`-tok needle `'NEEDLE-7492-FALCON'`, 1/2/4-image,
    `2,564`-tok wraparound+image, `810/810` multimodal prefix-cache
    replay, 2-concurrent images, `70.73 tok/s` decode / `70.64 tok/s`
    total with TTFT `0.0045s` and MTP `337` accepted drafts / `131`
    rounds ≈ `2.57` drafts/round).
- Prior end-to-end export & live-server A/B (`flare run`, SM120x1 RTX PRO
  6000 Blackwell, `google/gemma-4-31B-it@842da379` BF16 TP1,
  `--max-concurrency 4`, 57 graphs each, release `flare` built from
  `v0.4.0` `5adb27f2` + `#484` `6463aa58` [whose `_copy_rows` kernel
  and launch geometry are unchanged in `#484` tip `15002977`] + `#483`
  `c3f3311f`):
  - Runtime KV capacity (`34.7 GiB` cache budget): BF16 KV allocates
    402,432 KV tokens / 38 snapshot slots (`--mtp-draft-tokens 0`) and
    401,408 KV tokens / 38 snapshot slots (MTP enabled); FP8 KV allocates
    858,112 KV tokens / 82 snapshot slots (`--mtp-draft-tokens 0`).
  - Live-server fidelity vs HF BF16 (`--mtp-draft-tokens 0`, 64
    teacher-forced decode positions per context, 63/63 prefix-cache hits):
    - `ctx_1600`: mean top-20 KL 0.020872 -> 0.004351 (4.8x lower), max
      KL 1.134912 -> 0.159679 (7.1x lower), top-1 LP MAE 0.02779 ->
      0.00877 (3.2x lower), top-1 match 63/64 -> 64/64 (100.0%).
    - `ctx_4600` (crosses 4,096 chunk boundary): mean top-20 KL
      0.002687 -> 0.000540 (5.0x lower), max KL 0.136322 -> 0.024978
      (5.5x lower), top-1 LP MAE 0.00471 -> 0.00187 (2.5x lower), top-1
      match 63/64 -> 63/64.
    - Greedy 128-tok `code_1600` exact prefix match vs HF BF16: 32/128
      (FP8) -> 82/128 (BF16; positional 37 -> 112/128).
  - BF16-KV serving parity (MTP enabled): short greedy (`391`),
    multi-turn prefix reuse (`ORBITAL-7491`, 41 cached), 4,082-tok
    wraparound snapshot/restore (4,050 cached), 53,036-tok needle
    (`AMETHYST-42918`, 22.6s), and 163,834-tok needle (`SAPPHIRE-90371`,
    132.4s) all passed.
  - Throughput A/B (`--mtp-draft-tokens 0`, without `local-inference-lab#15` wide decode):
    prefill 8K 3,910 -> 3,786 (-3.2%), 16K 3,583 -> 3,349 (-6.5%), 32K
    3,107 -> 2,812 (-9.5%) tok/s; decode 0K C1 24.6 -> 24.5 (-0.4%), C2
    48.5 -> 48.3 (-0.4%); 16K C1 15.2 -> 12.6 (-17.1%), C2 29.9 -> 24.6
    (-17.7%); 32K C1 10.9 -> 8.4 (-22.9%) tok/s.
- Limitations: BF16 KV + `local-inference-lab#15` wide decode + `local-inference-lab#14`/PR 4 vision are now
  verified end to end on the combined SM120 31B BF16 TP1 stack, while
  KL/throughput A/Bs remain from the prior isolated SM120 `v0.4.0` run;
  TP2/TP4, NVFP4 + `--kv-cache-dtype bf16`, E2B/E4B/12B/26B-A4B, and
  SM103/SM121 were verified in unit/CUDA tests only.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 multimodal checkpoints include a 27-block BF16 vision tower
(1152 hidden size, 16 heads of dim 72, unit-scale attention with
`softmax_scale=1.0`, 2D rotary embeddings over `(x, y)` coordinates,
3x3 average spatial pooling, and a multimodal embedder projecting into
the text hidden dimension). Previously, `hyperflare_recipes` had no
prepared Gemma 4 vision encoder, and `PreparedVarlenAttention` hardcoded
`softmax_scale = q.shape[-1] ** -0.5`.

Changes:
- hyperflare_recipes/components/varlen_attention.py: add an optional
  `softmax_scale: float | None = None` parameter to
  `PreparedVarlenAttention`, defaulting to `q.shape[-1] ** -0.5` both
  at initialization and via `getattr(self, "softmax_scale", None)` in
  `__call__` so existing callers and `object.__new__` test fixtures
  remain unchanged while Gemma 4 passes `1.0`.
- hyperflare_recipes/recipes/gemma4/vision.py: add `PreparedVision`,
  `VisionMetadata`, and `VisionScratch` implementing the 27-block BF16
  vision tower, 3x3 patch pooling, and multimodal embedder parameterized
  by `text_hidden`, using `PreparedVarlenAttention(softmax_scale=1.0)`
  and `UnquantizedProjection` for CUDA-graph capture.
- tests/components/test_functional_attention_operands.py,
  tests/recipes/test_gemma4_vision.py: add an SM120 CUDA numerical parity
  test comparing `PreparedVision` against Hugging Face's
  `Gemma4VisionModel` + `Gemma4MultimodalEmbedder` on the cached
  `google/gemma-4-31B-it` checkpoint, and verify default and explicit
  `softmax_scale=1.0` forwarding in `PreparedVarlenAttention.__call__`.

Claimed result:
The Gemma 4 vision tower prepares and executes in CUDA graphs with
numerical parity against Hugging Face Transformers, ready to be wired
into `gemma4` multimodal preparation without modifying existing text
recipes or exported cores.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -v tests/recipes/test_gemma4_vision.py`:
    1 passed in 7.13s.
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/components/test_functional_attention_operands.py -k varlen`:
    2 passed, 11 deselected in 1.29s
    (`test_varlen_releases_templates_and_preserves_strided_output` and
    `test_varlen_gather_source_alias_is_explicit`).
- Post-rebase `v0.5.3` combined E2E serving (`recipes/gemma4-integration-v053`
  stack combining all 5 Gemma 4 recipe PRs + `NVIDIA/hyperflare-inference#483`
  `70546769`, SM120 GPU 0, `--max-concurrency 4 --image-concurrency 2`, 80
  graphs each, `seed=42`): both `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8
  KV) and `google/gemma-4-31B-it` TP1 (`--kv-cache-dtype bf16`) passed
  11/11 live `/v1/chat/completions` checks including 1-image, 2-image,
  4-image, >1.5K wraparound+image (`2,564` tokens), `810/810`
  prefix-cached multimodal replay, and 2-concurrent image requests.
- Limitations: E2E serving ran on the combined 5-PR stack (not this PR
  in isolation); standalone vision parity was tested on SM120
  `google/gemma-4-31B-it`, and E2B/E4B/12B/26B-A4B and SM103/SM121
  hardware were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 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`, `c15b6fe`)
and `local-inference-lab#14` (`recipes/gemma4-vision-encoder`, `ebe9196` on `c15b6fe`) and
requires companion core PR `NVIDIA/hyperflare-inference#483`
(`core/gemma4-image-frontend`, `70546769`) 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 over public
  `b12x.preparation` APIs, accepting both FP8 E4M3 and BF16
  paged/staged K/V caches with optional unbound `k_cache`/`v_cache`,
  overwriting only image rows in place and exiting early on text-only
  tiles).
- hyperflare_recipes/components/image_specs.py: add
  `gemma4_image_spec(snapshot)` returning a recipe-owned
  `ImageProcessorSpec` validating `Gemma4Processor`,
  `Gemma4ImageProcessor`, `patch_size=16`, `pooling_kernel_size=3`,
  `model_type="gemma4"` (`vision_config.model_type="gemma4_vision"`),
  and `image_token`/`boi_token`/`eoi_token` against `tokenizer.json`
  and optional `config.json` token IDs.
- 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 across both
  `prefill` and `terminal_prefill` variants (with `"vision"` in
  `compile_kinds`), `getattr(self, "vision", None)` in
  `PreparedDecoder.__call__`, `gemma4_image_spec` in `prepare_frontend`,
  and `PreparedImageSlidingAttention` over the staged circular sliding KV
  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,
  `gemma4_image_spec` rejection (including `gemma4_unified`), and
  atomic-token validation tests against `ignition.preparation.frontend`.

Claimed result:
Exported Gemma 4 31B NVFP4 TP1 and BF16 TP1 cores serve single-image,
multi-image (up to 4 images), long-prefix (>1.5K wraparound) image,
prefix-cached image replay, and concurrent 2-request image workloads
accurately on a single 96 GiB SM120 GPU with 1,537,024 KV tokens and 148
shared snapshot slots in NVFP4 FP8-KV (and 377,856 KV tokens / 36
shared snapshots in BF16 `--kv-cache-dtype bf16`, `--max-concurrency 4
--image-concurrency 2`, 80 graphs). Legacy pre-PR cores fail closed when
loaded by Core PR `#483`, while non-Gemma-4 cores inspect unchanged.

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 0, rebased on
  `20e360b` + `local-inference-lab#16` `c15b6fe` + `local-inference-lab#14` `ebe9196`, paired with editable
  Core PR `#483` `70546769` and `flashinfer-python` `5a8ceed8`):
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/components/test_image_sliding_attention_cuda.py tests/frontend/test_gemma4_images.py tests/recipes/test_gemma4_vision.py`:
    12 passed in 85.00s (8 sliding image CUDA tests including BF16 cache
    parity + 3 `gemma4_image_spec` frontend tests + 1 vision tower HF
    parity test).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    63 passed, 5 skipped, 9 deselected in 4.14s.
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/preparation/test_frontend_metadata.py -k gemma4`:
    1 passed, 1 skipped, 88 deselected in 0.93s (9 unrelated tests in full
    `test_frontend_metadata.py` fail pre-existing on `20e360b` due to
    upstream recipe/repo-split drift).
- Post-rebase `v0.5.3` combined E2E serving (`recipes/gemma4-integration-v053`
  stack combining all 5 Gemma 4 recipe PRs + `NVIDIA/hyperflare-inference#483`
  `70546769`, SM120 GPU 0, `--max-concurrency 4 --image-concurrency 2`, 80
  graphs each, `seed=42`, MTP enabled):
  - Matrix 1 (`nvidia/Gemma-4-31B-IT-NVFP4` TP1, FP8 KV): `60.6 GiB` ·
    `1,537,024` KV tokens (`12,008` pages) · `148` shared slots · `7.3 GiB`
    host prefix slab (`1,500` slots); `vision.patch_features=768`,
    `feature_slots=2`; 11/11 checks passed (`short_math` `'391'`,
    `multi_turn_prefix` `614/614`, >4K wraparound restore `cached=5565`,
    `5,703`-tok needle `'NEEDLE-7492-FALCON'`, 1/2/4-image, `2,564`-tok
    wraparound+image, `810/810` multimodal prefix-cache replay,
    2-concurrent images, `119.36 tok/s` decode / `119.13 tok/s` total
    with TTFT `0.005s` and MTP `788/313` ≈ `2.52` drafts/round).
  - Matrix 2 (`google/gemma-4-31B-it` TP1, `--kv-cache-dtype bf16`):
    `32.8 GiB` · `377,856` KV tokens (`2,952` pages) · `36` shared
    snapshots · `11.2 GiB` host prefix slab (`1,142` slots); 11/11
    checks passed (`multi_turn_prefix` `583/614`, >4K wraparound
    restore `cached=5529`, `5,703`-tok needle, 1/2/4-image, `2,564`-tok
    wraparound+image, `810/810` multimodal replay, 2-concurrent images,
    `70.73 tok/s` decode / `70.64 tok/s` total with TTFT `0.0045s` and
    MTP `337/131` ≈ `2.57` drafts/round).
  - Backward-compat & fail-closed load checks (`70546769` release `flare`):
    legacy `nvidia_2FGemma-4-31B-IT-NVFP4/gb202-tp1-202611240119` rejected
    with `bracketed image layout patch width (1176) differs from image
    processor (768); re-export the core with vision.patch_features`;
    existing `GLM-5.3-Flash` core `gb202-tp2-202611090656` passed `flare
    inspect` (`signatures verified`).
- Prior 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, text
  throughput 0K-128K C1/C2/C4 44.0->38.2 / 86.2->72.8 / 167.1->125.2
  tok/s.
- Limitations: E2E serving on `v0.5.3` ran on the combined 5-PR stack for
  31B NVFP4 FP8-KV and 31B BF16 BF16-KV on SM120 (without an isolated
  PR 4 vs PR 3 text A/B); TP2/TP4, E2B/E4B/12B/26B-A4B vision serving,
  and SM103/SM121 hardware were not executed end-to-end.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 global full-attention layers use 512-dim heads (with values
split into two 256-dim halves `value_lo` and `value_hi`). Previously,
`hyperflare_recipes/recipes/gemma4/attention.py` ran global decode and
verify through two padded `PreparedPagedAttention(mode="prefill")` calls
that lacked KV-length parallelism at small batch sizes, causing severe
long-context decode slowdown (4.5 tok/s at 128K C=1 on SM120 NVFP4).

Changes:
- hyperflare_recipes/components/wide_paged_decode.py: add
  `PreparedWidePagedDecode` (`flare.wide_paged_decode` recipe-side
  `native_contract` Triton operator over public `b12x.preparation` APIs),
  a split-KV decode/verify attention operator that handles 512-dim K and
  split 256+256 V (both FP8 E4M3 and BF16 caches, keeping BF16 tactics at
  `BLOCK_N <= 32` to stay within SM120's 99 KiB shared-memory limit) in
  a single pass with adaptive split-KV reduction across sequence length,
  `width` causal masking for MTP verification, and CUDA-graph capture
  safety.
- hyperflare_recipes/recipes/gemma4/attention.py: route non-prefill
  global layers through `PreparedWidePagedDecode`, removing the padded
  `q_full` / `attended_lo_full` / `attended_hi_full` buffers on global
  decode and verify while keeping `PreparedPagedAttention(mode="prefill")`
  on global prefill layers.
- tests/components/test_wide_paged_decode_cuda.py: add 13 SM120 CUDA
  tests verifying FP32 reference parity across head counts, batch sizes,
  verification widths (1, 4, 6), sequence lengths, NaN-poisoned tail
  slots, FP8 and BF16 KV caches, and CUDA graph capture/replay.

Claimed result:
Global full-attention decode and MTP verification on 512-dim Gemma 4
heads scale cleanly with context length on SM120 (measured 43.1 -> 37.3
tok/s from 0K to 128K C=1 on `gemma-4-31b-nvfp4` TP1 with `--mtp-draft-tokens 0`,
vs 40.7 -> 4.5 tok/s on baseline prefill-mode decode, an 8.3x speedup at
128K) while preserving greedy outputs and existing exported cores.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/components/test_wide_paged_decode_cuda.py`:
    13 passed in 7.52s (11 FP8 + 2 BF16 KV parity & CUDA graph replay).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    63 passed, 5 skipped, 9 deselected in 4.96s (the 9 deselected template
    tests require pre-generated `.source.jinja` files under
    `FLARE_TEST_TEMPLATE_DIR`).
- Post-rebase `v0.5.3` combined E2E serving (`recipes/gemma4-integration-v053`
  stack combining all 5 Gemma 4 recipe PRs + `NVIDIA/hyperflare-inference#483`
  `70546769`, SM120 GPU 0, `--max-concurrency 4 --image-concurrency 2`, 80
  graphs each, `seed=42`, MTP enabled):
  - Matrix 1 (`nvidia/Gemma-4-31B-IT-NVFP4` TP1, FP8 KV): `119.36 tok/s`
    decode (`119.13` tok/s total, TTFT `0.005s`), MTP `788` accepted
    drafts / `313` rounds (~`2.52` drafts/round), `5,703`-tok needle
    `NEEDLE-7492-FALCON` passed, 11/11 checks passed.
  - Matrix 2 (`google/gemma-4-31B-it` TP1, `--kv-cache-dtype bf16`):
    `70.73 tok/s` decode (`70.64` tok/s total, TTFT `0.0045s`), MTP `337`
    accepted drafts / `131` rounds (~`2.57` drafts/round), `5,703`-tok
    needle `NEEDLE-7492-FALCON` passed, 11/11 checks passed.
- Limitations: prior 0K-128K A/B was measured on pre-split
  `gemma-4-31b-nvfp4` TP1 SM120, and BF16 checkpoint + BF16 KV cache were
  executed live on the combined 5-PR stack on SM120; TP2/TP4, other
  Gemma 4 sizes, and SM103/SM121 hardware remain unit-tested only.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
@rickybrent

rickybrent commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto origin/main (3d1614cc, post-#683 ImageProcessorSpec refactor) at 4f777ec0:

  • Code, tests, and docs (4f777ec0):

    • Removed the redundant Vec::with_capacity before ProcessedImages::reserve_outputs (checked_mul + reserve_exact) in helios/src/frontend/images/gemma4.rs, matching glm.rs.
    • Removed the test-local _gemma4_extract / _gemma4_spec helpers, private _token import, and cached-checkpoint tests from tests/preparation/test_frontend_gemma4.py so core Python tests stay recipe-free and deterministic (covering _validate_image_payload, default_preprocessor, checked-in gemma4_images.json fixture validation, and runtime_core_pb2.ImageSettings round-trip).
    • Updated docs/TODO.txt and the PR description so both align on current verification scope and open items (26B-A4B multimodal serving, E2B/E4B 16-layer clipped-linear vision-tower parameterization in the recipe, and partial-span prefix-cache audit).
  • Full --locked --release verification on 4f777ec0 (origin/main 3d1614cc):

    • eos: 12 passed, 0 failed
    • selene (--features test-support): 553 passed, 0 failed
    • selene-manager (--features test-support): 425 passed, 0 failed, 1 ignored
    • helios (--features runtime-core,server with FLARE_TEST_TEMPLATE_DIR for un-gated recipes matching .github/workflows/native-serving.yml): 1,913 passed, 0 failed, 85 ignored
    • helios (--features runtime-core,server,test-tools --lib frontend::images): 48 passed, 0 failed, 1 ignored; live --ignored --exact frontend::images::gemma4::tests::checkpoint_tokens_expand_the_image_envelope on nvidia/Gemma-4-31B-IT-NVFP4@4135a98a: 1 passed, 0 failed (model:: 58, runtime_core::protobuf 29, server::config 3)
    • flare-cli: 246 passed, 0 failed, 3 ignored (including --test unverified_payload: 7 passed, 0 failed)
    • flare: 255 passed, 0 failed, 4 ignored
    • heliopause: 229 passed, 0 failed, 6 ignored
    • Rebuilt release flare + flare-heliopause; CI CPU Python suite (CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest tests/ -q): 2,504 passed, 459 skipped, 0 failed (21 passed, 0 skipped across tests/preparation/{test_core_boundary,test_source_identity,test_frontend_spec,test_frontend_gemma4}.py).
  • Combined-stack E2E multimodal serving & compatibility checks (paired with the companion local-inference-lab/hyperflare-recipes Gemma 4 stack on 20e360b, SM120×1 RTX PRO 6000 Blackwell, --max-concurrency 4 --image-concurrency 2, 80 graphs each, seed=42, MTP enabled; clean single-pass cold-cache runs):

    • nvidia/Gemma-4-31B-IT-NVFP4 TP1 (FP8 KV): flare inspect verified vision.image.profile="gemma4", vision.patch_features=768, feature_slots=2, patch_capacities=[630, 1260, 2520, 5040, 10080]; served with up to 1,537,024 KV tokens (12,008 pages) or up to 148 GPU snapshot slots sharing the 60.6 GiB VMM-aliased pool, and passed 11/11 live /v1/chat/completions checks (1-, 2-, and 4-image prompts, 2,564-token wraparound + image, 810/810 Turn-1 multimodal prefix-cache replay [Turn-2 follow-up t2_cached_tokens=0/834 under default enable_thinking=false, 815/839 with enable_thinking=true], 2-concurrent image requests, 5,703-token needle NEEDLE-7492-FALCON, cold multi_turn_prefix 583/614, cold >4K wraparound restore p1=5536, cached=5529, and 122.56 tok/s decode / 122.31 tok/s total; TTFT 0.0041s on a 37-token prefix-cached prompt, MTP 342/134 ≈ 2.55 drafts/round).
    • google/gemma-4-31B-it TP1 (--kv-cache-dtype bf16): served with up to 377,856 KV tokens (2,952 pages) or up to 36 GPU snapshot slots sharing the 32.8 GiB VMM-aliased pool, and passed 11/11 checks (1-, 2-, and 4-image prompts, 2,564-token wraparound + image, 810/810 Turn-1 multimodal replay [Turn-2 0/834], 2-concurrent image requests, 5,703-token needle, cold multi_turn_prefix 583/614, cold >4K wraparound restore p1=5536, cached=5529, and 70.73 tok/s decode / 70.64 tok/s total; TTFT 0.0045s on a 37-token prefix-cached prompt, MTP 337/131 ≈ 2.57 drafts/round).
    • Fail-closed & compatibility checks:
      • Loading a legacy pre-patch_features Gemma 4 core (gb202-tp1-202611240119) fails closed with an actionable re-export error (intentional compatibility narrowing since patch_features == 0 implies legacy width 1176 vs Gemma 4's 768, noted here for maintainer sign-off):
        Error: bracketed image layout patch width (1176) differs from image processor (768); re-export the core with vision.patch_features
      • Existing non-Gemma-4 core (GLM-5.3-Flash, gb202-tp2-202611090656) passed flare inspect (signatures verified).
    • Companion recipe branches (20e360b): #14 0f914fa, #15 7695db8, #16 d9ef2a2, rickybrent:recipes/gemma4-vision-wiring c1018c5, and rickybrent:recipes/gemma4-bf16-kv ae47fd4 pass their SM120 GPU 0 CUDA and frontend suites against 4f777ec0's ignition/flare-heliopause (test_image_sliding_attention_cuda.py + test_gemma4_images.py + test_gemma4_vision.py: 24 passed; test_wide_paged_decode_cuda.py: 14 passed; test_gemma4_sliding_window_cuda.py + test_window_attention_cuda.py: 74 passed).

rickybrent added a commit to rickybrent/hyperflare-inference that referenced this pull request Dec 3, 2026
…omic spans

Why:
Gemma 4 multimodal checkpoints preprocess images into aspect-preserving 16x16
interleaved RGB patches (768 float32 elements per patch), 2D (x, y) patch
coordinates, 3x3 spatial pooling (patches_per_feature = 9, up to 1,120 soft
tokens per image), and an atomic envelope (start_token, repeated image_token
features, end_token). Before this change, Helios had no Gemma 4 image
preparation profile, ImageLayoutKind::Bracketed hardcoded 2x2 merge and 1,176
floats per patch, and Bracketed layouts did not emit atomic image spans.
Without these changes, Gemma 4 cores cannot prepare or load native image
inputs, Bracketed vision uploads cannot pack 3x3 / 768-float patches, and
span-declaring Bracketed prompts fail per request at prompt validation instead
of failing closed at server bootstrap. To keep shared packing independent of
model identity without breaking MiniMax (the existing Bracketed user whose
PatchMerge profile uses 2x temporal duplication: 3 * 2 * 14^2 = 1,176 floats per
patch), prepared metadata declares per-patch float width via
VisionCapacity.patch_features instead of hardcoding a lookup table or assuming
3 * patch_size^2.

What changed:
- Wire & contract metadata (helios/proto/runtime_core.proto, helios/build.rs,
  ignition/preparation/{runtime_core_pb2.py,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):
  - Before: VisionCapacity carried no patch-width field, ImageSettings and
    ImagePreparationKind ended at tag 10 (PaddedGrid), and model_contract()
    omitted patch_features from its default vision map.
  - After: Added additive ImageSettings.profile tag 11 (Gemma4ImageSettings),
    ImagePreparationKind::Gemma4 (tag 11), and VisionCapacity.patch_features
    (tag 6, serde default 0) with VisionCapabilities::bracketed_patch_features()
    (where 0 inherits legacy width 1176) and non-zero validation requiring a
    positive multiple of 3. Defaulted vision["patch_features"] = 0 in
    ignition/preparation/contract.py, regenerated runtime_core_pb2.py with
    protoc 36.1 (Protobuf Python Version 7.36.1, descriptor-only diff), added a
    protobuf round-trip test for Gemma4ImageSettings, and documented the Gemma 4
    profile, fixture provenance, patch_features field, and Bracketed spans.
    Updated docs/TODO.txt to reflect 31B NVFP4/BF16 serving verified on the
    combined Gemma 4 recipe stack with 26B-A4B, E2B/E4B vision parameterization,
    and partial-span prefix-cache audit still open.
- Native image preparation, packing, and load validation
  (helios/src/frontend/images/{gemma4,mod,conditioned,packing,patch_merge}.rs,
  helios/src/model/packing.rs, helios/src/server/config.rs):
  - Before: No Gemma 4 preprocessor existed; Bracketed hardcoded 2x2 stride and
    width 1176 from a lookup branch; server bootstrap did not check patch width
    or maximum image envelope against prefill_chunk_size / span.max_tokens.
  - After: Added helios/src/frontend/images/gemma4.rs (area-bounded uint8
    antialiased bicubic resize matching PyTorch/torchvision, 1/255 scaling,
    interleaved (y, x, channel) patches, (x, y) coordinates, shared
    patch_merge::Envelope, ProcessedImages::reserve_outputs for checked-mul
    overflow checks and single reserve_exact reservation matching glm.rs, and
    per-condition load errors). Updated Bracketed packing to derive merge
    stride from any positive-square patches_per_feature and read pixel width
    from VisionCapabilities::bracketed_patch_features(). Unified per-profile
    patch width behind ImageProcessor::patch_features() (via
    PatchProcessor::pixel_width() for Qwen/PatchMerge and conditioned.rs), and
    added server bootstrap checks enforcing patch width, patches_per_feature,
    per-image patch capacity, and max envelope <= prefill_chunk_size and
    span.max_tokens.
- Layout-owned atomic spans (helios/src/frontend/images/layouts/bracketed.rs,
  helios/src/model/prompt.rs):
  - Before: Bracketed emitted no atomic spans and model/prompt.rs carried no
    Bracketed span path.
  - After: layouts::bracketed::prepare_input emits atomic spans when
    frontend.image_tokens.span is configured and validates prompt bounds on both
    ends.
- Preparation wire validation & tests (ignition/preparation/frontend.py,
  tests/frontend/{generate_gemma4_image_fixtures.py,gemma4_images.json},
  tests/preparation/{test_frontend_spec.py,test_frontend_gemma4.py},
  helios/src/model/tests.rs):
  - Before: Core ignition.preparation.frontend accepted only the 8 prior profiles.
  - After: Added "gemma4" to IMAGE_PROFILES and _validate_image_payload in
    ignition/preparation/frontend.py, validating wire bounds (patch_size in
    1..=64, pooling_kernel_size in 1..=16, max_soft_tokens in
    {70,140,280,560,1120}, and 3 distinct nonempty envelope tokens) for
    recipe-owned ImageProcessorSpec contracts. Added checked-in HF fixture
    generator and 8-case SHA-256 fixture JSON (max_soft_tokens 280 and 1120),
    unconditional Rust Envelope::expand, Bracketed span, legacy Bracketed
    Inputs::new core-load (1176-wide), cross-profile width, and bootstrap
    validation tests, an #[ignore] checkpoint envelope test, and recipe-free
    Python tests in test_frontend_gemma4.py covering _validate_image_payload,
    default_preprocessor, checked-in fixture verification, and pb2 round-trip.

Benefit & compatibility:
Helios natively decodes, resizes, rescales and packs, and validates Gemma 4
images with bit-exact SHA-256 parity against Hugging Face Gemma4ImageProcessor,
while catching patch-width and chunk-bound mismatches at bootstrap. MiniMax and
all non-Bracketed upstream cores remain loadable unchanged (missing
patch_features decodes as 0 -> legacy 1176 for Bracketed; envelope bounds apply
only to Gemma 4). Fail-closed narrowings: Bracketed now requires a
positive-square patches_per_feature, and any legacy Gemma 4 core prepared
before this change (with patch_features == 0) is rejected at load with an
actionable re-export error (`bracketed image layout patch width (1176) differs
from image processor (768); re-export the core with vision.patch_features`).

Evidence & limitations (verified on origin/main 3d1614c):
- Release Rust test suites (`--locked --release`):
  - eos: 12 passed, 0 failed
  - selene (--features test-support): 553 passed, 0 failed
  - selene-manager (--features test-support): 425 passed, 0 failed, 1 ignored
  - helios (--features runtime-core,server with FLARE_TEST_TEMPLATE_DIR):
    1,913 passed, 0 failed, 85 ignored (1,851 unit + 62 across integration
    targets)
  - helios (--features runtime-core,server,test-tools --lib): frontend::images
    48 passed, 0 failed, 1 ignored; live ignored checkpoint envelope test on
    nvidia/Gemma-4-31B-IT-NVFP4@4135a98a (`-- --ignored --exact
    frontend::images::gemma4::tests::checkpoint_tokens_expand_the_image_envelope`):
    1 passed, 0 failed; model:: 58 passed; runtime_core::protobuf 29 passed;
    server::config 3 passed
  - flare-cli: 246 passed, 0 failed, 3 ignored (including `cargo test --locked
    --release --manifest-path flare-cli/Cargo.toml --test unverified_payload`:
    7 passed, 0 failed)
  - flare: 255 passed, 0 failed, 4 ignored
  - heliopause: 229 passed, 0 failed, 6 ignored
- Rebuilt release `flare` binary (`flare-cli/target/release/flare`) and
  `flare-heliopause`, synced `.venv` (`flashinfer-python` `5a8ceed8`), and ran
  CI CPU Python suite (`CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest
  tests/ -q`): 2,504 passed, 459 skipped, 0 failed (including 21 passed, 0
  skipped across `tests/preparation/{test_core_boundary,test_source_identity,
  test_frontend_spec,test_frontend_gemma4}.py`).
- Combined-stack E2E multimodal serving (evaluated on the companion 5-PR Gemma 4
  recipe stack in `local-inference-lab/hyperflare-recipes` paired with this PR,
  RTX PRO 6000 Blackwell SM120 GPU 0, TP1, `--max-concurrency 4
  --image-concurrency 2`, MTP enabled):
  - `nvidia/Gemma-4-31B-IT-NVFP4` (FP8 KV): 11/11 checks passed (short math
    `'391'`, 5,703-tok needle `'NEEDLE-7492-FALCON'`, 1/2/4-image, 2,564-tok
    wraparound+image, `810/810` Turn-1 multimodal prefix-cache replay,
    2-concurrent images, 119.32 tok/s decode / 119.07 tok/s total, TTFT
    0.0045s on a 37-tok prefix-cached prompt).
  - `google/gemma-4-31B-it` (BF16 KV): 11/11 checks passed (`810/810` Turn-1
    multimodal replay, 2-concurrent images, 70.73 tok/s decode / 70.64 tok/s
    total, TTFT 0.0045s on cached prompt).
  - Backward-compat & fail-closed load checks with release `flare`: legacy
    pre-NVIDIA#483 Gemma 4 core `gb202-tp1-202611240119` fails load with `bracketed
    image layout patch width (1176) differs from image processor (768);
    re-export the core with vision.patch_features`; existing `GLM-5.3-Flash`
    core `gb202-tp2-202611090656` passes `flare inspect` (`signatures
    verified`).
- Limitations: End-to-end multimodal serving requires the companion Gemma 4
  recipe stack (`local-inference-lab/hyperflare-recipes`). On that combined
  stack, 31B NVFP4 (FP8 KV) and 31B BF16 (BF16 KV) serving are verified on SM120
  TP1, whereas TP2/TP4, 26B-A4B vision serving, E2B/E4B (16-layer 768-dim
  clipped-linear tower not yet parameterized in the recipe), SM103/SM121
  hardware, and partial-span prefix-cache hits remain unverified (tracked in
  `docs/TODO.txt`).

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from 7054676 to 687481e Compare December 3, 2026 17:14
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 26B-A4B and 31B multimodal checkpoints include a 27-block BF16 vision
tower (1152 hidden size, 16 heads of dim 72, 4304 MLP intermediate size,
unit-scale attention with `softmax_scale=1.0`, 2D rotary embeddings over
`(x, y)` coordinates, 3x3 average spatial pooling, standardize buffers
(`std_bias`/`std_scale`), non-clipped linears, and a multimodal embedder
projecting into the text hidden dimension). Previously, `hyperflare-recipes` had
no prepared Gemma 4 vision encoder, and `PreparedVarlenAttention` hardcoded
`softmax_scale = q.shape[-1] ** -0.5` and conflated invalid `softmax_scale` with
`max_seqlen` in its error message.

Changes:
- hyperflare_recipes/components/varlen_attention.py: add an optional
  `softmax_scale: float | None = None` parameter to `PreparedVarlenAttention`
  and separate validation errors for invalid `max_seqlen` vs invalid
  `softmax_scale`, defaulting to `q.shape[-1] ** -0.5` both at initialization
  and via `getattr(self, "softmax_scale", None)` in `__call__` so existing
  callers and `object.__new__` test fixtures remain unchanged while Gemma 4
  passes `1.0`.
- hyperflare_recipes/recipes/gemma4/vision.py: add `PreparedVision`,
  `VisionMetadata`, `VisionScratch`, `VisionWeights`, and
  `supports_vision_config` implementing the 27-block 1152-dim standardized
  non-clipped BF16 vision tower (`LAYERS = 27`, `PATCH_SIZE = 16`), 3x3 patch
  pooling, and multimodal embedder parameterized by `text_hidden`, using
  `PreparedVarlenAttention(softmax_scale=1.0)` and `UnquantizedProjection` for
  CUDA-graph capture; fail closed in both `VisionWeights.from_checkpoint` and
  `PreparedVision.__init__` for unsupported architectures (`E2B`/`E4B` 16-block
  768-dim clipped-linear towers and `12B` `gemma4_unified_vision`).
- tests/components/test_functional_attention_operands.py,
  tests/recipes/test_gemma4_vision.py: add CPU unit tests for separate
  `max_seqlen` and `softmax_scale` `ValueError` messages and
  `supports_vision_config` / `VisionWeights.from_checkpoint` rejection of E2B
  and `gemma4_unified_vision`, plus an SM120 CUDA numerical parity test comparing
  `PreparedVision` against Hugging Face's `Gemma4VisionModel` +
  `Gemma4MultimodalEmbedder` on a cached 31B checkpoint (`google/gemma-4-31B-it`
  or `nvidia/Gemma-4-31B-IT-NVFP4`, which share the identical BF16 vision
  tower).

Claimed result:
The 27-block 1152-dim standardized Gemma 4 vision tower (26B-A4B and 31B)
prepares and executes in CUDA graphs with measured BF16 direction, scale, and
relative-L2 agreement against Hugging Face Transformers without modifying
existing text recipes or exported cores, while E2B/E4B (16-block 768-dim
clipped-linear) and 12B (`gemma4_unified`) vision configs fail closed.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/components/test_functional_attention_operands.py -k varlen`:
    3 passed, 11 deselected in 1.51s (including separate `max_seqlen` and
    `softmax_scale` `ValueError` validation).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/recipes/test_gemma4_vision.py -k "not matches_checkpoint"`:
    2 passed, 1 deselected in 2.99s (`supports_vision_config` and fail-closed
    `VisionWeights.from_checkpoint` rejection of E2B / `gemma4_unified_vision`).
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -v -o junit_family=legacy tests/recipes/test_gemma4_vision.py --junitxml=/tmp/gemma4_vision_junit.xml`:
    3 passed in 5.90s. On `nvidia/Gemma-4-31B-IT-NVFP4@4135a98a` (BF16 vision
    tower), `test_vision_encoder_matches_checkpoint` measured
    `relative_l2 = 0.089821` (8.98% vs 15% test bound), `cosine = 0.995965`
    (> 0.99 bound), `norm_ratio = 0.999697` (±2% bound), and
    `max_abs_ratio = 0.203887` (20.39% vs 30% test bound); these wider test
    tolerances accommodate BF16 accumulation variance across the 27-layer tower.
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe stack
  + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`): both
  `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV) and `google/gemma-4-31B-it` TP1
  (`--kv-cache-dtype bf16`) passed 11/11 live `/v1/chat/completions` checks
  including 1-image, 2-image, 4-image, >1.5K wraparound+image (`2,564` tokens),
  `810/810` Turn-1 multimodal prefix-cache replay, and 2-concurrent image
  requests.
- Limitations: E2E serving ran on the combined 5-PR stack (not this PR in
  isolation); standalone vision parity ran on SM120 using the 31B BF16 vision
  tower (`nvidia/Gemma-4-31B-IT-NVFP4@4135a98a`); `26B-A4B` vision parity was
  not executed independently on GPU; `E2B`/`E4B` (16-block 768-dim
  clipped-linear tower) and `12B` (`gemma4_unified`) remain out of scope; and
  SM103/SM121 GPUs were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 global full-attention layers use 512-dim heads (with values
split into two 256-dim halves `value_lo` and `value_hi`), and `b12x` does
not currently provide a native 512-dim split-V decode operator.
Previously, `hyperflare_recipes/recipes/gemma4/attention.py` ran global
decode and verify through two padded `PreparedPagedAttention(mode="prefill")`
calls that lacked KV-length parallelism at small batch sizes, causing severe
long-context decode slowdown (4.5 tok/s at 128K C=1 on SM120 NVFP4).

Changes:
- hyperflare_recipes/components/wide_paged_decode.py: add
  `PreparedWidePagedDecode` (`flare.wide_paged_decode` recipe-side
  `native_contract` Triton operator over public `b12x.preparation` APIs),
  a split-KV decode/verify attention operator that handles 512-dim K and
  split 256+256 V (both FP8 E4M3 and BF16 caches, keeping BF16 tactics at
  `BLOCK_N <= 32` to stay within SM120's 99 KiB shared-memory limit) in
  a single pass with adaptive split-KV reduction across sequence length,
  `width` causal masking for MTP verification, positive 16-aligned
  `page_size` validation, and CUDA-graph capture safety.
- hyperflare_recipes/recipes/gemma4/attention.py: route non-prefill
  global layers through `PreparedWidePagedDecode`, removing the padded
  `q_full` / `attended_lo_full` / `attended_hi_full` buffers on global
  decode and verify while keeping `PreparedPagedAttention(mode="prefill")`
  on global prefill layers.
- tests/components/test_wide_paged_decode_cuda.py: add 14 SM120 CUDA
  tests verifying FP32 reference parity across head counts, batch sizes,
  verification widths (1, 4, 6), sequence lengths, NaN-poisoned tail
  slots, unaligned `page_size` rejection, FP8 and BF16 KV caches, and
  CUDA graph capture/replay.

Claimed result:
Global full-attention decode and MTP verification on 512-dim Gemma 4
heads scale cleanly with context length on SM120 (measured 43.1 -> 37.3
tok/s from 0K to 128K C=1 on earlier single-repo `gemma-4-31b-nvfp4` TP1
with `--mtp-draft-tokens 0`, vs 40.7 -> 4.5 tok/s on baseline prefill-mode
decode, an 8.3x speedup at 128K) while preserving greedy outputs and
existing exported cores.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/components/test_wide_paged_decode_cuda.py`:
    14 passed in 7.28s (11 FP8 + 2 BF16 KV parity & CUDA graph replay +
    unaligned `page_size` rejection).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    63 passed, 5 skipped, 9 deselected in 4.59s (excluding the 9
    `test_model_sizes_select_canonical_chat_templates` parameterized cases
    that validate pinned upstream HF chat templates outside this PR).
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe
  stack + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`, MTP enabled):
  - `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV): `119.32 tok/s` decode
    (`119.07` tok/s total; TTFT `0.0045s` on a 37-token prefix-cached prompt),
    MTP `788` accepted drafts / `313` rounds (~`2.52` drafts/round),
    `5,703`-tok needle `NEEDLE-7492-FALCON` passed, 11/11 checks passed.
  - `google/gemma-4-31B-it` TP1 (`--kv-cache-dtype bf16`): `70.73 tok/s`
    decode (`70.64` tok/s total; TTFT `0.0045s` on a 37-token prefix-cached
    prompt), MTP `337` accepted drafts / `131` rounds (~`2.57` drafts/round),
    `5,703`-tok needle `NEEDLE-7492-FALCON` passed, 11/11 checks passed.
- Limitations: prior 0K-128K A/B was measured on an earlier single-repo
  `gemma-4-31b-nvfp4` TP1 SM120 build, and BF16 checkpoint + BF16 KV cache
  were executed live on the combined 5-PR stack on SM120; TP2/TP4, other
  Gemma 4 sizes, and SM103/SM121 hardware were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 26B-A4B and 31B multimodal checkpoints include a 27-block BF16 vision
tower (1152 hidden size, 16 heads of dim 72, 4304 MLP intermediate size,
unit-scale attention with `softmax_scale=1.0`, 2D rotary embeddings over
`(x, y)` coordinates, 3x3 average spatial pooling, standardize buffers
(`std_bias`/`std_scale`), non-clipped linears, and a multimodal embedder
projecting into the text hidden dimension). Previously, `hyperflare-recipes` had
no prepared Gemma 4 vision encoder, and `PreparedVarlenAttention` hardcoded
`softmax_scale = q.shape[-1] ** -0.5` and conflated invalid `softmax_scale` with
`max_seqlen` in its error message.

Changes:
- hyperflare_recipes/components/varlen_attention.py: add an optional
  `softmax_scale: float | None = None` parameter to `PreparedVarlenAttention`
  and separate validation errors for invalid `max_seqlen` vs invalid
  `softmax_scale`, defaulting to `q.shape[-1] ** -0.5` both at initialization
  and via `getattr(self, "softmax_scale", None)` in `__call__` so existing
  callers and `object.__new__` test fixtures remain unchanged while Gemma 4
  passes `1.0`.
- hyperflare_recipes/recipes/gemma4/vision.py: add `PreparedVision`,
  `VisionMetadata`, `VisionScratch`, `VisionWeights`, and
  `supports_vision_config` implementing the 27-block 1152-dim standardized
  non-clipped BF16 vision tower (`LAYERS = 27`, `PATCH_SIZE = 16`), 3x3 patch
  pooling, and multimodal embedder parameterized by `text_hidden`, using
  `PreparedVarlenAttention(softmax_scale=1.0)` and `UnquantizedProjection` for
  CUDA-graph capture; fail closed in both `VisionWeights.from_checkpoint` and
  `PreparedVision.__init__` for unsupported architectures (`E2B`/`E4B` 16-block
  768-dim clipped-linear towers and `12B` `gemma4_unified_vision`).
- tests/components/test_functional_attention_operands.py,
  tests/recipes/test_gemma4_vision.py: add CPU unit tests for separate
  `max_seqlen` and `softmax_scale` `ValueError` messages and
  `supports_vision_config` / `VisionWeights.from_checkpoint` rejection of E2B
  and `gemma4_unified_vision`, plus an SM120 CUDA numerical parity test comparing
  `PreparedVision` against Hugging Face's `Gemma4VisionModel` +
  `Gemma4MultimodalEmbedder` on a cached 31B checkpoint (`google/gemma-4-31B-it`
  or `nvidia/Gemma-4-31B-IT-NVFP4`, which share the identical BF16 vision
  tower).

Claimed result:
The 27-block 1152-dim standardized Gemma 4 vision tower (26B-A4B and 31B)
prepares and executes in CUDA graphs with measured BF16 direction, scale, and
relative-L2 agreement against Hugging Face Transformers without modifying
existing text recipes or exported cores, while E2B/E4B (16-block 768-dim
clipped-linear) and 12B (`gemma4_unified`) vision configs fail closed.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/components/test_functional_attention_operands.py -k varlen`:
    3 passed, 11 deselected in 1.51s (including separate `max_seqlen` and
    `softmax_scale` `ValueError` validation).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/recipes/test_gemma4_vision.py -k "not matches_checkpoint"`:
    2 passed, 1 deselected in 2.99s (`supports_vision_config` and fail-closed
    `VisionWeights.from_checkpoint` rejection of E2B / `gemma4_unified_vision`).
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -v -o junit_family=legacy tests/recipes/test_gemma4_vision.py --junitxml=/tmp/gemma4_vision_junit.xml`:
    3 passed in 5.90s. On `nvidia/Gemma-4-31B-IT-NVFP4@4135a98a` (BF16 vision
    tower), `test_vision_encoder_matches_checkpoint` measured
    `relative_l2 = 0.089821` (8.98% vs 15% test bound), `cosine = 0.995965`
    (> 0.99 bound), `norm_ratio = 0.999697` (±2% bound), and
    `max_abs_ratio = 0.203887` (20.39% vs 30% test bound); these wider test
    tolerances accommodate BF16 accumulation variance across the 27-layer tower.
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe stack
  + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`): both
  `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV) and `google/gemma-4-31B-it` TP1
  (`--kv-cache-dtype bf16`) passed 11/11 live `/v1/chat/completions` checks
  including 1-image, 2-image, 4-image, >1.5K wraparound+image (`2,564` tokens),
  `810/810` Turn-1 multimodal prefix-cache replay, and 2-concurrent image
  requests.
- Limitations: E2E serving ran on the combined 5-PR stack (not this PR in
  isolation); standalone vision parity ran on SM120 using the 31B BF16 vision
  tower (`nvidia/Gemma-4-31B-IT-NVFP4@4135a98a`); `26B-A4B` vision parity was
  not executed independently on GPU; `E2B`/`E4B` (16-block 768-dim
  clipped-linear tower) and `12B` (`gemma4_unified`) remain out of scope; and
  SM103/SM121 GPUs were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 sliding-window layers allow each image token to attend over
`window intersect (causal union 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 and current chunk into a
contiguous buffer via `PreparedWindowStaging`, 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 builds on `recipes/gemma4-sliding-window-kv` (`local-inference-lab#16`) and
`recipes/gemma4-vision-encoder` (`local-inference-lab#14`), and requires companion core PR
`NVIDIA/hyperflare-inference#483` (`core/gemma4-image-frontend`) for
native Gemma 4 image preprocessing, 3x3 bracketed packing, and atomic
image spans. (`uv.lock` on `main` `20e360b` already pins `c513e46a`
containing merged `#484` `50c876df`.)

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 over public
  `b12x.preparation` APIs, supporting both `float8_e4m3fn` and `bfloat16`
  staged circular-window / paged caches with optional unbound
  `k_cache`/`v_cache`, overwriting only image rows in place and exiting
  early on text-only tiles). BF16 cache execution in
  `PreparedImageSlidingAttention` is unit-tested in this PR and
  exercised in recipe bootstrap once `--kv-cache-dtype bf16` lands.
- hyperflare_recipes/components/image_specs.py: add
  `gemma4_image_spec(snapshot)` defining the recipe-owned
  `ImageProcessorSpec` validating `Gemma4Processor`,
  `Gemma4ImageProcessor`, `patch_size = 16`, `pooling_kernel_size = 3`,
  `model_type = "gemma4"` (`vision_config.model_type = "gemma4_vision"`),
  and `image_token`/`boi_token`/`eoi_token` against `tokenizer.json` and
  optional `config.json` token IDs.
- hyperflare_recipes/recipes/gemma4/{vision_state,config,weights,contract,
  attention,decoder,bootstrap,recipe}.py: wire `VisionInputs`, pass
  `VisionParameters(separable_encoder=True)` on `RECIPE` (inherited from
  `RecipeParameters`), set `VISION["patch_features"] = 768` (matching
  `NVIDIA/hyperflare-inference#483`), build `PreparedVisionGeneration`
  (5 vision graphs for capacities `630..10080`), gate default vision
  loading via `should_load_vision` so 27-layer 1152-dim standardized
  non-clipped checkpoints (26B-A4B, 31B) load vision while E2B/E4B
  (16-layer 768-dim clipped-linear) and 12B (`gemma4_unified`) plus
  `--language-model-only` / `--image-concurrency 0` cleanly export text-only
  cores, wire vision feature injection across both `prefill` and
  `terminal_prefill` variants (with `"vision"` in `compile_kinds`), use
  `getattr(self, "vision", None)` in `PreparedDecoder.__call__`, pass
  `gemma4_image_spec` in `prepare_frontend`, compute per-prefill staged
  span offsets in `PreparedDecoder`, run `PreparedImageSlidingAttention`
  over the staged circular sliding KV output in `PreparedAttention`, and
  tag `"vision"` in the compilation identity hash.
- tests/components/test_image_sliding_attention_cuda.py,
  tests/frontend/test_gemma4_images.py: add 8 SM120 CUDA tests covering
  paged and 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, BF16 cache
  parity, and CUDA graph capture/replay with text-only early exit; add 3
  cached-31B frontend tests plus 3 CI-runnable synthetic tests covering
  `gemma4_image_spec`, `prepare_contract(..., vision=True)` (`patch_features
  = 768` and `Bracketed` atomic spans), and `should_load_vision` gating on
  E2B and 12B.

Claimed result:
On the combined 5-PR `v0.5.3` multimodal stack paired with Core PR `#483`,
exported Gemma 4 31B NVFP4 TP1 and 31B BF16 TP1 cores serve single-image,
multi-image (up to 4 images), long-prefix (>1.5K wraparound) image,
Turn-1 prefix-cached multimodal replay (`810/810`), and concurrent
2-request image workloads accurately on a single 96 GiB SM120 GPU, with
up to `1,537,024` KV tokens (`148` snapshot slots sharing the `60.6 GiB`
VMM-aliased pool) in NVFP4 FP8-KV and up to `377,856` KV tokens (`36`
snapshot slots sharing the `32.8 GiB` pool) in BF16 `--kv-cache-dtype bf16`
(`--max-concurrency 4 --image-concurrency 2`, 80 graphs). `E2B`/`E4B` and
`12B` skip unsupported vision towers cleanly during default text export,
legacy pre-`#483` Gemma 4 cores fail closed when loaded by Core PR `#483`,
and existing non-Gemma-4 cores inspect unchanged.

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 0, stacked on
  `20e360b` + `local-inference-lab#16` `530b433` + `local-inference-lab#14` `3842bee`, paired with editable
  `ignition` + `flare-heliopause` from Core PR `#483` `687481e3`,
  `flashinfer-python` `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/frontend/test_gemma4_images.py -k "synthetic or prepare_contract or unsupported"`:
    3 passed, 3 deselected in 2.86s (CI-runnable without cached weights).
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/components/test_image_sliding_attention_cuda.py tests/frontend/test_gemma4_images.py tests/recipes/test_gemma4_vision.py`:
    17 passed in 84.34s (8 sliding image CUDA tests including BF16 cache
    parity + 6 `gemma4_image_spec`/contract/gating frontend tests + 3
    vision tower tests).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    63 passed, 5 skipped, 9 deselected in 4.45s (9 deselected template
    cases require `FLARE_TEST_TEMPLATE_DIR`).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/preparation/test_frontend_metadata.py -k gemma4`:
    1 passed, 1 skipped, 88 deselected in 0.98s (9 unrelated tests in full
    `test_frontend_metadata.py` fail pre-existing on `20e360b` due to
    upstream recipe/repo-split drift).
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe
  stack + Core PR `#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`, MTP enabled):
  - `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV): `60.6 GiB` · `1,537,024`
    KV tokens (`12,008` pages) · `148` shared snapshot slots · `7.3 GiB`
    host prefix slab (`1,500` page-sized `5 MiB` slab units);
    `vision.patch_features=768`, `feature_slots=2`; 11/11 checks passed
    (`short_math` `'391'`, cold `multi_turn_prefix` `583/614`, cold >4K
    wraparound restore `p1=5536, cached=5529`, `5,703`-tok needle
    `'NEEDLE-7492-FALCON'`, 1/2/4-image, `2,564`-tok wraparound+image,
    Turn-1 multimodal prefix-cache replay `810/810` [Turn-2 follow-up
    `t2_cached_tokens=0/834`], 2-concurrent images, `119.32 tok/s` decode /
    `119.07 tok/s` total, TTFT `0.0045s` on a 37-token prefix-cached prompt,
    MTP `788/313` ~ `2.52` drafts/round).
  - `google/gemma-4-31B-it` TP1 (`--kv-cache-dtype bf16`): `32.8 GiB` ·
    `377,856` KV tokens (`2,952` pages) · `36` shared snapshot slots ·
    `11.2 GiB` host prefix slab (`1,142` page-sized `10 MiB` slab units);
    11/11 checks passed (cold `multi_turn_prefix` `583/614`, cold >4K
    wraparound restore `p1=5536, cached=5529`, `5,703`-tok needle,
    1/2/4-image, `2,564`-tok wraparound+image, Turn-1 `810/810` replay
    [Turn-2 `t2_cached_tokens=0/834`], 2-concurrent images, `70.73 tok/s`
    decode / `70.64 tok/s` total, TTFT `0.0045s` on cached prompt, MTP
    `337/131` ~ `2.57` drafts/round).
  - Backward-compat & fail-closed load checks (rebuilt release `flare`):
    legacy `nvidia_2FGemma-4-31B-IT-NVFP4/gb202-tp1-202611240119` rejected
    with `bracketed image layout patch width (1176) differs from image
    processor (768); re-export the core with vision.patch_features`;
    existing `GLM-5.3-Flash` core `gb202-tp2-202611090656` passed `flare
    inspect` (`signatures verified`).
- Earlier single-repo multimodal E2E serving (`gemma-4-31b-nvfp4` TP1
  package `gb202-tp1-202611230337` built from `feb712de`, combining PR 1 +
  PR 2 + PR 3 + PR 4): 7/7 multimodal checks passed, `60.7 GiB` KV /
  `1,540,096` KV tokens / `148` shared snapshot slots, text throughput
  0K-128K C1/C2/C4 `44.0->38.2 / 86.2->72.8 / 167.1->125.2 tok/s`.
- Limitations: E2E serving on `v0.5.3` ran on the combined 5-PR stack
  paired with Core PR `#483` for 31B NVFP4 FP8-KV and 31B BF16 BF16-KV on
  SM120 (without an isolated PR 4 vs PR 3 text A/B); `26B-A4B` vision
  serving, `E2B`/`E4B`/`12B` vision (16-layer clipped-linear and
  `gemma4_unified` towers remain text-only by default), TP2/TP4, and
  SM103/SM121 hardware were not executed end-to-end.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
…ged global KV

Gemma 4 models apply RMSNorm to Q/K/V and attend with unit scale
(`softmax_scale = 1.0`), making their attention logits unusually sensitive
to FP8 E4M3 KV cache quantization (3-bit mantissa on K/V). With circular
sliding-window KV (`local-inference-lab#16`, `recipes/gemma4-sliding-window-kv`) shrinking
paged KV storage by 11x at TP1 on 31B and 21x on 12B, full lossless
BF16 KV becomes practical on a single 96 GiB GPU (`401,408` KV tokens
and `38` shared snapshot slots on isolated `google/gemma-4-31B-it` BF16
TP1 with MTP enabled, `765,952` tokens / `73` slots on `31B NVFP4`, and
`2,363,392` tokens / `227` slots on `26B-A4B`) with zero core
`NVIDIA/hyperflare-inference` or `b12x` changes.

This PR stacks directly on `recipes/gemma4-sliding-window-kv` (`local-inference-lab#16`)
and keeps `fp8` as the default `--kv-cache-dtype` so existing exports
and defaults remain unchanged.

Changes:
- hyperflare_recipes/recipes/gemma4/recipe.py: add
  `KvCachePrecisionParameters(ParameterGroup)` exposing `--kv-cache-dtype
  {fp8,bf16}` (default `"fp8"`) on `Gemma4Parameters`, automatically
  wired into `ignition export` CLI, planner, and signed core reproduction
  manifests via `RecipeParameters`; implement `adjust_rank_costs()`
  returning exact `StateLayout.from_specs` BF16 `RankCosts` for all five
  Gemma 4 sizes (E2B, E4B, 12B, 26B-A4B, 31B) across TP1/TP2/TP4.
- hyperflare_recipes/components/window_attention.py: add batched Triton
  `stage_circular_kv` (`torch.library.wrap_triton`) to stage BF16
  circular sliding history and current prefill candidates into contiguous
  BF16 paged buffers without modifying `b12x`'s FP8-only
  `WindowStageKernel`, enforcing contiguous staging output tensors
  (`output_key.is_contiguous()` / `output_value.is_contiguous()` with
  `.view(...)`) and `(kv_heads, head_dim)` / trailing-stride checks.
- hyperflare_recipes/recipes/gemma4/{pool,attention,bootstrap}.py:
  parameterize `page_specs`, `page_bytes`, `continuation_layout`, and
  `ContinuationPool` by `kv_dtype`; route BF16 sliding prefill staging
  through `stage_circular_kv`; pre-scale queries by `math.sqrt(dim)`
  before BF16 `PreparedPagedAttention` (an exact BF16 exponent shift of
  16.0 on 256-dim sliding heads, whereas `sqrt(512)` on global heads is a
  BF16 mantissa multiply, since `b12x` ignores `k_descale` for BF16 KV);
  keep `PreparedWindowAttention(softmax_scale=1.0)` and
  `commit_circular_kv` in native BF16 without FP8 clamping; include
  `"kv_dtype"` in the compilation identity hash.
- tests/recipes/{test_gemma4.py,test_gemma4_sliding_window_cuda.py}: add
  exact BF16 `RankCosts` across all 5 variants x TP1/TP2/TP4,
  `stage_circular_kv` non-contiguous output rejection, SM120 BF16 sliding
  prefill/commit/wraparound decode/verify parity, and BF16 512-dim
  global KV write + unit-scale prefill parity tests.

Claimed result:
Exporting Gemma 4 checkpoints with `--kv-cache-dtype bf16` stores both
circular sliding-window and paged global KV caches in lossless BF16 while
keeping `--kv-cache-dtype fp8` unchanged by default. In the archived
211,692-position live-server study (`REPORT.md`), switching to BF16 KV
cuts mean top-20 KL vs Hugging Face BF16 by 2.61x on 31B BF16 Dense
(`0.2417 -> 0.0926`, median KL 5.64x lower `0.01214 -> 0.00215`, P95 KL
4.16x lower `1.220 -> 0.293`, top-1 agreement `85.73% -> 92.63%`, 32K
delta-NLL `+0.161 -> +0.011`) and 1.64x on 26B-A4B MoE (`0.3982 ->
0.2431`), while fitting `401,408` KV tokens (`38` snapshot slots, `1.53x`
262K) on isolated 31B BF16 TP1 (`377,856` KV tokens / `36` slots on the
combined 5-PR multimodal build), `765,952` tokens (`73` slots, `2.92x`
262K) on 31B NVFP4, and `2,363,392` tokens (`227` slots, `9.02x` 262K) on
26B-A4B on a single 96 GiB SM120 GPU. Existing exported cores embed their
compiled graphs and remain unaffected.

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 0, rebased on
  `20e360b` + `local-inference-lab#16` `530b433`, `ignition` `c513e46a`, `flashinfer-python`
  `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4_sliding_window_cuda.py -k reject`:
    2 passed, 5 deselected (`commit_circular_kv` and `stage_circular_kv`
    contiguity rejection).
  - `CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/recipes/test_gemma4_sliding_window_cuda.py tests/components/test_window_attention_cuda.py`:
    74 passed in 200.35s.
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    64 passed, 5 skipped, 9 deselected in 4.29s (9 deselected template
    cases require `FLARE_TEST_TEMPLATE_DIR`).
- Archived 211,692-position E2E study (`/home/ricky/flare/reports/gemma4-kv-benchmark/REPORT.md`,
  SM120 96 GiB TP1 vs HF BF16):
  - 31B BF16 Dense (BF16 vs FP8 KV): mean top-20 KL `0.0926` vs `0.2417`
    (2.61x lower), median KL `0.00215` vs `0.01214` (5.64x lower), P95 KL
    `0.293` vs `1.220` (4.16x lower), top-1 agreement `92.63%` vs `85.73%`,
    weighted delta-NLL `+0.0121` vs `+0.1210` (32K delta-NLL `+0.011` vs
    `+0.161`); capacity `401,408` KV tokens (`38` snapshot slots) on
    isolated text core; C1 128K decode `19.9` vs `21.7 tok/s` (-8.3%).
  - 26B-A4B MoE (BF16 vs FP8 KV): mean top-20 KL `0.2431` vs `0.3982`
    (1.64x lower), `2,363,392` KV tokens (`227` snapshot slots), C1 128K
    decode `95.7` vs `108.2 tok/s` (-11.6%).
  - 31B NVFP4 (BF16 vs FP8 KV): `765,952` KV tokens (`73` snapshot slots),
    C1 128K decode `30.8` vs `35.4 tok/s` (-13.0%), `5/5` MTP parity checks
    including `168,231`-token needle; within-engine FP8 KV induces `0.6548`
    KL and flips 26.9% of top-1 tokens (`0.7465 -> 0.6962` vs HF BF16).
- Post-rebase `v0.5.3` combined E2E serving (`google/gemma-4-31B-it` TP1,
  combined 5-PR stack + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0,
  `--kv-cache-dtype bf16 --max-concurrency 4 --image-concurrency 2`, 80
  graphs, `seed=42`, MTP enabled): `32.8 GiB`, `377,856` KV tokens (`2,952`
  pages), `36` shared snapshot slots, `11.2 GiB` host prefix slab (`1,142`
  page-sized `10 MiB` slab units); 11/11 checks passed (`short_math` `'391'`,
  cold `multi_turn_prefix` `583/614`, >4K wraparound `p1=5536, cached=5529`,
  `5,703`-tok needle `'NEEDLE-7492-FALCON'`, 1/2/4-image, `2,564`-tok
  wraparound+image, `810/810` Turn-1 multimodal replay, 2-concurrent images,
  `70.73 tok/s` decode / `70.64 tok/s` total, TTFT `0.0045s` on a 37-token
  prefix-cached prompt, MTP `337/131` ~ `2.57` drafts/round).
- Limitations / tradeoffs: continuation row size doubles in BF16 (`810
  MiB`/row on 31B TP1 vs `405 MiB` in FP8; requires merged core `#484`
  `50c876df`), halving KV token and host/disk snapshot capacity relative
  to FP8. TP2/TP4, E2B/E4B/12B, 26B-A4B multimodal serving, and
  SM103/SM121 hardware were not executed end-to-end.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
…omic spans

Why:
Gemma 4 multimodal checkpoints preprocess images into aspect-preserving 16x16
interleaved RGB patches (768 float32 elements per patch), 2D (x, y) patch
coordinates, 3x3 spatial pooling (patches_per_feature = 9, up to 1,120 soft
tokens per image), and an atomic envelope (start_token, repeated image_token
features, end_token). Before this change, Helios had no Gemma 4 image
preparation profile, ImageLayoutKind::Bracketed hardcoded 2x2 merge and 1,176
floats per patch, and Bracketed layouts did not emit atomic image spans.
Without these changes, Gemma 4 cores cannot prepare or load native image
inputs, Bracketed vision uploads cannot pack 3x3 / 768-float patches, and
span-declaring Bracketed prompts fail per request at prompt validation instead
of failing closed at server bootstrap. To keep shared packing independent of
model identity without breaking MiniMax (the existing Bracketed user whose
PatchMerge profile uses 2x temporal duplication: 3 * 2 * 14^2 = 1,176 floats per
patch), prepared metadata declares per-patch float width via
VisionCapacity.patch_features instead of hardcoding a lookup table or assuming
3 * patch_size^2.

What changed:
- Wire & contract metadata (helios/proto/runtime_core.proto, helios/build.rs,
  ignition/preparation/{runtime_core_pb2.py,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):
  - Before: VisionCapacity carried no patch-width field, ImageSettings and
    ImagePreparationKind ended at tag 10 (PaddedGrid), and model_contract()
    omitted patch_features from its default vision map.
  - After: Added additive ImageSettings.profile tag 11 (Gemma4ImageSettings),
    ImagePreparationKind::Gemma4 (tag 11), and VisionCapacity.patch_features
    (tag 6, serde default 0) with VisionCapabilities::bracketed_patch_features()
    (where 0 inherits legacy width 1176) and non-zero validation requiring a
    positive multiple of 3. Defaulted vision["patch_features"] = 0 in
    ignition/preparation/contract.py, regenerated runtime_core_pb2.py with
    protoc 36.1 (Protobuf Python Version 7.36.1, descriptor-only diff), added a
    protobuf round-trip test for Gemma4ImageSettings, and documented the Gemma 4
    profile, fixture provenance, patch_features field, and Bracketed spans.
    Updated docs/TODO.txt to reflect 31B NVFP4/BF16 serving verified on the
    combined Gemma 4 recipe stack with 26B-A4B, E2B/E4B vision parameterization,
    and partial-span prefix-cache audit still open.
- Native image preparation, packing, and load validation
  (helios/src/frontend/images/{gemma4,mod,conditioned,packing,patch_merge}.rs,
  helios/src/model/packing.rs, helios/src/server/config.rs):
  - Before: No Gemma 4 preprocessor existed; Bracketed hardcoded 2x2 stride and
    width 1176 from a lookup branch; server bootstrap did not check patch width
    or maximum image envelope against prefill_chunk_size / span.max_tokens.
  - After: Added helios/src/frontend/images/gemma4.rs (area-bounded uint8
    antialiased bicubic resize matching PyTorch/torchvision, 1/255 scaling,
    interleaved (y, x, channel) patches, (x, y) coordinates, shared
    patch_merge::Envelope, ProcessedImages::reserve_outputs for checked-mul
    overflow checks and single reserve_exact reservation matching glm.rs, and
    per-condition load errors). Updated Bracketed packing to derive merge
    stride from any positive-square patches_per_feature and read pixel width
    from VisionCapabilities::bracketed_patch_features(). Unified per-profile
    patch width behind ImageProcessor::patch_features() (via
    PatchProcessor::pixel_width() for Qwen/PatchMerge and conditioned.rs), and
    added server bootstrap checks enforcing patch width, patches_per_feature,
    per-image patch capacity, and max envelope <= prefill_chunk_size and
    span.max_tokens.
- Layout-owned atomic spans (helios/src/frontend/images/layouts/bracketed.rs,
  helios/src/model/prompt.rs):
  - Before: Bracketed emitted no atomic spans and model/prompt.rs carried no
    Bracketed span path.
  - After: layouts::bracketed::prepare_input emits atomic spans when
    frontend.image_tokens.span is configured and validates prompt bounds on both
    ends.
- Preparation wire validation & tests (ignition/preparation/frontend.py,
  tests/frontend/{generate_gemma4_image_fixtures.py,gemma4_images.json},
  tests/preparation/{test_frontend_spec.py,test_frontend_gemma4.py},
  helios/src/model/tests.rs):
  - Before: Core ignition.preparation.frontend accepted only the 8 prior profiles.
  - After: Added "gemma4" to IMAGE_PROFILES and _validate_image_payload in
    ignition/preparation/frontend.py, validating wire bounds (patch_size in
    1..=64, pooling_kernel_size in 1..=16, max_soft_tokens in
    {70,140,280,560,1120}, and 3 distinct nonempty envelope tokens) for
    recipe-owned ImageProcessorSpec contracts. Added checked-in HF fixture
    generator and 8-case SHA-256 fixture JSON (max_soft_tokens 280 and 1120),
    unconditional Rust Envelope::expand, Bracketed span, legacy Bracketed
    Inputs::new core-load (1176-wide), cross-profile width, and bootstrap
    validation tests, an #[ignore] checkpoint envelope test, and recipe-free
    Python tests in test_frontend_gemma4.py covering _validate_image_payload,
    default_preprocessor, checked-in fixture verification, and pb2 round-trip.

Benefit & compatibility:
Helios natively decodes, resizes, rescales and packs, and validates Gemma 4
images with bit-exact SHA-256 parity against Hugging Face Gemma4ImageProcessor,
while catching patch-width and chunk-bound mismatches at bootstrap. MiniMax and
all non-Bracketed upstream cores remain loadable unchanged (missing
patch_features decodes as 0 -> legacy 1176 for Bracketed; envelope bounds apply
only to Gemma 4). Fail-closed narrowings: Bracketed now requires a
positive-square patches_per_feature, and any legacy Gemma 4 core prepared
before this change (with patch_features == 0) is rejected at load with an
actionable re-export error (`bracketed image layout patch width (1176) differs
from image processor (768); re-export the core with vision.patch_features`).

Evidence & limitations (verified on origin/main 3d1614c):
- Release Rust test suites (`--locked --release`):
  - eos: 12 passed, 0 failed
  - selene (--features test-support): 553 passed, 0 failed
  - selene-manager (--features test-support): 425 passed, 0 failed, 1 ignored
  - helios (--features runtime-core,server with FLARE_TEST_TEMPLATE_DIR):
    1,913 passed, 0 failed, 85 ignored (1,851 unit + 62 across integration
    targets)
  - helios (--features runtime-core,server,test-tools --lib): frontend::images
    48 passed, 0 failed, 1 ignored; live ignored checkpoint envelope test on
    nvidia/Gemma-4-31B-IT-NVFP4@4135a98a (`-- --ignored --exact
    frontend::images::gemma4::tests::checkpoint_tokens_expand_the_image_envelope`):
    1 passed, 0 failed; model:: 58 passed; runtime_core::protobuf 29 passed;
    server::config 3 passed
  - flare-cli: 246 passed, 0 failed, 3 ignored (including `cargo test --locked
    --release --manifest-path flare-cli/Cargo.toml --test unverified_payload`:
    7 passed, 0 failed)
  - flare: 255 passed, 0 failed, 4 ignored
  - heliopause: 229 passed, 0 failed, 6 ignored
- Rebuilt release `flare` binary (`flare-cli/target/release/flare`) and
  `flare-heliopause`, synced `.venv` (`flashinfer-python` `5a8ceed8`), and ran
  CI CPU Python suite (`CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest
  tests/ -q`): 2,504 passed, 459 skipped, 0 failed (including 21 passed, 0
  skipped across `tests/preparation/{test_core_boundary,test_source_identity,
  test_frontend_spec,test_frontend_gemma4}.py`).
- Combined-stack E2E multimodal serving (evaluated on the companion 5-PR Gemma 4
  recipe stack in `local-inference-lab/hyperflare-recipes` paired with this PR,
  RTX PRO 6000 Blackwell SM120 GPU 0, TP1, `--max-concurrency 4
  --image-concurrency 2`, MTP enabled):
  - `nvidia/Gemma-4-31B-IT-NVFP4` (FP8 KV): 11/11 checks passed (short math
    `'391'`, 5,703-tok needle `'NEEDLE-7492-FALCON'`, 1/2/4-image, 2,564-tok
    wraparound+image, `810/810` Turn-1 multimodal prefix-cache replay,
    2-concurrent images, 122.56 tok/s decode / 122.31 tok/s total, TTFT
    0.0041s on a 37-tok prefix-cached prompt).
  - `google/gemma-4-31B-it` (BF16 KV): 11/11 checks passed (`810/810` Turn-1
    multimodal replay, 2-concurrent images, 70.73 tok/s decode / 70.64 tok/s
    total, TTFT 0.0045s on cached prompt).
  - Backward-compat & fail-closed load checks with release `flare`: legacy
    pre-NVIDIA#483 Gemma 4 core `gb202-tp1-202611240119` fails load with `bracketed
    image layout patch width (1176) differs from image processor (768);
    re-export the core with vision.patch_features`; existing `GLM-5.3-Flash`
    core `gb202-tp2-202611090656` passes `flare inspect` (`signatures
    verified`).
- Limitations: End-to-end multimodal serving requires the companion Gemma 4
  recipe stack (`local-inference-lab/hyperflare-recipes`). On that combined
  stack, 31B NVFP4 (FP8 KV) and 31B BF16 (BF16 KV) serving are verified on SM120
  TP1, whereas TP2/TP4, 26B-A4B vision serving, E2B/E4B (16-layer 768-dim
  clipped-linear tower not yet parameterized in the recipe), SM103/SM121
  hardware, and partial-span prefix-cache hits remain unverified (tracked in
  `docs/TODO.txt`).

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
@rickybrent
rickybrent force-pushed the core/gemma4-image-frontend branch from 687481e to 4f777ec Compare December 3, 2026 20:01
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 26B-A4B and 31B multimodal checkpoints include a 27-block BF16 vision
tower (1152 hidden size, 16 heads of dim 72, 4304 MLP intermediate size,
unit-scale attention with `softmax_scale=1.0`, 2D rotary embeddings over
`(x, y)` coordinates, 3x3 average spatial pooling, standardize buffers
(`std_bias`/`std_scale`), non-clipped linears, and a multimodal embedder
projecting into the text hidden dimension). Previously, `hyperflare-recipes` had
no prepared Gemma 4 vision encoder, and `PreparedVarlenAttention` hardcoded
`softmax_scale = q.shape[-1] ** -0.5`.

Changes:
- hyperflare_recipes/components/varlen_attention.py: add an optional
  `softmax_scale: float | None = None` parameter to `PreparedVarlenAttention`
  and separate validation errors for invalid `max_seqlen` vs invalid
  `softmax_scale`, defaulting to `q.shape[-1] ** -0.5` both at initialization
  and via `getattr(self, "softmax_scale", None)` in `__call__` so existing
  callers and `object.__new__` test fixtures remain unchanged while Gemma 4
  passes `1.0`.
- hyperflare_recipes/recipes/gemma4/vision.py: add `PreparedVision`,
  `VisionMetadata`, `VisionScratch`, `VisionWeights`, and
  `supports_vision_config` implementing the 27-block 1152-dim standardized
  non-clipped BF16 vision tower (`LAYERS = 27`, `PATCH_SIZE = 16`), 3x3 patch
  pooling, and multimodal embedder parameterized by `text_hidden`, using
  `PreparedVarlenAttention(softmax_scale=1.0)` and `UnquantizedProjection` for
  CUDA-graph capture; fail closed in both `VisionWeights.from_checkpoint` and
  `PreparedVision.__init__` for unsupported architectures (`E2B`/`E4B` 16-block
  768-dim clipped-linear towers and `12B` `gemma4_unified_vision`).
- tests/components/test_functional_attention_operands.py,
  tests/recipes/test_gemma4_vision.py: add CPU unit tests for separate
  `max_seqlen` and `softmax_scale` `ValueError` messages and
  `supports_vision_config` / `VisionWeights.from_checkpoint` rejection of E2B
  and `gemma4_unified_vision`, plus an SM120 CUDA numerical parity test comparing
  `PreparedVision` against Hugging Face's `Gemma4VisionModel` +
  `Gemma4MultimodalEmbedder` on a cached 31B checkpoint (`google/gemma-4-31B-it`
  or `nvidia/Gemma-4-31B-IT-NVFP4`, which share the identical BF16 vision
  tower).

Claimed result:
The 27-block 1152-dim standardized Gemma 4 vision tower (26B-A4B and 31B)
prepares and executes in CUDA graphs with measured BF16 direction, scale, and
relative-L2 agreement against Hugging Face Transformers without modifying
existing text recipes or exported cores, while E2B/E4B (16-block 768-dim
clipped-linear) and 12B (`gemma4_unified`) vision configs fail closed.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/components/test_functional_attention_operands.py -k varlen`:
    3 passed, 11 deselected in 1.51s (including separate `max_seqlen` and
    `softmax_scale` `ValueError` validation).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/recipes/test_gemma4_vision.py -k "not matches_checkpoint"`:
    2 passed, 1 deselected in 2.99s (`supports_vision_config` and fail-closed
    `VisionWeights.from_checkpoint` rejection of E2B / `gemma4_unified_vision`).
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -v -o junit_family=legacy tests/recipes/test_gemma4_vision.py --junitxml=/tmp/gemma4_vision_junit.xml`:
    3 passed in 5.90s. On `nvidia/Gemma-4-31B-IT-NVFP4@4135a98a` (BF16 vision
    tower), `test_vision_encoder_matches_checkpoint` measured
    `relative_l2 = 0.089821` (8.98% vs 15% test bound), `cosine = 0.995965`
    (> 0.99 bound), `norm_ratio = 0.999697` (±2% bound), and
    `max_abs_ratio = 0.203887` (20.39% vs 30% test bound); these wider test
    tolerances accommodate BF16 accumulation variance across the 27-layer tower.
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe stack
  + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`): both
  `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV) and `google/gemma-4-31B-it` TP1
  (`--kv-cache-dtype bf16`) passed 11/11 live `/v1/chat/completions` checks
  including 1-image, 2-image, 4-image, >1.5K wraparound+image (`2,564` tokens),
  `810/810` Turn-1 multimodal prefix-cache replay, and 2-concurrent image
  requests.
- Limitations: E2E serving ran on the combined 5-PR stack (not this PR in
  isolation); standalone vision parity ran on SM120 using the 31B BF16 vision
  tower (`nvidia/Gemma-4-31B-IT-NVFP4@4135a98a`); `26B-A4B` vision parity was
  not executed independently on GPU; `E2B`/`E4B` (16-block 768-dim
  clipped-linear tower) and `12B` (`gemma4_unified`) remain out of scope; and
  SM103/SM121 GPUs were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 sliding-window layers allow each image token to attend over
`window intersect (causal union 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 and current chunk into a
contiguous buffer via `PreparedWindowStaging`, 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 builds on `recipes/gemma4-sliding-window-kv` (`local-inference-lab#16`) and
`recipes/gemma4-vision-encoder` (`local-inference-lab#14`), and requires companion core PR
`NVIDIA/hyperflare-inference#483` (`core/gemma4-image-frontend`) for
native Gemma 4 image preprocessing, 3x3 bracketed packing, and atomic
image spans. (`uv.lock` on `main` `20e360b` already pins `c513e46a`
containing merged `#484` `50c876df`.)

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 over public
  `b12x.preparation` APIs, supporting both `float8_e4m3fn` and `bfloat16`
  staged circular-window / paged caches with optional unbound
  `k_cache`/`v_cache`, overwriting only image rows in place and exiting
  early on text-only tiles). BF16 cache execution in
  `PreparedImageSlidingAttention` is unit-tested in this PR and
  exercised in recipe bootstrap once `--kv-cache-dtype bf16` lands.
- hyperflare_recipes/components/image_specs.py: add
  `gemma4_image_spec(snapshot)` defining the recipe-owned
  `ImageProcessorSpec` validating `Gemma4Processor`,
  `Gemma4ImageProcessor`, `patch_size = 16`, `pooling_kernel_size = 3`,
  `model_type = "gemma4"` (`vision_config.model_type = "gemma4_vision"`),
  and `image_token`/`boi_token`/`eoi_token` against `tokenizer.json` and
  optional `config.json` token IDs.
- hyperflare_recipes/recipes/gemma4/{vision_state,config,weights,contract,
  attention,decoder,bootstrap,recipe}.py: wire `VisionInputs`, pass
  `VisionParameters(separable_encoder=True)` via `Gemma4Parameters`
  (subclassing `RecipeParameters` with `_checkpoint_supports_vision` so
  unsupported `E2B`/`E4B`/`12B` checkpoints resolve as text-only across
  export planning, status output, `rebuild_manifest`, and reproduction
  args and explicitly reject `--image-concurrency` on CLI), set
  `VISION["patch_features"] = 768` (matching
  `NVIDIA/hyperflare-inference#483`), build `PreparedVisionGeneration`
  (5 vision graphs for capacities `630..10080`), gate default vision
  loading via `should_load_vision` so 27-layer 1152-dim standardized
  non-clipped checkpoints (26B-A4B, 31B) load vision while E2B/E4B
  (16-layer 768-dim clipped-linear) and 12B (`gemma4_unified`) plus
  `--language-model-only` cleanly export text-only cores, wire vision
  feature injection across both `prefill` and `terminal_prefill` variants
  (with `"vision"` in `compile_kinds`), use `getattr(self, "vision", None)`
  in `PreparedDecoder.__call__`, pass `gemma4_image_spec` in
  `prepare_frontend`, compute per-prefill staged span offsets in
  `PreparedDecoder`, run `PreparedImageSlidingAttention` over the staged
  circular sliding KV output in `PreparedAttention`, and tag `"vision"` in
  the compilation identity hash.
- tests/components/test_image_sliding_attention_cuda.py,
  tests/frontend/test_gemma4_images.py: add 8 SM120 CUDA tests covering
  paged and 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, BF16 cache
  parity, and CUDA graph capture/replay with text-only early exit; add 3
  cached-31B frontend tests plus 10 CI-runnable synthetic/planning tests
  covering `gemma4_image_spec`, `prepare_contract(..., vision=True)`
  (`patch_features = 768` and `Bracketed` atomic spans), and
  `Gemma4Parameters` / `should_load_vision` text-only gating and explicit
  `--image-concurrency` rejection across `E2B`/`E4B`/`12B` vs `26B-A4B`/`31B`.

Claimed result:
On the combined 5-PR `v0.5.3` multimodal stack paired with Core PR `#483`,
exported Gemma 4 31B NVFP4 TP1 and 31B BF16 TP1 cores serve single-image,
multi-image (up to 4 images), long-prefix (>1.5K wraparound) image,
Turn-1 prefix-cached multimodal replay (`810/810`), and concurrent
2-request image workloads accurately on a single 96 GiB SM120 GPU, with
up to `1,537,024` KV tokens (`148` snapshot slots sharing the `60.6 GiB`
VMM-aliased pool) in NVFP4 FP8-KV and up to `377,856` KV tokens (`36`
snapshot slots sharing the `32.8 GiB` pool) in BF16 `--kv-cache-dtype bf16`
(`--max-concurrency 4 --image-concurrency 2`, 80 graphs). `E2B`/`E4B` and
`12B` skip unsupported vision towers cleanly during default text export,
legacy pre-`#483` Gemma 4 cores fail closed when loaded by Core PR `#483`,
and existing non-Gemma-4 cores inspect unchanged.

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 0, stacked on
  `20e360b` + `local-inference-lab#16` `d9ef2a2` + `local-inference-lab#14` `0f914fa`, paired with editable
  `ignition` + `flare-heliopause` from Core PR `#483` `4f777ec0`,
  `flashinfer-python` `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/frontend/test_gemma4_images.py -k "synthetic or prepare_contract or unsupported or supported_vision"`:
    10 passed, 3 deselected in 3.41s (CI-runnable without cached weights).
  - `HF_HOME=/opt/textllm/cache/huggingface HF_HUB_OFFLINE=1 CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/components/test_image_sliding_attention_cuda.py tests/frontend/test_gemma4_images.py tests/recipes/test_gemma4_vision.py`:
    24 passed in 85.37s (8 sliding image CUDA tests including BF16 cache
    parity + 13 `gemma4_image_spec`/contract/gating frontend tests + 3
    vision tower tests).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    63 passed, 5 skipped, 9 deselected in 4.38s (9 deselected template
    cases require `FLARE_TEST_TEMPLATE_DIR`).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/preparation/test_frontend_metadata.py -k gemma4`:
    1 passed, 1 skipped, 88 deselected in 0.98s (9 unrelated tests in full
    `test_frontend_metadata.py` fail pre-existing on `20e360b` due to
    upstream recipe/repo-split drift).
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe
  stack + Core PR `#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`, MTP enabled):
  - `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV): `60.6 GiB` · `1,537,024`
    KV tokens (`12,008` pages) · `148` shared snapshot slots · `7.3 GiB`
    host prefix slab (`1,500` page-sized `5 MiB` slab units);
    `vision.patch_features=768`, `feature_slots=2`; 11/11 checks passed
    (`short_math` `'391'`, cold `multi_turn_prefix` `583/614`, cold >4K
    wraparound restore `p1=5536, cached=5529`, `5,703`-tok needle
    `'NEEDLE-7492-FALCON'`, 1/2/4-image, `2,564`-tok wraparound+image,
    Turn-1 multimodal prefix-cache replay `810/810` [Turn-2 follow-up
    `t2_cached_tokens=0/834`], 2-concurrent images, `122.56 tok/s` decode /
    `122.31 tok/s` total, TTFT `0.0041s` on a 37-token prefix-cached prompt,
    MTP `342/134` ~ `2.55` drafts/round).
  - `google/gemma-4-31B-it` TP1 (`--kv-cache-dtype bf16`): `32.8 GiB` ·
    `377,856` KV tokens (`2,952` pages) · `36` shared snapshot slots ·
    `11.2 GiB` host prefix slab (`1,142` page-sized `10 MiB` slab units);
    11/11 checks passed (cold `multi_turn_prefix` `583/614`, cold >4K
    wraparound restore `p1=5536, cached=5529`, `5,703`-tok needle,
    1/2/4-image, `2,564`-tok wraparound+image, Turn-1 `810/810` replay
    [Turn-2 `t2_cached_tokens=0/834`], 2-concurrent images, `70.73 tok/s`
    decode / `70.64 tok/s` total, TTFT `0.0045s` on cached prompt, MTP
    `337/131` ~ `2.57` drafts/round).
  - Turn-2 multimodal prefix behavior: under default `enable_thinking=false`,
    Gemma 4 appends an empty closed `<|channel>thought\n<channel|>` suffix
    (`OutputStart::Content`, leaving `preserve_message_anchor=false`), so once
    1024/128 prefill timings are populated, Helios's default
    `checkpoint_extra_work_fraction=0.05` skips the interior split point before
    `<|turn>model` and retains only the 810-token prompt endpoint
    (`flare_checkpoint_skips_total{reason="work_budget"} = 3`). In a post-run
    NVFP4 follow-up check with `chat_template_kwargs={"enable_thinking": true}`
    (`OutputStart::Reasoning` retaining the message anchor), Turn-2 reused
    `815/839` tokens (`t1_prompt_tokens = 815`).
  - Backward-compat & fail-closed load checks (rebuilt release `flare`):
    legacy `nvidia_2FGemma-4-31B-IT-NVFP4/gb202-tp1-202611240119` rejected
    with `bracketed image layout patch width (1176) differs from image
    processor (768); re-export the core with vision.patch_features`;
    existing `GLM-5.3-Flash` core `gb202-tp2-202611090656` passed `flare
    inspect` (`signatures verified`).
- Earlier single-repo multimodal E2E serving (`gemma-4-31b-nvfp4` TP1
  package `gb202-tp1-202611230337` built from `feb712de`, combining global
  decode, vision encoder, circular sliding KV, and vision wiring): 7/7
  multimodal checks passed, `60.7 GiB` KV / `1,540,096` KV tokens / `148`
  shared snapshot slots, text throughput 0K-128K C1/C2/C4 `44.0->38.2 /
  86.2->72.8 / 167.1->125.2 tok/s`.
- Limitations: E2E serving on `v0.5.3` ran on the combined 5-PR stack
  paired with Core PR `#483` for 31B NVFP4 FP8-KV and 31B BF16 BF16-KV on
  SM120 (without an isolated vision-wiring vs circular-sliding-KV text A/B);
  `26B-A4B` vision serving, `E2B`/`E4B`/`12B` vision (16-layer clipped-linear
  and `gemma4_unified` towers remain text-only by default), TP2/TP4, and
  SM103/SM121 hardware were not executed end-to-end.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
…ged global KV

Gemma 4 models apply RMSNorm to Q/K/V and attend with unit scale
(`softmax_scale = 1.0`), making their attention logits unusually sensitive
to FP8 E4M3 KV cache quantization (3-bit mantissa on K/V). With circular
sliding-window KV (`local-inference-lab#16`, `recipes/gemma4-sliding-window-kv`) shrinking
paged KV storage by 11x at TP1 on 31B and 21x on 12B, full lossless
BF16 KV becomes practical on a single 96 GiB GPU (`401,408` KV tokens
and `38` shared snapshot slots on isolated `google/gemma-4-31B-it` BF16
TP1 with MTP enabled, `765,952` tokens / `73` slots on `31B NVFP4`, and
`2,363,392` tokens / `227` slots on `26B-A4B`) with zero core
`NVIDIA/hyperflare-inference` or `b12x` changes.

This PR stacks directly on `recipes/gemma4-sliding-window-kv` (`local-inference-lab#16`)
and keeps `fp8` as the default `--kv-cache-dtype` so existing exports
and defaults remain unchanged.

Changes:
- hyperflare_recipes/recipes/gemma4/recipe.py: add
  `KvCachePrecisionParameters(ParameterGroup)` exposing `--kv-cache-dtype
  {fp8,bf16}` (default `"fp8"`) on `Gemma4Parameters`, automatically
  wired into `ignition export` CLI, planner, and signed core reproduction
  manifests via `RecipeParameters`; implement `adjust_rank_costs()`
  returning exact `StateLayout.from_specs` BF16 `RankCosts` for all five
  Gemma 4 sizes (E2B, E4B, 12B, 26B-A4B, 31B) across TP1/TP2/TP4.
- hyperflare_recipes/components/window_attention.py: add batched Triton
  `stage_circular_kv` (`torch.library.wrap_triton`) to stage BF16
  circular sliding history and current prefill candidates into contiguous
  BF16 paged buffers without modifying `b12x`'s FP8-only
  `WindowStageKernel`, enforcing contiguous staging output tensors
  (`output_key.is_contiguous()` / `output_value.is_contiguous()` with
  `.view(...)`) and `(kv_heads, head_dim)` / trailing-stride checks.
- hyperflare_recipes/recipes/gemma4/{pool,attention,bootstrap}.py:
  parameterize `page_specs`, `page_bytes`, `continuation_layout`, and
  `ContinuationPool` by `kv_dtype`; route BF16 sliding prefill staging
  through `stage_circular_kv`; pre-scale queries by `math.sqrt(dim)`
  before BF16 `PreparedPagedAttention` (an exact BF16 exponent shift of
  16.0 on 256-dim sliding heads, whereas `sqrt(512)` on global heads is a
  BF16 mantissa multiply, since `b12x` ignores `k_descale` for BF16 KV);
  keep `PreparedWindowAttention(softmax_scale=1.0)` and
  `commit_circular_kv` in native BF16 without FP8 clamping; include
  `"kv_dtype"` in the compilation identity hash.
- tests/recipes/{test_gemma4.py,test_gemma4_sliding_window_cuda.py}: add
  exact BF16 `RankCosts` across all 5 variants x TP1/TP2/TP4,
  `stage_circular_kv` non-contiguous output rejection, SM120 BF16 sliding
  prefill/commit/wraparound decode/verify parity, and BF16 512-dim
  global KV write + unit-scale prefill parity tests.

Claimed result:
Exporting Gemma 4 checkpoints with `--kv-cache-dtype bf16` stores both
circular sliding-window and paged global KV caches in lossless BF16 while
keeping `--kv-cache-dtype fp8` unchanged by default. In the archived
211,692-position live-server study, switching to BF16 KV
cuts mean top-20 KL vs Hugging Face BF16 by 2.61x on 31B BF16 Dense
(`0.2417 -> 0.0926`, median KL 5.64x lower `0.01214 -> 0.00215`, P95 KL
4.16x lower `1.220 -> 0.293`, top-1 agreement `85.73% -> 92.63%`, 32K
delta-NLL `+0.161 -> +0.011`) and 1.64x on 26B-A4B MoE (`0.3982 ->
0.2431`), while fitting `401,408` KV tokens (`38` snapshot slots, `1.53x`
262K) on isolated 31B BF16 TP1 (`377,856` KV tokens / `36` slots on the
combined 5-PR multimodal build), `765,952` tokens (`73` slots, `2.92x`
262K) on 31B NVFP4, and `2,363,392` tokens (`227` slots, `9.02x` 262K) on
26B-A4B on a single 96 GiB SM120 GPU. Existing exported cores embed their
compiled graphs and remain unaffected.

Supporting evidence and limitations:
- Unit & CUDA tests (SM120 RTX PRO 6000 Blackwell, GPU 0, rebased on
  `20e360b` + `local-inference-lab#16` `d9ef2a2`, `ignition` `c513e46a`, `flashinfer-python`
  `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4_sliding_window_cuda.py -k reject`:
    2 passed, 5 deselected (`commit_circular_kv` and `stage_circular_kv`
    contiguity rejection).
  - `CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/recipes/test_gemma4_sliding_window_cuda.py tests/components/test_window_attention_cuda.py`:
    74 passed in 200.35s.
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    64 passed, 5 skipped, 9 deselected in 4.29s (9 deselected template
    cases require `FLARE_TEST_TEMPLATE_DIR`).
- Archived 211,692-position E2E study (SM120 96 GiB TP1 vs HF BF16):
  - 31B BF16 Dense (BF16 vs FP8 KV): mean top-20 KL `0.0926` vs `0.2417`
    (2.61x lower), median KL `0.00215` vs `0.01214` (5.64x lower), P95 KL
    `0.293` vs `1.220` (4.16x lower), top-1 agreement `92.63%` vs `85.73%`,
    weighted delta-NLL `+0.0121` vs `+0.1210` (32K delta-NLL `+0.011` vs
    `+0.161`); capacity `401,408` KV tokens (`38` snapshot slots) on
    isolated text core; C1 128K decode `19.9` vs `21.7 tok/s` (-8.3%).
  - 26B-A4B MoE (BF16 vs FP8 KV): mean top-20 KL `0.2431` vs `0.3982`
    (1.64x lower), `2,363,392` KV tokens (`227` snapshot slots), C1 128K
    decode `95.7` vs `108.2 tok/s` (-11.6%).
  - 31B NVFP4 (BF16 vs FP8 KV): `765,952` KV tokens (`73` snapshot slots),
    C1 128K decode `30.8` vs `35.4 tok/s` (-13.0%), `5/5` MTP parity checks
    including `168,231`-token needle; within-engine FP8 KV induces `0.6548`
    KL and flips 26.9% of top-1 tokens (`0.7465 -> 0.6962` vs HF BF16).
- Post-rebase `v0.5.3` combined E2E serving (`google/gemma-4-31B-it` TP1,
  combined 5-PR stack + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0,
  `--kv-cache-dtype bf16 --max-concurrency 4 --image-concurrency 2`, 80
  graphs, `seed=42`, MTP enabled): `32.8 GiB`, `377,856` KV tokens (`2,952`
  pages), `36` shared snapshot slots, `11.2 GiB` host prefix slab (`1,142`
  page-sized `10 MiB` slab units); 11/11 checks passed (`short_math` `'391'`,
  cold `multi_turn_prefix` `583/614`, >4K wraparound `p1=5536, cached=5529`,
  `5,703`-tok needle `'NEEDLE-7492-FALCON'`, 1/2/4-image, `2,564`-tok
  wraparound+image, `810/810` Turn-1 multimodal replay, 2-concurrent images,
  `70.73 tok/s` decode / `70.64 tok/s` total, TTFT `0.0045s` on a 37-token
  prefix-cached prompt, MTP `337/131` ~ `2.57` drafts/round).
- Limitations / tradeoffs: continuation row size doubles in BF16 (`810
  MiB`/row on 31B TP1 vs `405 MiB` in FP8; requires merged core `#484`
  `50c876df`), halving KV token and host/disk snapshot capacity relative
  to FP8. TP2/TP4, E2B/E4B/12B, 26B-A4B multimodal serving, and
  SM103/SM121 hardware were not executed end-to-end.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 global full-attention layers use 512-dim heads (with values
split into two 256-dim halves `value_lo` and `value_hi`), and `b12x` does
not currently provide a native 512-dim split-V decode operator.
Previously, `hyperflare_recipes/recipes/gemma4/attention.py` ran global
decode and verify through two padded `PreparedPagedAttention(mode="prefill")`
calls that lacked KV-length parallelism at small batch sizes, causing severe
long-context decode slowdown (4.5 tok/s at 128K C=1 on SM120 NVFP4).

Changes:
- hyperflare_recipes/components/wide_paged_decode.py: add
  `PreparedWidePagedDecode` (`flare.wide_paged_decode` recipe-side
  `native_contract` Triton operator over public `b12x.preparation` APIs),
  a split-KV decode/verify attention operator that handles 512-dim K and
  split 256+256 V (both FP8 E4M3 and BF16 caches, keeping BF16 tactics at
  `BLOCK_N <= 32` to stay within SM120's 99 KiB shared-memory limit) in
  a single pass with adaptive split-KV reduction across sequence length,
  `width` causal masking for MTP verification, positive 16-aligned
  `page_size` validation, and CUDA-graph capture safety.
- hyperflare_recipes/recipes/gemma4/attention.py: route non-prefill
  global layers through `PreparedWidePagedDecode`, removing the padded
  `q_full` / `attended_lo_full` / `attended_hi_full` buffers on global
  decode and verify while keeping `PreparedPagedAttention(mode="prefill")`
  on global prefill layers.
- tests/components/test_wide_paged_decode_cuda.py: add 14 SM120 CUDA
  tests verifying FP32 reference parity across head counts, batch sizes,
  verification widths (1, 4, 6), sequence lengths, NaN-poisoned tail
  slots, unaligned `page_size` rejection, FP8 and BF16 KV caches, and
  CUDA graph capture/replay.

Claimed result:
Global full-attention decode and MTP verification on 512-dim Gemma 4
heads scale cleanly with context length on SM120 (measured 43.1 -> 37.3
tok/s from 0K to 128K C=1 on earlier single-repo `gemma-4-31b-nvfp4` TP1
with `--mtp-draft-tokens 0`, vs 40.7 -> 4.5 tok/s on baseline prefill-mode
decode, an 8.3x speedup at 128K) while preserving greedy outputs and
existing exported cores.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -q tests/components/test_wide_paged_decode_cuda.py`:
    14 passed in 7.28s (11 FP8 + 2 BF16 KV parity & CUDA graph replay +
    unaligned `page_size` rejection).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -q tests/recipes/test_gemma4.py tests/recipes/test_terminal_prefill_rollout.py -k "not test_model_sizes_select_canonical_chat_templates"`:
    63 passed, 5 skipped, 9 deselected in 4.59s (excluding the 9
    `test_model_sizes_select_canonical_chat_templates` parameterized cases
    that validate pinned upstream HF chat templates outside this PR).
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe
  stack + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`, MTP enabled):
  - `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV): `122.56 tok/s` decode
    (`122.31` tok/s total; TTFT `0.0041s` on a 37-token prefix-cached prompt),
    MTP `342` accepted drafts / `134` rounds (~`2.55` drafts/round),
    `5,703`-tok needle `NEEDLE-7492-FALCON` passed, 11/11 checks passed.
  - `google/gemma-4-31B-it` TP1 (`--kv-cache-dtype bf16`): `70.73 tok/s`
    decode (`70.64` tok/s total; TTFT `0.0045s` on a 37-token prefix-cached
    prompt), MTP `337` accepted drafts / `131` rounds (~`2.57` drafts/round),
    `5,703`-tok needle `NEEDLE-7492-FALCON` passed, 11/11 checks passed.
- Limitations: prior 0K-128K A/B was measured on an earlier single-repo
  `gemma-4-31b-nvfp4` TP1 SM120 build, and BF16 checkpoint + BF16 KV cache
  were executed live on the combined 5-PR stack on SM120; TP2/TP4, other
  Gemma 4 sizes, and SM103/SM121 hardware were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=6fcc
Signed-off-by: Ricky Brent <ricky@rickybrent.com>
rickybrent added a commit to rickybrent/hyperflare-recipes that referenced this pull request Dec 3, 2026
Gemma 4 26B-A4B and 31B multimodal checkpoints include a 27-block BF16 vision
tower (1152 hidden size, 16 heads of dim 72, 4304 MLP intermediate size,
unit-scale attention with `softmax_scale=1.0`, 2D rotary embeddings over
`(x, y)` coordinates, 3x3 average spatial pooling, standardize buffers
(`std_bias`/`std_scale`), non-clipped linears, and a multimodal embedder
projecting into the text hidden dimension). Previously, `hyperflare-recipes` had
no prepared Gemma 4 vision encoder, and `PreparedVarlenAttention` hardcoded
`softmax_scale = q.shape[-1] ** -0.5`.

Changes:
- hyperflare_recipes/components/varlen_attention.py: add an optional
  `softmax_scale: float | None = None` parameter to `PreparedVarlenAttention`
  and separate validation errors for invalid `max_seqlen` vs invalid
  `softmax_scale`, defaulting to `q.shape[-1] ** -0.5` both at initialization
  and via `getattr(self, "softmax_scale", None)` in `__call__` so existing
  callers and `object.__new__` test fixtures remain unchanged while Gemma 4
  passes `1.0`.
- hyperflare_recipes/recipes/gemma4/vision.py: add `PreparedVision`,
  `VisionMetadata`, `VisionScratch`, `VisionWeights`, and
  `supports_vision_config` implementing the 27-block 1152-dim standardized
  non-clipped BF16 vision tower (`LAYERS = 27`, `PATCH_SIZE = 16`), 3x3 patch
  pooling, and multimodal embedder parameterized by `text_hidden`, using
  `PreparedVarlenAttention(softmax_scale=1.0)` and `UnquantizedProjection` for
  CUDA-graph capture; fail closed in both `VisionWeights.from_checkpoint` and
  `PreparedVision.__init__` for unsupported architectures (`E2B`/`E4B` 16-block
  768-dim clipped-linear towers and `12B` `gemma4_unified_vision`).
- tests/components/test_functional_attention_operands.py,
  tests/recipes/test_gemma4_vision.py: add CPU unit tests for separate
  `max_seqlen` and `softmax_scale` `ValueError` messages and
  `supports_vision_config` / `VisionWeights.from_checkpoint` rejection of E2B
  and `gemma4_unified_vision`, plus an SM120 CUDA numerical parity test comparing
  `PreparedVision` against Hugging Face's `Gemma4VisionModel` +
  `Gemma4MultimodalEmbedder` on a cached 31B checkpoint (`google/gemma-4-31B-it`
  or `nvidia/Gemma-4-31B-IT-NVFP4`, which share the identical BF16 vision
  tower).

Claimed result:
The 27-block 1152-dim standardized Gemma 4 vision tower (26B-A4B and 31B)
prepares and executes in CUDA graphs with measured BF16 direction, scale, and
relative-L2 agreement against Hugging Face Transformers without modifying
existing text recipes or exported cores, while E2B/E4B (16-block 768-dim
clipped-linear) and 12B (`gemma4_unified`) vision configs fail closed.

Supporting evidence and limitations:
- Unit & CUDA tests (`20e360b`, SM120 RTX PRO 6000 Blackwell, GPU 0,
  `ignition` `c513e46a`, `flashinfer-python` `5a8ceed8`):
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/components/test_functional_attention_operands.py -k varlen`:
    3 passed, 11 deselected in 1.51s (including separate `max_seqlen` and
    `softmax_scale` `ValueError` validation).
  - `CUDA_VISIBLE_DEVICES="" .venv/bin/pytest -v tests/recipes/test_gemma4_vision.py -k "not matches_checkpoint"`:
    2 passed, 1 deselected in 2.99s (`supports_vision_config` and fail-closed
    `VisionWeights.from_checkpoint` rejection of E2B / `gemma4_unified_vision`).
  - `HF_HOME=/opt/textllm/cache/huggingface CUDA_HOME=/opt/cuda CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/pytest -v -o junit_family=legacy tests/recipes/test_gemma4_vision.py --junitxml=/tmp/gemma4_vision_junit.xml`:
    3 passed in 5.90s. On `nvidia/Gemma-4-31B-IT-NVFP4@4135a98a` (BF16 vision
    tower), `test_vision_encoder_matches_checkpoint` measured
    `relative_l2 = 0.089821` (8.98% vs 15% test bound), `cosine = 0.995965`
    (> 0.99 bound), `norm_ratio = 0.999697` (±2% bound), and
    `max_abs_ratio = 0.203887` (20.39% vs 30% test bound); these wider test
    tolerances accommodate BF16 accumulation variance across the 27-layer tower.
- Post-rebase `v0.5.3` combined E2E serving (combined 5-PR Gemma 4 recipe stack
  + `NVIDIA/hyperflare-inference#483`, SM120 GPU 0, `--max-concurrency 4
  --image-concurrency 2`, 80 graphs each, `seed=42`): both
  `nvidia/Gemma-4-31B-IT-NVFP4` TP1 (FP8 KV) and `google/gemma-4-31B-it` TP1
  (`--kv-cache-dtype bf16`) passed 11/11 live `/v1/chat/completions` checks
  including 1-image, 2-image, 4-image, >1.5K wraparound+image (`2,564` tokens),
  `810/810` Turn-1 multimodal prefix-cache replay, and 2-concurrent image
  requests.
- Limitations: E2E serving ran on the combined 5-PR stack (not this PR in
  isolation); standalone vision parity ran on SM120 using the 31B BF16 vision
  tower (`nvidia/Gemma-4-31B-IT-NVFP4@4135a98a`); `26B-A4B` vision parity was
  not executed independently on GPU; `E2B`/`E4B` (16-block 768-dim
  clipped-linear tower) and `12B` (`gemma4_unified`) remain out of scope; and
  SM103/SM121 GPUs were not executed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); 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