Repository navigation
Add Gemma 4 image preparation, Bracketed patch-width metadata, and atomic spans - #483
rickybrent wants to merge 1 commit into
Conversation
|
A case file has been opened for 483 To opt out, include #autobot:ignore in the PR or any comment. |
Changes RequestedThe bones are good — the proto/contract additions are properly additive, the Blockers:
Should fix:
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. |
f2340e4 to
792522d
Compare
792522d to
2b4a31e
Compare
|
Thanks for the thorough review! The branch has been rebased onto
|
Autobot ReviewFull Review for Agents. Recommendation: Changes RequestedBlockers: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:
Nits:5 nits PR #483 — Add Gemma 4 image preparation, Bracketed patch-width metadata, and atomic spansHead Key findingsNo 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 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, Verified resolved this round — not re-litigated
BlockersNone. Should FixS1 — The profile lands ahead of the exporter that can use it, and no test mounts an existing
|
2b4a31e to
ab9a432
Compare
|
I updated
|
Autobot ReviewFull Review for Agents. Recommendation: Changes RequestedBlockers:None. Should fix:
Nits:10 nits Full report — no blockers; every round-3 should-fix is fixed and verified in code at To opt out, include #autobot:ignore in your post or comment. |
|
Context on the remaining automated review items at
|
ab9a432 to
c3f3311
Compare
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>
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>
…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>
4f42d94 to
445c665
Compare
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>
445c665 to
7054676
Compare
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>
…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>
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>
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>
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>
|
Rebased onto
|
…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>
7054676 to
687481e
Compare
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>
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>
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>
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>
…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>
687481e to
4f777ec
Compare
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>
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>
…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>
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>
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>
Why
Gemma 4 multimodal checkpoints preprocess images into aspect-preserving 16×16 interleaved RGB patches (
768float32 elements per patch), 2D(x, y)patch coordinates, 3×3 spatial pooling (patches_per_feature = 9, up to1,120soft tokens per image), and an atomic image envelope (start_token, repeatedimage_tokenfeatures,end_token). Before this change, Helios had no Gemma 4 image preparation profile,ImageLayoutKind::Bracketedhardcoded 2×2 merge (patches_per_feature = 4) and 1,176 floats per patch, andBracketedlayouts did not emit atomic image spans when declared byImageTokenLayout.span. Without these changes, Gemma 4 multimodal cores cannot prepare or load native image processing,Bracketedvision uploads cannot pack 3×3 / 768-float patches, and a span-declaringBracketedimage fails per request atvalidate_prompt_data(or hits per-request chunk-size rejections rather than failing closed at bootstrap when the maximum image envelope exceedsprefill_chunk_sizeorspan.max_tokens).What changed
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):VisionCapacityhad no patch-width field,ImageSettings/ImagePreparationKindended at tag 10 (PaddedGrid), andmodel_contract()omittedpatch_featuresfrom its defaultvisionmap.ImageSettings.profiletag 11 (Gemma4ImageSettings),ImagePreparationKind::Gemma4(tag 11),VisionCapacity.patch_features(tag 6,#[serde(default)],0= legacyBracketedwidth1176), andVisionCapabilities::bracketed_patch_features(). Defaultedvision["patch_features"] = 0inignition/preparation/contract.pywith a docstring note for non-1176Bracketedrecipes, regeneratedignition/preparation/runtime_core_pb2.pymatchingorigin/main(Protobuf Python Version: 7.36.1, pure descriptor-only diff), updatedVisionCapabilities::validate()to allow0and 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, andBracketedatomic spans. Updateddocs/TODO.txtto 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.Bracketedpacking, 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):ImageLayoutKind::Bracketedhardcoded 2×2 merge and width1176in a lookup branch; server bootstrap did not check patch width or maximum image envelope againstprefill_chunk_size/span.max_tokens.helios/src/frontend/images/gemma4.rs(area-bounded uint8 antialiased bicubic resize matching PyTorch/torchvision,1/255scaling, interleaved(y, x, channel)16×16 patches,(x, y)patch coordinates, sharedpatch_merge::Envelopeexpansion, singleProcessedImages::reserve_outputsallocation withchecked_muloverflow checks andreserve_exactmatchingglm.rs, and per-condition load errors naming failing fields and bounds). UpdatedBracketedpacking to derive merge stride from any positive squarepatches_per_featureand read pixel width viaVisionCapabilities::bracketed_patch_features()(0defaults to legacy MiniMax temporal-merge width3 * 2 * 14² = 1176, which cannot be derived from3 * patch_size²alone because MiniMax duplicates frames temporally). Unified per-profile patch widths behindImageProcessor::patch_features()(viaPatchProcessor::pixel_width()for Qwen/PatchMerge and inconditioned.rs) and enforced load-time consistency acrossgemma4::Processor::loadandserver::config::validate_loaded_image_processor(single actionable re-export error for anyBracketedmismatch, non-zerovision.patch_featurescheck for other layouts, andmax_image_envelope_tokens <= prefill_chunk_sizeand<= image_tokens.span.max_tokens).helios/src/frontend/images/layouts/bracketed.rs,helios/src/model/prompt.rs):Bracketedemitted no atomic spans.atomic_spanshandling inlayouts::bracketed::prepare_input(matchinglayouts::deepseek), gated onimage_tokens.span.is_some()and validating prompt bounds on both ends.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):ignition/preparation/frontend.pyaccepted only the 8 existingIMAGE_PROFILESunder recipe-ownedImageProcessorSpeccontracts."gemma4"inIMAGE_PROFILESand added wire-schema validation in_validate_image_payload(patch_sizein1..=64,pooling_kernel_sizein1..=16,max_soft_tokensin{70, 140, 280, 560, 1120}, and three distinct nonempty envelope token strings), keeping all checkpoint-specific metadata in recipe-ownedImageProcessorSpecdefinitions. Checked intests/frontend/generate_gemma4_image_fixtures.pyandtests/frontend/gemma4_images.json(8 bit-exact SHA-256 cases acrossmax_soft_tokens = 280and1120), added unconditional RustEnvelope::expand,Bracketedspan-bearing contract, cross-profile width, bootstrap validation, and legacyBracketedInputs::newcore-load tests, kept the live-tokenizer envelope test#[ignore], updatedtest_frontend_spec.py'sIMAGE_PROFILEScheck, and kepttests/preparation/test_frontend_gemma4.pystrictly recipe-free (covering_validate_image_payload,default_preprocessor, checked-ingemma4_images.jsonvalidation, andruntime_core_pb2.ImageSettingsround-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'sGemma4ImageProcessor, enforces patch-width and atomic-span invariants at load time, and emits atomic spans from theBracketedlayout.Load-path impact & fail-closed narrowings: MiniMax (
Bracketed+PatchMerge) and all non-Bracketedupstream cores remain loadable and unchanged (missingpatch_featuresdecodes as0, preserving legacy width1176forBracketed— exercised bylegacy_bracketed_core_omitting_patch_features_loads_and_stages_1176_wide_pixelsthroughInputs::new; envelope bound checks apply only to profiles exposingmax_image_envelope_tokens, i.e., Gemma 4; among existing span-declaring layouts in-tree,Deepseek/DeepseekRowMajorcontinue emitting their owndata.spans). Narrowings:Bracketednow requires a positive-squarepatches_per_feature, and any legacy Gemma 4 core prepared before this change (withpatch_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):--releaseRust test suites (--locked --release):cargo test --offline --locked --release --manifest-path eos/Cargo.toml --target-dir flare-cli/target: 12 passed, 0 failedcargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --target-dir flare-cli/target: 553 passed, 0 failed (552lib +1mixed_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 (187lib +238across 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,851unit +62across 15 integration targets; prepared un-gated templates excluding gatedmuse_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 (plusmodel::58 passed,runtime_core::protobuf29 passed, andserver::config3 passed)tokenizer.jsonandtokenizer_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 failedcargo test --offline --locked --release --manifest-path flare-cli/Cargo.toml --target-dir flare-cli/target: 246 passed, 0 failed, 3 ignored (includingcargo 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 ignoredcargo test --offline --locked --release --manifest-path heliopause/Cargo.toml --target-dir flare-cli/target: 229 passed, 0 failed, 6 ignoredflarebinary (cargo build --offline --locked --release --manifest-path flare-cli/Cargo.toml) andflare-heliopause(uv pip install --offline --python .venv/bin/python --no-deps ./heliopause), synced Core.venv(flashinfer-python5a8ceed8), 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 acrosstests/preparation/{test_core_boundary,test_source_identity,test_frontend_spec,test_frontend_gemma4}.py).local-inference-lab/hyperflare-recipespaired 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/810Turn-1 multimodal prefix-cache replay, 2-concurrent images,122.56 tok/sdecode /122.31 tok/stotal, TTFT0.0041son a 37-tok prefix-cached prompt).google/gemma-4-31B-it(BF16 KV): 11/11 checks passed (810/810Turn-1 multimodal replay, 2-concurrent images,70.73 tok/sdecode /70.64 tok/stotal, TTFT0.0045son cached prompt).flare: pre-#483Gemma 4 coregb202-tp1-202611240119fails load withbracketed image layout patch width (1176) differs from image processor (768); re-export the core with vision.patch_features; existingGLM-5.3-Flashcoregb202-tp2-202611090656passesflare inspect(signatures verified).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 indocs/TODO.txt).Branch logistics
NVIDIA/hyperflare-inferencerickybrent:core/gemma4-image-frontend(4f777ec0) targetingmain(3d1614cc).Discord: ran.cossack