Skip to content

perf(dflash, glm5_next): reuse nax sparse attention - #4342

Merged
jundot merged 1 commit into
jundot:mainfrom
N1k1tung:perf/glm5-flash-dflash-nax-attn
Oct 9, 2026
Merged

jundot merged 1 commit into
jundot:mainfrom
N1k1tung:perf/glm5-flash-dflash-nax-attn

Conversation

@N1k1tung

@N1k1tung N1k1tung commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR reuses existing NAX attn kernel (already used for attn during prefill) for block verify.

Validation

M5U 80c 256gb
GLM5.3-Flash-4bit affine
GLM5.3-Flash-oQ4e

Validated performance and parity against main 2238a44

Size TG TG diff % PP Acceptance Identical
4096 59.1 → 68.0 +15.06% 2432.8 → 2412.9 58.79% → 64.06% No
16768 112.3 → 117.2 +4.36% 2357.3 → 2345.8 83.79% → 83.79% No
32536 80.7 → 87.1 +7.93% 2386.9 → 2381.5 73.05% → 75.59% No

Stacked with #4338 against main:

Size TG TG diff % PP Acceptance Identical
4096 59.1 → 74.5 +26.06% 2432.8 → 2419.3 58.79% → 64.06% No
16768 112.3 → 125.6 +11.84% 2357.3 → 2360.2 83.79% → 83.79% No
32536 80.7 → 94.4 +16.98% 2386.9 → 2389.2 73.05% → 75.59% No

Since the acceptance is varied, the gain seems a bit higher. The overall gain against similar acceptance result looks to be around +4.3%.
Tested with this script:

check.py ``` python import argparse import asyncio import gc import hashlib import json import logging import statistics import subprocess import sys import time from dataclasses import replace from pathlib import Path
import mlx.core as mx
from omlx.admin.benchmark import _load_bench_corpus, _run_single_test
from omlx.engine.dflash import DFlashEngine
from omlx.engine_core import get_mlx_executor, shutdown_mlx_executor
from omlx.model_settings import ModelSettings


async def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--model-dir')
    parser.add_argument('--model', default='GLM-5.3-Flash-MLX-4bit')
    parser.add_argument('--draft-model', default='GLM-5.3-Flash-DFlash2')
    parser.add_argument('--output', default='/private/tmp/dflash-perf-parity.json')
    args = parser.parse_args()
    records = []
    
    engine = DFlashEngine(
        model_name=str(Path(args.model_dir) / args.model),
        draft_model_path=str(Path(args.model_dir) / args.draft_model),
        draft_quant_enabled=False,
    )
    saved_summary = []
    original_record = engine._record_speculation_summary

    def record(summary):
        saved_summary[:] = [summary.to_payload()]
        original_record(summary)

    engine._record_speculation_summary = record
    original_stream = engine.stream_generate

    async def stream(*a, **kw):
        kw.update(seed=0, top_k=0, min_p=0.0, repetition_penalty=1.0)
        async for output in original_stream(*a, **kw):
            if output.finish_reason == 'error':
                raise RuntimeError('Generation failed')
            yield output

    engine.stream_generate = stream
    started = time.time()
    try:
        await engine.start()
        assert not engine._in_memory_cache_enabled
        assert not engine._runtime_context.runtime.prefix_cache
        engine._runtime_context = replace(
            engine._runtime_context,
            runtime=replace(engine._runtime_context.runtime, prefill_step_size=2048),
        )
        tokenizer = engine.tokenizer
        corpus = _load_bench_corpus('code_python')
        body = tokenizer.encode(corpus, add_special_tokens=False)
        while len(body) < 131071:
            corpus += _load_bench_corpus('code_python')
            body = tokenizer.encode(corpus, add_special_tokens=False)
        prompts = {n: [tokenizer.encode(str(i), add_special_tokens=False)[0]] + body[:n - 1] for i, n in enumerate([4096, 16768, 32768])}
        
        meta = {
            'model': args.model,
            'device': mx.device_info()['device_name'], 'temperature': 0.0,
            'top_p': 1.0, 'seed': 0, 'max_tokens': 512,
            'verify_mode': engine._verify_mode,
            'window': engine._draft_window_size, 'block_max': 8,
            'started': started,
            'prompt_sha256': {str(n): hashlib.sha256(json.dumps(p).encode()).hexdigest() for n, p in prompts.items()},
        }
        print(json.dumps({'meta': meta}), flush=True)
        async for _ in engine.stream_generate(prompt=body[:2048], max_tokens=128, temperature=0.0, top_p=1.0):
            pass

        async def run(n, iteration):
            saved_summary.clear()
            metrics = await _run_single_test(engine, prompts[n], 512, n)
            assert metrics['completion_tokens'] == 512, metrics
            assert metrics['cached_tokens'] == 0, metrics
            assert len(saved_summary) == 1
            summary = saved_summary[0]
            token_hash = hashlib.sha256(json.dumps(summary['generated_token_ids']).encode()).hexdigest()
            result = {'pp': n, 'iteration': iteration, 'metrics': metrics, 'summary': summary, 'token_sha256': token_hash}
            records.append(result)
            Path(args.output).write_text(json.dumps({'meta': meta, 'records': records}, indent=2))
            print(json.dumps({'pp': n, 'iteration': iteration, 'tg': metrics['gen_tps'], 'acceptance': summary['acceptance_ratio'], 'cycles': summary['cycles_completed'], 'token_sha256': token_hash}), flush=True)
            await asyncio.get_running_loop().run_in_executor(get_mlx_executor(), lambda: (mx.synchronize(), gc.collect(), mx.clear_cache()))

        for iteration in range(1, 4):
            for n in prompts:
                await run(n, iteration)
        
        aggregate = {}
        for n in prompts:
            group = [r for r in records if r['pp'] == n]
            rates = [r['metrics']['gen_tps'] for r in group]
            sha = {r['token_sha256'] for r in group}
            aggregate[str(n)] = {
                'tg_median': statistics.median(rates), 'tg_min': min(rates), 'tg_max': max(rates),
                'pp_median': statistics.median(r['metrics']['processing_tps'] for r in group),
                'acceptance_median': statistics.median(r['summary']['acceptance_ratio'] for r in group),
                'cycles': sorted({r['summary']['cycles_completed'] for r in group}),
                'output_variants': len(sha), 'repetitions': len(group),
                'token_sha256': sha.pop() if len(sha)==1 else 'varied'
            }
        Path(args.output).write_text(json.dumps({'meta': meta, 'records': records, 'aggregate': aggregate}, indent=2))
        print(json.dumps({'aggregate': aggregate}), flush=True)
    finally:
        await engine.stop()
        shutdown_mlx_executor()


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s %(message)s')
    asyncio.run(main())
```

NAX attention is not producing identical results to existing baseline. The drift comes from different intermediate precision, however it turns out NAX route has more accurate math.

Stock 512-wide SDPA rounds QK scores and normalized softmax probabilities to BF16. NAX attention keeps them near FP32 precision until the final output.

Small synthetic checks with 64 heads, 512-wide latents and 2,051 selected keys reproduces the drift:

Width Current NAX vs SDPA Decomposed reference
4 0.581% 0%, bit-identical to SDPA
8 0.558% 0%, bit-identical to SDPA

These are relative L2 differences. Against an independent FP64 reference, NAX’s error was 0.166%, versus 0.534–0.558% for SDPA. So NAX is mathematically more accurate here:

parity_probe.py ```python """Synthetic sparse-attention precision check; no model loading or timing.
    TF32 is disabled before importing MLX so it cannot reduce the precision of the FP32 reference products.

    The rounding variants are decomposed references, not modified NAX kernels.
    Decomposed pipeline matching stock SDPA:
    FP32 QK → BF16 scores → full-row FP32 softmax → BF16 probabilities → MLX P×V.
    """

    import json
    import os

    os.environ["MLX_ENABLE_TF32"] = "0"

    import mlx.core as mx
    import numpy as np

    from omlx.patches.glm_moe_dsa import sparse_mla_nax as nax


    def metrics(value, reference):
    error = value - reference
    return {
        "relative_l2_percent": float(100 * np.linalg.norm(error) / np.linalg.norm(reference)),
        "max_abs": float(np.max(np.abs(error))),
        "different_percent": float(100 * np.mean(value != reference)),
    }


    def run(length, q_scale=1.0, dtype=mx.bfloat16, seed=0):
    # Build seeded MLA inputs: length query positions, 64 heads, 512-wide
    # latents and 2051 sparse slots per query. Indices sample each query's
    # causal KV prefix with replacement, with 2% masked padding; K and V
    # share the same latent rows. q_scale stresses the score range, and
    # every path receives the same dtype-rounded inputs.
    heads, dim, cache, topk = 64, 512, 4096, 2051
    scale = 1 / 16
    mx.random.seed(seed)
    q = (mx.random.normal((1, heads, length, dim)) * q_scale).astype(dtype)
    kv = mx.random.normal((1, 1, cache, dim)).astype(dtype)
    positions = cache - length + mx.arange(length)[:, None]
    selected = (mx.random.uniform(shape=(length, topk)) * (positions + 1)).astype(mx.int32)
    selected = mx.where(mx.random.uniform(shape=selected.shape) < 0.02, -1, selected)
    idx = selected[None, None]
    gathered = kv[0, 0][mx.maximum(selected, 0)][:, None]
    queries = q[0].swapaxes(0, 1)[:, :, None]
    mask = (selected >= 0)[:, None, None]

    # Stock SDPA baseline on the selected rows, gathered into per-query KV.
    # One KV head broadcasts across all query heads. The mask excludes -1
    # padding, gathered as row 0 only to keep indexing valid. For these
    # BF16/512-wide inputs, stock rounds scores and probabilities to BF16;
    # this baseline checks parity with the existing MLX execution path.
    stock = mx.fast.scaled_dot_product_attention(
        queries, gathered, gathered, scale=scale, mask=mask
    )
    q32, kv32 = queries.astype(mx.float32), gathered.astype(mx.float32)
    scores = mx.where(mask, (q32 * scale) @ kv32.swapaxes(-1, -2), -mx.inf)
    probs = mx.softmax(scores, axis=-1, precise=True)
    full = probs @ kv32
    rounded_probs = mx.softmax(scores.astype(dtype).astype(mx.float32), axis=-1, precise=True)

    # Also preserve scaled-query rounding here; it can affect FP16 subnormals.
    stock_scores = mx.where(mask, (queries * scale) @ gathered.swapaxes(-1, -2), -mx.inf)
    manual_stock = mx.softmax(stock_scores, axis=-1, precise=True) @ gathered
    actual = nax.sparse_mla_attention_nax(q, kv, idx, scale)
    assert actual is not None, "NAX sparse attention is unavailable"
    actual = actual[0].swapaxes(0, 1)[:, :, None]
    rowwise = mx.concatenate(
        [
            nax.sparse_mla_attention_nax(
                q[:, :, row : row + 1],
                kv[:, :, : cache - length + row + 1],
                idx[:, :, row : row + 1],
                scale,
            )[0].swapaxes(0, 1)[:, :, None]
            for row in range(length)
        ],
        axis=0,
    )
    outputs = {
        "nax": actual,
        "fp32_output_rounded": full.astype(dtype),
        "score_rounding_only": (rounded_probs @ kv32).astype(dtype),
        "probability_rounding_only": (probs.astype(dtype).astype(mx.float32) @ kv32).astype(dtype),
        "both_rounding": rounded_probs.astype(dtype) @ gathered,
    }
    mx.eval(outputs, stock, manual_stock, rowwise)
    assert mx.array_equal(stock, manual_stock).item(), "SDPA differs from its decomposed reference"
    assert mx.array_equal(actual, rowwise).item(), "NAX block and sequential rows differ"
    if dtype == mx.bfloat16:
        assert mx.array_equal(stock, outputs["both_rounding"]).item(), "BF16 rounding reference differs from SDPA"

    # Copy each output once; all comparisons then stay on the CPU.
    arrays = {name: np.asarray(value.astype(mx.float32), dtype=np.float64) for name, value in outputs.items()}
    stock_array = np.asarray(stock.astype(mx.float32), dtype=np.float64)
    result = {
        "length": length, "q_scale": q_scale, "dtype": str(dtype), "seed": seed,
        "heads": heads, "dim": dim, "cache": cache, "topk": topk,
        "against_stock": {name: metrics(value, stock_array) for name, value in arrays.items()},
        "sdpa_decomposition_bitwise": True,
        "nax_block_vs_rowwise_bitwise": True,
    }

    # same decomposed pipeline in fp64 on CPU
    q64, kv64 = np.asarray(q32, dtype=np.float64), np.asarray(kv32, dtype=np.float64)
    scores64 = np.where(np.asarray(mask), (q64 * scale) @ kv64.swapaxes(-1, -2), -np.inf)
    probs64 = np.exp(scores64 - scores64.max(axis=-1, keepdims=True))
    probs64 /= probs64.sum(axis=-1, keepdims=True)
    reference = probs64 @ kv64
    result["against_float64"] = {
        name: metrics(value, reference) for name, value in {**arrays, "stock": stock_array}.items()
    }
    result["fp32_reference_vs_float64"] = metrics(np.asarray(full, dtype=np.float64), reference)
    assert result["fp32_reference_vs_float64"]["relative_l2_percent"] < 0.001
    assert result["against_float64"]["nax"]["relative_l2_percent"] <= result["against_float64"]["stock"]["relative_l2_percent"]

    print(f"\nWidth {length}, {str(dtype).rsplit('.', 1)[-1]}, q_scale={q_scale}, seed={seed}", flush=True)
    print(f"{'Variant':28} {'L2 vs SDPA %':>13} {'Max abs':>11} {'Different %':>12}")
    for name, value in result["against_stock"].items():
        print(f"{name:28} {value['relative_l2_percent']:13.6f} {value['max_abs']:11.6g} {value['different_percent']:12.4f}")
    print("PASS: SDPA decomposition and NAX block/row checks", flush=True)
    errors = result["against_float64"]
    print(f"FP64 L2 error: NAX={errors['nax']['relative_l2_percent']:.6f}%, SDPA={errors['stock']['relative_l2_percent']:.6f}%", flush=True)
    return result


    if __name__ == "__main__":
    results = [
        run(4),
        run(8, seed=7),
        run(4, q_scale=3, seed=3),
        run(2, seed=1),
    ]
    print("Raw results:\n" + json.dumps(results))


```

All relevant tests pass. Added 2 additional tests for the nax route and fallback.

Checklist

  • I read CONTRIBUTING.md.
  • I understand every change in this PR and can explain it in review.
  • For UI or UX changes, I attached before and after screenshots.

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I measured the verify step on M5 Max and it's 7-10% faster. The logits change a little, but verify stays as close to normal decode as it is on main. LGTM, merging after #4338.

@jundot
jundot merged commit f727062 into jundot:main Oct 9, 2026
1 check passed
jundot added a commit that referenced this pull request Oct 9, 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.

2 participants