"""Model-free correctness receipts from the pinned MTPLX custom kernels. No timings, generation, weights download, or replacement implementations. Run with the pinned runtime and PYTHONPATH pointing at the MTPLX checkout. """ import hashlib import json import os from pathlib import Path import runpy import sys import mlx.core as mx from mlx_lm.models import gated_delta import numpy as np from mtplx.kernels.gdn_conv_norm import fused_gdn_conv_norm, fused_gdn_conv_norm_rows from mtplx.kernels.gdn_step_fused import fused_gdn_step from mtplx.kernels.gdn_out_fused import fused_gdn_out from mtplx.kernels.hyper_connection import fused_hyper_read from mtplx.kernels.hyper_connection_v3 import fused_hyper_read_v3 from mtplx.kernels import hyper_connection def pattern(count, salt): return mx.array((((np.arange(count, dtype=np.int64) * 17 + salt * 13) % 257) - 128).astype(np.float32) / 128, dtype=mx.bfloat16) def qsa_attention_module_fixtures(*, profile_filter=None): """Whole unchanged Attention, ongoing KV/indexer state and actual consumers.""" from contextlib import nullcontext from mtplx.models import qwen4_exp as model from mtplx.attention_context import attention_phase, vision_rope from mtplx.kernels import qsa_flash_skip, qsa_prefill_flash assert mx.__version__ == "0.32.2" defaults=dict(fused=True,compiled=True,prefill=True,phase_prefill=True, prefill_min_rows=32,prefill_compile_rows=2048,prefill_min_context=2049, prefill_workspace=128*1024*1024,tile_rows=0,flash=True,gather_decode=False, gather=True,gather_max_rows=8,gather_min_context=0,tf32=os.environ.get("MLX_ENABLE_TF32","1")!="0") envs=dict(fused="MTPLX_FUSED_QSA_INDEXER",compiled="MTPLX_COMPILED_QSA_INDEXER",prefill="MTPLX_QSA_PREFILL", prefill_min_rows="MTPLX_QSA_PREFILL_MIN_ROWS",prefill_compile_rows="MTPLX_QSA_PREFILL_COMPILE_ROWS", prefill_min_context="MTPLX_QSA_PREFILL_MIN_CONTEXT",flash="MTPLX_QSA_FLASH",gather_decode="MTPLX_QSA_GATHER_DECODE", gather="MTPLX_QSA_GATHER",gather_max_rows="MTPLX_QSA_GATHER_MAX_ROWS",gather_min_context="MTPLX_QSA_GATHER_MIN_CONTEXT",tile_rows="MTPLX_QSA_SCORE_TILE_ROWS") saved=os.environ.copy() profiles=[(0,(1,4,33),4,{},"none",False,False,2049,True), (0,(2048,1),3,{},"none",False,False,2049,True), (2051,(1,4,33),4,{},"none",False,False,2049,True), (2051,(33,1,4),0,dict(compiled=False,flash=False,gather=False),"none",False,False,32768,True), (2051,(33,1,4),3,{},"none",False,False,32768,False), (2051,(1,4),0,dict(compiled=False,fused=False,flash=False,gather_decode=True),"none",False,False,32768,True), (32768,(2048,1,4),4,{},"none",False,False,32768,True), (2051,(1,4,2,1),4,{},"table",False,False,2049,True), (0,(3,1,4),0,{},"none",True,True,2049,True), (2051,(1,4),3,{},"no_axes",False,False,2049,True)] trace=[];hooks=[] def hook(owner,name,label): original=getattr(owner,name) def call(*args,**kwargs): trace.append(label);return original(*args,**kwargs) hooks.append((owner,name,original));setattr(owner,name,call) hook(qsa_flash_skip,"qsa_flash_skip","flash") hook(qsa_prefill_flash,"qsa_prefill_flash","prefill_flash") hook(model,"_qsa_rows_gather_attention","rows_gather") hook(model,"_qsa_prefill_gather_attention","prefill_gather") hook(model,"_qsa_blocks_to_dense_mask","dense_mask") hook(mx.fast,"scaled_dot_product_attention","sdpa") try: for profile,(prefix,steps,fused,override,vision,no_indexer,biased,flash_min,gather) in enumerate(profiles): if profile_filter is not None and profile!=profile_filter:continue opt=defaults|override os.environ.update({env:str(int(opt[key])) for key,env in envs.items()}) os.environ.update(MTPLX_QSA_PREFILL_SCORE_MB="128",MTPLX_QSA_PREFILL_FLASH_MIN_CONTEXT=str(flash_min),MTPLX_QSA_PREFILL_GATHER=str(int(gather)),MTPLX_QSA_PREFILL_GATHER_TILE="64") args=model.TextArgs(hidden_size=64,indexer_n_heads=0 if no_indexer else 4, mrope_section=[8,12,12] if vision=="table" else None,mrope_interleaved=True) attn=model.Attention(args) for name,n,k,salt in [("q_proj",12288,64,400),("k_proj",512,64,402),("v_proj",512,64,404),("o_proj",64,6144,406)]: layer=quantized_linear_fixture(n,k,4,64,salt) if biased:layer.bias=pattern(n,salt+40)/64 setattr(attn,name,layer) attn.q_norm.weight=pattern(256,410);attn.k_norm.weight=pattern(256,411) if attn.indexer is not None: attn.indexer.index_qk_proj=quantized_linear_fixture(640,64,4,64,408) attn.indexer.q_layernorm.weight=pattern(128,72);attn.indexer.k_layernorm.weight=pattern(128,73) if fused: parts=[attn.q_proj,attn.k_proj,attn.v_proj] if fused==4:parts.append(attn.indexer.index_qk_proj) splits=np.cumsum([a.weight.shape[0] for a in parts[:-1]]).tolist() attn.qkv_fused=model._FusedGDNInProj(*(mx.concatenate([getattr(a,name) for a in parts],axis=0) for name in ("weight","scales","biases")),64,4,"affine",splits) for name in ("q_proj","k_proj","v_proj"):attn.pop(name,None) if fused==4:attn.indexer.pop("index_qk_proj",None) cache=model.QSACache() if prefix: cache.write_raw(pattern(prefix*128,88).reshape(1,prefix,128)) attn.indexer._extend_pooled(cache,prefix) kv=pattern(prefix*512,89).reshape(1,prefix,2,256).transpose(0,2,1,3) cache.kv.update_and_fetch(kv,kv) mx.eval(*cache.state) table=mx.array(np.stack([np.arange(prefix+5)//3,np.arange(prefix+5)%17,np.arange(prefix+5)%11]),mx.int32) if vision=="table" else None for step,rows in enumerate(steps): if step==2 and profile in (2,7):assert cache.trim(2)==2 pos=cache.offset trace.clear();before=model.qsa_prefill_engagement() with attention_phase("prefill"), vision_rope(table,-2) if vision!="none" else nullcontext(): result=attn(pattern(rows*64,420+step).reshape(1,rows,64),cache) counts={k:v-before.get(k,0) for k,v in model.qsa_prefill_engagement().items() if v!=before.get(k,0)} state=[cache.raw_keys,cache.pooled,cache.pooled_f32_t,cache.kv.keys,cache.kv.values] leaves=[result,*[a for a in state if a is not None]] core=None if attn.indexer is None else attn.indexer._compiled_indexer_core emit(f"qsa_attention_p{profile}_s{step}",leaves,profile=profile,step=step,rows=rows,pos=pos,prefix=prefix, fused=fused,vision=vision,no_indexer=no_indexer,biased=biased,flash_min=flash_min,prefill_gather=gather, options=opt,consumers=trace.copy(),counts=counts,offset=cache.offset,pooled_len=cache.pooled_len, state_present=[a is not None for a in state],shapes=[a.shape for a in leaves], core=None if core is None else core.to_dict(),frequencies=attn._inv_freq.tolist()) finally: for owner,name,original in reversed(hooks):setattr(owner,name,original) for key in set(envs.values())|{"MTPLX_QSA_PREFILL_SCORE_MB","MTPLX_QSA_PREFILL_FLASH_MIN_CONTEXT","MTPLX_QSA_PREFILL_GATHER","MTPLX_QSA_PREFILL_GATHER_TILE"}: if key in saved:os.environ[key]=saved[key] else:os.environ.pop(key,None) def qsa_indexer_commit_fixtures(): """Unmodified indexer core lifecycle, ongoing cache commit and return API.""" from mtplx.models.qwen4_exp import QSAIndexer, TextArgs, QSACache import mlx.nn as nn assert mx.__version__ == "0.32.2" saved = os.environ.get("MTPLX_QSA_PREFILL_SCORE_MB") steps = [(1,"update_only"),(3,"update_only"),(33,"prefill_blocks"), (1,"blocks"),(4,"row_tokens"),(4,"dense_mask"),(221,"prefill_blocks"), (1,"blocks"),(4,"row_tokens"),(4,"dense_mask"),(4,"row_tokens"), (1,"blocks"),(4,"dense_mask")] try: for quantized in (False, True): os.environ["MTPLX_QSA_PREFILL_SCORE_MB"] = "128" idx=QSAIndexer(TextArgs());idx.block_topk=8 idx.q_layernorm.weight=pattern(128,72);idx.k_layernorm.weight=pattern(128,73) if quantized:idx.index_qk_proj=quantized_linear_fixture(640,128,4,64,75) else: idx.index_qk_proj=nn.Linear(128,640,bias=False) idx.index_qk_proj.weight=pattern(640*128,231).reshape(640,128) cache=QSACache() for step,(rows,mode) in enumerate(steps): # Same bytes, new Python array identity: every leaf matters. if step==2: idx._fused_score_scratch_bytes=1024*1024 os.environ["MTPLX_QSA_PREFILL_SCORE_MB"]="2" if step==3:idx.q_layernorm.weight=mx.array(idx.q_layernorm.weight) if step==4:idx.k_layernorm.weight=mx.array(idx.k_layernorm.weight) if step==5:idx._inv_freq=mx.array(idx._inv_freq) if step==6:idx.index_qk_proj.weight=mx.array(idx.index_qk_proj.weight) if step==7 and quantized:idx.index_qk_proj.scales=mx.array(idx.index_qk_proj.scales) if step==8 and quantized:idx.index_qk_proj.biases=mx.array(idx.index_qk_proj.biases) if step==9:cache.reserve_indexer_capacity(raw_capacity=2048,pooled_capacity=512) if step==10:assert cache.trim(3)==3 pos=cache.offset if step==11: old_core=idx._compiled_indexer_core;old_seal=idx._compiled_indexer_parameter_signature valid=idx.q_layernorm.weight idx.q_layernorm.weight=mx.zeros((127,),mx.bfloat16) try:idx._get_compiled_indexer_core() except ValueError:pass else:raise AssertionError("invalid replacement must fail") assert idx._compiled_indexer_core is old_core and idx._compiled_indexer_parameter_signature==old_seal idx.q_layernorm.weight=valid hidden=pattern(rows*128,300+step).reshape(1,rows,128) supplied=step%2==0 qk=pattern(rows*704,320+step).reshape(1,rows,704)[...,:640] if supplied else None if cache.pooled is not None:cache.pooled_f32_view(cache.pooled_len) old_raw,old_pool=cache.raw_keys,cache.pooled old_arrays=[a for a in (old_raw,old_pool) if a is not None] mx.eval(*old_arrays) result=idx._call_rows_compiled(hidden,pos,cache,qk,mode=mode) assert cache.offset==pos and cache.pooled_f32_t is None assert cache.raw_keys is not old_raw and cache.pooled is not old_pool if result is None:kind,values,tail="none",[],None elif isinstance(result,tuple): kind=result[0];tail=result[2] if kind=="flash" else None values=[result[1]] if kind=="flash" else list(result[1:]) else:kind,values,tail="dense",[result],None outputs=[*values,cache.raw_keys,cache.pooled,*old_arrays] emit(f"qsa_indexer_commit_q{int(quantized)}_s{step}",outputs, quantized=quantized,step=step,rows=rows,pos=pos,mode=mode,supplied=supplied, kind=kind,tail=tail,shapes=[a.shape for a in outputs], pooled_len=cache.pooled_len,report=idx._compiled_indexer_core.to_dict(), frequencies=idx._inv_freq.tolist()) cache.kv.offset=pos+rows # Attention owns this later frontier. finally: if saved is None:os.environ.pop("MTPLX_QSA_PREFILL_SCORE_MB",None) else:os.environ["MTPLX_QSA_PREFILL_SCORE_MB"]=saved def qsa_core_host_fixtures(): """Original Core validation, engagement and replay; real compile/eval.""" from mtplx.kernels.qsa_indexer_compile import QSACompiledIndexerCore from mtplx.models.qwen4_exp import QSAIndexer, TextArgs assert mx.__version__ == "0.32.2" norm=pattern(128,72);freq=QSAIndexer(TextArgs())._inv_freq weight=pattern(640*128,231).reshape(640,128) def make(project=lambda x:x@weight.T): return QSACompiledIndexerCore(n_heads=4,kv_heads=1,head_dim=128,block_topk=8, compress_ratio=4,q_norm_weight=norm,k_norm_weight=norm,inv_freq=freq,rms_norm_eps=1e-6, project_qk=project,minimum_raw_capacity=16,minimum_pooled_capacity=16, selector_scratch_bytes=1024,prefill_score_workspace_bytes=4096) core=make() cases=[(1,64,128,32,"blocks",False,None), (1,65,128,32,"blocks",False,None), (4,64,128,32,"row_tokens",False,None),(4,65,128,32,"row_tokens",False,None), (17,64,128,32,"prefill_blocks",False,None),(17,65,256,64,"prefill_blocks",False,None), (4,65,256,64,"dense_mask",True,None),(4,66,256,64,"update_only",True,None), (4,65,256,64,"dense_mask",False,300),(4,65,256,64,"dense_mask",False,None), (1,64,128,32,"blocks",False,None)] for i,(rows,pos,rc,pc,mode,hidden,dense) in enumerate(cases): width=128 if hidden else 640 stride=width+(64 if i%2 else 0) source=pattern(rows*stride,232+i).reshape(1,rows,stride)[...,:width] raw=pattern(rc*128,250+i).reshape(1,rc,128) pool=pattern(pc*128,270+i).reshape(1,pc,128) front=[pos,pos+rows,(pos+rows)//4,pos//4] states=[mx.array(n,mx.int32) if i%2 else n for n in front] out=(core.select_hidden if hidden else core.select_qk_rows)(source,raw,pool,pos_start=states[0],total_tokens=states[1],logical_blocks=states[2],pooled_len=states[3],mode=mode,dense_output_tokens=dense) selected=[] if out.selection is None else list(out.selection) if isinstance(out.selection,tuple) else [out.selection] report=core.to_dict();report.pop("compiled_keys") emit(f"qsa_core_host_{i}",[*selected,out.raw_keys,out.pooled,out.pooled_len,out.offset],case=i,rows=rows,pos=pos,raw_capacity=rc,pooled_capacity=pc,mode=mode,hidden=hidden,dense=dense,frequencies=freq.tolist(),report=report) print(json.dumps(dict(kernel="qsa_core_report",report=core.to_dict()),separators=(",",":")),flush=True) invalid=[dict(pos=-1),dict(pos=127),dict(total=69),dict(total=-1),dict(logical=33),dict(logical=15),dict(frontier=0),dict(frontier=33),dict(raw_capacity=96),dict(raw_capacity=2),dict(pooled_capacity=0),dict(dense=100,mode="dense_mask"),dict(dense=1),dict(mode="prefill_blocks",rows=1),dict(width=639),dict(index_dtype="float32"),dict(index_dtype="int32",pos=127)] for i,change in enumerate(invalid): params=dict(pos=64,total=68,logical=17,frontier=16,raw_capacity=128,pooled_capacity=32,dense=None,mode="blocks",rows=4,width=640,index_dtype=None)|change x=mx.zeros((1,params["rows"],params["width"]),mx.bfloat16) raw=mx.zeros((1,params["raw_capacity"],128),mx.bfloat16);pool=mx.zeros((1,params["pooled_capacity"],128),mx.bfloat16) pos=mx.array(params["pos"],getattr(mx,params["index_dtype"])) if params["index_dtype"] else params["pos"] try: core.select_qk_rows(x,raw,pool,pos_start=pos,total_tokens=params["total"],logical_blocks=params["logical"],pooled_len=params["frontier"],mode=params["mode"],dense_output_tokens=params["dense"]) except (ValueError,TypeError):ok=True else:ok=False print(json.dumps(dict(kernel=f"qsa_core_invalid_{i}",params=params,rejected=ok),separators=(",",":")),flush=True) bad=make(lambda x:x@weight[:639].T) for i in range(2): try:bad.select_hidden(mx.zeros((1,4,128),mx.bfloat16),mx.zeros((1,128,128),mx.bfloat16),mx.zeros((1,32,128),mx.bfloat16),pos_start=64,total_tokens=68,logical_blocks=17,pooled_len=16,mode="blocks") except ValueError:ok=True else:ok=False print(json.dumps(dict(kernel=f"qsa_core_failed_trace_{i}",rejected=ok,report=bad.to_dict()),separators=(",",":")),flush=True) print(json.dumps(dict(kernel="qsa_core_report_after_invalid",report=core.to_dict()),separators=(",",":")),flush=True) def dynamic_slice_graph_fixtures(dtype_tag): """Original runtime dynamic slice/update; indices stay device arrays.""" assert mx.__version__=="0.32.2" dtype=getattr(mx,dtype_tag) profiles=[((1,16,8),(1,3,8),(1,),(5,),"plain"), ((1,16,8),(1,3,8),(1,),(12,),"stride"), ((1,16,8),(1,3,8),(1,),(6,),"transpose"), ((1,16,8),(1,3,8),(1,),(5,),"broadcast"), ((3,7,8),(2,3,4),(0,1,2),(1,2,3),"plain"), ((2,3,4,5),(1,2,3,4),(0,1,2,3),(1,1,1,1),"stride"), ((1,8,4),(1,2,4),(1,),(3,),"reverse"), ((1,8,4),(1,0,4),(1,),(2,),"plain"), ((1,8,4),(1,2,4),(-2,),(4,),"scalar_update"), ((1,16,128),(1,3,128),(1,),(5,),"plain")] for i,(shape,size,axes,values,kind) in enumerate(profiles): idx_dtype=getattr(mx,("int32","int64","uint32","uint64","int8","uint8","int16","uint16","int32","uint16")[i]) phys=shape[:-1]+(shape[-1]*2,) if kind=="stride" else shape if kind=="transpose":phys=(shape[0],shape[2],shape[1]) if kind=="broadcast":phys=(1,1,shape[-1]) a=pattern(int(np.prod(phys)),221).astype(dtype).reshape(phys) if kind=="stride":a=a[...,::2] if kind=="transpose":a=a.swapaxes(-1,-2) if kind=="broadcast":a=mx.broadcast_to(a,shape) if kind=="reverse":a=a[:,::-1,:] idx=mx.array(values,dtype=idx_dtype) if i==0:idx=idx.reshape(()) if i==2:idx=mx.array([values[0],99],dtype=idx_dtype)[:1] upd=pattern(int(np.prod(size)),222).astype(dtype).reshape(size) if kind=="scalar_update":upd=mx.array(0.5,dtype=mx.float32) sliced=mx.slice(a,idx,axes=axes,slice_size=size) changed=mx.slice_update(a,upd,idx,axes=axes) # Reuse outputs as subsequent input, mirroring moving cache windows. back=mx.slice(changed,idx,axes=axes,slice_size=size) emit(f"dynamic_slice_graph_{dtype_tag}_{i}",[sliced,changed,back],dtype=dtype_tag,idx_dtype=str(idx_dtype).split('.')[-1],profile=i,shape=shape,size=size,axes=axes,values=values,kind=kind,shapes=[x.shape for x in (sliced,changed,back)]) def qsa_prefill_graph_fixtures(dtype_tag): """Unmodified producer-selected prefill plus standalone strided top-k.""" from mtplx.kernels.qsa_indexer_prefill import (qsa_indexer_prefill_metal, qsa_indexer_prefill_scores_mpp_supported, qsa_indexer_prefill_score_chunk_rows, qsa_indexer_prefill_topk_metal) assert mx.__version__=="0.32.2" tf32=os.environ.get("MLX_ENABLE_TF32","1")!="0" profiles=[(2,4,128,513,512,4,2051,"plain",128*1024*1024), (65,4,128,1024,512,4,2051,"strided",1024*4*40), (17,4,128,37,7,3,80,"transpose",128*1024*1024), (5,2,7,17,3,3,9,"broadcast",128*1024*1024), (9,1,8,33,7,1,15,"mixed",33*4*3), (3,4,128,1,1,4,0,"plain",1), (33,4,128,64,7,4,128,"mixed",64*4*40)] for i,(rows,heads,dim,blocks,topk,ratio,pos,kind,budget) in enumerate(profiles): dtype=getattr(mx,dtype_tag) pdtype=(mx.float32 if i==4 else mx.float16 if dtype!=mx.float16 else mx.bfloat16) if kind=="mixed" else dtype def source(shape,salt,dtype): count=int(np.prod(shape));a=pattern(count,salt).astype(dtype) if dtype==mx.float32:a=a+mx.array((np.arange(count)%7).astype(np.float32)/65536) return a.reshape(shape) qs=(1,rows,dim,heads) if kind=="transpose" else (1,1 if kind=="broadcast" else rows,heads,dim*(2 if kind=="strided" else 1)) ps=(1,dim,blocks) if kind=="transpose" else (1,blocks,dim*(2 if kind=="strided" else 1)) q=source(qs,211,dtype);p=source(ps,212,pdtype) if kind=="transpose":q=q.swapaxes(-1,-2);p=p.swapaxes(-1,-2) if kind=="strided":q=q[...,::2];p=p[...,::2] if kind=="broadcast":q=mx.broadcast_to(q,(1,rows,heads,dim)) mpp=qsa_indexer_prefill_scores_mpp_supported(q,p) chunk=qsa_indexer_prefill_score_chunk_rows(rows,heads,blocks,budget,producer="mpp" if mpp else "mlx") total=pos+rows for mode in ("blocks","row_tokens","dense_mask"): out=qsa_indexer_prefill_metal(q,p,pos_start=pos,total_tokens=total,logical_blocks=total//ratio,block_topk=topk,compress_ratio=ratio,output_total_tokens=total+3,mode=mode,score_workspace_bytes=budget) outputs=[out] if mode=="dense_mask" else list(out) emit(f"qsa_prefill_graph_{dtype_tag}_{i}_{mode}_tf{int(tf32)}",outputs,dtype=dtype_tag,pdtype=str(pdtype).split('.')[-1],tf32=tf32,rows=rows,heads=heads,dim=dim,blocks=blocks,topk=topk,ratio=ratio,pos=pos,kind=kind,budget=budget,mpp=mpp,chunk=chunk,mode=mode,shapes=[a.shape for a in outputs]) if dtype_tag=="float32": for i,(rows,blocks,topk,ratio,pos,kind) in enumerate(((1,8193,512,1,8192,"stride"),(3,2049,7,4,8190,"transpose"),(2,65,3,3,7,"broadcast"))): shape=(blocks,rows) if kind=="transpose" else (1 if kind=="broadcast" else rows,blocks*2 if kind=="stride" else blocks) scores=pattern(int(np.prod(shape)),213).astype(mx.float32).reshape(shape) if kind=="transpose":scores=scores.T if kind=="stride":scores=scores[:,::2] if kind=="broadcast":scores=mx.broadcast_to(scores,(rows,blocks)) for mode in ("blocks","row_tokens","dense_mask"): total=pos+rows out=qsa_indexer_prefill_topk_metal(scores,pos_start=mx.array(pos,dtype=mx.int32),total_tokens=mx.array(total,dtype=mx.int32),logical_blocks=mx.array(total//ratio,dtype=mx.int32),block_topk=topk,compress_ratio=ratio,output_total_tokens=total+3,mode=mode) outputs=[out] if mode=="dense_mask" else list(out) emit(f"qsa_prefill_topk_graph_{i}_{mode}_tf{int(tf32)}",outputs,tf32=tf32,rows=rows,blocks=blocks,topk=topk,ratio=ratio,pos=pos,kind=kind,mode=mode,shapes=[a.shape for a in outputs]) def qsa_fused_graph_fixtures(dtype_tag): """Original selector factory and actual QSAIndexer chunking, no replacements.""" from types import SimpleNamespace from mtplx.models.qwen4_exp import QSAIndexer from mtplx.kernels.qsa_indexer_select import qsa_indexer_select_metal assert mx.__version__=="0.32.2" tf32=os.environ.get("MLX_ENABLE_TF32","1")!="0" profiles=[(1,4,128,513,512,4,2051,"plain"), (8,4,128,1024,512,4,2051,"strided"), (3,1,8,17,7,1,9,"transpose"), (5,2,7,5,3,3,7,"broadcast"), (2,4,64,0,1,4,0,"plain"), (2,4,64,5,1,4,0,"plain"), (129,1,8,65537,7,4,1024,"chunk")] for i,(rows,heads,dim,blocks,topk,ratio,pos,kind) in enumerate(profiles): qdtype=getattr(mx,dtype_tag) pdtype=mx.float32 if i==1 else (mx.float16 if i==2 else qdtype) def source(shape,salt,dtype): count=int(np.prod(shape)) a=pattern(count,salt).astype(dtype) if dtype==mx.float32: a=a+mx.array((np.arange(count)%7).astype(np.float32)/65536) return a.reshape(shape) qshape=(1,rows,dim,heads) if kind=="transpose" else (1,1 if kind=="broadcast" else rows,heads,dim*(2 if kind=="strided" else 1)) pshape=(1,dim,blocks) if kind=="transpose" else (1,blocks,dim*(2 if kind=="strided" else 1)) q=source(qshape,201,qdtype);p=source(pshape,202,pdtype) if kind=="transpose": q=q.swapaxes(-1,-2);p=p.swapaxes(-1,-2) if kind=="strided": q=q[...,::2];p=p[...,::2] if kind=="broadcast": q=mx.broadcast_to(q,(1,rows,heads,dim)) total=pos+rows;logical=total//ratio for mode in ("blocks","row_tokens","dense_mask"): if kind=="chunk": indexer=SimpleNamespace(block_topk=topk,ratio=ratio,_fused_score_scratch_bytes=32*1024*1024) # Bind the original helper, not a fixture implementation. from types import MethodType indexer._fused_query_chunk_rows=MethodType(QSAIndexer._fused_query_chunk_rows,indexer) out=QSAIndexer._select_fused(indexer,q,pos,p,logical,total,mode) else: out=qsa_indexer_select_metal(q,p,pos_start=pos,total_tokens=total,logical_blocks=logical, block_topk=topk,compress_ratio=ratio,output_total_tokens=total+3 if mode=="dense_mask" else None,mode=mode) outputs=[out] if mode=="dense_mask" else list(out) emit(f"qsa_fused_graph_{dtype_tag}_{i}_{mode}_tf{int(tf32)}",outputs,dtype=dtype_tag,pdtype=str(pdtype).split('.')[-1], tf32=tf32,profile=i,rows=rows,heads=heads,dim=dim,blocks=blocks,topk=topk,ratio=ratio,pos=pos,kind=kind,mode=mode,shapes=[a.shape for a in outputs]) def qsa_indexer_prefix_fixtures(dtype_tag): """Unmodified QSAIndexer call, stateful prefix/rollback, actual cache.""" import mlx.nn as nn from mtplx.models.qwen4_exp import QSAIndexer, QSACache assert mx.__version__=="0.32.2" tf32=os.environ.get("MLX_ENABLE_TF32","1")!="0" dtype=getattr(mx,dtype_tag) profiles=[(128,64,False,"dense"),(128,128,True,"dense"),(64,32,True,"supplied"), (256,64,True,"dense"),(128,64,True,"promoted")] if dtype_tag=="bfloat16": profiles += [(128,64,False,"q4"),(128,64,True,"q8")] for profile,(dim,rot,fused,kind) in enumerate(profiles): # Real supported reference configuration: eager selection with either # original preparation branch. S>=2 is not legacy-fused eligible; # decode-gather excludes that selector on S1. No method replacements. for key,value in dict(MTPLX_COMPILED_QSA_INDEXER=0,MTPLX_FUSED_QSA_INDEXER=int(fused), MTPLX_QSA_PREFILL=0,MTPLX_QSA_PREFILL_MIN_ROWS=2,MTPLX_QSA_GATHER=1, MTPLX_QSA_GATHER_MIN_CONTEXT=0,MTPLX_QSA_GATHER_MAX_ROWS=8, MTPLX_QSA_GATHER_DECODE=1,MTPLX_QSA_FLASH=0,MTPLX_QSA_SCORE_TILE_ROWS=0).items(): os.environ[key]=str(value) indexer=QSAIndexer.__new__(QSAIndexer) nn.Module.__init__(indexer) indexer.n_heads=4;indexer.kv_heads=1;indexer.head_dim=dim;indexer.ratio=4 indexer.block_topk=512;indexer.budget=2048;indexer.rms_norm_eps=1e-6 indexer._inv_freq=mx.array([1/(j+1) for j in range(rot//2)],dtype=mx.float32) indexer._rope_attention_scaling=1.125 indexer.q_layernorm=nn.RMSNorm(dim,eps=1e-6) indexer.k_layernorm=nn.RMSNorm(dim,eps=1e-6) norm_dtype=mx.float32 if kind=="promoted" else dtype indexer.q_layernorm.weight=pattern(dim,185).astype(norm_dtype) indexer.k_layernorm.weight=pattern(dim,186).astype(norm_dtype) if kind in ("q4","q8"): indexer.index_qk_proj=quantized_linear_fixture(5*dim,64,int(kind[1:]),64,187) else: indexer.index_qk_proj=nn.Linear(64,5*dim,bias=False) indexer.index_qk_proj.weight=pattern(5*dim*64,187).astype(dtype).reshape(5*dim,64) cache=QSACache() cache.reserve_indexer_capacity(raw_capacity=256,pooled_capacity=256) for step,(rows,trim) in enumerate(((3,0),(1,0),(5,0),(2041,0),(1,0),(4,0),(8,5),(33,0),(1,0))): if trim: cache.trim(trim) pos=cache.offset hidden=pattern(rows*64,190+step*7).astype(dtype).reshape(1,rows,64) qk=None if kind=="supplied": qk=pattern(rows*5*dim*2,191+step*7).astype(dtype).reshape(1,rows,5*dim*2)[...,::2] result=indexer(hidden,pos,cache,qk_rows=qk) outputs=[cache.raw_keys] names=["raw"] if cache.pooled is not None: outputs += [cache.pooled,cache.pooled_f32_t];names += ["pooled","mirror"] if result is None: lane="none" elif isinstance(result,tuple): lane=result[0];outputs+=list(result[1:]);names+=["indices","valid"] else: lane="decode_tokens" if result.ndim==1 else "dense";outputs.append(result);names.append("selection") emit(f"qsa_indexer_prefix_{dtype_tag}_{profile}_{step}_tf{int(tf32)}",outputs, dtype=dtype_tag,tf32=tf32,profile=profile,dim=dim,rot=rot,fused=fused,kind=kind, step=step,rows=rows,trim=trim,pos=pos,offset=cache.offset,pooled_len=cache.pooled_len, lane=lane,names=names,shapes=[a.shape for a in outputs]) assert cache.offset==pos # Only Attention advances this frontier. cache.kv.offset=pos+rows def qsa_eager_graph_fixtures(dtype_tag): """Actual QSAIndexer._select_eager with its actual QSACache and all exits.""" from types import SimpleNamespace, MethodType from mtplx.models.qwen4_exp import QSAIndexer, QSACache, _qsa_large_prefill_enabled from mtplx.attention_context import attention_phase assert mx.__version__=="0.32.2" tf32=os.environ.get("MLX_ENABLE_TF32","1")!="0" profiles=[(1,2051,4,512,0,m) for m in ("dense","flash","decode","all")] profiles += [(8,2052,4,512,t,m) for t,m in ((0,"dense"),(0,"rows"),(3,"rows"),(8,"rows"),(9,"rows"),(0,"min"),(0,"max"))] profiles += [(137,2052,4,512,t,m) for t,m in ((0,"prefill"),(31,"prefill"),(0,"all"),(31,"all"),(0,"verify"))] profiles += [(2048,4,4,512,0,"dense"),(2,32768,4,512,0,"prefill"), (33,32768,4,512,8,"prefill"),(1,4096,4,512,0,"decode"), (8,2052,8,512,0,"prefill"),(3,13,1,7,0,"rows"), (3,13,1,7,1,"dense"),(1,13,1,7,0,"flash")] for i,(rows,pos,ratio,topk,tile,mode) in enumerate(profiles): flash=mode in ("flash","all") decode=mode in ("decode","all") gather=mode in ("rows","all","min","max") prefill=mode in ("prefill","all","verify") phase="decode_verify" if mode=="verify" else "prefill" minimum=16384 if mode=="min" else 0 maximum=7 if mode=="max" else 8 for key,value in dict(MTPLX_QSA_FLASH=int(flash),MTPLX_QSA_GATHER_DECODE=int(decode), MTPLX_QSA_GATHER=int(gather),MTPLX_QSA_GATHER_MIN_CONTEXT=minimum,MTPLX_QSA_GATHER_MAX_ROWS=maximum, MTPLX_QSA_PREFILL=int(prefill),MTPLX_QSA_PREFILL_MIN_ROWS=2,MTPLX_QSA_PREFILL_MIN_CONTEXT=2049, MTPLX_QSA_SCORE_TILE_ROWS=tile).items(): os.environ[key]=str(value) total=pos+rows nb=total//ratio dtype=getattr(mx,dtype_tag) q=pattern(rows*4*128,181).astype(dtype) if dtype==mx.float32: q=q+mx.array((np.arange(q.size)%7).astype(np.float32)/65536) q=q.reshape(1,rows,4,128) pooled=pattern(nb*128,182).astype(dtype).reshape(1,nb,128) cache=QSACache(compress_ratio=ratio) cache.write_pooled(pooled,0,nb) indexer=SimpleNamespace(head_dim=128,ratio=ratio,block_topk=topk) indexer._tiled_topk=MethodType(QSAIndexer._tiled_topk,indexer) with attention_phase(phase): large=_qsa_large_prefill_enabled(rows,total) result=QSAIndexer._select_eager(indexer,q,pos,cache,pooled,total) tail=None if isinstance(result,tuple): lane=result[0] if lane=="flash": outputs=[result[1]];tail=result[2] else: outputs=list(result[1:]) else: lane="decode_tokens" if result.ndim==1 else "dense" outputs=[result] emit(f"qsa_eager_graph_{dtype_tag}_{i}_tf{int(tf32)}",outputs,dtype=dtype_tag,tf32=tf32, rows=rows,pos=pos,ratio=ratio,topk=topk,tile=tile,mode=mode,large=large,flash=flash,decode=decode, gather=gather,minimum=minimum,maximum=maximum,lane=lane,tail=tail,shapes=[a.shape for a in outputs]) def sort_graph_fixtures(dtype_tag): """All four original sort primitives, axis/layout and merge boundaries.""" assert mx.__version__ == "0.32.2" dtype=getattr(mx,dtype_tag) profiles=[((2,w),-1,"plain") for w in (1,128,129,256,257,512,513,1024,1025,2048,2049,4097,8193)] profiles += [((3,7,5),axis,kind) for axis,kind in ((0,"plain"),(1,"plain"),(2,"transpose"),(1,"strided"),(-1,"reverse"),(1,"broadcast"),(None,"transpose"))] profiles += [((2049,3),0,"plain"),((2,2049,3),1,"strided"),((4097,),0,"offset")] for i,(shape,axis,kind) in enumerate(profiles): physical=list(shape) if kind=="strided": physical[-1]*=2 if kind=="broadcast": physical[1]=1 count=int(np.prod(physical))+(kind=="offset") values=((np.arange(count,dtype=np.int64)*17+31)%257) if dtype_tag not in ("uint32","uint64"): values-=128 a=mx.array(values).astype(dtype) if kind=="offset": a=a[1:] a=a.reshape(physical) if kind=="transpose": a=a.swapaxes(0,-1) if kind=="strided": a=a[...,::2] if kind=="reverse": a=a[...,::-1] if kind=="broadcast": a=mx.broadcast_to(a,shape) width=a.size if axis is None else a.shape[axis] kth=-min(3,width) outputs=[mx.sort(a,axis=axis),mx.argsort(a,axis=axis),mx.partition(a,kth,axis=axis),mx.argpartition(a,kth,axis=axis)] emit(f"sort_graph_{dtype_tag}_{i}",outputs,dtype=dtype_tag,profile=i,shape=shape,axis=axis,kind=kind,kth=kth,output_shape=outputs[0].shape) def dense_float_fixtures(dtype_tag=None, start=0, end=None): """Pinned Matmul factory/backend including scalar, vector and empty cases.""" assert mx.__version__ == "0.32.2" tf32=os.environ.get("MLX_ENABLE_TF32","1")!="0" profiles=[(m,n,k,"plain",ta,tb) for m,n,k in ((3,5,128),(16,17,129),(40,40,127),(40,40,128)) for ta in (False,True) for tb in (False,True)] profiles += [(m,n,k,kind,ta,tb) for m,n,k,kind,ta,tb in ( (1,1,7,"vectors",False,False),(1,1,16385,"vectors",False,False), (1,17,64,"left-vector",False,False),(1,17,65,"left-vector",False,True), (7,1,65,"right-vector",False,False),(7,1,65,"right-vector",True,False), (1,1,129,"cross",False,False),(7,1,129,"cross",True,False), (5,7,64,"cross",False,True),(5,7,64,"copy",False,False), (5,7,64,"offset",False,True),(5,7,64,"collapse",False,True), (5,7,64,"flatten",False,True),(65,513,128,"plain",False,True), (2,2,4097,"plain",False,False),(193,17,8193,"plain",False,True), (0,5,7,"plain",False,False),(5,0,7,"plain",False,False), (5,7,0,"plain",False,False),(0,5,0,"flatten",False,False), (3,7,128,"mixed",False,True),(3,7,128,"mixed-f32",False,True), )] for dtype in (mx.bfloat16,mx.float16,mx.float32): tag=str(dtype).split('.')[-1] if dtype_tag is not None and tag!=dtype_tag: continue for i,(m,n,k,kind,ta,tb) in enumerate(profiles): if i=end): continue def source(shape,salt,typ): physical=list(shape) if kind=="copy": physical[-1]*=2 count=int(np.prod(physical))+(kind=="offset") a=pattern(count,salt).astype(typ) if typ==mx.float32: a=a+mx.array((np.arange(count)%7).astype(np.float32)/65536) if kind=="offset": a=a[1:] a=a.reshape(physical) return a[...,::2] if kind=="copy" else a abatch=(2,1) if kind=="cross" else ((3,) if kind in ("copy","offset","collapse","flatten") else ()) bbatch=(1,3) if kind=="cross" else ((3,) if kind in ("copy","offset") else ((1,) if kind=="collapse" else ())) adtype=mx.bfloat16 if kind.startswith("mixed") else dtype bdtype=(mx.float32 if kind=="mixed-f32" else mx.float16) if kind.startswith("mixed") else dtype a=source(abatch+((k,m) if ta else (m,k)),171,adtype) b=source(bbatch+((n,k) if tb else (k,n)),172,bdtype) if ta: a=a.swapaxes(-2,-1) if tb: b=b.swapaxes(-2,-1) if kind in ("left-vector","vectors"): a=a.reshape(k) if kind in ("right-vector","vectors"): b=b.reshape(k) out=a@b emit(f"dense_float_{tag}_{i}_tf{int(tf32)}",[out],dtype=tag,profile=i,m=m,n=n,k=k,kind=kind,ta=ta,tb=tb,tf32=tf32, a_dtype=str(adtype).split('.')[-1],b_dtype=str(bdtype).split('.')[-1],output_shape=out.shape) def sum_graph_fixtures(dtype_tag=None, start=0, end=None): """Original runtime reductions used by QSA/HC/PLE/GDN; no custom sums.""" assert mx.__version__ == "0.32.2" profiles = [ ((4096,), (0,), "plain"), ((4097,), (0,), "offset"), ((31,128), (-1,), "plain"), ((32,128), (-1,), "plain"), ((32,512), (1,), "plain"), ((32,513), (1,), "plain"), ((32,1024), (1,), "plain"), ((32,1025), (1,), "plain"), ((2,4097), (1,), "plain"), ((5,7), (1,), "plain"), ((1,1024,4,128), (2,), "plain"), ((1,137,4,513), (2,), "plain"), ((31,128), (0,), "plain"), ((32,128), (0,), "plain"), ((256,128), (0,), "plain"), ((257,128), (0,), "plain"), ((1023,17), (0,), "plain"), ((1024,17), (0,), "plain"), ((32768,2), (0,), "plain"), ((3,5,7,128), (0,2), "plain"), ((3,5,7,9,2,128), (0,2,4), "plain"), ((3,5,7,128), (0,3), "plain"), ((3,5,7,9,2,128), (0,2,5), "plain"), ((64,7,4), (0,2), "plain"), ((64,7,16), (0,2), "plain"), ((5,7,128), (-1,), "transpose"), ((5,7,128), (1,), "transpose"), ((5,7,128), (0,1,2), "transpose"), ((5,7,128), (-1,), "strided"), ((5,7,128), (0,), "strided"), ((5,7,128), (1,), "reverse"), ((5,7,128), (-1,), "broadcast"), ((5,7,128), (0,), "broadcast"), ((5,7,128), (0,1,2), "scalar"), ((1,7,1), (0,2), "offset"), ((0,7,128), (0,), "plain"), ((5,0,128), (-1,), "plain"), ((5,7,128), (), "plain"), ((257,32768), (0,), "plain"), ((16777217,), (0,), "plain"), ] for dtype in (mx.bfloat16,mx.float16,mx.float32): tag=str(dtype).split('.')[-1] if dtype_tag is not None and tag != dtype_tag: continue for i,(shape,axes,layout) in enumerate(profiles): if i=end): continue if i>=38 and dtype!=mx.float32: continue base=list(shape) if layout=="broadcast": base[0]=1 if layout=="strided": base[-1]*=2 n=int(np.prod(base)) a=pattern(1 if layout=="scalar" else n+(layout=="offset"),170).astype(dtype) if layout=="offset": a=a[1:] a=mx.broadcast_to(a.reshape(()),shape) if layout=="scalar" else a.reshape(base) if layout=="strided": a=a[...,::2] if layout=="reverse": a=a[...,::-1] if layout=="broadcast": a=mx.broadcast_to(a,shape) if layout=="transpose": a=a.swapaxes(0,1) for keep in (False,True): out=mx.sum(a,axis=axes,keepdims=keep) mean=mx.mean(a.astype(mx.float32),axis=axes,keepdims=keep) emit(f"sum_graph_{tag}_{i}_{keep}",[out,mean],dtype=tag,profile=i,shape=shape, axes=axes,layout=layout,keep=keep,output_shape=out.shape) def qsa_dense_mask_fixtures(): from mtplx.models.qwen4_exp import _qsa_blocks_to_dense_mask assert mx.__version__ == "0.32.2" for rows,pos,ratio,topk in ((1,0,4,0),(1,0,4,8),(2,1,4,8),(5,0,4,9), (8,3,4,17),(9,2045,4,512),(137,32767,4,512), (2048,2048,4,512),(5,2,1,9),(8,17,7,8),(0,0,4,0)): total=pos+rows for strided in (False,True): for empty in (False,True): cols=topk*(2 if strided else 1) ids=[];valid=[] for r in range(rows): for c in range(cols): slot=c//2 if strided else c candidate=(pos+r+1)//ratio-1-slot//2 ids.append(total if slot%11==5 else (-1 if slot%11==3 else candidate)) valid.append(not empty and slot%7!=2) ids=mx.array(ids,dtype=mx.int32).reshape(rows,cols) valid=mx.array(valid,dtype=mx.bool_).reshape(rows,cols) if strided: ids,valid=ids[:,::2],valid[:,::2] out=_qsa_blocks_to_dense_mask(ids,valid,pos_start=pos,total_tokens=total,compress_ratio=ratio) emit(f"qsa_dense_mask_{rows}_{pos}_{ratio}_{topk}_{strided}_{empty}",[out], rows=rows,pos=pos,ratio=ratio,topk=topk,strided=strided,empty=empty) def scatter_axis_graph_fixtures(): assert mx.__version__ == "0.32.2" for shape,axis in (((7,),0),((3,5),0),((3,5),1),((2,3,5),1)): for strided in (False,True): for scalar in (False,True): for src_layout in ("plain","scalar","offset","strided"): n=int(np.prod(shape)) if src_layout=="scalar": src=mx.broadcast_to(mx.array(False),shape) else: mult=2 if src_layout=="strided" else 1 src=(mx.arange(n*mult+1,dtype=mx.int32)%3==0) src=src[1:] if src_layout=="offset" else src[:n*mult] if src_layout=="strided": src=src[::2] src=src.reshape(shape) ishape=list(shape);ishape[axis]=2 size=int(np.prod(ishape)) mult=2 if strided else 1 idx=mx.arange(size*mult,dtype=mx.int64)//mult%2 idx=mx.where(idx==0,-1,0) if strided: idx=idx[::2] idx=idx.reshape(ishape) upd=mx.array(True) if scalar else (mx.arange(size,dtype=mx.int32)%3==0).reshape(ishape) out=mx.put_along_axis(src,idx,upd,axis=axis) emit(f"scatter_axis_{shape}_{axis}_{strided}_{scalar}_{src_layout}",[out], shape=shape,axis=axis,strided=strided,scalar=scalar,src_layout=src_layout) def sparse_attention_graph_fixtures(): """Actual MTPLX sparse attention consumers, never a dense substitute.""" from mtplx.kernels.qsa_flash_skip import qsa_flash_skip from mtplx.kernels.qsa_prefill_flash import qsa_prefill_flash, qsa_prefill_flash_supported assert mx.__version__ == "0.32.2" for dtype in (mx.bfloat16,mx.float16): tag=str(dtype).split('.')[-1] for heads,total,nsel in ((24,3,0),(24,4099,512),(2,2052,17)): for layout in ("plain","offset","strided"): cap=total+7 def source(shape,salt): n=int(np.prod(shape)) if layout=="offset": return pattern(n+1,salt).astype(dtype)[1:].reshape(shape) if layout=="strided": return pattern(n*2,salt).astype(dtype).reshape(*shape[:-1],shape[-1]*2)[...,::2] return pattern(n,salt).astype(dtype).reshape(shape) q=source((heads,256),111) k,v=source((1,2,cap,256),112),source((1,2,cap,256),113) ids=mx.arange(nsel*2 if layout=="strided" else nsel,dtype=mx.int32) if layout=="strided": ids=ids[::2] else: ids=ids*2 tail=(total//4)*4 out=qsa_flash_skip(q,k,v,ids,total,tail,0.0625) emit(f"sparse_skip_{tag}_{heads}_{total}_{layout}",[out],kind="skip",dtype=tag,heads=heads,total=total,nsel=nsel,layout=layout) for rows,pos in ((2,2050),(8,8191),(137,32767),(2048,2048)): for layout in ("plain","offset","strided","holes"): total=pos+rows;cap=total+7 def source(shape,salt): n=int(np.prod(shape)) if layout=="offset": return pattern(n+1,salt).astype(dtype)[1:].reshape(shape) if layout=="strided": return pattern(n*2,salt).astype(dtype).reshape(*shape[:-1],shape[-1]*2)[...,::2] return pattern(n,salt).astype(dtype).reshape(shape) q=source((1,rows,24,256),114).transpose(0,2,1,3) k,v=source((1,2,cap,256),115),source((1,2,cap,256),116) slots=mx.arange(512,dtype=mx.int32)[None,:] ids=mx.broadcast_to(slots,(rows,512)) valid=mx.broadcast_to((slots<17) | ((slots==511) if layout=="holes" else mx.array(False)),(rows,512)) if layout=="holes": ids=mx.where(slots==3,-1,mx.where(slots==5,total,ids)) if layout=="strided": ids=mx.stack([ids,ids],axis=-1).reshape(rows,1024)[:,::2] valid=mx.stack([valid,valid],axis=-1).reshape(rows,1024)[:,::2] assert qsa_prefill_flash_supported(q,k,v,ids,valid,pos_start=pos,total_tokens=total,scale=0.0625) out=qsa_prefill_flash(q,k,v,ids,valid,pos_start=pos,total_tokens=total,scale=0.0625) emit(f"sparse_prefill_{tag}_{rows}_{pos}_{layout}",[out],kind="prefill",dtype=tag,rows=rows,pos=pos,total=total,layout=layout) def qsa_prepare_graph_fixtures(*, dtype_tag=None, profile_only=None): """Actual parameterized MTPLX query/pool kernels, including traced starts.""" from mtplx.kernels.qsa_indexer_prepare import ( qsa_indexer_prepare_queries_metal,qsa_indexer_pool_keys_metal,qsa_indexer_prepare_supported) assert mx.__version__ == "0.32.2" profiles=((1,4,128,64,4,1e-6,1.0,0),(3,1,2,2,1,1e-4,1.25,-7), (7,3,17,16,7,0.0,0.5,2047),(137,7,64,32,3,1e-5,1.1,65535), (2048,2,128,128,8,1e-6,1.3,131071),(1,4,128,64,4,0.25,1.0,0)) for dtype in (mx.bfloat16,mx.float16,mx.float32): tag=str(dtype).split('.')[-1] if dtype_tag is not None and tag!=dtype_tag: continue for profile,(rows,heads,dim,rotary,ratio,eps,scale,pos) in enumerate(profiles): if profile_only is not None and profile!=profile_only: continue for layout in ("plain","offset","strided","broadcast"): def source(shape,salt,ty=dtype): n=int(np.prod(shape)) if layout=="broadcast": return mx.broadcast_to(pattern(1,salt).astype(ty),shape) if layout=="offset": return pattern(n+1,salt).astype(ty)[1:].reshape(shape) if layout=="strided": return pattern(n*2,salt).astype(ty).reshape(*shape[:-1],shape[-1]*2)[...,::2] return pattern(n,salt).astype(ty).reshape(shape) q=source((1,rows,heads,dim),160) keys=source((1,rows*ratio,dim),161) norm=source((dim,),162) freq=source((rotary//2,),163,mx.float32) start=pos if layout=="offset": start=mx.array([123,pos],dtype=mx.int32)[1:].reshape(1,1) elif layout=="strided": start=mx.array([[pos+5]],dtype=mx.int32)-5 elif layout=="broadcast": start=mx.array(pos,dtype=mx.int32) assert qsa_indexer_prepare_supported(q,norm,freq,expected_ndim=4) assert qsa_indexer_prepare_supported(keys,norm,freq,expected_ndim=3) out=qsa_indexer_prepare_queries_metal(q,norm,freq,pos_start=start,eps=eps,attention_scaling=scale) pooled=qsa_indexer_pool_keys_metal(keys,norm,freq,block_start=start,compress_ratio=ratio,eps=eps,attention_scaling=scale) emit(f"qsa_prepare_graph_{tag}_{profile}_{layout}",[out,pooled],dtype=tag,profile=profile, layout=layout,rows=rows,heads=heads,dim=dim,rotary=rotary,ratio=ratio,eps=eps,scale=scale,pos=pos) def qsa_cache_graph_fixtures(*, profile=None, deferred_only=None): """Actual positional QSACache methods, retaining Python array aliases.""" from types import SimpleNamespace from mtplx.models.qwen4_exp import QSACache,QSAIndexer assert mx.__version__ == "0.32.2" profiles=[(n,4,128,mx.bfloat16) for n in (0,1,255,256,257,1025)] profiles += [(257,1,17,mx.float16),(257,7,32,mx.float32)] for initial,ratio,dim,dtype in profiles: if profile is not None and (initial,ratio)!=tuple(profile): continue for deferred in (False,True): if deferred_only is not None and deferred!=deferred_only: continue cache=QSACache(ratio) outputs=[];snapshots=[];metadata=[] tag=str(dtype).split('.')[-1] actions=[("reserve",768,320),("append",initial,0),("snapshot",0,0), ("reserve",2049,769),("view",0,0),("append",3,0), ("trim",2,0),("append",4,0),("restore",0,0),("view",0,0), ("append",257,0),("trim",999999,0),("append",1,0), ("ensure",1025,0),("append",4,0)] def source(shape,salt,strided): n=int(np.prod(shape));mult=2 if strided else 1 a=pattern(n*mult,salt).astype(dtype).reshape(*shape[:-1],shape[-1]*mult) return a[...,::2] if strided else a def append(n,step): start=cache.offset;total=start+n cache.write_raw(source((1,n,dim),140+step*3,step%2==1)) old=min(cache.pooled_len,total//ratio) if total//ratio>old: cache.write_pooled(source((1,total//ratio-old,dim),141+step*3,step%2==1),old,total//ratio) cache.kv.update_and_fetch( source((1,n,2,256),142+step*3,False).transpose(0,2,1,3), source((1,n,2,256),143+step*3,False).transpose(0,2,1,3)) for step,(action,a,b) in enumerate(actions): extra={} if action=="reserve": cache.reserve_indexer_capacity(raw_capacity=a,pooled_capacity=b) elif action=="append": append(a,step) elif action=="snapshot": snapshots.append(cache.state) elif action=="trim": extra["trimmed"]=cache.trim(a) elif action=="restore": cache.state=snapshots[a] elif action=="view" and cache.pooled is not None: outputs.append(cache.pooled_f32_view(cache.pooled_len)) elif action=="ensure": indexer=SimpleNamespace(ratio=ratio,head_dim=dim) raw,pooled=QSAIndexer._ensure_compiled_backings(indexer,cache,dtype=dtype,pos_start=cache.offset,rows=a) assert raw is cache.raw_keys and pooled is cache.pooled current=[cache.kv.keys,cache.kv.values,cache.raw_keys,cache.pooled,cache.pooled_f32_t] if cache.kv.keys is not None: current.extend(cache.state) outputs.extend(v for v in current if v is not None) if not deferred: mx.eval(*(v for v in outputs if v is not None)) metadata.append(dict(action=action,a=a,b=b,offset=cache.offset,pooled_len=cache.pooled_len, capacities=[0 if v is None else v.shape[axis] for v,axis in zip(current[:5],(2,2,1,1,3))], reserved=[cache._reserved_raw_capacity,cache._reserved_pooled_capacity],nbytes=cache.nbytes,**extra)) emit(f"qsa_cache_graph_{initial}_{ratio}_{dim}_{tag}_{int(deferred)}",outputs, initial=initial,ratio=ratio,dim=dim,dtype=tag,deferred=deferred,actions=metadata, shapes=[list(v.shape) for v in outputs]) def kv_cache_graph_fixtures(): """Actual KVCache mutations, retaining old states across lazy updates.""" from mlx_lm.models.cache import KVCache for initial in (0,1,255,256,257,2048): for deferred in (False,True): cache=KVCache() outputs=[] snapshots=[] metadata=[] actions=[("append",initial),("append",3),("trim",2),("append",4), ("restore",0),("append",257),("trim",999999),("append",1)] for step,(action,n) in enumerate(actions): if action=="trim": trimmed=cache.trim(n) metadata.append(dict(action=action,n=n,trimmed=trimmed,offset=cache.offset)) continue if action=="restore": cache.state=snapshots[0] metadata.append(dict(action=action,n=n,offset=cache.offset)) continue k=pattern(n*2*256,104+step*2).reshape(1,n,2,256).transpose(0,2,1,3) v=pattern(n*2*256,105+step*2).reshape(1,n,2,256).transpose(0,2,1,3) state=cache.update_and_fetch(k,v) snapshots.append(state) current=[*state,cache.keys,cache.values] outputs.extend(current) if not deferred: mx.eval(*current) metadata.append(dict(action=action,n=n,offset=cache.offset,capacity=cache.keys.shape[2])) emit(f"kv_cache_graph_{initial}_{int(deferred)}",outputs,initial=initial,deferred=deferred,actions=metadata) def rope_graph_fixtures(): """Original Qwen RoPE functions, including static YaRN and vision axes.""" from types import SimpleNamespace from mtplx.models.qwen4_exp import (_rope_inv_freq_and_scaling, _rope_cos_sin, _mrope_cos_sin, _build_mrope_axes, _apply_partial_rope) assert mx.__version__ == "0.32.2" profiles = [ (64, 10000000., 1, 0, {}), (256, 10000., 7, 511, {}), (64, 10000000., 2048, 262143, dict(rope_type="yarn", factor=4., original_max_position_embeddings=262144)), (64, 10000., 7, 1048576, dict(rope_type="yarn", factor=1., original_max_position_embeddings=128)), (64, 10000., 64, 8191, dict(rope_type="yarn", factor=8., original_max_position_embeddings=4096, mscale=2., mscale_all_dim=1., truncate=False, beta_fast=4., beta_slow=4.)), (64, 10000., 7, 32767, dict(rope_type="yarn", factor=4., original_max_position_embeddings=128, attention_factor=0.75, beta_fast=0., beta_slow=0.)), ] for profile,(rot,base,rows,pos,parameters) in enumerate(profiles): inv,scale = _rope_inv_freq_and_scaling(SimpleNamespace(rotary_dim=rot, rope_theta=base, rope_parameters=parameters)) heads=24 if rows<=7 else 2 half=rot//2 section=[(half+2)//3,(half+1)//3,half//3] for mode in ("text","equal","interleaved","sections"): axes=_build_mrope_axes(section,mode!="sections") positions=mx.arange(pos,pos+rows,dtype=mx.int32) positions3=mx.stack([positions,positions+(0 if mode=="equal" else 7),positions+(0 if mode=="equal" else 19)]) cos,sin=(_rope_cos_sin(positions,inv,scale) if mode=="text" else _mrope_cos_sin(positions3,inv,mx.array(axes,mx.int32))) for strided in (False,True): width=512 if strided else 256 x=pattern(rows*heads*width,103).reshape(1,rows,heads,width) if strided: x=x[...,1::2] out=_apply_partial_rope(x,cos,sin) emit(f"rope_graph_{profile}_{mode}_{int(strided)}",[inv,cos,sin,out], rot=rot,base=base,rows=rows,pos=pos,parameters=parameters,heads=heads, mode=mode,strided=strided,section=section,axes=axes,scale=scale) def qsa_rows_attention_fixtures(): """Actual MTPLX per-row gathered attention, not a reconstructed formula.""" from mtplx.models.qwen4_exp import _qsa_rows_gather_attention assert mx.__version__ == "0.32.2" for heads,rows,total,count in ((24,1,33,8),(24,3,1057,1025),(24,8,4193,4097), (24,64,113,17),(2,3,33,8),(2,16,1057,1025)): for layout in ("plain","offset","strided"): q=pattern(rows*heads*256,97).reshape(1,rows,heads,256).transpose(0,2,1,3) def cached(salt): cap=total+7 if layout=="offset" else total*2 if layout=="strided" else total a=pattern(2*cap*256,salt).reshape(1,2,cap,256) return a[:,:,2:total+2] if layout=="offset" else a[:,:,::2] if layout=="strided" else a k,v=cached(98),cached(99) idx=(mx.arange(rows*count,dtype=mx.int32)*7%total).reshape(rows,count) ok=(mx.arange(rows*count,dtype=mx.int32).reshape(rows,count)%5)!=1 emit(f"qsa_rows_attention_h{heads}_s{rows}_t{total}_k{count}_{layout}", [_qsa_rows_gather_attention(q,k,v,idx,ok,0.0625)], heads=heads,rows=rows,total=total,count=count,layout=layout) def qsa_prefill_gather_fixtures(): """Actual portable prefill function, with its explicit per-tile evals.""" from mtplx.models.qwen4_exp import _qsa_prefill_gather_attention assert mx.__version__ == "0.32.2" for heads,rows,pos,ratio,topk in ((24,1,0,4,2),(24,7,3,4,2),(24,17,127,128,2), (24,17,511,128,2),(2,7,0,1,2),(2,2048,0,4,2)): for tile in (1,4,64) if rows<2048 else (64,2048): for strided in (False,True): cap=pos+rows+7 q=pattern(rows*heads*256,100).reshape(1,rows,heads,256).transpose(0,2,1,3) k=pattern(2*cap*256,101).reshape(1,2,cap,256) v=pattern(2*cap*256,102).reshape(1,2,cap,256) nb=(pos+np.arange(rows)+1)//ratio raw_ids=nb[:,None]-1-np.arange(topk)[None,:] raw_ok=raw_ids>=0 raw_ids=np.where(raw_ok,raw_ids,-999) if strided: ids=np.full((rows,topk*2),-888,dtype=np.int64);ids[:,1::2]=raw_ids ok=np.zeros((rows,topk*2),dtype=np.bool_);ok[:,1::2]=raw_ok ids=mx.array(ids)[:,1::2];ok=mx.array(ok)[:,1::2] else: ids=mx.array(raw_ids.astype(np.int32));ok=mx.array(raw_ok) calls=[]; original_eval=mx.eval def tracked(*a): calls.append([list(x.shape) for x in a]);return original_eval(*a) mx.eval=tracked try: out=_qsa_prefill_gather_attention(q,k,v,ids,ok,pos_start=pos,total_tokens=pos+rows, compress_ratio=ratio,scale=0.0625,tile_rows=tile) finally: mx.eval=original_eval emit(f"qsa_prefill_gather_h{heads}_s{rows}_p{pos}_r{ratio}_t{tile}_strided{int(strided)}",[out], heads=heads,rows=rows,pos=pos,ratio=ratio,topk=topk,tile=tile,strided=strided,evals=calls) def sdpa_vector_fixtures(): """Actual MTPLX runtime fused D256 SDPA, including the 2-pass boundaries.""" assert mx.__version__ == "0.32.2" assert not os.environ.get("MLX_SDPA_BLOCKS") for batch,heads,rows,total in ((1,24,1,17),(1,24,2,1023),(1,24,2,1024), (1,24,2,16384),(1,24,1,65536),(2,24,2,33)): for copied in (False,True): for mode in ("none","bool","add","causal"): step=2 if copied else 1 q=pattern(batch*rows*heads*256*step,103).reshape(batch,rows,heads,256*step)[...,::step].transpose(0,2,1,3) k=pattern(batch*2*(total+7)*256*step,104).reshape(batch,2,total+7,256*step)[:,:,2:total+2,::step] v=pattern(batch*2*(total+7)*256*step,105).reshape(batch,2,total+7,256*step)[:,:,2:total+2,::step] raw=np.arange(rows*total).reshape(rows,total)%3!=1 mask=mx.array(raw)[None,None] if mode=="bool" else mx.array(np.where(raw,0,-10),dtype=mx.bfloat16)[None,None] if mode=="add" else "causal" if mode=="causal" else None emit(f"sdpa_vector_b{batch}_h{heads}_s{rows}_t{total}_copy{int(copied)}_{mode}", [mx.fast.scaled_dot_product_attention(q,k,v,scale=0.0625,mask=mask)], batch=batch,heads=heads,rows=rows,total=total,copied=copied,mode=mode) def gather_array_fixtures(): """Pinned GatherQMM on the actual expert/broadcast/sliced Array layouts.""" assert mx.__version__ == "0.32.2" # x batches, rows per matrix, output width, input width, experts, routes, # layout, explicit lhs, explicit rhs, sorted, route rank. cases = [ (1,1,80,512,8,10,"plain",False,True,False,1), (4,1,80,512,8,40,"expert_slice",False,True,False,2), (7,1,81,64,8,70,"expert_slice",False,True,False,2), (2,33,80,512,8,8,"plain",True,True,False,1), (2,17,81,64,8,8,"transpose",True,True,False,1), (2,33,80,512,8,8,"expert_slice",True,True,False,1), (16,1,80,512,4,16,"plain",False,True,True,1), (256,1,80,512,4,256,"expert_slice",False,True,True,1), (16,1,80,512,4,16,"expert_slice",True,True,True,1), (2,4,80,512,8,8,"plain",True,False,True,1), (1,1,80,512,8,10,"rank2",False,True,False,1), (4,1,80,512,8,40,"input_slice",False,True,False,3), (32,1,80,512,4,32,"transpose",False,True,True,1), ] for bits,group in ((4,32),(4,64),(8,32),(8,64)): for case,(xb,m,n,k,e,r,layout,left,right,sorted_indices,rank) in enumerate(cases): extra = 2 if layout == "expert_slice" else 1 wp=k*bits//32;sp=k//group words=(np.arange(e*n*extra*wp,dtype=np.uint64)*2654435761+12345).astype(np.uint32) w=mx.array(words).reshape(e,n*extra,wp) s=(pattern(e*n*extra*sp,33)/64).reshape(e,n*extra,sp) b=(pattern(e*n*extra*sp,34)/64).reshape(e,n*extra,sp) if layout=="expert_slice":w=w[:,n:];s=s[:,n:];b=b[:,n:] x=pattern(xb*m*k*(2 if layout=="input_slice" else 1),32) if layout=="transpose": x=x.reshape(xb,k,m).transpose(0,2,1) w=w.reshape(e,wp,n).transpose(0,2,1) s=s.reshape(e,sp,n).transpose(0,2,1) b=b.reshape(e,sp,n).transpose(0,2,1) elif layout=="input_slice":x=x.reshape(xb,m,k*2)[...,::2] else:x=x.reshape(xb,m,k) if rank==2:x=x.reshape(1,xb,1,m,k) if rank==3:x=x.reshape(2,xb//2,1,m,k) if layout=="rank2":x=x.reshape(m,k) rhs=(np.arange(r,dtype=np.uint32)*5+2)%e if sorted_indices:rhs=np.sort(rhs) if rank>1: raw=np.zeros((xb,r//xb+3),np.int32);raw[:,1:1+r//xb]=rhs.reshape(xb,-1) rhs=mx.array(raw)[:,1:1+r//xb] rhs=rhs.reshape((1,xb,r//xb) if rank==2 else (2,xb//2,r//xb)) else:rhs=mx.array(rhs,mx.int32) lhs=mx.array((np.arange(r)*2+1)%xb,mx.int64) if left else None out=mx.gather_qmm(x,w,s,b,lhs_indices=lhs,rhs_indices=rhs if right else None, transpose=True,group_size=group,bits=bits,sorted_indices=sorted_indices) emit(f"gather_array_{case}_b{bits}_g{group}",[out],case=case,xb=xb,m=m,n=n,k=k,e=e,r=r, layout=layout,left=left,right=right,sorted=sorted_indices,rank=rank,bits=bits,group=group,shape=out.shape) def emit(name, outputs, **metadata): mx.eval(*outputs) # Some original-runtime empty Matmul results have a null data pointer; # numpy.asarray crashes although mx.eval succeeded. No bytes exist to read. print(json.dumps({"kernel": name, "sha256": [hashlib.sha256( b"" if value.size == 0 else np.asarray(value.astype(mx.float32)).astype('=2. def part(cols,packed=False,salt=3): shape=(cols,17) if layout=="transpose" else (18,cols) if layout=="offset" else (17,cols) count=int(np.prod(shape)) a=mx.array((np.arange(count,dtype=np.uint64)*2654435761+12345).astype(np.uint32)) if packed else (pattern(count,salt)/64).astype(dtype) a=a.reshape(shape) return a.T if layout=="transpose" else a[1:] if layout=="offset" else a table=NGramTable(17,width,sidecar=True) table._lazy_parts=(part(width*bits//32,True),part(width//32),part(width//32,salt=4)) if bits else (part(width),None,None) table._lazy_bits=bits;table._lazy_group=32 shapes={"vector":(7,),"scalar":(),"matrix":(2,7),"head3":(2,4,16),"head4":(2,2,4,16),"slice":(2,9,16),"broadcast":(1,1,16)} shape=shapes[ids_layout];count=int(np.prod(shape)) ids=mx.array(((np.arange(count,dtype=np.int64)*7)%34)-17).reshape(shape) if ids_layout=="slice": ids=ids[:,1::2,:] if ids_layout=="broadcast": ids=mx.broadcast_to(ids,(2,4,16)) emit(f"ngram_resident_{str(dtype).split('.')[-1]}_b{bits}_w{width}_{layout}_{ids_layout}",[table._lazy_gather(ids)], dtype=str(dtype).split('.')[-1],bits=bits,width=width,layout=layout,ids_layout=ids_layout) def hyper_forward_fixtures(): """Actual GatedResidual, including selection and persistent module pack.""" from mtplx.models.qwen4_exp import GatedResidual, TextArgs from mtplx.kernels import hyper_connection as hc, hyper_connection_v3 as v3 calls=[] original_read,original_v3=hc.fused_hyper_read,v3.fused_hyper_read_v3 def read(*args,**kwargs): calls.append("fused") return original_read(*args,**kwargs) def read_v3(*args,**kwargs): calls.append("v3") return original_v3(*args,**kwargs) hc.fused_hyper_read,v3.fused_hyper_read_v3=read,read_v3 try: for layout in ("dense","quantized"): for combine in (False,True): layer=GatedResidual(TextArgs(),use_combine=combine) layer.hc_norm.weight=pattern(10240,2) names=[("input_mix_weight_down",320,10240,3),("input_mix_weight_up",10240,320,4)] if combine: names.append(("block_inject_weight",4,10240,5)) for name,n,k,salt in names: if layout=="dense": getattr(layer,name).weight=pattern(n*k,salt).reshape(n,k) else: setattr(layer,name,quantized_linear_fixture(n,k,4,64,salt)) for rows in (1,2,4,8,15,16,32,2048): for mode in range(4): os.environ["MTPLX_FUSED_HC"]=str(mode & 1) os.environ["MTPLX_FUSED_HC_V3"]=str(bool(mode & 2)).lower() x=pattern(rows*10240,1).reshape(1,rows,10240) calls.clear() output=layer(x) selected=calls[-1] if calls else "eager" if combine: mixed,hyper,inject=output assert hyper is x output=[mixed,inject] else: output=[output] emit(f"hyper_forward_{layout}_combine{int(combine)}_r{rows}_mode{mode}",output, layout=layout,combine=combine,rows=rows,mode=mode,selected=selected,pack_exists=getattr(layer,"_v3_pack",None) is not None) finally: hc.fused_hyper_read,v3.fused_hyper_read_v3=original_read,original_v3 def ngram_rows_fixtures(): """Actual NGramEmbedding CPU stage hash; raw I64, EOS and continuation.""" from mtplx.models.qwen4_exp import NGramEmbedding, TextArgs layer=NGramEmbedding(TextArgs(ngram_sidecar=True,eos_token_id=248044),0) mult,sizes,offsets=layer._np_consts() print(json.dumps(dict(contract=True,multipliers=mult.tolist(),sizes=sizes.tolist(), offsets=offsets.tolist(),eos=layer.eos_id)),flush=True) def ids(n,salt): palette=np.array([0,1,42,layer.eos_id,layer.eos_id,248000,-1,2**63-1,-2**63,43],dtype=np.int64) return palette[(np.arange(n)*7+salt)%len(palette)] for batch in (1,2): for rows in (0,1,4,2048): for prev_len in (0,1,2,5): prev=ids(batch*prev_len,3).reshape(batch,prev_len) for step,tokens in enumerate((rows,1)): values=ids(batch*tokens,step).reshape(batch,tokens) result,history=layer._rows_np(values,prev) print(json.dumps(dict(kernel=f"ngram_rows_b{batch}_r{rows}_p{prev_len}_step{step}", batch=batch,rows=rows,prev_len=prev_len,step=step, result_shape=list(result.shape),history_shape=list(history.shape), sha256=[hashlib.sha256(np.asarray(v).astype('=0: cache[3]=mx.array(ids(batch*prev_len,3).reshape(batch,prev_len)) for step,tokens in enumerate((rows,1)): values=mx.array(ids(batch*tokens,step).reshape(batch,tokens)) result=layer._graph_path(values,cache,3) mx.eval(result,cache[3]) print(json.dumps(dict(kernel=f"ngram_gpu_b{batch}_r{rows}_p{prev_len}_step{step}", batch=batch,rows=rows,prev_len=prev_len,step=step, result_shape=list(result.shape),history_shape=list(cache[3].shape), sha256=[hashlib.sha256(np.asarray(v).astype('