interplane.Get Omega
Read in your language

aien-yardsticks

aien-dev/aien-yardsticks

Brought by drakestapleton

branch main Branches Tags History

aien-yardsticks / yardsticks / tinyllama-oracle / generate_tinyllama_oracle.py

371 lines · 13614 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Deterministic Reference Oracle Fixture Generator for TinyLlama-1.1B-Chat-v1.0.
3
4Executes TinyLlama on CPU in FP32 using Hugging Face Transformers to generate
5canonical reference activation fixtures, logits, and multi-step greedy generation
6sequences for numerical parity verification.
7"""
8
9import argparse
10import hashlib
11import json
12import os
13import shutil
14import sys
15from typing import Any, Dict, List, Tuple
16
17import torch
18from transformers import AutoModelForCausalLM, AutoTokenizer
19from transformers.models.llama import modeling_llama
20import safetensors.torch
21
22
23PINNED_SNAPSHOT = os.path.join(
24 os.environ.get("HF_HUB_CACHE", os.path.expanduser("~/.cache/huggingface/hub")),
25 "models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/"
26 "fe8a4ea1ffedaf415f4da2f062534de366a451e6",
27)
28
29CANONICAL_PROMPT = (
30 "<|system|>\n"
31 "You are a sovereign AI assistant.</s>\n"
32 "<|user|>\n"
33 "Explain the role of an operating system in one sentence.</s>\n"
34 "<|assistant|>\n"
35)
36
37EXPECTED_PROMPT_TOKENS = [
38 1, 529, 29989, 5205, 29989, 29958, 13, 3492, 526, 263, 577, 369, 7577, 319,
39 29902, 20255, 29889, 2, 13, 29966, 29989, 1792, 29989, 29958, 13, 9544,
40 7420, 278, 6297, 310, 385, 13598, 1788, 297, 697, 10541, 29889, 2, 13,
41 29966, 29989, 465, 22137, 29989, 29958, 13
42]
43
44EXPECTED_GREEDY_16 = [
45 2744, 13598, 1788, 313, 3267, 29897, 338, 263, 7047, 393, 767, 1179,
46 278, 12837, 322, 7047
47]
48
49EXPECTED_DECODED_TEXT = (
50 "An operating system (OS) is a software that manages the hardware and software"
51)
52
53
54def compute_file_sha256(path: str) -> str:
55 """Compute hex-encoded SHA-256 digest of a file."""
56 hasher = hashlib.sha256()
57 with open(path, "rb") as f:
58 while chunk := f.read(1024 * 1024):
59 hasher.update(chunk)
60 return hasher.hexdigest()
61
62
63def capture_oracle(
64 model_path: str,
65 output_dir: str,
66 num_steps: int = 16,
67) -> Tuple[str, str]:
68 """Execute reference forward passes and export oracle fixtures."""
69 os.makedirs(output_dir, exist_ok=True)
70
71 print(f"Loading tokenizer from: {model_path}")
72 tokenizer = AutoTokenizer.from_pretrained(model_path)
73
74 print(f"Loading model on CPU in FP32 from: {model_path}")
75 model = AutoModelForCausalLM.from_pretrained(
76 model_path,
77 dtype=torch.float32,
78 device_map="cpu",
79 attn_implementation="eager",
80 )
81 model.eval()
82
83 # 1. Validate prompt tokenization
84 input_ids = tokenizer.encode(CANONICAL_PROMPT, return_tensors="pt")
85 prompt_tokens = input_ids[0].tolist()
86
87 if prompt_tokens != EXPECTED_PROMPT_TOKENS:
88 raise ValueError(
89 f"Prompt token ID mismatch:\nExpected: {EXPECTED_PROMPT_TOKENS}\nActual: {prompt_tokens}"
90 )
91 print(f"Tokenization validated: {len(prompt_tokens)} tokens matching golden spec.")
92
93 # 2. Setup activation capture dictionaries
94 activations: Dict[str, torch.Tensor] = {}
95 current_layer_idx = [-1]
96
97 # Intercept RoPE via monkey-patch
98 orig_apply_rotary = modeling_llama.apply_rotary_pos_emb
99
100 def hooked_apply_rotary(q, k, cos, sin, unsqueeze_dim=1):
101 q_rot, k_rot = orig_apply_rotary(q, k, cos, sin, unsqueeze_dim=unsqueeze_dim)
102 layer_idx = current_layer_idx[0]
103 if layer_idx >= 0:
104 activations[f"layers.{layer_idx}.post_rope_q"] = (
105 q_rot.detach().clone().contiguous()
106 )
107 activations[f"layers.{layer_idx}.post_rope_k"] = (
108 k_rot.detach().clone().contiguous()
109 )
110 return q_rot, k_rot
111
112 modeling_llama.apply_rotary_pos_emb = hooked_apply_rotary
113
114 # Intercept layer operations
115 layer_in_states: Dict[int, torch.Tensor] = {}
116 attn_out_states: Dict[int, torch.Tensor] = {}
117
118 def make_layer_pre_hook(i: int):
119 def hook(mod, inp):
120 current_layer_idx[0] = i
121 layer_in_states[i] = inp[0].detach().clone()
122 return hook
123
124 def make_input_norm_hook(i: int):
125 def hook(mod, inp, out):
126 activations[f"layers.{i}.post_rmsnorm"] = (
127 out.detach().clone().contiguous()
128 )
129 return hook
130
131 def make_attn_o_hook(i: int):
132 def hook(mod, inp, out):
133 attn_out_states[i] = out.detach().clone()
134 activations[f"layers.{i}.post_attention"] = (
135 out.detach().clone().contiguous()
136 )
137 return hook
138
139 def make_post_attn_norm_hook(i: int):
140 def hook(mod, inp, out):
141 activations[f"layers.{i}.post_attn_norm"] = (
142 out.detach().clone().contiguous()
143 )
144 return hook
145
146 def make_down_proj_hook(i: int):
147 def hook(mod, inp, out):
148 activations[f"layers.{i}.post_swiglu"] = (
149 out.detach().clone().contiguous()
150 )
151 return hook
152
153 def make_layer_post_hook(i: int):
154 def hook(mod, inp, out):
155 attn_res = layer_in_states[i] + attn_out_states[i]
156 activations[f"layers.{i}.post_attn_residual"] = (
157 attn_res.detach().clone().contiguous()
158 )
159 activations[f"layers.{i}.post_residual"] = (
160 out.detach().clone().contiguous()
161 )
162 return hook
163
164 hooks = []
165 for i, layer in enumerate(model.model.layers):
166 hooks.append(layer.register_forward_pre_hook(make_layer_pre_hook(i)))
167 hooks.append(layer.input_layernorm.register_forward_hook(make_input_norm_hook(i)))
168 hooks.append(layer.self_attn.o_proj.register_forward_hook(make_attn_o_hook(i)))
169 hooks.append(layer.post_attention_layernorm.register_forward_hook(make_post_attn_norm_hook(i)))
170 hooks.append(layer.mlp.down_proj.register_forward_hook(make_down_proj_hook(i)))
171 hooks.append(layer.register_forward_hook(make_layer_post_hook(i)))
172
173 # Global embedding, final norm, and logits hooks
174 def embed_hook(mod, inp, out):
175 activations["embed_tokens"] = out.detach().clone().contiguous()
176
177 def norm_hook(mod, inp, out):
178 activations["final_norm"] = out.detach().clone().contiguous()
179
180 def lm_head_hook(mod, inp, out):
181 activations["logits"] = out.detach().clone().contiguous()
182 activations["last_token_logits"] = out[0, -1, :].detach().clone().contiguous()
183
184 hooks.append(model.model.embed_tokens.register_forward_hook(embed_hook))
185 hooks.append(model.model.norm.register_forward_hook(norm_hook))
186 hooks.append(model.lm_head.register_forward_hook(lm_head_hook))
187
188 # 3. Execute Golden Prompt Forward Pass
189 print("Executing single-forward pass on prompt tokens...")
190 with torch.no_grad():
191 outputs = model(input_ids)
192
193 # Clean up forward hooks
194 for h in hooks:
195 h.remove()
196 modeling_llama.apply_rotary_pos_emb = orig_apply_rotary
197
198 logits = outputs.logits
199 last_token_logits = logits[0, -1, :]
200
201 # 4. Compute Top-10 Logits and Next Token
202 top10_vals, top10_inds = torch.topk(last_token_logits, 10)
203 top10_token_ids = top10_inds.tolist()
204 top10_logit_values = [float(v) for v in top10_vals.tolist()]
205
206 greedy_next_token_id = int(top10_token_ids[0])
207 greedy_next_token_logit = float(top10_logit_values[0])
208 greedy_next_token_text = tokenizer.decode([greedy_next_token_id])
209
210 print(f"Greedy next token: ID={greedy_next_token_id} ({repr(greedy_next_token_text)}), logit={greedy_next_token_logit:.4f}")
211 if greedy_next_token_id != 2744:
212 raise ValueError(f"Greedy next token mismatch: expected 2744, got {greedy_next_token_id}")
213
214 top_tokens_meta = []
215 for idx, logit in zip(top10_token_ids, top10_logit_values):
216 tok_str = tokenizer.decode([idx])
217 top_tokens_meta.append({
218 "token_id": idx,
219 "token_str": tok_str,
220 "logit": logit,
221 })
222 print(f" Rank {len(top_tokens_meta)}: ID {idx:>5} ({repr(tok_str):<10}) -> logit {logit:.4f}")
223
224 # 5. Multi-Step Autoregressive Greedy Decode
225 print(f"Executing {num_steps}-step autoregressive greedy generation...")
226 curr_ids = input_ids.clone()
227 generated_tokens: List[int] = []
228 generated_pieces: List[str] = []
229
230 with torch.no_grad():
231 for step in range(num_steps):
232 step_out = model(curr_ids)
233 next_tok = torch.argmax(step_out.logits[:, -1, :], dim=-1)
234 tok_id = int(next_tok.item())
235 generated_tokens.append(tok_id)
236 generated_pieces.append(tokenizer.decode([tok_id]))
237 curr_ids = torch.cat([curr_ids, next_tok.unsqueeze(0)], dim=-1)
238
239 decoded_text = tokenizer.decode(generated_tokens)
240 print(f"Generated tokens: {generated_tokens}")
241 print(f"Decoded text: {repr(decoded_text)}")
242
243 if generated_tokens != EXPECTED_GREEDY_16:
244 raise ValueError(
245 f"16-step token ID sequence mismatch:\nExpected: {EXPECTED_GREEDY_16}\nActual: {generated_tokens}"
246 )
247 if decoded_text != EXPECTED_DECODED_TEXT:
248 raise ValueError(
249 f"Decoded text mismatch:\nExpected: {repr(EXPECTED_DECODED_TEXT)}\nActual: {repr(decoded_text)}"
250 )
251
252 # 6. Save Safetensors Fixture
253 # Ensure every tensor is contiguous and detached
254 contiguous_activations = {
255 name: tensor.detach().clone().contiguous()
256 for name, tensor in activations.items()
257 }
258
259 safetensors_path = os.path.join(output_dir, "tinyllama_oracle.safetensors")
260 print(f"Saving {len(contiguous_activations)} oracle tensors to {safetensors_path}...")
261 safetensors.torch.save_file(contiguous_activations, safetensors_path)
262 safetensors_sha256 = compute_file_sha256(safetensors_path)
263 safetensors_bytes = os.path.getsize(safetensors_path)
264 print(f"Safetensors fixture saved: {safetensors_bytes} bytes, SHA-256: {safetensors_sha256}")
265
266 # 7. Copy Model Config and Tokenizer to Fixtures
267 tokenizer_src = os.path.join(model_path, "tokenizer.json")
268 tokenizer_dst = os.path.join(output_dir, "tokenizer.json")
269 shutil.copy2(tokenizer_src, tokenizer_dst)
270 tokenizer_sha256 = compute_file_sha256(tokenizer_dst)
271
272 config_src = os.path.join(model_path, "config.json")
273 if os.path.exists(config_src):
274 shutil.copy2(config_src, os.path.join(output_dir, "config.json"))
275
276 tok_config_src = os.path.join(model_path, "tokenizer_config.json")
277 if os.path.exists(tok_config_src):
278 shutil.copy2(tok_config_src, os.path.join(output_dir, "tokenizer_config.json"))
279
280 model_safetensors_path = os.path.join(model_path, "model.safetensors")
281 model_sha256 = compute_file_sha256(model_safetensors_path) if os.path.exists(model_safetensors_path) else "unknown"
282
283 # 8. Build JSON Manifest
284 tensor_catalog: Dict[str, Dict[str, Any]] = {}
285 for name, tensor in sorted(contiguous_activations.items()):
286 tensor_catalog[name] = {
287 "shape": list(tensor.shape),
288 "dtype": str(tensor.dtype).replace("torch.", "").upper(),
289 "numel": tensor.numel(),
290 }
291
292 manifest = {
293 "model_id": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
294 "model_sha256": model_sha256,
295 "tokenizer_sha256": tokenizer_sha256,
296 "safetensors_file": "tinyllama_oracle.safetensors",
297 "safetensors_sha256": safetensors_sha256,
298 "safetensors_bytes": safetensors_bytes,
299 "prompt_text": CANONICAL_PROMPT,
300 "prompt_tokens": prompt_tokens,
301 "prompt_token_count": len(prompt_tokens),
302 "greedy_next_token_id": greedy_next_token_id,
303 "greedy_next_token_text": greedy_next_token_text,
304 "greedy_next_token_logit": greedy_next_token_logit,
305 "top_10_tokens": top_tokens_meta,
306 "top_10_token_ids": top10_token_ids,
307 "top_10_logits": top10_logit_values,
308 "decoded_16_steps": {
309 "token_ids": generated_tokens,
310 "token_strings": generated_pieces,
311 "text": decoded_text,
312 },
313 "tolerances": {
314 "abs_tol": 1e-4,
315 "rel_tol": 1e-4,
316 "min_cosine": 0.9999,
317 },
318 "tensor_count": len(tensor_catalog),
319 "tensors": tensor_catalog,
320 }
321
322 manifest_path = os.path.join(output_dir, "tinyllama_oracle_manifest.json")
323 with open(manifest_path, "w", encoding="utf-8") as f:
324 json.dump(manifest, f, indent=2)
325 manifest_sha256 = compute_file_sha256(manifest_path)
326 print(f"Manifest saved to {manifest_path}, SHA-256: {manifest_sha256}")
327
328 return safetensors_path, manifest_path
329
330
331def main():
332 parser = argparse.ArgumentParser(
333 description="Generate TinyLlama FP32 reference oracle fixtures on Spark."
334 )
335 parser.add_argument(
336 "--model-path",
337 type=str,
338 default=PINNED_SNAPSHOT,
339 help="Path to Hugging Face snapshot directory.",
340 )
341 parser.add_argument(
342 "--output-dir",
343 type=str,
344 default="crates/aien-inference-abi/fixtures",
345 help="Output directory for generated fixtures.",
346 )
347 parser.add_argument(
348 "--steps",
349 type=int,
350 default=16,
351 help="Number of greedy decode steps.",
352 )
353
354 args = parser.parse_args()
355
356 if not os.path.exists(args.model_path):
357 print(f"Error: model path does not exist: {args.model_path}", file=sys.stderr)
358 sys.exit(1)
359
360 safetensors_path, manifest_path = capture_oracle(
361 model_path=args.model_path,
362 output_dir=args.output_dir,
363 num_steps=args.steps,
364 )
365 print("Oracle generation completed successfully.")
366 print(f"Safetensors: {safetensors_path}")
367 print(f"Manifest: {manifest_path}")
368
369
370if __name__ == "__main__":
371 main()