MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / tests / test_nan_scan.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Scan each layer for NaN introduction in Qwen3-30B-A3B inference.""" |
| 3 | import sys, os, time, ctypes, numpy as np |
| 4 | os.environ['OMP_NUM_THREADS']='32' |
| 5 | sys.path.insert(0,'/onedev-workspace/work/src/mojollama/kernels') |
| 6 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 7 | |
| 8 | e=TurboEngineV7MoE('/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf',32) |
| 9 | lib=ctypes.CDLL('/onedev-workspace/work/src/mojollama/kernels/cengine_batch_instr.so') |
| 10 | cv=ctypes.c_void_p;ci=ctypes.c_int |
| 11 | |
| 12 | L,N,NH,NKH,HD,FF,V=e.n_layers,e.n_embd,e.n_head,e.n_kv_head,e.head_dim,e.n_ff,e.vocab_size |
| 13 | S=max(N,NH*HD,FF,NKH*HD,e.n_ff_expert) |
| 14 | |
| 15 | class BC(ctypes.Structure): |
| 16 | _fields_=[('L',ci),('N',ci),('NH',ci),('NKH',ci),('HD',ci),('FF',ci),('V',ci),('eps',ctypes.c_float), |
| 17 | ('wQ',cv),('wK',cv),('wV',cv),('wO',cv),('wG',cv),('wU',cv),('wD',cv), |
| 18 | ('wAN',cv),('wFN',cv),('nQ',cv),('nK',cv),('nV',cv),('nO',cv),('nG',cv),('nU',cv),('nD',cv), |
| 19 | ('nc',ci),('emb',cv),('onw',cv),('wOut',cv),('outNR',ci),('outNC',ci),('outQuant',ci), |
| 20 | ('kv_array',cv),('logits',cv),('n_experts',ci),('n_experts_per_tok',ci),('moe_intermediate',ci), |
| 21 | ('w_gate_inp',cv),('w_gate_exps',cv),('w_up_exps',cv),('w_down_exps',cv), |
| 22 | ('gate_exp_quant',ci),('up_exp_quant',ci),('down_exp_quant',ci), |
| 23 | ('q_quant',cv),('k_quant',cv),('v_quant',cv),('o_quant',cv), |
| 24 | ('g_quant',cv),('u_quant',cv),('d_quant',cv),('emb_quant',ci), |
| 25 | ('cos_table',cv),('sin_table',cv),('max_ctx',ci), |
| 26 | ('workspace',cv),('ws_size',ci)] |
| 27 | class KVBlock(ctypes.Structure): |
| 28 | _fields_=[('k',cv),('v',cv),('n_blocks',ci),('seq_len',ci*64),('block_map',(ci*1024)*64)] |
| 29 | lib.batch_forward.argtypes=[cv,cv,ci,cv];lib.batch_forward.restype=None |
| 30 | lib.kv_init.argtypes=[cv,ci,ci,ci];lib.kv_init.restype=None |
| 31 | |
| 32 | def build_bc(weights_setup=True): |
| 33 | bc=BC() |
| 34 | for a,v in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',e.eps),('nc',N),('outNR',V),('outNC',N),('outQuant',8),('n_experts',e.n_experts),('n_experts_per_tok',e.n_experts_per_tok),('moe_intermediate',e.n_ff_expert),('gate_exp_quant',12),('up_exp_quant',12),('down_exp_quant',14),('emb_quant',0)]: |
| 35 | setattr(bc,a,v) |
| 36 | |
| 37 | if weights_setup: |
| 38 | wQ,wK,wV,wO,wG,wU,wD,wAN,wFN=[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L |
| 39 | nQ,nK,nV,nO,nG,nU,nD=[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L |
| 40 | qQ,qK,qV,qO,qG,qU,qD=[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L,[0]*L |
| 41 | for i,lw in enumerate(e._layers): |
| 42 | for atr,nm in [('attn_q','Q'),('attn_k','K'),('attn_v','V'),('attn_out','O'),('ffn_gate','G'),('ffn_up','U'),('ffn_down','D')]: |
| 43 | if hasattr(lw,f'{atr}_raw'):rw=getattr(lw,f'{atr}_raw');nr=getattr(lw,f'{atr}_nr').value;qt=getattr(lw,f'{atr}_qt').value |
| 44 | else:f32=getattr(lw,f'{atr}_f32');rw=f32.ctypes.data_as(cv)if f32 is not None else cv(0);nr=f32.shape[0]if f32 is not None else 0;qt=0 |
| 45 | t=nm |
| 46 | if t=='Q':wQ[i]=rw;nQ[i]=nr;qQ[i]=qt |
| 47 | elif t=='K':wK[i]=rw;nK[i]=nr;qK[i]=qt |
| 48 | elif t=='V':wV[i]=rw;nV[i]=nr;qV[i]=qt |
| 49 | elif t=='O':wO[i]=rw;nO[i]=nr;qO[i]=qt |
| 50 | elif t=='G':wG[i]=rw;nG[i]=nr;qG[i]=qt |
| 51 | elif t=='U':wU[i]=rw;nU[i]=nr;qU[i]=qt |
| 52 | elif t=='D':wD[i]=rw;nD[i]=nr;qD[i]=qt |
| 53 | wAN[i]=lw.attn_norm_w.ctypes.data_as(cv);wFN[i]=lw.ffn_norm_w.ctypes.data_as(cv) |
| 54 | w_gi,w_ge,w_ue,w_de=[0]*L,[0]*L,[0]*L,[0]*L |
| 55 | for i in range(L): |
| 56 | if e.is_moe: |
| 57 | me2=e._moe_layers[i] |
| 58 | w_gi[i]=me2.router_f32.ctypes.data_as(cv)if me2.router_f32 is not None else cv(0) |
| 59 | if me2.gate_raw and len(me2.gate_raw)>0:w_ge[i]=me2.gate_raw[0].ctypes.data_as(cv) |
| 60 | if me2.up_raw and len(me2.up_raw)>0:w_ue[i]=me2.up_raw[0].ctypes.data_as(cv) |
| 61 | if me2.down_raw and len(me2.down_raw)>0:w_de[i]=me2.down_raw[0].ctypes.data_as(cv) |
| 62 | bc.wQ=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wQ]),cv) |
| 63 | bc.wK=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wK]),cv) |
| 64 | bc.wV=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wV]),cv) |
| 65 | bc.wO=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wO]),cv) |
| 66 | bc.wG=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wG]),cv) |
| 67 | bc.wU=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wU]),cv) |
| 68 | bc.wD=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wD]),cv) |
| 69 | bc.wAN=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wAN]),cv) |
| 70 | bc.wFN=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in wFN]),cv) |
| 71 | bc.nQ=ctypes.cast((ci*L)(*[int(t)for t in nQ]),cv) |
| 72 | bc.nK=ctypes.cast((ci*L)(*[int(t)for t in nK]),cv) |
| 73 | bc.nV=ctypes.cast((ci*L)(*[int(t)for t in nV]),cv) |
| 74 | bc.nO=ctypes.cast((ci*L)(*[int(t)for t in nO]),cv) |
| 75 | bc.nG=ctypes.cast((ci*L)(*[int(t)for t in nG]),cv) |
| 76 | bc.nU=ctypes.cast((ci*L)(*[int(t)for t in nU]),cv) |
| 77 | bc.nD=ctypes.cast((ci*L)(*[int(t)for t in nD]),cv) |
| 78 | bc.q_quant=ctypes.cast((ci*L)(*[int(t)for t in qQ]),cv) |
| 79 | bc.k_quant=ctypes.cast((ci*L)(*[int(t)for t in qK]),cv) |
| 80 | bc.v_quant=ctypes.cast((ci*L)(*[int(t)for t in qV]),cv) |
| 81 | bc.o_quant=ctypes.cast((ci*L)(*[int(t)for t in qO]),cv) |
| 82 | bc.g_quant=ctypes.cast((ci*L)(*[int(t)for t in qG]),cv) |
| 83 | bc.u_quant=ctypes.cast((ci*L)(*[int(t)for t in qU]),cv) |
| 84 | bc.d_quant=ctypes.cast((ci*L)(*[int(t)for t in qD]),cv) |
| 85 | bc.w_gate_inp=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in w_gi]),cv) |
| 86 | bc.w_gate_exps=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in w_ge]),cv) |
| 87 | bc.w_up_exps=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in w_ue]),cv) |
| 88 | bc.w_down_exps=ctypes.cast((cv*L)(*[ctypes.cast(t,cv)for t in w_de]),cv) |
| 89 | bc.emb=e.emb.ctypes.data_as(cv) |
| 90 | bc.onw=e._out_norm_w.ctypes.data_as(cv) |
| 91 | bc.wOut=ctypes.cast(e._out_raw,cv) |
| 92 | |
| 93 | hd2=HD//2;mc=4096 |
| 94 | freq_v=e.rope_freq_base**(np.arange(0,HD,2,dtype=np.float32)/HD) |
| 95 | ang=np.arange(mc,dtype=np.float32).reshape(-1,1)/freq_v.reshape(1,-1) |
| 96 | ct=np.cos(ang).astype(np.float32).reshape(-1);st=np.sin(ang).astype(np.float32).reshape(-1) |
| 97 | bc.cos_table=ct.ctypes.data_as(cv);bc.sin_table=st.ctypes.data_as(cv);bc.max_ctx=mc |
| 98 | |
| 99 | return bc |
| 100 | |
| 101 | bc=build_bc() |
| 102 | s=np.zeros(12*S,dtype=np.float32) |
| 103 | lb=np.zeros(V,dtype=np.float32) |
| 104 | kv=KVBlock();lib.kv_init(ctypes.byref(kv),ci(L),ci(NKH),ci(HD)) |
| 105 | kva=(cv*1)(ctypes.cast(ctypes.pointer(kv),cv)) |
| 106 | bc.kv_array=ctypes.cast(kva,cv);bc.logits=lb.ctypes.data_as(cv) |
| 107 | |
| 108 | # Run all layers first |
| 109 | bc.L=L |
| 110 | lib.batch_forward(ctypes.byref(bc),(ci*1)(785),ci(1),s.ctypes.data_as(cv)) |
| 111 | nan_all=np.isnan(lb[:V]).sum() |
| 112 | print(f'Full {L}-layer: NaN={nan_all}/{V}', flush=True) |
| 113 | |
| 114 | # If all NaN, find where NaN first appears by running 1 layer at a time |
| 115 | print('\nBinary search for NaN introduction...', flush=True) |
| 116 | lo, hi = 1, L |
| 117 | while lo < hi: |
| 118 | mid = (lo + hi) // 2 |
| 119 | bc_i=build_bc() |
| 120 | si=np.zeros(12*S,dtype=np.float32) |
| 121 | lbi=np.zeros(V,dtype=np.float32) |
| 122 | kvi=KVBlock();lib.kv_init(ctypes.byref(kvi),ci(L),ci(NKH),ci(HD)) |
| 123 | kvai=(cv*1)(ctypes.cast(ctypes.pointer(kvi),cv)) |
| 124 | bc_i.kv_array=ctypes.cast(kvai,cv);bc_i.logits=lbi.ctypes.data_as(cv) |
| 125 | bc_i.L=mid |
| 126 | lib.batch_forward(ctypes.byref(bc_i),(ci*1)(785),ci(1),si.ctypes.data_as(cv)) |
| 127 | nan_c=np.isnan(lbi[:V]).sum() |
| 128 | print(f' L=0..{mid-1}: NaN={nan_c}/{V}', flush=True) |
| 129 | if nan_c > 0: |
| 130 | hi = mid |
| 131 | else: |
| 132 | lo = mid + 1 |
| 133 | |
| 134 | print(f'\nNaN first appears at layer {lo}', flush=True) |
| 135 | if lo > 0: |
| 136 | print(f'Re-running up to layer {lo-1} with NaN checks...', flush=True) |