Skip to content

feat(models): add Hy4 (hy_v4) support - #3281

Merged
inureyes merged 16 commits into
mainfrom
feature/issue-2354-hy-v4
Nov 23, 2026
Merged

inureyes merged 16 commits into
mainfrom
feature/issue-2354-hy-v4

Conversation

@inureyes

@inureyes inureyes commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds Tencent Hy4 (model_type: hy_v4, mlx-community/Hy4-preview-4bit), which failed with Unsupported model type: hy_v4. It is a DeepSeek-V3.2 derivative with an identity hyper-connection residual, a gated MLA with learnable sinks, and DSA indexers shared across layers. Validated on the real checkpoint with scripts/validate_hy_v4.sh.

What changed

  • hy_v4 is a child module of deepseek_v32, so it reuses the private MLA, indexer, MoE and shared DsaRope pieces. The V3.2 forward is untouched, so no V3.2 before/after trace was needed.
  • The attention forward is Hy4's own, because no V3.2 kernel takes a sink: SDPA with sinks, then the per-head sigmoid(linear_gate(x)) gate. A full layer caches [kv_latent | indexer key] and publishes its top-k; a shared layer caches the latent alone and attends to that selection.
  • Load errors for hc_* shapes that disagree with hc_mult * hidden_size, hc_mult outside 1..=64 or a 2 * hc_mult * hidden_size that overflows i32, a negative or out-of-range eos_token_id, a bad indexer_types length or value, and indexer weights that disagree with indexer_types.
  • The server splits <think:opensource>...</think:opensource> into reasoning_content. The first smoke returned the raw tag in content.
  • Batched decode uses the per-row fallback.

Validation on Hy4-preview-4bit (M3 Ultra, 512 GB, iogpu.wired_limit_mb 491520)

  • Memory: loads in 59 to 61 s at 403.59 GB resident. Peak footprint 434.1 GB for generate, 434.2 GB for the server, up to 435.6 GB for the traces. No swap.
  • Generate (-p "Hello" -n 50, 14.5 tok/s): "Hello world / Let's wrap up your first integration with Dorsal! You will learn how to accept, check, and get results. ..."
  • Server: /v1/chat/completions returned 200 with 40 tokens.
  • Logit trace vs mlx-vlm, decided positions (gap >= 2), 512-token context: no_swiglu_limit arm 0/125 (perplexity +0.47%), shipped model 0/125 (+0.53%, 1/256 top-1 overall).
  • LONG=1 (4096-token context, indexer selecting): 0/55 on both arms.
  • Arms that must fail: no_sinks 78/125 (perplexity 7528), no_gate 124/125 (1.6e6).
  • RoPE pairing: mean NLL 2.1995 interleaved vs 3.9121 half-split. Interleaved stays, as mlx-vlm has it.
  • Quantized latent vs fp16: int8 0/124 decided, 98.0% top-1 agreement, perplexity +1.00%; int4 0/124, 95.7%, +0.68%. Both generate coherent text (effective int8; applied to 78 of 78 layers).

Decisions

  • swiglu_limit is applied to the routed experts, as the transformers reference does and mlx-vlm does not. The two arms agree at every decided position.
  • enable_lm_head_fp32 is not applied: the MLX checkpoint ships a quantized lm_head.
  • hy_v4 stays out of QUANTIZED_LATENT_FAMILIES, like deepseek_v32: the decided-position gate passes, but both latent traces ran behind 512 tokens, where kv_len <= index_topk, so the indexer's top-k overlap over a quantized slot (the gate DeepSeek-V3.2 missed, feat: Store a quantized MLA latent in the DSA families (V3.2, GLM-5) #3163) was not exercised. auto keeps fp16; --mla-latent-quant int8|int4 is accepted and experimental.

Changes during review

  • scripts/validate_hy_v4.sh: the server step now runs under the GPU lock and a script-level EXIT trap stops the server, so a failing request no longer leaves a 433 GB server running.
  • hc_mult and eos_token_id are bounded at config parse (above), and a non-UTF-8 MLXCEL_HY4_ARM is an error instead of being ignored.
  • The --mla-latent-quant warning for hy_v4 cites this PR's measurement instead of the DeepSeek-V3.2 report.
  • A bilingual technical report is in TECHNICAL_REPORTS/3281-hy-v4-20261123.{en,ko}.md.

Follow-ups

  • Tool calls: the template's <tool_calls:opensource> / <arg_key:opensource> format needs its own parser.
  • A quantized-latent trace with the indexer selecting (needed before hy_v4 can join QUANTIZED_LATENT_FAMILIES).
  • The hy_v4_mtp drafter and the original mxfp8 tencent/Hy4-preview layout are out of scope.

Test plan

  • Synthetic-checkpoint unit tests: shared-layer selection and cache layout, hyper-connection math, sink semantics, parity arms, prefill and decode agreement, int8/int4 latent, bf16 stability, plain default RoPE, reasoning split
  • cargo fmt, clippy, coverage_tests, and the scripts/ci contract checks
  • Real-checkpoint runs above

Closes #2354

Tencent Hy4 (`mlx-community/Hy4-preview-4bit`) failed with `Unsupported model type: hy_v4`. It is a DeepSeek-V3.2 derivative with an identity hyper-connection residual, a gated MLA with learnable sinks, and DSA indexers shared across layers.

- `hy_v4` is a child module of `deepseek_v32`, so it reuses the private MLA, indexer and MoE pieces and their loaders. The V3.2 forward is untouched: the only change in that file is the module declaration.
- The attention forward is Hy4's own, because no V3.2 kernel takes a sink: every step runs MLX's SDPA with sinks. A `full` layer caches `[kv_latent | indexer key]` and publishes its top-k; a `shared` layer caches the latent alone and attends to that selection.
- The router is scored in float32 and the routed experts apply `swiglu_limit`, as the transformers reference does and mlx-vlm does not. `enable_lm_head_fp32` is not applied. RoPE pairing follows mlx-vlm (interleaved); the transformers reference rotates half-split pairs, which stays open until a real-checkpoint run.
- `--mla-latent-quant int8|int4` is accepted and fp16 stays the default: `hy_v4` joins the latent-pair and DSA key families, and `kv_arch` sizes the indexer key on `full` layers only.
- `MLXCEL_HY4_ARM` selects parity arms (`no_sinks`, `no_gate`, `no_swiglu_limit`, `rope_half_split`).

Validated with synthetic-checkpoint unit tests and by matching the loader's key set against the checkpoint index (4286 keys). No run loaded the 433 GB checkpoint, which needs a raised `iogpu.wired_limit_mb`; `scripts/validate_hy_v4.sh` holds the pending generate, server, logit-trace and quantized-latent runs.

Refs #2354
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:text Text-only language model arch:moe Sparse mixture-of-experts decoder labels Nov 22, 2026
Tencent Hy4 (`mlx-community/Hy4-preview-4bit`) failed with `Unsupported model type: hy_v4`. It is a DeepSeek-V3.2 derivative with an identity hyper-connection residual, a gated MLA with learnable sinks, and DSA indexers shared across layers.

- `hy_v4` is a child module of `deepseek_v32`, so it reuses the private MLA, indexer and MoE pieces and their loaders. The V3.2 forward is untouched: the only change in that file is the module declaration.
- The attention forward is Hy4's own, because no V3.2 kernel takes a sink: every step runs MLX's SDPA with sinks. A `full` layer caches `[kv_latent | indexer key]` and publishes its top-k; a `shared` layer caches the latent alone and attends to that selection.
- The router is scored in float32 and the routed experts apply `swiglu_limit`, as the transformers reference does and mlx-vlm does not. `enable_lm_head_fp32` is not applied. RoPE pairing follows mlx-vlm (interleaved); the transformers reference rotates half-split pairs, which stays open until a real-checkpoint run.
- `--mla-latent-quant int8|int4` is accepted and fp16 stays the default: `hy_v4` joins the latent-pair and DSA key families, and `kv_arch` sizes the indexer key on `full` layers only.
- `MLXCEL_HY4_ARM` selects parity arms (`no_sinks`, `no_gate`, `no_swiglu_limit`, `rope_half_split`).

Validated with synthetic-checkpoint unit tests and by matching the loader's key set against the checkpoint index (4286 keys). No run loaded the 433 GB checkpoint, which needs a raised `iogpu.wired_limit_mb`; `scripts/validate_hy_v4.sh` holds the pending generate, server, logit-trace and quantized-latent runs.

Refs #2354
Main gained `xing4_0` (#3276) in `MLA_LATENT_CACHE_FAMILIES` while this branch added `hy_v4`. Both edits set the pinned length to 17, so the textual merge kept 17 for a list of 18 and `only_the_fallback_less_families_are_latent_families` failed. Found by rerunning `-p mlxcel-core --lib mla::` after bringing the branch up to date with main.

Refs #2354
The branch was rebuilt on current main (f315dc2) to clear the CHANGELOG.md and docs/supported-models.md conflicts with #3270, #3275 and #3276. This merge records the previously pushed commit 2642118 as a parent so the update is a fast-forward of the remote branch; the tree is the rebuilt branch's, which already carries every change of that commit.

Refs #2354
Main gained the shared `DsaRope` for the DeepSeek-V3.2 attention and indexer (#3279), which replaced the `rope_base` field the Hy4 attention read. Hy4 now rotates through the same helper, built once per model from its own `rope_parameters`: the shipped `rope_type: default` resolves to plain RoPE with no frequency table, so V3.2's YaRN cannot leak in, and the interleaved or half-split pairing stays Hy4's choice. A new test pins that bit for bit against `fast_rope` at the config's `rope_theta`.

Conflicts kept both sides: CHANGELOG.md, the latent-family notes and doc list (`hy_v4` beside `longcat_flash_sparse`), and `kv_arch`, where the LongCat sparse indexer group is appended to the Hy4-aware latent group. `MLA_LATENT_CACHE_FAMILIES` is now 19 entries.

The validation script records peak memory per run with `/usr/bin/time -l`.

Refs #2354
`mlxcel arch` prints the display name `Hy4`, so the preflight's `grep -i hy_v4` on the plain listing could never match. The check now reads `mlxcel arch --json`, where the family id `hy_v4` appears. Found by running the release binary: the JSON entry lists `generate` and `serve` runtimes and `kv_modes: ["fp16"]`.

Refs #2354
Two defects surfaced when `scripts/validate_hy_v4.sh` first ran against `mlx-community/Hy4-preview-4bit`.

- The server smoke posted a chat completion without a `model` field and the server answered 400. The request now names the model directory's basename.
- The `--mlx-vlm` reference in `scripts/mlx_lm_logit_trace.py` evaluated all parameters at once. Over a 400 GB checkpoint that is a single Metal command buffer, which hit the GPU watchdog timeout. It now loads lazily and evaluates the parameters in slices of 64.

Refs #2354
Brings in eleven commits from main. The only conflict was docs/supported-models.md, where main reworded the Xing4.0 entry next to the Hy4 one: main's Xing4.0 text and the Hy4 entry are both kept. The shared DeepSeek MLA RoPE change (#3306) and the per-thread MLA dispatch counters (#3308) merged cleanly under the Hy4 attention.

Refs #2354
The first server smoke on Hy4-preview-4bit returned `<think:opensource>We need to respond ...` in `content` and no `reasoning_content`. Every structural tag of the Hy4 chat template carries an `:opensource` suffix, the template primes the open tag, and the model emitted it again, but no marker table knew the pair.

- `<think:opensource>` / `</think:opensource>` is registered wherever a think pair is: tokenizer marker inference, the thinking-budget ids, the stream filter, the non-streaming parser and the primed-close list. New tests cover the primed prompt, a repeated open tag, a block truncated before its close, streaming and non-streaming, through the real chat route.
- The template's `<tool_calls:opensource>` tool-call format is not parsed; that needs its own format and is left as a follow-up.
- `hy_v4` stays out of `QUANTIZED_LATENT_FAMILIES`. On the real checkpoint the int8 latent had 0 of 124 decided disagreements against fp16 (98.0% top-1) and int4 0 of 124 (95.7%), but behind 512 tokens the DSA indexer selects nothing, so the top-k overlap gate DeepSeek-V3.2 missed was not exercised. The reason and numbers are beside the list entry and in the experimental-latent notes.
- The module header, docs and changelog now state the measured results: RoPE pairing settled by mean NLL (2.1995 interleaved, 3.9121 half-split), 0 decided disagreements against mlx-vlm behind 512 and 4096 tokens.

Refs #2354
@inureyes inureyes mentioned this pull request Nov 23, 2026
6 tasks done
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Load and run hy_v4 (Hy4-preview-4bit) through the normal CLI and server paths as a child of deepseek_v32, with identity hyper connections, gated sink MLA, shared DSA indexers and an accepted explicit quantized latent.

Findings Addressed

  • None needed: no CRITICAL or HIGH finding.

Remaining Items

  • The int8 ExperimentalLatentNote for hy_v4 in src/lib/mlxcel-core/src/mla/latent_option.rs cites docs/benchmark_results/mla-quantized-latent-dsa-m3ultra-2026-11-19.md, which is the DeepSeek-V3.2 measurement and does not mention Hy4; the warning a user sees points at the wrong source (LOW). Cite this PR or drop the path.
  • hy_v4_moe.rs restates the V3.2 MoEGate routing and SwitchGLU forward with f32 routing and the swiglu_limit clamp instead of parameterizing them. This keeps the V3.2 forward byte-identical, so it is a deliberate trade, noted only for a later refactor (LOW).

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

Checked against references/mlx-vlm/mlx_vlm/models/hy_v4/: hyper connection and head math, gate placement, sinks, the full/shared top-k handoff (decode gather, prefill sparse mask, dense fallback at kv_len <= index_topk), the indexer (same as the V3.2 one), and f32 routing. deepseek_v32.rs only gains the child-module declaration; the shared kv_arch.rs refactor is equivalent for every other family. The reasoning pair is registered at the same five sites as K2-Horizon, and the Hy4 tokenizer has no <think> token that would shadow it in the thinking-budget lookup. Ran: the hy_v4 selector (39 tests, including the server reasoning tests), coverage_tests, the latent-option, kv_arch and DSA resolver tests, clippy with -D warnings, cargo fmt --check, and the scripts/ci contract checks.

The server step relied on a RETURN trap to stop `mlxcel-server`. Under `set -e` a failing command inside the function (for example `curl -sf` on an HTTP error from the chat completion) exits the script without running that trap, so the server stayed up with the 433 GB checkpoint resident, reparented to launchd. The step also bypassed `GPU_LOCK`, so on a shared host it could load the checkpoint beside another job's GPU run.

The background job now runs under `lockf -k "$GPU_LOCK"` when the lock is set, and a script-level EXIT trap (with INT and TERM routed to exit) stops the server by walking lockf, time and the server, so `time -l` still writes its report.

Checked with a stub server on both a passing and a failing chat completion: no process is left behind in either case and `mem-server.txt` is written; the previous script left the stub running on failure.
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL findings. One HIGH, fixed in be0cfb3.

HIGH, fixed (be0cfb3). scripts/validate_hy_v4.sh server step: under set -e, a failing command inside step_server (such as curl -sf on an HTTP error) exits without running the RETURN trap, so mlxcel-server stayed up with the 433 GB checkpoint resident. The step also skipped GPU_LOCK. It now runs under the lock and an EXIT trap stops the server. Reproduced and verified with a stub server.

MEDIUM, open. hy_v4_config.rs accepts any hc_mult >= 1; hy_v4.rs casts it with as i32, and 2 * hc_mult and hc_mult * hidden_size in hy_v4_hyper.rs can overflow i32. A hostile config.json panics the loader in a build with overflow checks and wraps silently in release (the shape check then rejects it). Suggested fix: bound hc_mult at parse time and check that 2 * hc_mult * hidden_size fits in i32.

LOW, open.

  • eos_token_id values are truncated from i64 with as i32; negative or out-of-range ids are kept rather than rejected.
  • ParityArms::from_env treats a non-UTF-8 MLXCEL_HY4_ARM as unset instead of an error.
  • The server smoke interpolates the model directory's basename into the JSON body unescaped (operator-controlled).
  • The decode path re-casts the sinks and rebuilds the eps scalars on every layer call. The cost is small next to the attention.

Server tag changes are table entries with ASCII delimiters, and <think:opensource> does not prefix-collide with <think>. On the DeepSeek-V3.2 path, deepseek_v32.rs and mla_batched.rs change only comments and a module declaration, and kv_arch.rs changes only the estimate. No forward-path change and no new host sync (trace_topk is gated on the trace env).

A hostile config.json could set hc_mult large enough that 2 * hc_mult or hc_mult * hidden_size overflowed i32 in the hyper-connection shapes, panicking in debug builds. The config now accepts hc_mult only in 1..=64 and checks 2 * hc_mult * hidden_size with checked i32 arithmetic, returning a load error.

eos_token_id entries are no longer truncated from i64 with `as i32`: a negative or out-of-range entry is a load error. A non-UTF-8 MLXCEL_HY4_ARM is now an error instead of being treated as unset.

The int8 latent warning for hy_v4 cited the DeepSeek-V3.2 benchmark report, which never measured Hy4; it now cites PR #3281. supported-models.md notes the new refusals.

Validation: models::deepseek_v32 (71 passed), the new hc_mult_and_eos_ids_are_bounded test, coverage_tests (18 passed), mlxcel-core mla:: (119 passed), clippy -D warnings, fmt and the CI contract scripts.

Refs #2354
@inureyes
inureyes marked this pull request as ready for review November 23, 2026 09:27
@inureyes
inureyes merged commit a9686c0 into main Nov 23, 2026
33 checks passed
@inureyes
inureyes deleted the feature/issue-2354-hy-v4 branch November 23, 2026 09:27
inureyes added a commit that referenced this pull request Nov 23, 2026
…on (#3332)

Closes #3318

The 39 decided disagreements left on `longcat-flash-lite-4bit` after #3306 come from a weight difference, not from mlxcel drift. The checkpoint ships a fused 4-bit `kv_b_proj`. mlxcel splits it into dense `embed_q` / `unembed_out`. mlx-lm quantizes both halves again, and `embed_q` is quantized along the transposed axis. No runtime code changes.

## Arms (36864 positions, #3306 corpus, 2048-step cached reference prefill)

| Reference | Candidate | Per 4096-position chunk | Decided | PPL cand. / ref. |
| --- | --- | --- | --- | --- |
| mlx-lm bf16 | mlxcel main | 0 1 0 4 10 4 6 8 6 | 39 / 20486 | 25.45 / 25.82 |
| same | `MLXCEL_KEEP_BF16=1` (byte-identical rows) | 0 1 0 4 10 4 6 8 6 | 39 / 20486 | same |
| same | `MLXCEL_TRACE_KV_CACHE_MODE=fp16` (identical rows) | 0 1 0 4 10 4 6 8 6 | 39 / 20486 | same |
| same | rope term as additive mask, fused 128-wide SDPA (local experiment, not committed) | 0 0 0 1 6 5 8 8 5 | 33 / 20486 | 25.40 / 25.82 |
| mlx-lm bf16 | mlx-lm cast to float16 (dtype noise floor) | 0 0 0 1 1 0 0 1 2 | 5 / 20486 | 25.89 / 25.82 |
| mlx-lm bf16, dense split | mlxcel main | 0 0 0 2 1 0 0 0 1 | 4 / 20489 | 25.45 / 25.63 |
| mlx-lm float32, dense split | mlxcel main | 0 1 0 1 0 0 0 0 0 | 2 / 20208 | 25.45 / 25.82 |

- Arm 1 does not move because `bf16_to_f16_at_load` already keeps a quantized checkpoint's bf16 side data. The issue's premise that this checkpoint runs in f16 does not hold.
- Arm 3: `MLXCEL_TRACE_MLA_STATS=1` reports `decompressed=476` with no absorbed step, so there is no second path to force.
- The per-layer bisection (arm 4) was not needed once the dense-split reference reached the floor.

## Changes

- `scripts/mlx_lm_logit_trace.py` docstring: mlxcel converts bf16 to f16 only for unquantized checkpoints on Apple Silicon (unless `MLXCEL_KEEP_BF16`), and a fused quantized `kv_b_proj` loads different weights in the two runtimes. The `--mlx-vlm` block that #3281 edits is untouched.
- `docs/supported-models.md`: the LongCat entry states the finding instead of "source not identified".
- `docs/benchmark_results/longcat-flash-lite-trace-residual-m3ultra-2026-11-23.md`: all arm rows, plus a no-context check.
- Bilingual technical report in `TECHNICAL_REPORTS/3332-longcat-trace-residual-20261123.*.md`.

Because no runtime code changed, the sparse variant and the GigaChat3 traces are unaffected by construction. Checks: fmt, the `scripts/ci` contract scripts, the header check, and the `coverage_tests` (18 passed) and `longcat` (57 passed) lib selectors. The issue's broad `-- --test-threads=1 longcat` gate is left to the orchestrator.
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:moe Sparse mixture-of-experts decoder area:models Model architectures, weights, loading, metadata modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:text Text-only language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): add Hy4 (hy_v4) support

1 participant