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 / convert_lance.py

302 lines · 10348 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Convert Lance text backbone to GGUF Q4_K_M.
3
4Lance has a dual-path architecture:
5 - standard path: layers.N.input_layernorm → self_attn → post_attention_layernorm → mlp
6 - moe_gen path: layers.N.input_layernorm_moe_gen → self_attn_moe_gen → post_attention_layernorm_moe_gen → mlp_moe_gen
7 - diffusion components: vae2llm, llm2vae, time_embedder, latent_pos_embed
8
9This extracts ONLY the standard text path (ignoring moe_gen + diffusion).
10The resulting GGUF runs as a Qwen2-like 3B text-only model on MojoLlama.
11"""
12
13import sys, os, struct, json, numpy as np
14from pathlib import Path
15
16MODEL_PATH = "/tmp/models/lance_model.safetensors"
17CONFIG_PATH = "/tmp/models/lance_llm_config.json"
18OUTPUT_GGUF = "/tmp/models/lance-text-q8_0.gguf"
19OUTPUT_QUANT = "/tmp/models/lance-text-q4_k_m.gguf"
20TOKENIZER_PATH = "/tmp/models/lance_tokenizer.json"
21VOCAB_PATH = "/tmp/models/lance_vocab.json"
22
23import safetensors
24
25# Load config
26with open(CONFIG_PATH) as f:
27 config = json.load(f)
28
29hidden_size = config["hidden_size"]
30n_layers = config["num_hidden_layers"]
31n_heads = config["num_attention_heads"]
32n_kv_heads = config["num_key_value_heads"]
33intermediate_size = config["intermediate_size"]
34vocab_size = config["vocab_size"]
35max_seq_len = config["max_position_embeddings"]
36rms_eps = config["rms_norm_eps"]
37rope_theta = config["rope_theta"]
38
39print(f"Lance text backbone: {n_layers}L/{hidden_size}D/{n_heads}H/{n_kv_heads}KV/{intermediate_size}FF")
40print(f"Vocab: {vocab_size}, Max seq: {max_seq_len}")
41
42# Open safetensors
43st = safetensors.safe_open(MODEL_PATH, framework='pt')
44all_keys = st.keys()
45
46# Determine which tensors to extract (standard path only)
47def is_text_tensor(name):
48 """Check if tensor should be included in text-only GGUF."""
49 # Skip moe_gen, vae, llm2vae, time_embedder, latent_pos_embed
50 if '_moe_gen' in name: return False
51 if 'vae2llm' in name or 'llm2vae' in name: return False
52 if 'time_embedder' in name: return False
53 if 'latent_pos_embed' in name: return False
54 # Only include language_model.*
55 if 'language_model.' not in name: return False
56 return True
57
58text_tensors = [k for k in all_keys if is_text_tensor(k)]
59print(f"Text tensors: {len(text_tensors)} / {len(all_keys)} total")
60
61# GGUF key constants
62GGUF_TYPE = {
63 'uint32': 4, 'int32': 5, 'float32': 10, 'bool': 11,
64 'string': 8, 'array': 12,
65}
66GGML_TYPE = {'F32': 0, 'F16': 1, 'Q8_0': 8}
67
68def gguf_meta_writer():
69 """Write GGUF metadata and return the tensor offset."""
70 offset = 0
71 data = bytearray()
72
73 def w_string(s):
74 nonlocal offset
75 b = s.encode('utf-8')
76 data += struct.pack('<Q', len(b)) + b
77 offset += 8 + len(b)
78
79 def w_uint32(v):
80 nonlocal offset
81 data += struct.pack('<I', v)
82 offset += 4
83
84 def w_int32(v):
85 nonlocal offset
86 data += struct.pack('<i', v)
87 offset += 4
88
89 def w_float32(v):
90 nonlocal offset
91 data += struct.pack('<f', v)
92 offset += 4
93
94 def w_bool(v):
95 nonlocal offset
96 data += struct.pack('<?', v)
97 offset += 1
98
99 def w_key_value(key, vtype, value):
100 nonlocal offset
101 w_string(key)
102 data += struct.pack('<I', vtype)
103 offset += 4
104 if vtype == 8: # string
105 w_string(value)
106 elif vtype == 4: # uint32
107 w_uint32(value)
108 elif vtype == 5: # int32
109 w_int32(value)
110 elif vtype == 10: # float32
111 w_float32(value)
112 elif vtype == 11: # bool
113 w_bool(value)
114 elif vtype == 12: # array
115 data += struct.pack('<I', value['type'])
116 offset += 4
117 data += struct.pack('<Q', len(value['items']))
118 offset += 8
119 for item in value['items']:
120 if value['type'] == 8:
121 w_string(item)
122 elif value['type'] == 5:
123 w_int32(item)
124
125 data_buf_start = len(data)
126
127 # Write header
128 data += b'GGUF' # magic
129 data += struct.pack('<I', 3) # version
130 offset += 4 + 4 + 4 + 8 # magic(4) + version(4) + tensor_count_placeholder(4) + metadata_kv_count_placeholder(8)
131
132 # Placeholders
133 tensor_count_pos = len(data) - 12
134 kv_count_pos = len(data) - 8
135
136 kv_count = 0
137
138 # Write metadata
139 def add_kv(key, vtype, value):
140 nonlocal kv_count, offset
141 w_key_value(key, vtype, value)
142 kv_count += 1
143
144 add_kv('general.architecture', 8, 'qwen2')
145 add_kv('general.name', 8, 'Lance-Text-3B')
146 add_kv('general.file_type', 4, 2) # Q8_0
147 add_kv('general.version', 8, '1')
148
149 add_kv('llm.block_count', 4, n_layers)
150 add_kv('llm.embedding_length', 4, hidden_size)
151 add_kv('llm.feed_forward_length', 4, intermediate_size)
152 add_kv('llm.attention.head_count', 4, n_heads)
153 add_kv('llm.attention.head_count_kv', 4, n_kv_heads)
154 add_kv('llm.attention.layer_norm_rms_epsilon', 10, rms_eps)
155 add_kv('llm.rope.freq_base', 10, rope_theta)
156 add_kv('llm.rope.dimension_count', 4, hidden_size // n_heads)
157 add_kv('llm.vocab_size', 4, vocab_size)
158 add_kv('llm.max_position_embeddings', 4, max_seq_len)
159 add_kv('general.file_type', 4, 2)
160 add_kv('tokenizer.ggml.model', 8, 'gpt2')
161 add_kv('tokenizer.ggml.bos_token_id', 4, 151643)
162 add_kv('tokenizer.ggml.eos_token_id', 4, 151645)
163
164 # Write kv_count
165 data[kv_count_pos:kv_count_pos+8] = struct.pack('<Q', kv_count)
166
167 return data, kv_count_pos, tensor_count_pos
168
169# Build tensor info
170TENSOR_MAP = {
171 'language_model.model.embed_tokens.weight': 'token_embd',
172 'language_model.model.norm.weight': 'output_norm',
173 'language_model.lm_head.weight': 'output',
174}
175
176# Per-layer mappings
177PER_LAYER_MAP = {
178 'input_layernorm.weight': 'attn_norm',
179 'self_attn.q_proj.weight': 'attn_q',
180 'self_attn.k_proj.weight': 'attn_k',
181 'self_attn.v_proj.weight': 'attn_v',
182 'self_attn.o_proj.weight': 'attn_output',
183 'self_attn.q_proj.bias': 'attn_q.bias',
184 'self_attn.k_proj.bias': 'attn_k.bias',
185 'self_attn.v_proj.bias': 'attn_v.bias',
186 'self_attn.k_norm.weight': 'attn_k_norm',
187 'self_attn.q_norm.weight': 'attn_q_norm',
188 'post_attention_layernorm.weight': 'ffn_norm',
189 'mlp.gate_proj.weight': 'ffn_gate',
190 'mlp.up_proj.weight': 'ffn_up',
191 'mlp.down_proj.weight': 'ffn_down',
192}
193
194tensor_infos = []
195for name in text_tensors:
196 # Map name to GGUF tensor name
197 if name.startswith('language_model.model.layers.'):
198 parts = name.split('.')
199 layer_idx = int(parts[3])
200 inner = '.'.join(parts[4:])
201 if inner in PER_LAYER_MAP:
202 gguf_name = f'blk.{layer_idx}.{PER_LAYER_MAP[inner]}'
203 tensor_infos.append((name, gguf_name, 'q8_0'))
204 elif name in TENSOR_MAP:
205 gguf_name = TENSOR_MAP[name]
206 tensor_infos.append((name, gguf_name, 'q8_0'))
207
208print(f"Mapped tensors: {len(tensor_infos)}")
209
210# Build GGUF file
211metadata, kv_count_pos, tensor_count_pos = gguf_meta_writer()
212tensor_count = len(tensor_infos)
213
214# Write tensor info header
215data = bytearray(metadata)
216with open(MODEL_PATH, 'rb') as f_model:
217 # Seek past header
218 header_end = len(data)
219
220 # Write tensor count
221 data[tensor_count_pos:tensor_count_pos+4] = struct.pack('<I', tensor_count)
222
223 # Write tensor info entries
224 tensor_data_offset = 0
225 for name, gguf_name, qtype in tensor_infos:
226 tensor = st.get_tensor(name)
227 shape = list(tensor.shape)
228 n_elems = int(np.prod(shape))
229 n_dims = len(shape)
230
231 # GGUF tensor info
232 name_bytes = gguf_name.encode('utf-8')
233 data += struct.pack('<Q', len(name_bytes)) + name_bytes
234 data += struct.pack('<I', n_dims)
235 for dim in reversed(shape): # GGUF stores dims in reverse
236 data += struct.pack('<Q', dim)
237 data += struct.pack('<I', 8) # Q8_0 type
238 data += struct.pack('<Q', 0) # offset placeholder
239
240 # Align to 32 bytes
241 while len(data) % 32 != 0:
242 data.append(0)
243
244 tensor_data_start = len(data)
245
246 # Now write actual tensor data
247 data_current = len(data)
248 for i, (name, gguf_name, qtype) in enumerate(tensor_infos):
249 tensor = st.get_tensor(name)
250 if isinstance(tensor, np.ndarray):
251 arr = tensor
252 else:
253 arr = tensor.numpy()
254
255 # Convert to Q8_0: quantize each block of 32 elements
256 if arr.ndim == 1:
257 arr = arr.astype(np.float32)
258 n = arr.shape[0]
259 n_blocks = (n + 31) // 32
260 q_data = bytearray()
261 for b in range(n_blocks):
262 block = arr[b*32:(b+1)*32]
263 if len(block) < 32:
264 block = np.pad(block, (0, 32 - len(block)))
265 d = np.abs(block).max() / 127.0
266 if d == 0: d = 1.0
267 quants = np.clip(np.round(block / d), -128, 127).astype(np.int8)
268 q_data += struct.pack('<f', d)
269 q_data += quants.tobytes()
270 elif arr.ndim == 2:
271 rows, cols = arr.shape
272 arr = arr.astype(np.float32)
273 q_data = bytearray()
274 for r in range(rows):
275 row = arr[r, :]
276 n = row.shape[0]
277 n_blocks = (n + 31) // 32
278 for b in range(n_blocks):
279 block = row[b*32:(b+1)*32]
280 if len(block) < 32:
281 block = np.pad(block, (0, 32 - len(block)))
282 d = np.abs(block).max() / 127.0
283 if d == 0: d = 1.0
284 quants = np.clip(np.round(block / d), -128, 127).astype(np.int8)
285 q_data += struct.pack('<f', d)
286 q_data += quants.tobytes()
287
288 # Update tensor data offset info
289 # The tensor info was written earlier, need to update the offset
290 # For now, just append data
291 data += q_data
292
293 if i % 50 == 0:
294 print(f" [{i}/{len(tensor_infos)}] {gguf_name}: {list(arr.shape)} ({len(q_data)} bytes)")
295
296# Write final file
297with open(OUTPUT_GGUF, 'wb') as f:
298 f.write(data)
299
300size_gb = len(data) / 1024**3
301print(f"\nWritten {OUTPUT_GGUF}: {size_gb:.2f} GB")
302print(f"Now quantizing to Q4_K_M...")