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 / gguf / reader.mojo

136 lines · 5113 bytes Raw Blame History
1from std.python import Python, PythonObject
2from .types import *
3
4struct GGUFFile:
5 var data: PythonObject
6 var offset: PythonObject
7 var alignment: UInt64
8
9 fn __init__(out self, path: String) raises:
10 self.data = Python.evaluate("open")(path, "rb").read()
11 self.offset = Python.evaluate("0")
12 self.alignment = 32
13
14 fn read_slice(mut self, n: PythonObject) raises -> PythonObject:
15 var py_slice = Python.evaluate("slice")(self.offset, self.offset + n)
16 var result = self.data[py_slice]
17 self.offset = self.offset + n
18 return result
19
20 fn read_py_uint32(mut self) raises -> PythonObject:
21 var b = self.read_slice(Python.evaluate("4"))
22 return Python.evaluate("int.from_bytes")(b, "little")
23
24 fn read_py_uint64(mut self) raises -> PythonObject:
25 var b = self.read_slice(Python.evaluate("8"))
26 return Python.evaluate("int.from_bytes")(b, "little")
27
28 fn read_uint32(mut self) raises -> UInt32:
29 return UInt32(py=self.read_py_uint32())
30
31 fn read_uint64(mut self) raises -> UInt64:
32 return UInt64(py=self.read_py_uint64())
33
34 fn read_string(mut self) raises -> PythonObject:
35 var length = self.read_py_uint64()
36 var raw = self.read_slice(length)
37 return raw.decode("utf-8")
38
39fn load_gguf(path: String) raises -> PythonObject:
40 var f = GGUFFile(path)
41
42 var magic = f.read_uint32()
43 if magic != GGUF_MAGIC:
44 print("Invalid GGUF magic:", magic)
45 return Python.evaluate("None")
46
47 var version = f.read_uint32()
48 if version != GGUF_VERSION:
49 print("Unsupported GGUF version:", version)
50 return Python.evaluate("None")
51
52 var tensor_count = Int(py=f.read_py_uint64())
53 var metadata_kv_count = Int(py=f.read_py_uint64())
54
55 var metadata = Python.evaluate("{}")
56 var struct_mod = Python.evaluate("__import__('struct')")
57
58 for i in range(metadata_kv_count):
59 var key = f.read_string()
60 var value_type = f.read_uint32()
61 var value: PythonObject
62
63 if value_type == GGUFValueType.STRING:
64 value = f.read_string()
65 elif value_type == GGUFValueType.UINT32 or value_type == GGUFValueType.INT32:
66 value = f.read_py_uint32()
67 elif value_type == GGUFValueType.UINT64 or value_type == GGUFValueType.INT64:
68 value = f.read_py_uint64()
69 elif value_type == GGUFValueType.FLOAT32:
70 var bits = f.read_py_uint32()
71 var b4 = struct_mod.pack("I", bits)
72 value = struct_mod.unpack("f", b4)[0]
73 elif value_type == GGUFValueType.FLOAT64:
74 var bits_lo = f.read_py_uint32()
75 var bits_hi = f.read_py_uint32()
76 var b8 = struct_mod.pack("II", bits_lo, bits_hi)
77 value = struct_mod.unpack("d", b8)[0]
78 elif value_type == GGUFValueType.BOOL:
79 var byte_slice = f.read_slice(Python.evaluate("1"))
80 value = Python.evaluate("bool")(byte_slice[0])
81 elif value_type == GGUFValueType.ARRAY:
82 var arr_type = f.read_uint32()
83 var arr_len = Int(py=f.read_py_uint64())
84 var arr = Python.evaluate("[]")
85 for j in range(arr_len):
86 if arr_type == GGUFValueType.STRING:
87 arr.append(f.read_string())
88 elif arr_type == GGUFValueType.UINT32 or arr_type == GGUFValueType.INT32:
89 arr.append(f.read_py_uint32())
90 elif arr_type == GGUFValueType.FLOAT32:
91 var bits2 = f.read_py_uint32()
92 var b4_2 = struct_mod.pack("I", bits2)
93 arr.append(struct_mod.unpack("f", b4_2)[0])
94 elif arr_type == GGUFValueType.UINT64 or arr_type == GGUFValueType.INT64:
95 arr.append(f.read_py_uint64())
96 value = arr
97 else:
98 value = Python.evaluate("None")
99
100 metadata[key] = value
101
102 var alignment = GGUF_DEFAULT_ALIGNMENT
103 if metadata.__contains__("general.alignment"):
104 alignment = UInt64(py=metadata["general.alignment"])
105 f.alignment = alignment
106
107 var tensor_info_list = Python.evaluate("[]")
108 for i in range(tensor_count):
109 var name = f.read_string()
110 var n_dim = Int(py=f.read_py_uint32())
111 var dims = Python.evaluate("[]")
112 for j in range(n_dim):
113 dims.append(f.read_py_uint64())
114 var dtype = f.read_uint32()
115 var offset = f.read_py_uint64()
116
117 var n_elems: UInt64 = 1
118 for j in range(n_dim):
119 n_elems *= UInt64(py=dims[j])
120 var size_bytes = ggml_type_size_in_bytes(dtype, n_elems)
121
122 var t = Python.evaluate("{}")
123 t["name"] = name
124 t["n_dimensions"] = n_dim
125 t["dimensions"] = dims
126 t["dtype"] = dtype
127 t["offset"] = offset
128 t["size_bytes"] = size_bytes
129 tensor_info_list.append(t)
130
131 metadata["_tensor_count"] = tensor_count
132 metadata["_tensor_info"] = tensor_info_list
133 metadata["_alignment"] = alignment
134 metadata["_tensor_data_offset"] = f.offset
135
136 return metadata