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 / src / mojollama / mojo_engine / extract_zaya_vocab.py

128 lines · 4378 bytes Raw Blame History
1#!/usr/bin/env python3
2"""
3Extract ZAYA1-8B vocabulary from GGUF to flat .bin format.
4Output: /tmp/vocab_zaya.bin
5
6Uses low-level GGUF parsing to get tokens.
7"""
8
9import sys, os, struct
10import numpy as np
11sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels')
12import gguf
13
14GGUF_PATH = '/tmp/models/ZAYA1-8B-Q8_0.gguf'
15OUT_PATH = '/tmp/vocab_zaya.bin'
16
17
18def main():
19 if not os.path.exists(GGUF_PATH):
20 print(f"ERROR: GGUF not found: {GGUF_PATH}")
21 sys.exit(1)
22
23 reader = gguf.GGUFReader(GGUF_PATH)
24
25 # Find tokenizer.ggml.tokens field
26 field = None
27 for name, f in reader.fields.items():
28 if name == 'tokenizer.ggml.tokens':
29 field = f
30 break
31
32 if field is None:
33 print("ERROR: tokenizer.ggml.tokens not found")
34 sys.exit(1)
35
36 # field.parts contains: [type_meta, key_name_bytes, ...tokens_data]
37 # The token data is interleaved as: [uint64_count][bytes...][uint64_count][bytes...]...
38 # Each token's data is preceded by a uint64 length indicator
39 tokens = []
40
41 # Walk through parts looking for string data
42 i = 0
43 parts = field.parts
44 while i < len(parts):
45 p = parts[i]
46 # Check if this is a size indicator (uint64 with small value like string length)
47 if hasattr(p, 'dtype') and p.dtype == np.uint64 and p.shape == (1,):
48 length = int(p[0])
49 if length > 0 and length < 1000 and i + 1 < len(parts):
50 next_p = parts[i + 1]
51 if hasattr(next_p, 'dtype') and next_p.dtype == np.uint8 and next_p.shape == (length,):
52 token_bytes = bytes(next_p)
53 tokens.append(token_bytes)
54 i += 2
55 continue
56 i += 1
57
58 # If no tokens found via parsing, try to read the raw tensor data
59 if len(tokens) == 0:
60 print("Trying direct token extraction from field...")
61 # The field data might be a list of integers representing byte data
62 if hasattr(field, 'data') and isinstance(field.data, list):
63 raw_data = bytes(field.data)
64 # Try to parse as null-terminated strings
65 offset = 0
66 while offset < len(raw_data):
67 # Skip any non-printable or length-like prefix
68 end = raw_data.find(b'\x00', offset)
69 if end < 0:
70 break
71 token = raw_data[offset:end]
72 if len(token) > 0 and len(token) < 500:
73 tokens.append(token)
74 offset = end + 1
75
76 if len(tokens) == 0:
77 # Last resort: check tokenizer.ggml.scores field — it should have same count
78 print("Trying alternative extraction...")
79 # Check all fields with 'token' in name
80 for name, f in reader.fields.items():
81 if 'token' in name.lower():
82 print(f" {name}: parts={len(f.parts)}, types={f.types}")
83
84 # Try to extract from raw GGUF file using gguf parser internals
85 try:
86 # The tokens might be at a specific offset
87 token_list = reader.get_field("tokenizer.ggml.tokens")
88 if token_list:
89 print(f"token_list type: {type(token_list)}")
90 except:
91 pass
92
93 sys.exit(1)
94
95 print(f"Found {len(tokens)} tokens")
96 if len(tokens) > 0:
97 print(f"First token ({len(tokens[0])} bytes): {tokens[0][:40]}")
98 if len(tokens) > 1:
99 print(f"Second token ({len(tokens[1])} bytes): {tokens[1][:40]}")
100 print(f"Last token ({len(tokens[-1])} bytes): {tokens[-1][:40]}")
101
102 # Skip the first entry if it's the metadata key name
103 # token_embd.weight has NV=262147 rows, so skip 1 metadata entry
104 if tokens and tokens[0].startswith(b'tokenizer'):
105 print(f"Skipping metadata entry: {tokens[0]}")
106 tokens = tokens[1:]
107
108 print(f"Clean vocab: {len(tokens)} tokens")
109
110 # Build flat binary format
111 nv = len(tokens)
112 buf = bytearray()
113 buf += struct.pack('<I', nv)
114
115 for i, token_bytes in enumerate(tokens):
116 buf += struct.pack('<I', len(token_bytes))
117 buf += token_bytes
118 buf += struct.pack('<I', i)
119
120 with open(OUT_PATH, 'wb') as f:
121 f.write(bytes(buf))
122
123 print(f"Wrote {OUT_PATH}: {len(buf)} bytes ({nv} tokens)")
124 print("Done!")
125
126
127if __name__ == '__main__':
128 main()