Skip to content

[Engine] Add Hy4-Flash GGUF support for CUDA and Metal - #7120

Open
sjl623 wants to merge 10 commits into
Niko1221:hy4-flash-hpcfrom
sjl623:integrate/hy4-flash-hpc-rebase
Open

sjl623 wants to merge 10 commits into
Niko1221:hy4-flash-hpcfrom
sjl623:integrate/hy4-flash-hpc-rebase

Conversation

@sjl623

@sjl623 sjl623 commented Nov 25, 2026 •

Copy link
Copy Markdown

Problem and result

Strata could run Hy4-Flash in its native format, but users with Hy4-Flash GGUF checkpoints could not load them through strata launch on CUDA or Metal.

With this change, strata launch recognizes a Hy4-Flash GGUF checkpoint and selects the backend for the user's hardware. On NVIDIA GPUs, the CUDA backend can keep part of the expert weights in system RAM and use either built-in MTP or an external DFly drafter for speculative decoding. On Apple Silicon, the Metal backend can stream experts from SSD when the model exceeds the available unified memory.

Validation

Passed: From tools/hy4_flash, ran
./verify-fp16.sh ./A12B_1108_Q4KM-MTP-Q8_0/Hy4-flash-Q4_K_M-00001-of-00002.gguf

Compared logits against llama.cpp v1.1.0 (171527522) using the same Hy4-Flash Q4_K_M GGUF and fixed token inputs. All 15 cases passed, with top-1 agreement at all 1,263 positions.

jinlongsong and others added 6 commits November 25, 2026 12:23
Run hy4-flash GGUF models on a single NVIDIA GPU, with CPU expert
offload when the routed weights exceed available VRAM.

- Model loading: read single-file and sharded GGUF checkpoints, derive
  layer and expert geometry from metadata, and pack routed weights.
- CUDA inference: implement sliding-window and indexed sparse MLA,
  hyper-connections, Engram lookups, and dense and MoE feed-forward layers.
- Prefill and KV cache: process prompts layer by layer in chunks, borrow
  expert-cache space during prefill, and support FP16 and Q8_0 latent KV.
- Expert offload: support a full host copy or split GPU/RAM residency,
  and adapt CPU expert execution to measured transfer and compute costs.
- Speculative decoding: support the built-in MTP layer and an external
  Q8_0 DFly GGUF, with multi-token verification and CPU expert offload.
- Vision: load a GGUF vision projector and accept image inputs through
  the chat API.
- Serving: add hardware-aware launch defaults, session parking, streaming
  reasoning and tool calls, expert-cache metrics, and raw completion timings.
- Tests and tools: cover GGUF loading, CPU/CUDA arithmetic, draft
  verification, API behavior, and MTP/DFly quantization.
- Documentation: add English and Chinese CUDA build and serving guides.
The Apple-silicon hy4-flash engine (the commit after this one) is the first caller of these, so
they land separately: a reviewer who distrusts a change to the shared Metal runtime can read it
without the engine, and the engine's own commit then touches nothing outside its directory.

  * mtl_rt: WHERE run_graph_seg's wall time goes.  Its return value is one command buffer's
    GPUEndTime - GPUStartTime, and that span CONTAINS the host's turns at every cut, so it cannot
    say whether a slow window was the GPU or the host.  seg_timing() breaks it into spin, cut,
    encode, commit and final wait, with the command-buffer and dispatch counts; a module that
    shares the trunk's kernels (the MTP draft step) takes the accumulator before its own
    run_graph_seg and restores it after, so the two do not mix.  run_graph_seg also gains a form
    that places the GPU's wait for the host LATER than its signal: after segment s the GPU keeps
    computing the dispatches that do not depend on what the host writes, and only then waits, so
    the host's turn overlaps that work instead of the GPU idling through it.  The GPU filler
    (set_seg_fill) holds the GPU's clocks up across a cut, and is in every runtime rather than
    behind an engine's macro.

  * src/engine/stream: the expert stream's layer count stops being a compile-time constant.  It
    is the MODEL's expert ordinals - 48 for Qwen, 41 for the hy4-flash trunk - read in open(),
    because one build serves both.  The arena is indexed by ordinal rather than by block id for
    the same reason, and report() prints both byte hit rates and what the SSD really delivered,
    which is the number a tok/s budget divides by the bandwidth.

  * src/engine/sysmem.h: the memory probes the arena rules read, in one place: the engine and the
    arena planner were each asking macOS the same questions.

  * kernels/gemv.metal: per-head weights in ONE dispatch (function constants 10 / 11 / 12), for a
    projection stored as one matrix a head.  grid.y is the head.

Off this path nothing changes: every addition is new state or a new entry point, and the existing
callers' behaviour is unchanged.
The native Metal engine for the hy_v4_flash GGUF architecture: the Metal implementation of what
src/hy4flash_gguf/ implements on CUDA, not a second engine.  It defines strata::hy4_flash::run,
the entry point include/strata/hy4flash_gguf/engine.hpp declares and `strata`'s family switch
calls under STRATA_HAVE_HY4_FLASH, and it reads the same GGUF and the same pack, so one launch
command works on either device.  Its host-side geometry, Engram tables and sampler are
src/hy4flash_gguf/{geometry,engram,engram_io,sampler}.cpp, compiled as they are.

It is NOT related to src/hy4flash/metal/, which is a different implementation with its own main
and its own weight format.

Its own CMake target beside the Qwen and DeepSeek engines, on mtl_rt and the hy4-flash host code
of ../src that does not use CUDA.  Deliberately not linked against strata_metal_host (that
library pulls in core/device.cu and some forty other files through include/metal_compat, none of
which this engine calls), and deliberately not placed in src/engine/, whose *.cpp are collected
with file(GLOB) into both existing engines.  Every source is named.

The kernels are MSL under src/hy4flash_gguf/msl, compiled at run time; every numeric kernel is
gated against a CPU double-precision reference, and the engine refuses the environment switches
that would change its arithmetic rather than honouring them silently.

This arrived on a branch with no common ancestor here, so it is one commit rather than the
twenty-one it was written as.  Those, oldest first, and the branch note below says where they can
be read individually:

  [Engine] HY4 Metal engine: the Mac optimization line, rebased onto main
  [Engine] HY4: an unknown --consistency-* flag is a startup error, and forced routing must name its judge
  [Engine] HY4/Metal: comment-only cleanup of the engine source
  [Engine] HY4/Metal: the engine path of `strata`, so launch can drive it
  [Engine] HY4/Metal: the serve path refuses an arithmetic-changing environment too
  [Launch] HY4: recognise the IQ2 build on Apple silicon
  [Launch] HY4: plan and start on Apple silicon, without a CUDA card
  [Engine] HY4/Metal: the vision tower's GELU pair, as two named variants
  [Engine] HY4/Metal: the vision shard loader
  [Engine] HY4/Metal: pin the trunk's vocabulary size in the vision loader
  [Engine] HY4/Metal: assert the dense GEMM's BK constraint instead of documenting it
  [Engine] HY4/Metal: the vision tower's remaining kernels
  [Engine] HY4/Metal: drop the ffn_down tail kernel; DenseGemvF32 already handles it
  [Engine] HY4/Metal: the vision tower's host driver, with the stage sink in its interface
  [Engine] HY4/Metal: hy4_vis_ln raced its own threadgroup scratch between the mean and the variance
  [Engine] HY4: the trunk-side M-RoPE positions, gated against HuggingFace's own function
  [Engine] HY4: link the M-RoPE position builder into the host library
  [Engine] HY4: smart_resize's target size, gated against HuggingFace rather than against llama.cpp
  [Engine] HY4: say that the geometry pair is for gating, not for the request path
  [Engine] HY4/Metal: pictures end to end - the DSI1 splice and the trunk's 3-axis M-RoPE
  [Launch] HY4: offer --vision on Apple silicon, gated on the binary's own marker

The same work against the woa cleanup/hy4-upstream-review baseline keeps all twenty-one commits
and their messages.
defaults() refused hy4-flash whenever no nvidia card was present, before --engine-path was
consulted, and its whole planner was card-shaped: the expert budget came from nvidia-smi,
defaults switched on GPU model names, and config() emitted "backend": "cuda" as a literal.

Apple silicon takes its own small branch and returns before any of that.  Off Darwin every one of
these paths is byte-identical: the nvidia requirement, the nvidia-smi budget, the GPU-model-keyed
defaults and the CUDA command line all keep their behaviour, because a CUDA user's plan must not
change.

What the Mac branch deliberately does NOT do:
  * set STRATA_METAL_ARENA_GB.  Setting it short-circuits the engine's own arena plan and with it
    the live shrink and grow guards, so a number chosen here would be a fixed budget with the
    self-correction switched off - and the right number is the machine's.  --set
    STRATA_METAL_ARENA_GB=N still reaches it.
  * pass --expert-vram or --resident-experts.  This engine accepts and ignores them, and an
    argument that reads as a budget while having no effect is worse than its absence.
  * pass --draft-tokens.  The engine's default stands unless a person names one.
  * forward the CUDA serving environment.  Those switches belong to src/hy4flash_gguf, and the
    ones that would change this engine's arithmetic are refused by it; only what --set carried is
    passed.

int8 KV is refused rather than silently downgraded: this engine keeps its latent cache as fp16,
and a plan that said int8 while the engine served fp16 would be a quiet lie.  Pictures are
offered, gated on the engine binary carrying the vision marker exactly as the CUDA path is, so an
older Metal build refuses --vision for the same reason.

models.py: plan_import mapped hy_v4_flash to hy4-flash only for the Q4_K-family expert set, so
the one build with validated Metal output was unreachable through the supported entry point.  The
IQ2 case is ADDITIONAL, not a relaxation: which expert quantizations are accepted is a claim
about which engine implements them, the Metal engine implements the IQ2 experts, and IQ2_XXS is
required positively so the new case cannot widen the Q4_K-family one.  Off Darwin the condition
is byte-identical to before.
The Metal backend's own page, beside the NVIDIA one: models and the pack,
memory and why the arena is computed rather than pinned, the build, launch,
pictures, and the measured figures.  The two existing pages gain a link to it.
…he platform

`defaults()` takes the Apple-silicon path only when there is also no CUDA card, while `config()`
keyed on sys.platform alone.  Planning a CUDA target on a Mac therefore got CUDA defaults and a
Metal config.  Both now ask the engine: a Metal build is the one that reads the unified-memory
arena, so STRATA_METAL_ARENA_GB in its image is the discriminator - the same rule the vision gate
already uses.  The launch suite goes from 3 failures to the 1 the pristine base also fails.
@github-actions

Copy link
Copy Markdown

Thanks for the pull request. To keep the tracker readable, every item needs an area prefix in the title and the parts of the pull request template filled in. This one is missing:

  • Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] fix decode stop on long prompts".
  • Add "Problem and result": what triggered the change, and how it behaves before and after.

Edit the pull request (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment /reopen.

Details: CONTRIBUTING.md

@github-actions github-actions Bot added the needs-format Title or template does not follow CONTRIBUTING.md yet label Nov 25, 2026
@sjl623 sjl623 changed the title # [Engine] Add Hy4-Flash GGUF support for CUDA and Metal [Engine] Add Hy4-Flash GGUF support for CUDA and Metal Nov 25, 2026
harthuang and others added 4 commits November 25, 2026 14:31
Numbered sections and both languages in one file, matching the README this came from, with the
paths and names this tree actually uses: engine/metal, terminal/tools/strata_pack.py, the vendored
engine/third_party/strata-ggml, strata_hy4_flash_metal, and the HY4_FLASH_* environment names.
Compute MMQ correction sums from rounded Q8_1 activations. Add opt-in
reference math for residual mixing, Engram, batched router projections,
FP16 attention, sparse key selection and prefill feed-forward layers.
Reuse attention workspaces and operation graphs across decode steps.
Match GPU activation rounding, dot-product reductions and SwiGLU for
supported CPU experts. Generate reciprocal and exponential lookup
tables on the active device and reuse them across CPU workers.

Probe compiler intrinsics and the vector exp2f library at configure
time. Use the compatible Q8_1 path when the build or CPU lacks support.
Test quantization boundaries and document the native Q8_K override.
Keep pooled indexer keys in FP32 and use a full warp for each reference score reduction. Add teacher-forced logit capture and 15 fixed text and code cases to compare top-1, KL divergence, and maximum logit error.

Build missing GGUF packs locally and cache reference logits beside each model for repeat runs.
@github-actions

Copy link
Copy Markdown

Thanks, this follows the format now.

@github-actions github-actions Bot removed the needs-format Title or template does not follow CONTRIBUTING.md yet label Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant