interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / trace_5tokens.py

81 lines · 2968 bytes Raw Blame History
1"""Trace forward pass with 5 tokens."""
2import sys, time
3sys.path.insert(0, 'src')
4import numpy as np
5from mojollama.model.inference import load_model
6
7model = load_model('test_model.gguf')
8ids = model.encode('The capital of France is')
9print(f'ids={ids} len={len(ids)}')
10
11# Use same code as forward method but with timing
12seq_len = len(ids)
13h_ids = np.array(ids, dtype=np.int64)
14
15embed = model._get_persistent('token_embd.weight')
16x = embed[h_ids].astype(np.float32)
17print(f'embed shape={x.shape}')
18
19head_dim = model.n_embd // model.n_head
20cos, sin = model.precompute_freqs_cis(head_dim, seq_len, model.rope_theta)
21n_rep = model.n_head // model.n_kv_head
22mask = np.triu(np.full((seq_len, seq_len), -np.inf, dtype=np.float32), 1)
23
24print('Starting layers...')
25t_start = time.time()
26for i in range(model.n_layers):
27 t0 = time.time()
28 ln1 = model._tensor(f'blk.{i}.attn_norm.weight')
29 q_w = model._tensor(f'blk.{i}.attn_q.weight')
30 k_w = model._tensor(f'blk.{i}.attn_k.weight')
31 v_w = model._tensor(f'blk.{i}.attn_v.weight')
32 o_w = model._tensor(f'blk.{i}.attn_output.weight')
33 q_b = model._tensor(f'blk.{i}.attn_q.bias')
34 k_b = model._tensor(f'blk.{i}.attn_k.bias')
35 v_b = model._tensor(f'blk.{i}.attn_v.bias')
36 ln2 = model._tensor(f'blk.{i}.ffn_norm.weight')
37 gate_w = model._tensor(f'blk.{i}.ffn_gate.weight')
38 up_w = model._tensor(f'blk.{i}.ffn_up.weight')
39 down_w = model._tensor(f'blk.{i}.ffn_down.weight')
40 load_time = time.time() - t0
41
42 r = x
43 x = model.rms_norm(x, ln1, model.norm_eps)
44 q = x @ q_w.T
45 k = x @ k_w.T
46 v = x @ v_w.T
47 if q_b is not None: q += q_b
48 if k_b is not None: k += k_b
49 if v_b is not None: v += v_b
50 q = q.reshape(seq_len, model.n_head, head_dim)
51 k = k.reshape(seq_len, model.n_kv_head, head_dim)
52 v = v.reshape(seq_len, model.n_kv_head, head_dim)
53 q = model.apply_rope(q, cos, sin)
54 k = model.apply_rope(k, cos, sin)
55 if n_rep > 1:
56 k = np.repeat(k, n_rep, axis=1)
57 v = np.repeat(v, n_rep, axis=1)
58 att = np.einsum('ihd,jhd->hij', q, k) / np.sqrt(head_dim)
59 att = att + mask[np.newaxis, :, :]
60 am = np.max(att, axis=-1, keepdims=True)
61 att = np.exp(att - am)
62 att = att / np.sum(att, axis=-1, keepdims=True)
63 out = np.einsum('hij,jhd->ihd', att, v).reshape(seq_len, model.n_embd)
64 out = out @ o_w.T
65 x = r + out
66 r = x
67 x = model.rms_norm(x, ln2, model.norm_eps)
68 gate = x @ gate_w.T
69 up = x @ up_w.T
70 x = (model.silu(gate) * up) @ down_w.T
71 x = r + x
72 del ln1, q_w, k_w, v_w, o_w, q_b, k_b, v_b, ln2, gate_w, up_w, down_w
73 elapsed = time.time() - t_start
74 if i < 3 or i % 5 == 0 or i >= 22:
75 print(f'layer {i}: {elapsed:.3f}s (load={load_time:.3f}s)')
76
77norm_w = model._tensor('output_norm.weight')
78x = model.rms_norm(x, norm_w, model.norm_eps)
79lm_w = model._get_persistent('output.weight')
80logits = x @ lm_w.T
81print(f'Done! total={time.time()-t_start:.1f}s logits={logits.shape}')