MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / mojo_engine / safetensors_extract.c
| 1 | /* safetensors_extract.c — Safetensors → raw .bin extractor |
| 2 | * WHAT: Reads any .safetensors file, extracts all tensors to raw .bin files. |
| 3 | * WHY: Mojo 1.0.0b1 can't parse JSON headers (no String, no dicts). |
| 4 | * WHEN: 2026-05-22 — first version. |
| 5 | * |
| 6 | * Format: [8 bytes header_len LE] [JSON header] [binary tensor data...] |
| 7 | * JSON: {"__metadata__":{}, "tensor_name":{"dtype":"F16","shape":[N,M],"data_offsets":[S,E]}} |
| 8 | * |
| 9 | * Usage: ./safetensors_extract model.safetensors [out_dir] |
| 10 | * Default out_dir: ./weights/ |
| 11 | */ |
| 12 | |
| 13 | #include <stdio.h> |
| 14 | #include <stdlib.h> |
| 15 | #include <stdint.h> |
| 16 | #include <string.h> |
| 17 | #include <sys/stat.h> |
| 18 | #include <sys/types.h> |
| 19 | #include <errno.h> |
| 20 | |
| 21 | /* ── Read 8 bytes (little-endian) ── */ |
| 22 | static uint64_t r8(const void *p) { |
| 23 | const unsigned char *b = (const unsigned char*)p; |
| 24 | return (uint64_t)b[0] | ((uint64_t)b[1]<<8) | ((uint64_t)b[2]<<16) | ((uint64_t)b[3]<<24) |
| 25 | | ((uint64_t)b[4]<<32) | ((uint64_t)b[5]<<40) | ((uint64_t)b[6]<<48) | ((uint64_t)b[7]<<56); |
| 26 | } |
| 27 | |
| 28 | /* ── Human-readable size ── */ |
| 29 | static void fmt_sz(char *buf, size_t sz) { |
| 30 | if (sz < 1024) sprintf(buf, "%zuB", sz); |
| 31 | else if (sz < 1048576) sprintf(buf, "%.0fKB", (double)sz/1024); |
| 32 | else sprintf(buf, "%.0fMB", (double)sz/1048576); |
| 33 | } |
| 34 | |
| 35 | /* ── Convert HF tensor name → file-safe name ── */ |
| 36 | static void mangle(const char *src, char *dst, size_t cap) { |
| 37 | if (strncmp(src, "model.", 6) == 0) src += 6; |
| 38 | size_t j = 0; |
| 39 | for (; *src && j+5 < cap; src++) { |
| 40 | if (*src == '.') dst[j++] = '_'; |
| 41 | else if (*src == '/') dst[j++] = '_'; |
| 42 | else dst[j++] = *src; |
| 43 | } |
| 44 | dst[j] = 0; |
| 45 | } |
| 46 | |
| 47 | /* ── Find a key's value string in a sub-JSON buffer ── */ |
| 48 | /* Scans {"key":"val", ...} and copies val into out */ |
| 49 | static int sj_str(const unsigned char *sj, size_t len, const char *key, char *out, size_t cap) { |
| 50 | size_t kl = strlen(key), i = 0; |
| 51 | while (i < len) { |
| 52 | if (sj[i] != '"') { i++; continue; } |
| 53 | size_t ks = i+1, ke = ks; |
| 54 | while (ke < len && sj[ke] != '"') ke++; |
| 55 | size_t fl = ke - ks; |
| 56 | if (fl == kl && memcmp(sj+ks, key, kl) == 0) { |
| 57 | size_t p = ke+1; |
| 58 | while (p < len && (sj[p]==':'||sj[p]==' '||sj[p]=='\t'||sj[p]=='\n')) p++; |
| 59 | if (p >= len || sj[p] != '"') return 0; |
| 60 | size_t vs = p+1, ve = vs; |
| 61 | while (ve < len && sj[ve] != '"') ve++; |
| 62 | size_t vl = ve - vs; |
| 63 | if (vl >= cap) vl = cap-1; |
| 64 | memcpy(out, sj+vs, vl); out[vl] = 0; |
| 65 | return 1; |
| 66 | } |
| 67 | i = ke+1; |
| 68 | } |
| 69 | return 0; |
| 70 | } |
| 71 | |
| 72 | /* ── Find a key's integer array value in sub-JSON ── */ |
| 73 | /* Scans {"key":[N0,N1,...]} and returns nth integer */ |
| 74 | static int sj_int(const unsigned char *sj, size_t len, const char *key, int nth, int64_t *out) { |
| 75 | size_t kl = strlen(key), i = 0; |
| 76 | while (i < len) { |
| 77 | if (sj[i] != '"') { i++; continue; } |
| 78 | size_t ks = i+1, ke = ks; |
| 79 | while (ke < len && sj[ke] != '"') ke++; |
| 80 | size_t fl = ke - ks; |
| 81 | if (fl == kl && memcmp(sj+ks, key, kl) == 0) { |
| 82 | size_t p = ke+1; |
| 83 | while (p < len && (sj[p]==':'||sj[p]==' '||sj[p]=='\t'||sj[p]=='\n')) p++; |
| 84 | if (p >= len || sj[p] != '[') return 0; |
| 85 | p++; int cnt = 0; |
| 86 | while (p < len && sj[p] != ']') { |
| 87 | while (p < len && (sj[p]==' '||sj[p]==','||sj[p]=='\t'||sj[p]=='\n')) p++; |
| 88 | if (p >= len || sj[p] == ']') break; |
| 89 | if (sj[p] >= '0' && sj[p] <= '9') { |
| 90 | int64_t n = 0; |
| 91 | while (p < len && sj[p] >= '0' && sj[p] <= '9') { n = n*10 + (sj[p]-'0'); p++; } |
| 92 | if (cnt == nth) { *out = n; return 1; } |
| 93 | cnt++; |
| 94 | } else p++; |
| 95 | } |
| 96 | return 0; |
| 97 | } |
| 98 | i = ke+1; |
| 99 | } |
| 100 | return 0; |
| 101 | } |
| 102 | |
| 103 | int main(int argc, char **argv) { |
| 104 | if (argc < 2) { |
| 105 | fprintf(stderr, "Usage: %s model.safetensors [out_dir]\n", argv[0]); |
| 106 | return 1; |
| 107 | } |
| 108 | const char *inpath = argv[1]; |
| 109 | const char *outdir = (argc > 2) ? argv[2] : "./weights"; |
| 110 | |
| 111 | /* Create output dir */ |
| 112 | struct stat st = {0}; |
| 113 | if (stat(outdir, &st) == -1) |
| 114 | if (mkdir(outdir, 0755) != 0 && errno != EEXIST) |
| 115 | { fprintf(stderr, "ERROR: can't create '%s'\n", outdir); return 1; } |
| 116 | |
| 117 | /* Open file */ |
| 118 | FILE *f = fopen(inpath, "rb"); |
| 119 | if (!f) { fprintf(stderr, "ERROR: can't open '%s'\n", inpath); return 1; } |
| 120 | |
| 121 | /* Read 8-byte header = JSON length */ |
| 122 | unsigned char h8[8]; |
| 123 | if (fread(h8, 1, 8, f) != 8) { fprintf(stderr, "ERROR: short header\n"); fclose(f); return 1; } |
| 124 | uint64_t jlen = r8(h8); |
| 125 | |
| 126 | if (jlen > 100*1024*1024) { |
| 127 | fprintf(stderr, "ERROR: JSON header too large (%llu MB)\n", (unsigned long long)(jlen/1048576)); |
| 128 | fclose(f); return 1; |
| 129 | } |
| 130 | |
| 131 | /* Read JSON header */ |
| 132 | unsigned char *j = (unsigned char*)malloc(jlen + 1); |
| 133 | if (!j) { fprintf(stderr, "ERROR: out of memory\n"); fclose(f); return 1; } |
| 134 | if (fread(j, 1, jlen, f) != jlen) { fprintf(stderr, "ERROR: can't read JSON\n"); free(j); fclose(f); return 1; } |
| 135 | j[jlen] = 0; |
| 136 | |
| 137 | /* Read data section */ |
| 138 | fseek(f, 0, SEEK_END); |
| 139 | long fsz = ftell(f); |
| 140 | size_t doff = 8 + jlen; |
| 141 | size_t dlen = (size_t)(fsz - (long)doff); |
| 142 | |
| 143 | unsigned char *d = (unsigned char*)malloc(dlen); |
| 144 | if (!d) { fprintf(stderr, "ERROR: out of memory (%zu bytes)\n", dlen); free(j); fclose(f); return 1; } |
| 145 | fseek(f, (long)doff, SEEK_SET); |
| 146 | if (fread(d, 1, dlen, f) != dlen) { fprintf(stderr, "ERROR: can't read data\n"); free(j); free(d); fclose(f); return 1; } |
| 147 | fclose(f); |
| 148 | |
| 149 | printf("Safetensors: JSON=%lluKB Data=%zuMB\n", |
| 150 | (unsigned long long)(jlen/1024), dlen/1048576); |
| 151 | |
| 152 | /* Scan JSON for tensor entries */ |
| 153 | size_t pos = 0; |
| 154 | int count = 0; |
| 155 | char name[256], mang[256], dtype[32]; |
| 156 | |
| 157 | while (pos < jlen) { |
| 158 | /* Find '"' */ |
| 159 | if (j[pos] != '"') { pos++; continue; } |
| 160 | size_t ks = pos+1, ke = ks; |
| 161 | while (ke < jlen && j[ke] != '"') ke++; |
| 162 | if (ke >= jlen) break; |
| 163 | size_t nlen = ke - ks; |
| 164 | |
| 165 | /* Check if this key is followed by :{ (tensor entry) */ |
| 166 | size_t cp = ke+1; |
| 167 | while (cp < jlen && (j[cp]==' '||j[cp]=='\t'||j[cp]=='\n')) cp++; |
| 168 | if (cp >= jlen || j[cp] != ':') { pos = ke+1; continue; } |
| 169 | cp++; |
| 170 | while (cp < jlen && (j[cp]==' '||j[cp]=='\t'||j[cp]=='\n')) cp++; |
| 171 | if (cp >= jlen || j[cp] != '{') { pos = ke+1; continue; } |
| 172 | |
| 173 | /* Find matching '}' for this tensor's JSON object */ |
| 174 | size_t os = cp+1; /* past '{' */ |
| 175 | size_t oe = os; int depth = 1; |
| 176 | while (oe < jlen && depth > 0) { |
| 177 | if (j[oe] == '{') depth++; |
| 178 | else if (j[oe] == '}') depth--; |
| 179 | oe++; |
| 180 | } |
| 181 | /* oe is past the matching '}' */ |
| 182 | |
| 183 | /* Skip __metadata__ */ |
| 184 | if (nlen == 12 && memcmp(j+ks, "__metadata__", 12) == 0) { |
| 185 | pos = oe; continue; |
| 186 | } |
| 187 | |
| 188 | /* Copy tensor name */ |
| 189 | size_t cp_n = (nlen < 255) ? nlen : 254; |
| 190 | memcpy(name, j+ks, cp_n); name[cp_n] = 0; |
| 191 | |
| 192 | /* Extract from sub-JSON [os, oe-2] */ |
| 193 | size_t sj_start = os; |
| 194 | size_t sj_len = (oe > os) ? (oe - os - 1) : 0; |
| 195 | |
| 196 | if (sj_len > 0) { |
| 197 | int64_t off0 = 0, off1 = 0; |
| 198 | if (sj_int(j+sj_start, sj_len, "data_offsets", 0, &off0) && |
| 199 | sj_int(j+sj_start, sj_len, "data_offsets", 1, &off1)) { |
| 200 | |
| 201 | size_t ts = (size_t)off0; |
| 202 | size_t te = (size_t)off1; |
| 203 | size_t tsz = te - ts; |
| 204 | |
| 205 | if (tsz > 0 && ts + tsz <= dlen) { |
| 206 | mangle(name, mang, sizeof(mang)); |
| 207 | char fpath[1024]; |
| 208 | snprintf(fpath, sizeof(fpath), "%s/%s.bin", outdir, mang); |
| 209 | |
| 210 | FILE *fw = fopen(fpath, "wb"); |
| 211 | if (fw) { |
| 212 | size_t wr = fwrite(d+ts, 1, tsz, fw); |
| 213 | fclose(fw); |
| 214 | char sb[24]; fmt_sz(sb, wr); |
| 215 | printf(" [%d] %s (%s)\n", ++count, mang, sb); |
| 216 | } else { |
| 217 | fprintf(stderr, " [%d] FAIL: can't write %s\n", count+1, fpath); |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | pos = oe; |
| 223 | } |
| 224 | |
| 225 | printf("Extracted %d tensors to '%s/'\n", count, outdir); |
| 226 | free(j); free(d); |
| 227 | return 0; |
| 228 | } |