Skip to content

Improve Vulkan inference on Apple M4 Max GPU (Series 1–23 + Inkling 2 / DSpark) - #1

Draft
astaff wants to merge 38 commits into
masterfrom
agx/m4-max-series8
Draft

astaff wants to merge 38 commits into
masterfrom
agx/m4-max-series8

Conversation

@astaff

@astaff astaff commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Rebased onto upstream ggml-org/llama.cpp master (a28feb458, post-b12682) and updated with the full Series 1–23 Apple M4 Max (J616c / AGX G17P) Vulkan + Inkling 2 Mini + DSpark + Unsloth #385 performance stack (37 commits over a28feb458).

Summary of Changes

Series 1–15 (rebased onto a28feb458)

  • AGX device tuning & 8x8x8 coopmat1: Borealis/AGX device profiles, MoE tile selection, mul_mv_mma 8x8x8 kernels, and 16 KB WG=256 FlashAttention (flash_attn_cm1).
  • Command submission & replay: fence wait modes, submit batching, command-buffer replay cache, prealloc rings, batch-invariant speculative verification mode, and intra-submit barrier elision.
  • 0-ULP kernels & fusions: BF16-exact gate weights, in-place Gated DeltaNet recurrent state (STATE_OUT), 0-ULP SwiGLU / GDN L2+gate / M-RoPE / multi-add RMSNorm / dual F32+F16 norms, paired mat-vec/mat-vec-id, row-split DMMV, wide-tile FP16 MoE mma, Q8_0 roofline DMMV, magic-bias mma dequant, 512-thread argmax, greedy speculative fastpath, and fused LoRA twins.

Series 16–21 + Unsloth #385

  • Series 16: 0-ULP planar SoA Vulkan_Repack, Q8_0 hybrid subgroup magic-bias decode, BF16 compaction, agx_no_robust, Unsloth #385 query-row chunking of dense relative-position attention bias (kq_b) past 2^29 elements, and llm_graph_input_mem_hybrid_iswa_rel GDN gen_identity reuse check.
  • Series 17: Vulkan NVFP4 support across dequant / DMMV / MMQ / MMA / situ.comp / topk_moe, fused GGML_OP_INKLING_FUSED ops, and DSpark greedy ID-only fastpath.
  • Series 18: 0-ULP router topk_moe, kq_b / inkling_rel_gather, fused ffn_post_conv + residual add, 32-thread rms_norm_set_rows, and DSpark inkling_dspark_concat4 + inkling_dspark_gru shaders.
  • Series 19: 0-ULP planar NVFP4 repack, coalesced Inkling 2 loop-controller weights & fused shaders (inkling_ctrl_apply_rms_mul, inkling_depth_mix_rms, inkling_conv_scopy, inkling_l2_clip_qr, inkling_softcap, flash_attn_vec_mhm), inkling_dspark_joint_gru, per-shape DSpark scheduler pool, and common_speculative_process_rows.
  • Series 20: Multi-chunk command-buffer replay, zero-spin fence waiting, zero-copy UMA logits sampling, shared target/draft threadpool, and zero-copy nb == 1 anchor/prev views in dspark.cpp.
  • Series 21: Long-context V-row packing in flash_attn_cm1 + inkling_rel_gather, dormant grammar fastpath, and O_DIRECT GGUF loader (LLAMA_ARG_LOAD_MODE=dio).

Series 22–23 (Roofline & Speculative / Batch Acceleration)

  • Series 22: Unpadded 200,058-vocab LM head slice, active-span Q8_0 KV dequant_transpose + CM1 verify, single-CB replay, fence-epoch events, 44/44 MoE FP16 pipe, and context-aware adaptive DSpark draft depth (d=4 < 30k, d=7 >= 30k).
  • Series 23 Track A (61efda5e7..9c087409b):
    • 0-ULP magic-bias f16vec2 in-register Q8_0 K/V decoding inside flash_attn_cm1.comp and flash_attn_vec_mhm.comp (-48 KV_deq dispatches & -48 barriers/step, 1,296 B -> 272 B/row KV read).
    • Zero-offset 2D VIEW selected_experts fusion in ggml_vk_topk_moe (-96 count_experts dispatches/step), FP16 prealloc_y dual-writes in inkling_depth_mix_rms.comp & inkling_ctrl_apply_rms_mul.comp (-48 contig_cpy_f32_f16 dispatches & -48 barriers/step), and MSG = 2 (BM = 32) in mul_mv_mma_id for N <= 8.
    • Fused single-pass Q8_0 KV quantization + set_rows in inkling_l2_clip.comp and rms_norm_set_rows_q8_0.comp (-96 SET_ROWS dispatches & -48 barriers/step).
  • Series 23 Track B (403a2203e..f41a651ac):
    • Runtime Q8_0 quantization of drafter-only dspark_markov_w2 onto Vulkan0_Repack (102.4 MB -> 51.9 MB, LLAMA_DSPARK_W2_TYPE override).
    • Multi-sequence WAR-guarded can_direct_scopy (n_seqs = 1..8, tracked in llm_graph_input_rs::can_reuse) + rs_idx propagation in seq_cp + pure-greedy batched softcap_argmax routing (-6.4 MB/step logits pad copy at 8x).
    • Opt-in LLAMA_DSPARK_ENABLE_2BRANCH=1 logit-margin 2-branch speculative tree + exact greedy and residual-proposal stochastic verifiers (+16.1% TG on 4k Novel prose).

Verification

  • test-backend-ops on Vulkan0 (RMS_NORM, SET_ROWS, MUL_MAT_ID, FLASH_ATTN_EXT): 5,693/5,693 PASS.
  • Formal verification (Lean 4 Series23A/Series23B + TLA+ Inkling2TreeAndCohort across all 10 TLC specs): 0 sorry, 0 errors.
  • End-to-end M4 Max (m4-nixos) benchmark (Inkling-2-Mini-UD-Q4_K_XL + dspark-Inkling-2-Mini-Q8_0, 100% golden content_sha16 match):
    • Single-stream Code TG: 58.3 t/s (1k), 67.0 t/s (4k), 59.6 t/s (8k), 69.7 t/s (16k), 70.1 t/s (32k) — surpassing oMLX v0.8.3 across all 5/5 lengths (+6.5% to +20.8%) and 7/7 prompt-processing lengths (935–1,039 t/s).
    • Continuous Batching (1k Code): 65.0 t/s (2x), 85.6 t/s (4x, 88.3 w/ MMVID_MAX=1), 129.8–131.4 t/s (8x).

@astaff
astaff force-pushed the agx/m4-max-series8 branch from 5d80a43 to 1a6738a Compare November 17, 2026 05:38
@astaff astaff changed the title vulkan, llama: Apple AGX (M4 Max / Borealis & Honeykrisp) Series 8 inference stack vulkan, llama, common: Apple AGX (M4 Max / Honeykrisp) Series 14 inference stack Nov 17, 2026
@astaff
astaff force-pushed the agx/m4-max-series8 branch from 1a6738a to 0588996 Compare November 17, 2026 06:02
@astaff astaff changed the title vulkan, llama, common: Apple AGX (M4 Max / Honeykrisp) Series 14 inference stack Improve Vulkan inference on the Apple M4 Max GPU Nov 17, 2026
…election, and 8x8x8 coopmat1

Add device detection and matmul/MoE tile tuning for Apple AGX GPUs (M4 Max
T6041 under Borealis and Mesa Honeykrisp):

- Detect Borealis on Apple M4 Max (0x10005 / 0x6041) with GGML_VK_BOREALIS_TUNING
  (off|tiles|roll|all, default all) and disable SPIR-V BK loop unrolling on
  coopmat1 pipelines unless GGML_VK_CM1_ROLL_BK=1.
- Add 8x8x8 VK_KHR_cooperative_matrix (f32matmad8x8) s/m/l dense and MoE
  warptiles sized for the 192-half-reg AGX G17P register file (<=16 8x8
  accumulators per subgroup, BN=16 small MoE tile), subgroup-scoped barriers
  around coopMatStore, and guarded shared-memory bounds in mul_mm.comp.
- Default disable_narrow_mul_mat on Apple AGX (with GGML_VK_DISABLE_NARROW_MUL_MAT=0|1
  override) so 8x8x8 coopmat1 retains its tuned s/m/l tiles and split_k=1.
- Select MUL_MAT_ID tiles by average rows per expert (GGML_VK_MMID_SELECT=pairs,
  default on Apple AGX coopmat1) with a dedicated matmul_id_tile_selector, and
  prefer FP16 B activations on AGX coopmat1 when nei1 > 32 (GGML_VK_MMID_F16_B).
- Add tile/dispatch tuning knobs GGML_VK_CM1_TILES, GGML_VK_CM1_ID_TILES,
  GGML_VK_MMQ_S/M/L, GGML_VK_MMQID_S, GGML_VK_MMVID_MAX, GGML_VK_MMVID_ONE,
  and GGML_VK_DISABLE_INTEGER_DOT_PRODUCT.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…gnostics

Add configurable fence waiting, command-buffer submission policies, and
env-gated graph instrumentation for CPU/GPU synchronization profiling:

- Add GGML_VK_FENCE_WAIT=spin|block|wfe|nap|hybrid (with GGML_VK_FENCE_MARGIN_US,
  default 300 us) to control final graph fence waiting, including AArch64 WFE
  low-power polling and EMA-based hybrid sleep-then-spin after the almost-ready
  fence.
- Add GGML_VK_SUBMIT_MODE=default|one|geo (with GGML_VK_SUBMIT_FIRST and
  GGML_VK_SUBMIT_GROWTH) and GGML_VK_FLOPS_PER_SUBMIT to control command-buffer
  submission granularity.
- Add GGML_VK_GRAPH_STATS=1|2 (per-graph dispatch/barrier/submit/record/wait
  counters and per-dispatch pipeline+workgroup trace) and GGML_VK_DUP_OPS for
  non-in-place kernel timing ablations.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…taNet recurrent state

Add lossless BF16 storage for BF16-exact F32 gate weights and in-place Gated
DeltaNet (GDN) recurrent state updates with speculative rollback safety:

- Under GGML_GEN_BF16_EXACT=1, inspect F32 router, shared-expert gate, and GDN
  alpha/beta weights (.ffn_gate_inp.weight, .ffn_gate_inp_shexp.weight,
  .ssm_alpha.weight, .ssm_beta.weight, .ssm_beta_alpha.weight, .ssm_ba.weight)
  at load time; when every element has zero low 16 mantissa bits, store the
  tensor as BF16 and cast back to F32 above GGML_GEN_BF16_CAST_ABOVE columns
  (default 8) during graph build.
- Under GGML_GEN_GDN_INPLACE=1, view recurrent cache rows directly in build_rs
  when the sequence state mapping is the identity (skipping GET_ROWS gather)
  while guarding against speculative rollback snapshot consumption when
  n_rs_seq != 0.
- Add STATE_OUT variants of gated_delta_net.comp so single-step GDN writes its
  updated recurrent state directly into the destination cache slice and elides
  the trailing CPY node.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…logue fusions

Add Numerically Exact (0-ULP) RMS_NORM reductions and Tier-1 operator fusions
gated by GGML_GEN_FUSE (all or comma-separated tokens):

- Replace the non-subgroup shared-memory tail in rms_norm.comp with an exact
  0-ULP subgroupShuffleXor tree reduction when gl_SubgroupSize == 32 and skip
  the redundant initial workgroup barrier.
- Add lazy _glu mat-vec/mat-vec-id twin pipelines (specialization constant 3 = 1)
  so base mat-vec shaders incur zero extra register pressure.
- Support GGML_GEN_FUSE=glu (mat-vec / mat-vec-id + SwiGLU), l2 (deferred
  RMS_NORM + SCALE with precise IEEE rounding for GDN L2 norm), gate
  (RMS_NORM * weight * SiLU(z) in one dispatch), mrope (M-RoPE / IM-RoPE in
  RMS_NORM_MUL_ROPE), mmgate (mat-vec + sigmoid and mat-vec + bias + softplus +
  mul), and shexp (mat-vec + per-token row scale).

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…roup DMMV, and outer row reuse

Add row-split multi-subgroup dequant-mat-vec kernels, 0-ULP quantized fast
paths, and paired mat-vec / mat-vec-id twin pipelines:

- Add row-split multi-subgroup DMMV (local_size_y specialization constant 4 via
  GGML_VK_DMMV_NSG / GGML_VK_DMMV_ID_NSG), workgroup row/size knobs
  (GGML_VK_RM_STDQ/_ID, GGML_VK_RM_KQ/_ID, GGML_VK_DMMV_LARGE/_ID_LARGE), and
  0-ULP Q8_0, Q4_K, Q5_K, and Q6_K vectorization / outer row reuse
  (GGML_VK_FAST_KQ).
- Split paired mat-vec pipelines into lazy _pairmm (specialization constant
  3 = 2) and _pairglu (3 = 3) twins so standalone and single-epilogue shaders
  keep minimum register footprint.
- Support GGML_GEN_FUSE=gateup (single-dispatch gate + up + 0-ULP SwiGLU for
  MUL_MAT and MUL_MAT_ID) and GGML_GEN_FUSE=pairmm (sibling MUL_MAT sharing
  src1, including trailing sigmoid on the second output), with graph_optimize
  pairing and buffer lifetime dependencies.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…ubmit barrier elision

Add 0-ULP batch-invariant speculative verification mode and Series 8 graph
scheduling / intra-submit barrier elision:

- Under GGML_VK_BATCH_INVARIANT=1, size Flash Attention KV splits (including
  GQA ratios up to k <= 8 query tokens) identically to n=1, extend ADD+RMS_NORM
  partials to multi-row verification batches with an n=1 per-row 1 KB budget,
  and enable MUL_MAT + ADD fusion on the multi-column mat-vec path; also add
  GGML_VK_DISABLE_ADD_RMS.
- Under GGML_GEN_FUSE=s8 (or all), fuse CONT + [view] + UNARY + MUL into a
  single strided unary_mul dispatch, lift external views out of
  RMS_NORM_MUL_SILU subgraphs, and co-schedule independent dispatches in
  ggml_vk_graph_optimize (1-workgroup TOPK_MOE with shared-expert gate+up+glu,
  ffn_moe_down with ffn_shexp so trailing residual ADDs coalesce into
  MULTI_ADD, and mixed-quant GDN projections) with explicit add_alloc_dep
  buffer lifetime constraints to elide intra-submit pipeline barriers.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…d RMSNorm fusion

Series 9-11 optimizations for Apple AGX (Honeykrisp / M4 Max):
- Add per-graph Vulkan command-buffer replay cache for decode and speculative
  verification graphs with stable tensor buffer bindings.
- Add 8-slot prealloc_y and prealloc_split_k ring buffers to eliminate intra-graph
  pipeline drain syncs across quantize_y and split-k dispatches.
- Add multi_add_rms_mul.comp fusing residual ADD chains with RMS_NORM + MUL,
  fused ADD+SCALE, fused MoE top-k + scatter/gather epilogues, and fast FP16
  dequantization/accumulation paths.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…WG=256 FlashAttention

- Add mul_mv_mma.comp (8x8x8 simdgroup_matrix mat-vec/multi-col and grouped
  expert mul_mv_mma_id with fused paired-SwiGLU and expert-scale epilogues)
  and fused cm1 matmul/matmul_id epilogue variants (mul_mm_load_a_body.glsl).
- Specialize single-wave subgroup shuffle gated_delta_net.comp (S_V <= 128)
  and tiled shared-memory ssm_conv.comp (NC == 4) with fused SiLU output.
- Reduce 8x8x8 coopmat1 FlashAttention shared memory to <= 16 KB for dual
  workgroup occupancy per core (WG=256, 8 subgroups), add LPT GQA head/tile
  swizzle (Flags bit 256), and compact mask tiles for partial K blocks.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…hread argmax, and greedy speculative fastpath

- Add wide-tile RT=4/8 mul_mv_mma / mul_mv_mma_id variants with FP16
  shared-memory activation staging (SHB=6, NT=1 for RT>=4 to eliminate AGX
  register spills on long-context prefill) and paired expert count_experts.
- Add vec4 RMSNorm fast paths (32-lane 0-barrier d=128 QK-norm, dual F32+F16
  outputs in rms_norm.comp and multi_add_rms_mul.comp to elide standalone
  cpy_f32_f16 passes before coopmat1 matmul) and fused 2-row Q+K RMSNorm.
- Widen argmax.comp to 512 threads for large vocabularies (ne00 >= 65536) and
  optimize single-wave GDN/SSM kernels for multi-token prefill.
- Add greedy common_sampler_sample_greedy() fastpath and skip redundant logit
  copies during greedy speculative decoding (MTP / draft verification).

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…used LoRA twins

- Add 4-block (128-element) unrolled iter4_aligned_q8_0 / iter2_aligned_q8_0
  mat-vec paths paired with 128-thread (4-subgroup) DMMV_WG_SIZE_LARGE routing
  for wide-K Q8_0 projections (reaching 90.04% of the 529.5 GB/s M4 Max DRAM
  ceiling on Qwen3.8-27B-Q8_0).
- Replace unpack8 int-to-float Q8_0 coopmat conversions in mul_mv_mma.comp with
  2-cycle IEEE-754 FP16 magic-bias extraction ((| 0x64006400u) - 1152.0h),
  hoist sh_b=12 on paired SwiGLU, lower GGML_VK_MMA_Q8_MIN_N to 8 (M <= 65536),
  and raise GGML_VK_MMA_MAX_N to 4096.
- Hoist [lora_a] projections in ggml_vk_graph_optimize and fuse [mm, lora_b,
  scale, add] into lazy on-demand 11-binding gen_lora_twin pipelines with zero
  binding or register overhead on non-LoRA pipelines.
- Refine common_sampler_init pure_argmax_fast detection across default sampler
  chains when penalty/DRY/XTC parameters are inactive.

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…, hybrid_iswa_rel GDN reuse, and MTP-only router BI

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…sions, and DSpark greedy ID-only output

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
… and DSpark concat4+GRU shaders

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…usions, DSpark joint GRU, and schema tool args

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…UMA sampling, and shared DSpark threadpool

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
…t grammar fastpath, and O_DIRECT loader

Signed-off-by: Artyom Astafurov <artyom.astafurov@gmail.com>
@astaff
astaff force-pushed the agx/m4-max-series8 branch from f828324 to eb649ce Compare November 25, 2026 15:37
@astaff astaff changed the title Improve Vulkan inference on the Apple M4 Max GPU Improve Vulkan inference on Apple M4 Max GPU (Series 1–21 + Inkling 2 / DSpark) Nov 25, 2026
…rmup padding

Caught during live Apple M4 Max (Borealis/Vulkan) re-testing:

- gated_delta_net.comp: guard CONTIG_VEC4 fast path with REPLAY == 0u and
  sq1 == sk1 && sq2 == sk2 && sq3 == sk3 so pending-token replay and
  padded-Q / permuted-K fall through to the general path (fixes
  test-backend-ops -b Vulkan0 -o GATED_DELTA_NET from 85/98 to 98/98).
- llama-context.cpp: require batch_inp.state.empty() before applying the
  DSpark warmup block-padding path, preventing real mainline DSpark draft
  batches (n_block_tokens < dflash_block_size with Markov state) from
  having their output flags cleared.
@astaff astaff changed the title Improve Vulkan inference on Apple M4 Max GPU (Series 1–21 + Inkling 2 / DSpark) Improve Vulkan inference on Apple M4 Max GPU (Series 1–23 + Inkling 2 / DSpark) Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant