MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / mojo_engine / safetensors_extract.mojo
| 1 | # safetensors_extract.mojo — Pure Mojo safetensors → .bin extractor |
| 2 | # WHAT: Wraps the C safetensors_extract helper. Reads a .safetensors file, |
| 3 | # extracts all tensors to raw .bin weight files. |
| 4 | # WHY: JSON parsing impossible in Mojo 1.0.0b1 (no String, no dicts). |
| 5 | # C for I/O, Mojo orchestrates. Acceptable per "C for I/O" rule. |
| 6 | # WHEN: 2026-05-22 |
| 7 | # |
| 8 | # Naming: safetensors → flat .bin files (dots→underscores, "model." stripped) |
| 9 | # HF name → .bin file |
| 10 | # lm_head.weight → lm_head_weight.bin |
| 11 | # model.embed_tokens.weight → embed_tokens_weight.bin |
| 12 | # model.layers.N.self_attn.q → layers_N_self_attn_q_proj_weight.bin |
| 13 | # model.layers.N.mlp.gate_proj → layers_N_mlp_gate_proj_weight.bin |
| 14 | # model.norm.weight → norm_weight.bin |
| 15 | # |
| 16 | # Usage: mojo safetensors_extract.mojo path/to/model.safetensors [out_dir] |
| 17 | # (or build: mojo build safetensors_extract.mojo -o safetensors_extract_mojo) |
| 18 | |
| 19 | from sys import args, exit |
| 20 | |
| 21 | @extern("system") |
| 22 | def _c_system(cmd: UnsafePointer[UInt8, MutExternalOrigin]) -> Int: ... |
| 23 | |
| 24 | def main(): |
| 25 | var argv = args() |
| 26 | if argv.size < 2: |
| 27 | print("Usage: safetensors_extract model.safetensors [out_dir]") |
| 28 | print("Extracts all tensors from a .safetensors file to raw .bin files.") |
| 29 | print("Default out_dir: ./weights/") |
| 30 | print() |
| 31 | print("Example: mojo safetensors_extract.mojo model.safetensors /tmp/weights/") |
| 32 | exit(1) |
| 33 | |
| 34 | var inpath = argv[1] |
| 35 | var outdir = argv[2] if argv.size > 2 else String("./weights") |
| 36 | |
| 37 | # The C binary must be compiled first: gcc -O2 safetensors_extract.c -o safetensors_extract |
| 38 | # Located in the same directory as this Mojo file |
| 39 | var binary = String("/onedev-workspace/work/src/mojollama/mojo_engine/safetensors_extract") |
| 40 | |
| 41 | # Build command: binary inpath outdir |
| 42 | # Use a raw buffer to avoid String UInt8 bug |
| 43 | var args_str = String(" ") + inpath + String(" ") + outdir |
| 44 | var full_cmd = binary + args_str |
| 45 | |
| 46 | print("Extracting:", inpath, "→", outdir) |
| 47 | var ret = _c_system(full_cmd.unsafe_ptr()) |
| 48 | |
| 49 | if ret != 0: |
| 50 | print("ERROR: safetensors_extract failed with code", ret) |
| 51 | exit(ret) |