Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/debug_layer_trace.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / debug_layer_trace.py` 221 lines ยท 9132 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Layer-by-layer hidden state comparison between step 1 and step 2.""" 3 import sys, os, numpy as np 4 sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels') 5 6 os.environ['OMP_NUM_THREADS'] = '1' 7 os.environ['OPENBLAS_NUM_THREADS'] = '1' 8 9 from turbo_engine_v7_moe import TurboEngineV7MoE 10 11 print("Loading model...", flush=True) 12 e = TurboEngineV7MoE('/tmp/models/gpt-oss-20b-Q4_K_M.gguf', n_threads=1) 13 print("Model loaded.", flush=True) 14 15 # Save original forward and monkey-patch for instrumentation 16 original_forward = TurboEngineV7MoE.forward 17 18 def instrumented_forward(self, token_id, _call_id=0): 19 """Instrumented forward that saves hidden state at each layer.""" 20 import functools 21 22 # Create unique call tracking 23 if not hasattr(self, '_inst_call_count'): 24 self._inst_call_count = 0 25 self._inst_call_count += 1 26 call_id = self._inst_call_count 27 28 # Store hidden_state snapshots per layer 29 if not hasattr(self, '_inst_hidden_states'): 30 self._inst_hidden_states = {} 31 self._inst_hidden_states[call_id] = [] 32 33 b_x = self._x; b_r = self._residual; b_qn = self._x_norm 34 b_q = self._q; b_k = self._k; b_v = self._v 35 b_att = self._att_out; b_gate = self._gate; b_up = self._up 36 b_silu = self._silu_gate; b_ffn = self._ffn_out 37 b_oproj = self._o_proj 38 N = self.n_embd; NH = self.n_head; NKH = self.n_kv_head * self.head_dim; HD = self.head_dim 39 FF = self.n_ff; L = self.n_layers 40 kern = self._kern; simd = self._simd 41 eps_f = self._eps_f 42 p_x = self._p_x; p_xn = self._p_x_norm; p_r = self._p_residual 43 p_q = self._p_q; p_k = self._p_k; p_v = self._p_v 44 p_qk = self._p_qk 45 p_att = self._p_att_out; p_gate = self._p_gate; p_up = self._p_up 46 p_silu = self._p_silu_gate; p_oproj = self._p_o_proj 47 p_ffn = self._p_ffn; p_logits = self._p_logits 48 49 # Embedding lookup 50 np.copyto(b_x, self.emb[token_id]) 51 52 # Save embedding 53 if call_id <= 2: 54 print(f" [Call {call_id}] Embedding _x[:5] = {self._x[:5].copy()}", flush=True) 55 56 cf = ctypes.POINTER(ctypes.c_float) 57 cu = ctypes.POINTER(ctypes.c_uint8) 58 ci = ctypes.c_int 59 60 for i in range(L): 61 lw = self._layers[i] 62 is_ssm_layer = (self.layer_types is not None and self.layer_types[i] == 1) 63 64 b_r[:] = b_x 65 simd.rms_norm(p_xn, p_x, 66 lw.attn_norm_w.ctypes.data_as(cf), 67 N, eps_f) 68 69 if is_ssm_layer and self._cengine is not None and lw.ssm_conv1d_ptr is not None: 70 # SSM path (not used for gpt-oss) 71 pass 72 else: 73 # Attention path 74 if hasattr(lw, 'attn_qkv_use_c') and lw.attn_qkv_use_c: 75 pass # fused QKV 76 elif hasattr(lw, 'attn_qk_use_c') and lw.attn_qk_use_c: 77 kern.quant_matmul_omp(lw.attn_qk_raw, p_xn, p_qk, 78 lw.attn_qk_nr, lw.attn_qk_nc, lw.attn_qk_qt) 79 kern.quant_matmul_omp(lw.attn_v_raw, p_xn, p_v, 80 lw.attn_v_nr, lw.attn_v_nc, lw.attn_v_qt) 81 elif lw.attn_q_use_c and lw.attn_k_use_c and lw.attn_v_use_c: 82 kern.batch_qkv_omp( 83 lw.attn_q_raw, lw.attn_k_raw, lw.attn_v_raw, 84 p_xn, p_q, p_k, p_v, 85 lw.attn_q_nr, lw.attn_k_nr, lw.attn_v_nr, 86 lw.attn_q_nc, 87 lw.attn_q_qt, lw.attn_k_qt, lw.attn_v_qt) 88 else: 89 if lw.attn_q_use_c: 90 kern.quant_matmul_omp(lw.attn_q_raw, p_xn, p_q, lw.attn_q_nr, lw.attn_q_nc, lw.attn_q_qt) 91 if lw.attn_k_use_c: 92 kern.quant_matmul_omp(lw.attn_k_raw, p_xn, p_k, lw.attn_k_nr, lw.attn_k_nc, lw.attn_k_qt) 93 if lw.attn_v_use_c: 94 kern.quant_matmul_omp(lw.attn_v_raw, p_xn, p_v, lw.attn_v_nr, lw.attn_v_nc, lw.attn_v_qt) 95 96 # Q/K norm 97 if lw.has_q_norm: 98 q_2d = b_q.reshape(NH, HD) 99 q_rms = np.sqrt(np.mean(q_2d * q_2d, axis=1, keepdims=True) + self.eps) 100 q_2d[:] = q_2d / q_rms * lw.q_norm_w.reshape(1, HD) 101 if lw.has_k_norm: 102 k_2d = b_k[:NKH].reshape(self.n_kv_head, HD) 103 k_rms = np.sqrt(np.mean(k_2d * k_2d, axis=1, keepdims=True) + self.eps) 104 k_2d[:] = k_2d / k_rms * lw.k_norm_w.reshape(1, HD) 105 106 # RoPE 107 rope_d = self.rope_dim if hasattr(self, 'rope_dim') and self.rope_dim > 0 else HD 108 b_q[:] = self._apply_rope_fast(b_q, self.pos, NH, rope_dim=rope_d) 109 b_k[:] = self._apply_rope_fast(b_k, self.pos, self.n_kv_head, rope_dim=rope_d) 110 111 # KV cache 112 self.kv_k[i, self.kv_len[i], :NKH] = b_k[:NKH] 113 self.kv_v[i, self.kv_len[i], :NKH] = b_v[:NKH] 114 115 # GQA Attention 116 seq_len = self.kv_len[i] + 1 117 if self._gqa_attn is not None and seq_len <= 4096: 118 self._gqa_attn.gqa_attention_decode( 119 b_q.ctypes.data_as(cf), 120 self.kv_k[i].ctypes.data_as(cf), 121 self.kv_v[i].ctypes.data_as(cf), 122 b_att.ctypes.data_as(cf), 123 ci(seq_len), ci(NH), ci(self.n_kv_head), ci(HD), 124 self._p_gqa_ws) 125 else: 126 k_cache = self.kv_k[i, :seq_len].reshape(seq_len, self.n_kv_head, HD) 127 v_cache = self.kv_v[i, :seq_len].reshape(seq_len, self.n_kv_head, HD) 128 q_2d = b_q.reshape(NH, HD) 129 nk = self.n_kv_head; gqa = self._gqa_rep 130 q_g = q_2d.reshape(nk, gqa, HD) 131 k_T = k_cache.transpose(1, 0, 2) 132 scores = np.einsum('khd,ksd->khs', q_g, k_T) / np.sqrt(float(HD)) 133 scores = scores.reshape(NH, seq_len) 134 scores -= np.max(scores, axis=1, keepdims=True) 135 np.exp(scores, out=scores) 136 scores /= np.sum(scores, axis=1, keepdims=True) 137 v_T = v_cache.transpose(1, 0, 2) 138 att = np.einsum('khs,ksd->khd', scores.reshape(nk, gqa, seq_len), v_T) 139 b_att[:] = att.reshape(-1) 140 self.kv_len[i] += 1 141 142 # Output projection 143 if hasattr(lw, 'attn_gate_use_c') and lw.attn_gate_use_c: 144 pass # Qwen3.6 specific 145 else: 146 if lw.attn_out_use_c: 147 kern.quant_matmul_omp(lw.attn_out_raw, p_att, p_oproj, 148 lw.attn_out_nr, lw.attn_out_nc, lw.attn_out_qt) 149 b_x[:N] = b_r[:N] + b_oproj[:N] 150 else: 151 b_x[:N] = b_r[:N] + (lw.attn_out_f32 @ b_att)[:N] 152 153 # FFN 154 b_r[:] = b_x 155 simd.rms_norm(p_xn, p_x, 156 lw.ffn_norm_w.ctypes.data_as(cf), 157 N, eps_f) 158 159 if self.is_moe and self._moe_layers: 160 self._forward_moe(i, p_xn, b_ffn, b_r, N) 161 else: 162 if lw.ffn_gate_use_c and lw.ffn_up_use_c: 163 kern.batch_gate_up_omp( 164 lw.ffn_gate_raw, lw.ffn_up_raw, p_xn, p_gate, p_up, 165 lw.ffn_gate_nr, lw.ffn_up_nr, 166 lw.ffn_gate_nc, lw.ffn_gate_qt, lw.ffn_up_qt) 167 else: 168 pass 169 simd.silu(p_silu, p_gate, ci(FF)) 170 b_silu[:FF] *= b_up[:FF] 171 if lw.ffn_down_use_c: 172 kern.quant_matmul_omp(lw.ffn_down_raw, p_silu, p_ffn, 173 lw.ffn_down_nr, lw.ffn_down_nc, lw.ffn_down_qt) 174 b_x[:N] = b_r[:N] + b_ffn[:N] 175 else: 176 b_x[:N] = b_r[:N] + (lw.ffn_down_f32 @ b_silu[:lw.ffn_down_nc.value])[:N] 177 178 # Save hidden state after this layer 179 if call_id <= 2: 180 self._inst_hidden_states[call_id].append(self._x[:10].copy()) 181 182 # Final norm 183 simd.rms_norm(p_xn, p_x, 184 self._out_norm_w.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 185 N, eps_f) 186 187 # Output projection 188 if self._out_use_c: 189 kern.quant_matmul_omp(self._out_raw, p_xn, p_logits, 190 self._out_nr, self._out_nc, self._out_qt) 191 else: 192 self._logits[:] = self._out_f32 @ b_qn 193 194 self.pos += 1 195 return self._logits 196 197 # Patch 198 TurboEngineV7MoE.forward = instrumented_forward 199 200 import ctypes 201 202 e.reset() 203 print("\n=== Call 1: forward(42) ===", flush=True) 204 l1 = e.forward(42).copy() 205 206 print("\n=== Call 2: forward(42) ===", flush=True) 207 l2 = e.forward(42).copy() 208 209 print(f"\nMax diff l1 vs l2: {np.max(np.abs(l1 - l2)):.6f}", flush=True) 210 211 # Compare hidden states layer by layer 212 print("\n=== Layer-by-layer hidden state comparison ===", flush=True) 213 hs1 = e._inst_hidden_states[1] 214 hs2 = e._inst_hidden_states[2] 215 216 for i in range(len(hs1)): 217 diff = np.max(np.abs(hs1[i] - hs2[i])) 218 print(f" Layer {i}: max diff = {diff:.8f} | hs1[:5] = {hs1[i][:5]} | hs2[:5] = {hs2[i][:5]}", flush=True) 219 if diff > 0.001: 220 print(f" *** DIVERGENCE at layer {i} ***", flush=True) 221 break