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 / tinyllama_loader.mojo

54 lines · 2196 bytes Raw Blame History
1# TinyLlama Weight Loader — Pure Mojo Logic
2# Uses minimal C I/O wrappers (Mojo String→C is broken).
3# All indexing, memory management in Mojo.
4from std.algorithm.backend.cpu.parallelize import parallelize
5
6@extern("tl_fsize")
7def _fsz(idx: Int) abi("C") -> Int64: ...
8@extern("tl_fread")
9def _fread(idx: Int, buf: UnsafePointer[UInt8, MutExternalOrigin], sz: Int64) abi("C") -> Int64: ...
10@extern("malloc")
11def _c_malloc(sz: Int64) abi("C") -> Int64: ...
12@extern("free")
13def _c_free(p: Int64) abi("C") -> None: ...
14@extern("addr_to_f32")
15def _af32(a: Int64) abi("C") -> UnsafePointer[Float32, MutExternalOrigin]: ...
16@extern("addr_to_u8")
17def _au8(a: Int64) abi("C") -> UnsafePointer[UInt8, MutExternalOrigin]: ...
18
19comptime NL: Int = 22; comptime N_BASE: Int = 3
20comptime N_LAYER_FILES: Int = 9; comptime N_FILES: Int = N_BASE + NL * N_LAYER_FILES
21
22comptime W_EMB: Int = 0; comptime W_OUT_NORM: Int = 1; comptime W_OUT: Int = 2
23comptime L_ATTN_NORM: Int = 0; comptime L_FFN_NORM: Int = 1
24comptime L_Q: Int = 2; comptime L_K: Int = 3; comptime L_V: Int = 4
25comptime L_O: Int = 5; comptime L_GATE: Int = 6; comptime L_UP: Int = 7
26comptime L_DOWN: Int = 8; comptime L_STRIDE: Int = 9
27
28var _wp: UnsafePointer[Int64, MutExternalOrigin] = UnsafePointer[Int64, MutExternalOrigin]()
29var _n_loaded: Int = 0
30
31def tl_load():
32 _wp = alloc[Int64](N_FILES)
33 for i in range(N_FILES): _wp.store(i, 0)
34 for idx in range(N_FILES):
35 var fsz = _fsz(idx)
36 if fsz < 0: print("Error: can't stat file", idx); return
37 if fsz == 0: continue
38 var buf = _c_malloc(fsz)
39 if buf == 0: print("Error: OOM for file", idx, "size", fsz); return
40 var nread = _fread(idx, _au8(buf), fsz)
41 if nread != fsz: print("Error: read mismatch", idx); _c_free(buf); return
42 _wp.store(idx, buf)
43 _n_loaded = N_FILES
44 print("Loaded", _n_loaded, "files (", N_BASE, "+", NL, "×", N_LAYER_FILES, ")")
45
46def tl_get(idx: Int) -> Int64:
47 if _n_loaded == 0 or idx < 0 or idx >= _n_loaded: return 0
48 return _wp.load(idx)
49
50def tl_free():
51 for idx in range(_n_loaded):
52 var p = _wp.load(idx)
53 if p != 0: _c_free(p)
54 _wp.free(); _n_loaded = 0