tensorload 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ """File-format dispatch."""
2
+ from __future__ import annotations
3
+
4
+ import glob
5
+ import json
6
+ import os
7
+ import zipfile
8
+ from typing import List
9
+
10
+ from ..core import MultiFile, TensorFile
11
+ from .gguf import GGUFFile, save_gguf
12
+ from .npz import NpzFile, save_npz
13
+ from .pytorch import PytorchFile
14
+ from .safetensors import SafetensorsFile, save_safetensors, save_safetensors_bf16
15
+
16
+ _EXT = {
17
+ ".gguf": "gguf", ".safetensors": "safetensors", ".npz": "npz", ".npy": "npz",
18
+ ".pt": "pytorch", ".pth": "pytorch", ".bin": "pytorch", ".ckpt": "pytorch",
19
+ }
20
+ FORMATS = ("gguf", "safetensors", "pytorch", "npz")
21
+
22
+
23
+ def detect_format(path: str) -> str:
24
+ """Identify a weight file by extension, falling back to its magic bytes."""
25
+ ext = os.path.splitext(path)[1].lower()
26
+ with open(path, "rb") as f:
27
+ head = f.read(8)
28
+ if head[:4] == b"GGUF":
29
+ return "gguf"
30
+ if head[:2] == b"PK":
31
+ try:
32
+ with zipfile.ZipFile(path) as zf:
33
+ names = zf.namelist()
34
+ if any(n.endswith("data.pkl") for n in names):
35
+ return "pytorch"
36
+ if any(n.endswith(".npy") for n in names):
37
+ return "npz"
38
+ except zipfile.BadZipFile:
39
+ pass
40
+ if head[:6] == b"\x93NUMPY":
41
+ return "npz"
42
+ if len(head) == 8 and ext in (".safetensors", ""):
43
+ return "safetensors"
44
+ if ext in _EXT:
45
+ return _EXT[ext]
46
+ raise ValueError(f"cannot determine the weight format of {path!r}")
47
+
48
+
49
+ def _open_one(path: str, fmt: str = None) -> TensorFile:
50
+ fmt = fmt or detect_format(path)
51
+ cls = {"gguf": GGUFFile, "safetensors": SafetensorsFile, "pytorch": PytorchFile, "npz": NpzFile}[fmt]
52
+ return cls(path)
53
+
54
+
55
+ def _shards_in_dir(d: str) -> List[str]:
56
+ for pattern in ("*.safetensors", "*.gguf", "pytorch_model*.bin", "*.pt", "*.pth", "*.npz"):
57
+ found = sorted(glob.glob(os.path.join(d, pattern)))
58
+ if found:
59
+ if pattern == "*.safetensors" and os.path.exists(os.path.join(d, "model.safetensors.index.json")):
60
+ with open(os.path.join(d, "model.safetensors.index.json")) as f:
61
+ names = sorted(set(json.load(f)["weight_map"].values()))
62
+ return [os.path.join(d, n) for n in names]
63
+ if pattern == "*.gguf":
64
+ return found[:1]
65
+ return found
66
+ raise FileNotFoundError(f"no weight files (.safetensors/.gguf/.bin/.pt/.npz) found in {d!r}")
67
+
68
+
69
+ def open_tensors(path, format: str = None) -> TensorFile:
70
+ """Open a weight file (or a directory of shards) lazily; format is auto-detected."""
71
+ path = os.fspath(path)
72
+ if os.path.isdir(path):
73
+ files = [_open_one(p, format) for p in _shards_in_dir(path)]
74
+ return files[0] if len(files) == 1 else MultiFile(files, path)
75
+ return _open_one(path, format)
76
+
77
+
78
+ __all__ = ["open_tensors", "detect_format", "FORMATS", "GGUFFile", "SafetensorsFile", "PytorchFile",
79
+ "NpzFile", "save_safetensors", "save_safetensors_bf16", "save_gguf", "save_npz"]
@@ -0,0 +1,215 @@
1
+ """GGUF (llama.cpp) reader and a simple writer."""
2
+ from __future__ import annotations
3
+
4
+ import mmap
5
+ import os
6
+ import struct
7
+ from typing import Any, Dict, Optional
8
+
9
+ import numpy as np
10
+
11
+ from ..core import TensorFile, TensorInfo
12
+ from .quant import GGML_TYPES, TYPE_IDS, dequantize, quantize
13
+
14
+ MAGIC = b"GGUF"
15
+
16
+ # metadata value types
17
+ _SCALAR_FMT = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}
18
+ _SCALAR_NP = {0: np.uint8, 1: np.int8, 2: np.uint16, 3: np.int16, 4: np.uint32, 5: np.int32,
19
+ 6: np.float32, 7: np.bool_, 10: np.uint64, 11: np.int64, 12: np.float64}
20
+ T_STRING, T_ARRAY = 8, 9
21
+
22
+
23
+ class GGUFFile(TensorFile):
24
+ format = "gguf"
25
+
26
+ def __init__(self, path):
27
+ super().__init__(path)
28
+ self._fh = open(path, "rb")
29
+ self._mm = mmap.mmap(self._fh.fileno(), 0, access=mmap.ACCESS_READ)
30
+ self._p = 0
31
+ try:
32
+ self._parse()
33
+ except Exception:
34
+ self.close()
35
+ raise
36
+
37
+ # -- low level readers ----------------------------------------------------
38
+ def _unpack(self, fmt: str):
39
+ size = struct.calcsize(fmt)
40
+ (v,) = struct.unpack_from(fmt, self._mm, self._p)
41
+ self._p += size
42
+ return v
43
+
44
+ def _string(self) -> str:
45
+ n = self._unpack("<Q")
46
+ s = bytes(self._mm[self._p:self._p + n]).decode("utf-8", errors="replace")
47
+ self._p += n
48
+ return s
49
+
50
+ def _value(self, t: int):
51
+ if t in _SCALAR_FMT:
52
+ return self._unpack(_SCALAR_FMT[t])
53
+ if t == T_STRING:
54
+ return self._string()
55
+ if t == T_ARRAY:
56
+ et = self._unpack("<I")
57
+ n = self._unpack("<Q")
58
+ if et in _SCALAR_NP:
59
+ dt = np.dtype(_SCALAR_NP[et])
60
+ arr = np.frombuffer(self._mm, dtype=dt, count=n, offset=self._p).copy()
61
+ self._p += n * dt.itemsize
62
+ return arr
63
+ return [self._value(et) for _ in range(n)]
64
+ raise ValueError(f"unknown GGUF metadata value type {t}")
65
+
66
+ # -- parsing --------------------------------------------------------------
67
+ def _parse(self):
68
+ if bytes(self._mm[:4]) != MAGIC:
69
+ raise ValueError("not a GGUF file (bad magic)")
70
+ self._p = 4
71
+ self.version = self._unpack("<I")
72
+ if self.version not in (2, 3):
73
+ raise ValueError(f"unsupported GGUF version {self.version} (need 2 or 3)")
74
+ n_tensors = self._unpack("<Q")
75
+ n_kv = self._unpack("<Q")
76
+ md: Dict[str, Any] = {}
77
+ for _ in range(n_kv):
78
+ key = self._string()
79
+ t = self._unpack("<I")
80
+ md[key] = self._value(t)
81
+ self.metadata = md
82
+ self._tensors: Dict[str, tuple] = {}
83
+ for _ in range(n_tensors):
84
+ name = self._string()
85
+ nd = self._unpack("<I")
86
+ dims = tuple(self._unpack("<Q") for _ in range(nd))
87
+ gt = self._unpack("<I")
88
+ off = self._unpack("<Q")
89
+ self._tensors[name] = (dims, gt, off)
90
+ align = int(md.get("general.alignment", 32))
91
+ self._data_start = (self._p + align - 1) // align * align
92
+
93
+ # -- TensorFile API -------------------------------------------------------
94
+ @property
95
+ def architecture(self) -> Optional[str]:
96
+ return self.metadata.get("general.architecture")
97
+
98
+ def keys(self):
99
+ return list(self._tensors)
100
+
101
+ def __contains__(self, name):
102
+ return name in self._tensors
103
+
104
+ @staticmethod
105
+ def _numel(dims) -> int:
106
+ n = 1
107
+ for d in dims:
108
+ n *= int(d)
109
+ return n
110
+
111
+ def info(self, name):
112
+ dims, gt, _ = self._tensors[name]
113
+ tname, blk, bsz = GGML_TYPES.get(gt, (f"type{gt}", 1, 0))
114
+ return TensorInfo(name, tuple(reversed(dims)), tname, self._numel(dims) // blk * bsz)
115
+
116
+ def get_raw(self, name):
117
+ """Return ``(raw_bytes_uint8, ggml_type_name)`` without dequantising."""
118
+ dims, gt, off = self._tensors[name]
119
+ if gt not in GGML_TYPES:
120
+ raise NotImplementedError(f"unknown GGML type id {gt} for tensor {name!r}")
121
+ tname, blk, bsz = GGML_TYPES[gt]
122
+ nbytes = self._numel(dims) // blk * bsz
123
+ raw = np.frombuffer(self._mm, dtype=np.uint8, count=nbytes, offset=self._data_start + off)
124
+ return raw, tname
125
+
126
+ def get(self, name):
127
+ dims, gt, off = self._tensors[name]
128
+ raw, _ = self.get_raw(name)
129
+ return dequantize(raw, gt, self._numel(dims)).reshape(tuple(reversed(dims)))
130
+
131
+ def close(self):
132
+ try:
133
+ self._mm.close()
134
+ except (BufferError, ValueError):
135
+ pass
136
+ self._fh.close()
137
+
138
+
139
+ # --------------------------------------------------------------------------- writer
140
+ def _w_string(s: str) -> bytes:
141
+ b = s.encode("utf-8")
142
+ return struct.pack("<Q", len(b)) + b
143
+
144
+
145
+ def _infer_type(v) -> int:
146
+ if isinstance(v, (bool, np.bool_)): return 7
147
+ if isinstance(v, str): return 8
148
+ if isinstance(v, (int, np.integer)):
149
+ return 4 if 0 <= int(v) < 2**32 else (5 if -2**31 <= int(v) < 2**31 else 11)
150
+ if isinstance(v, (float, np.floating)): return 6
151
+ raise TypeError(f"unsupported metadata value {v!r}")
152
+
153
+
154
+ def _array_elem_type(v) -> int:
155
+ types = {_infer_type(x) for x in v}
156
+ if not types: return 4
157
+ if types == {8}: return 8
158
+ if types == {7}: return 7
159
+ if 6 in types and types <= {4, 5, 6, 11}: return 6
160
+ if types <= {4}: return 4
161
+ if types <= {4, 5}: return 5
162
+ if types <= {4, 5, 11}: return 11
163
+ raise TypeError("metadata arrays must be homogeneous")
164
+
165
+
166
+ def _w_value(v, t: Optional[int] = None) -> tuple:
167
+ if isinstance(v, np.ndarray):
168
+ v = v.tolist()
169
+ if isinstance(v, (list, tuple)):
170
+ et = _array_elem_type(v)
171
+ body = struct.pack("<IQ", et, len(v)) + b"".join(_w_value(x, et)[1] for x in v)
172
+ return T_ARRAY, body
173
+ t = _infer_type(v) if t is None else t
174
+ if t == T_STRING:
175
+ return t, _w_string(v)
176
+ return t, struct.pack(_SCALAR_FMT[t], v)
177
+
178
+
179
+ def save_gguf(path, tensors: Dict[str, np.ndarray], metadata: Optional[Dict[str, Any]] = None,
180
+ dtype: str = "F32", alignment: int = 32) -> None:
181
+ """Write a GGUF file.
182
+
183
+ ``dtype`` is one of F32, F16, BF16, Q8_0, Q4_0 and applies to float tensors with
184
+ ``ndim >= 2`` (1-D tensors such as norms stay F32). Include ``general.architecture``
185
+ in ``metadata`` if llama.cpp/tensorload should recognise the model.
186
+ """
187
+ md = dict(metadata or {})
188
+ if alignment != 32:
189
+ md.setdefault("general.alignment", alignment)
190
+ kv = b""
191
+ for k, v in md.items():
192
+ t, body = _w_value(v)
193
+ kv += _w_string(k) + struct.pack("<I", t) + body
194
+ infos, blobs, off = b"", [], 0
195
+ for name, arr in tensors.items():
196
+ a = np.asarray(arr)
197
+ tname = dtype if (a.ndim >= 2 and np.issubdtype(a.dtype, np.floating)) else (
198
+ "F16" if a.dtype == np.float16 else "F32" if np.issubdtype(a.dtype, np.floating) else None)
199
+ if tname is None:
200
+ raise TypeError(f"tensor {name!r}: only floating point tensors can be written")
201
+ if tname.startswith("Q") and a.shape[-1] % 32:
202
+ tname = "F32" # block quantisation impossible for this shape
203
+ data = quantize(a, tname)
204
+ pad = (-len(data)) % alignment
205
+ dims = tuple(reversed(a.shape))
206
+ infos += _w_string(name) + struct.pack("<I", len(dims)) + b"".join(struct.pack("<Q", d) for d in dims)
207
+ infos += struct.pack("<IQ", TYPE_IDS[tname], off)
208
+ blobs.append(data + b"\0" * pad)
209
+ off += len(data) + pad
210
+ header = MAGIC + struct.pack("<IQQ", 3, len(tensors), len(md)) + kv + infos
211
+ header += b"\0" * ((-len(header)) % alignment)
212
+ with open(path, "wb") as f:
213
+ f.write(header)
214
+ for b in blobs:
215
+ f.write(b)
@@ -0,0 +1,59 @@
1
+ """NumPy ``.npz`` / ``.npy`` reader and writer (pickles are never loaded)."""
2
+ from __future__ import annotations
3
+
4
+ import zipfile
5
+ from typing import Dict
6
+
7
+ import numpy as np
8
+ from numpy.lib import format as npformat
9
+
10
+ from ..core import TensorFile, TensorInfo
11
+
12
+
13
+ class NpzFile(TensorFile):
14
+ format = "npz"
15
+
16
+ def __init__(self, path):
17
+ super().__init__(path)
18
+ self._single = str(path).endswith(".npy")
19
+ if self._single:
20
+ self._arr = np.load(path, allow_pickle=False)
21
+ self._names = ["array"]
22
+ self._zf = None
23
+ else:
24
+ self._zf = zipfile.ZipFile(path)
25
+ self._names = [n[:-4] for n in self._zf.namelist() if n.endswith(".npy")]
26
+
27
+ def keys(self):
28
+ return list(self._names)
29
+
30
+ def __contains__(self, name):
31
+ return name in self._names
32
+
33
+ def info(self, name):
34
+ if self._single:
35
+ a = self._arr
36
+ return TensorInfo(name, tuple(a.shape), str(a.dtype), a.nbytes)
37
+ with self._zf.open(name + ".npy") as fh:
38
+ ver = npformat.read_magic(fh)
39
+ reader = npformat.read_array_header_1_0 if ver == (1, 0) else npformat.read_array_header_2_0
40
+ shape, _fortran, dt = reader(fh)
41
+ n = 1
42
+ for d in shape:
43
+ n *= d
44
+ return TensorInfo(name, tuple(shape), str(dt), n * dt.itemsize)
45
+
46
+ def get(self, name):
47
+ if self._single:
48
+ return self._arr.copy()
49
+ import io
50
+ with self._zf.open(name + ".npy") as fh:
51
+ return np.load(io.BytesIO(fh.read()), allow_pickle=False)
52
+
53
+ def close(self):
54
+ if self._zf is not None:
55
+ self._zf.close()
56
+
57
+
58
+ def save_npz(tensors: Dict[str, np.ndarray], path, compressed: bool = False) -> None:
59
+ (np.savez_compressed if compressed else np.savez)(path, **{k: np.asarray(v) for k, v in tensors.items()})
@@ -0,0 +1,178 @@
1
+ """Safe reader for PyTorch ``.pt`` / ``.pth`` / ``.bin`` checkpoints.
2
+
3
+ The modern zip format is parsed with a *restricted* unpickler that only understands
4
+ tensors, storages and ``OrderedDict`` - arbitrary code in a checkpoint can never run.
5
+ Legacy (pre-1.6) files are delegated to ``torch.load(weights_only=True)`` if torch is
6
+ installed.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import collections
11
+ import pickle
12
+ import zipfile
13
+ from typing import Dict
14
+
15
+ import numpy as np
16
+
17
+ from .._dtypes import bf16_to_f32
18
+ from ..core import TensorFile, TensorInfo
19
+
20
+ _STORAGE_DTYPES = {
21
+ "FloatStorage": np.float32, "DoubleStorage": np.float64, "HalfStorage": np.float16,
22
+ "BFloat16Storage": "bf16", "LongStorage": np.int64, "IntStorage": np.int32,
23
+ "ShortStorage": np.int16, "CharStorage": np.int8, "ByteStorage": np.uint8,
24
+ "BoolStorage": np.bool_,
25
+ }
26
+ _TORCH_DTYPE_NAMES = {
27
+ "float32": np.float32, "float": np.float32, "float64": np.float64, "double": np.float64,
28
+ "float16": np.float16, "half": np.float16, "bfloat16": "bf16", "int64": np.int64,
29
+ "long": np.int64, "int32": np.int32, "int": np.int32, "int16": np.int16,
30
+ "int8": np.int8, "uint8": np.uint8, "bool": np.bool_,
31
+ }
32
+
33
+
34
+ class _StorageType:
35
+ def __init__(self, name):
36
+ self.name = name
37
+ self.dtype = _STORAGE_DTYPES[name]
38
+
39
+
40
+ def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad=False, hooks=None, metadata=None):
41
+ arr = storage
42
+ itemsize = arr.dtype.itemsize
43
+ size = tuple(int(s) for s in size)
44
+ if len(size) == 0:
45
+ return np.array(arr[int(storage_offset)]).reshape(())
46
+ if any(s == 0 for s in size):
47
+ return np.empty(size, dtype=arr.dtype)
48
+ view = np.lib.stride_tricks.as_strided(
49
+ arr[int(storage_offset):], shape=size, strides=tuple(int(s) * itemsize for s in stride))
50
+ return np.array(view)
51
+
52
+
53
+ def _rebuild_parameter(data, requires_grad=False, hooks=None, state=None):
54
+ return data
55
+
56
+
57
+ class _Unpickler(pickle.Unpickler):
58
+ def __init__(self, fh, zf: zipfile.ZipFile, prefix: str):
59
+ super().__init__(fh)
60
+ self._zf, self._prefix, self._cache = zf, prefix, {}
61
+
62
+ def find_class(self, module, name):
63
+ if module == "collections" and name == "OrderedDict":
64
+ return collections.OrderedDict
65
+ if module == "torch._utils":
66
+ if name in ("_rebuild_tensor_v2", "_rebuild_tensor"):
67
+ return _rebuild_tensor_v2
68
+ if name in ("_rebuild_parameter", "_rebuild_parameter_with_state"):
69
+ return _rebuild_parameter
70
+ if module == "torch" and name in _STORAGE_DTYPES:
71
+ return _StorageType(name)
72
+ if module == "torch" and name == "Size":
73
+ return tuple
74
+ if module == "torch.nn.parameter" and name == "Parameter":
75
+ return _rebuild_parameter
76
+ raise pickle.UnpicklingError(
77
+ f"checkpoint references {module}.{name}, which tensorload refuses to load "
78
+ f"(only plain tensor state dicts are supported)")
79
+
80
+ def persistent_load(self, pid):
81
+ if not (isinstance(pid, tuple) and pid and pid[0] == "storage"):
82
+ raise pickle.UnpicklingError(f"unsupported persistent id {pid!r}")
83
+ _, stype, key, _loc, _numel = pid[:5]
84
+ if key in self._cache:
85
+ return self._cache[key]
86
+ if isinstance(stype, _StorageType):
87
+ dt = stype.dtype
88
+ else:
89
+ dt = _TORCH_DTYPE_NAMES[str(stype).split(".")[-1]]
90
+ data = self._zf.read(f"{self._prefix}data/{key}")
91
+ if dt == "bf16":
92
+ arr = bf16_to_f32(np.frombuffer(data, dtype=np.uint16))
93
+ else:
94
+ arr = np.frombuffer(data, dtype=dt)
95
+ self._cache[key] = arr
96
+ return arr
97
+
98
+
99
+ def _flatten(obj, prefix="") -> Dict[str, np.ndarray]:
100
+ out: Dict[str, np.ndarray] = {}
101
+ if isinstance(obj, np.ndarray):
102
+ out[prefix] = obj
103
+ elif isinstance(obj, dict):
104
+ for k, v in obj.items():
105
+ out.update(_flatten(v, f"{prefix}.{k}" if prefix else str(k)))
106
+ return out
107
+
108
+
109
+ _WRAPPER_KEYS = ("state_dict", "model_state_dict", "model", "module", "network", "net", "weights")
110
+
111
+
112
+ def load_pt_dict(path: str) -> Dict[str, np.ndarray]:
113
+ if not zipfile.is_zipfile(path):
114
+ try:
115
+ import torch # type: ignore
116
+ except ImportError:
117
+ raise RuntimeError(
118
+ f"{path} is a legacy (pre-1.6) PyTorch file; install torch to read it, "
119
+ "or re-save it with a recent torch.save()") from None
120
+ obj = torch.load(path, map_location="cpu", weights_only=True)
121
+ flat = {}
122
+ for k, v in _flatten_torch(obj).items():
123
+ flat[k] = v
124
+ return flat
125
+ with zipfile.ZipFile(path) as zf:
126
+ pkl = [n for n in zf.namelist() if n.endswith("data.pkl")]
127
+ if not pkl:
128
+ raise ValueError(f"{path}: zip archive has no data.pkl - not a PyTorch checkpoint")
129
+ prefix = pkl[0][: -len("data.pkl")]
130
+ with zf.open(pkl[0]) as fh:
131
+ obj = _Unpickler(fh, zf, prefix).load()
132
+ if isinstance(obj, dict) and not _flatten({k: v for k, v in obj.items() if isinstance(v, np.ndarray)}):
133
+ for key in _WRAPPER_KEYS:
134
+ if key in obj and isinstance(obj[key], dict):
135
+ obj = obj[key]
136
+ break
137
+ flat = _flatten(obj)
138
+ if not flat:
139
+ raise ValueError(f"{path}: no tensors found in checkpoint")
140
+ return flat
141
+
142
+
143
+ def _flatten_torch(obj, prefix=""):
144
+ import torch # type: ignore
145
+ out = {}
146
+ if isinstance(obj, torch.Tensor):
147
+ t = obj.detach().cpu()
148
+ if t.dtype == torch.bfloat16:
149
+ t = t.float()
150
+ out[prefix] = t.numpy()
151
+ elif isinstance(obj, dict):
152
+ for k, v in obj.items():
153
+ out.update(_flatten_torch(v, f"{prefix}.{k}" if prefix else str(k)))
154
+ return out
155
+
156
+
157
+ class PytorchFile(TensorFile):
158
+ format = "pytorch"
159
+
160
+ def __init__(self, path):
161
+ super().__init__(path)
162
+ self._tensors = load_pt_dict(str(path))
163
+
164
+ def keys(self):
165
+ return list(self._tensors)
166
+
167
+ def __contains__(self, name):
168
+ return name in self._tensors
169
+
170
+ def info(self, name):
171
+ a = self._tensors[name]
172
+ return TensorInfo(name, tuple(a.shape), str(a.dtype), a.nbytes)
173
+
174
+ def get(self, name):
175
+ return self._tensors[name].copy()
176
+
177
+ def close(self):
178
+ self._tensors = {}
@@ -0,0 +1,160 @@
1
+ """GGML block-quantisation kernels (dequantise everything, quantise a few types)."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+
6
+ from .._dtypes import bf16_to_f32
7
+
8
+ # id: (name, elements per block, bytes per block)
9
+ GGML_TYPES = {
10
+ 0: ("F32", 1, 4), 1: ("F16", 1, 2), 2: ("Q4_0", 32, 18), 3: ("Q4_1", 32, 20),
11
+ 6: ("Q5_0", 32, 22), 7: ("Q5_1", 32, 24), 8: ("Q8_0", 32, 34), 9: ("Q8_1", 32, 40),
12
+ 10: ("Q2_K", 256, 84), 11: ("Q3_K", 256, 110), 12: ("Q4_K", 256, 144),
13
+ 13: ("Q5_K", 256, 176), 14: ("Q6_K", 256, 210), 15: ("Q8_K", 256, 292),
14
+ 16: ("IQ2_XXS", 256, 66), 17: ("IQ2_XS", 256, 74), 18: ("IQ3_XXS", 256, 98),
15
+ 19: ("IQ1_S", 256, 50), 20: ("IQ4_NL", 32, 18), 21: ("IQ3_S", 256, 110),
16
+ 22: ("IQ2_S", 256, 82), 23: ("IQ4_XS", 256, 136), 24: ("I8", 1, 1), 25: ("I16", 1, 2),
17
+ 26: ("I32", 1, 4), 27: ("I64", 1, 8), 28: ("F64", 1, 8), 29: ("IQ1_M", 256, 56),
18
+ 30: ("BF16", 1, 2),
19
+ }
20
+ TYPE_IDS = {v[0]: k for k, v in GGML_TYPES.items()}
21
+
22
+ SUPPORTED = {"F32", "F16", "BF16", "F64", "I8", "I16", "I32", "I64",
23
+ "Q4_0", "Q4_1", "Q5_0", "Q5_1", "Q8_0", "Q2_K", "Q4_K", "Q5_K", "Q6_K"}
24
+
25
+
26
+ def _f16(b: np.ndarray) -> np.ndarray:
27
+ """(n,2) uint8 -> (n,1) float32."""
28
+ return np.ascontiguousarray(b).view(np.float16).astype(np.float32)
29
+
30
+
31
+ def _nibbles(qs: np.ndarray):
32
+ return (qs & 0x0F), (qs >> 4)
33
+
34
+
35
+ def _scale_min_k4(s: np.ndarray):
36
+ """Unpack the 12-byte 6-bit scale/min block used by Q4_K and Q5_K -> two (n,8) arrays."""
37
+ sc = np.empty((s.shape[0], 8), dtype=np.uint8)
38
+ mn = np.empty_like(sc)
39
+ sc[:, :4] = s[:, 0:4] & 63
40
+ mn[:, :4] = s[:, 4:8] & 63
41
+ sc[:, 4:] = (s[:, 8:12] & 0x0F) | ((s[:, 0:4] >> 6) << 4)
42
+ mn[:, 4:] = (s[:, 8:12] >> 4) | ((s[:, 4:8] >> 6) << 4)
43
+ return sc.astype(np.float32), mn.astype(np.float32)
44
+
45
+
46
+ def dequantize(raw: np.ndarray, ggml_type: int, n_elems: int) -> np.ndarray:
47
+ """Decode ``raw`` (uint8 bytes) of a GGML tensor to a flat float32/int array."""
48
+ if ggml_type not in GGML_TYPES:
49
+ raise NotImplementedError(f"unknown GGML tensor type id {ggml_type}")
50
+ name, blk, bsz = GGML_TYPES[ggml_type]
51
+ raw = np.ascontiguousarray(raw, dtype=np.uint8)
52
+ if name not in SUPPORTED:
53
+ raise NotImplementedError(
54
+ f"GGML type {name} is not supported by tensorload yet "
55
+ f"(supported: {', '.join(sorted(SUPPORTED))})")
56
+ if name == "F32": return raw.view(np.float32)[:n_elems].copy()
57
+ if name == "F16": return raw.view(np.float16)[:n_elems].astype(np.float32)
58
+ if name == "BF16": return bf16_to_f32(raw.view(np.uint16)[:n_elems])
59
+ if name == "F64": return raw.view(np.float64)[:n_elems].copy()
60
+ if name in ("I8", "I16", "I32", "I64"):
61
+ return raw.view({"I8": np.int8, "I16": np.int16, "I32": np.int32, "I64": np.int64}[name])[:n_elems].copy()
62
+
63
+ b = raw[: (n_elems // blk) * bsz].reshape(-1, bsz)
64
+ n = b.shape[0]
65
+
66
+ if name == "Q8_0":
67
+ d = _f16(b[:, :2])
68
+ q = np.ascontiguousarray(b[:, 2:]).view(np.int8).astype(np.float32)
69
+ return (q * d).reshape(-1)
70
+ if name == "Q4_0":
71
+ d = _f16(b[:, :2])
72
+ lo, hi = _nibbles(b[:, 2:])
73
+ q = np.concatenate([lo, hi], axis=1).astype(np.float32) - 8.0
74
+ return (q * d).reshape(-1)
75
+ if name == "Q4_1":
76
+ d, m = _f16(b[:, 0:2]), _f16(b[:, 2:4])
77
+ lo, hi = _nibbles(b[:, 4:])
78
+ q = np.concatenate([lo, hi], axis=1).astype(np.float32)
79
+ return (q * d + m).reshape(-1)
80
+ if name in ("Q5_0", "Q5_1"):
81
+ if name == "Q5_0":
82
+ d, m, o = _f16(b[:, 0:2]), 0.0, 2
83
+ else:
84
+ d, m, o = _f16(b[:, 0:2]), _f16(b[:, 2:4]), 4
85
+ qh = np.ascontiguousarray(b[:, o:o + 4]).view(np.uint32) # (n,1)
86
+ bits = ((qh >> np.arange(32, dtype=np.uint32)) & 1).astype(np.uint8) # (n,32)
87
+ lo, hi = _nibbles(b[:, o + 4:])
88
+ q = np.concatenate([lo | (bits[:, :16] << 4), hi | (bits[:, 16:] << 4)], axis=1).astype(np.float32)
89
+ if name == "Q5_0":
90
+ return ((q - 16.0) * d).reshape(-1)
91
+ return (q * d + m).reshape(-1)
92
+ if name == "Q2_K":
93
+ sc, d, dmin = b[:, 0:16], _f16(b[:, 80:82]), _f16(b[:, 82:84])
94
+ qs = b[:, 16:80].reshape(n, 2, 32)
95
+ q = np.stack([(qs >> (2 * j)) & 3 for j in range(4)], axis=2) # (n,2,4,32)
96
+ q = q.reshape(n, 2, 4, 2, 16).astype(np.float32)
97
+ scale = (sc & 0x0F).astype(np.float32).reshape(n, 2, 4, 2, 1)
98
+ mins = (sc >> 4).astype(np.float32).reshape(n, 2, 4, 2, 1)
99
+ y = d.reshape(n, 1, 1, 1, 1) * scale * q - dmin.reshape(n, 1, 1, 1, 1) * mins
100
+ return y.reshape(-1)
101
+ if name == "Q4_K":
102
+ d, dmin = _f16(b[:, 0:2]), _f16(b[:, 2:4])
103
+ sc, mn = _scale_min_k4(b[:, 4:16])
104
+ qs = b[:, 16:144].reshape(n, 4, 32)
105
+ q = np.stack([qs & 0x0F, qs >> 4], axis=2).reshape(n, 8, 32).astype(np.float32)
106
+ y = (d[:, :, None] * sc[:, :, None]) * q - (dmin[:, :, None] * mn[:, :, None])
107
+ return y.reshape(-1)
108
+ if name == "Q5_K":
109
+ d, dmin = _f16(b[:, 0:2]), _f16(b[:, 2:4])
110
+ sc, mn = _scale_min_k4(b[:, 4:16])
111
+ qh = b[:, 16:48]
112
+ qs = b[:, 48:176].reshape(n, 4, 32)
113
+ bits = (qh[:, None, :] >> np.arange(8, dtype=np.uint8)[None, :, None]) & 1 # (n,8,32)
114
+ q = np.stack([qs & 0x0F, qs >> 4], axis=2).reshape(n, 8, 32) | (bits << 4)
115
+ y = (d[:, :, None] * sc[:, :, None]) * q.astype(np.float32) - (dmin[:, :, None] * mn[:, :, None])
116
+ return y.reshape(-1)
117
+ if name == "Q6_K":
118
+ ql = b[:, 0:128].reshape(n, 2, 64)
119
+ qh = b[:, 128:192].reshape(n, 2, 32)
120
+ sc = np.ascontiguousarray(b[:, 192:208]).view(np.int8).astype(np.float32)
121
+ d = _f16(b[:, 208:210])
122
+ a, c = ql[:, :, 0:32], ql[:, :, 32:64]
123
+ q = np.stack([
124
+ (a & 0x0F) | ((qh & 3) << 4),
125
+ (c & 0x0F) | (((qh >> 2) & 3) << 4),
126
+ (a >> 4) | (((qh >> 4) & 3) << 4),
127
+ (c >> 4) | (((qh >> 6) & 3) << 4),
128
+ ], axis=2).astype(np.float32) - 32.0 # (n,2,4,32)
129
+ q = q.reshape(n, 2, 4, 2, 16)
130
+ y = q * sc.reshape(n, 2, 4, 2, 1) * d.reshape(n, 1, 1, 1, 1)
131
+ return y.reshape(-1)
132
+ raise NotImplementedError(name) # pragma: no cover
133
+
134
+
135
+ def quantize(x: np.ndarray, name: str) -> bytes:
136
+ """Quantise a float array (last dim divisible by the block size) to GGML bytes."""
137
+ x = np.ascontiguousarray(x, dtype=np.float32).reshape(-1)
138
+ if name == "F32": return x.tobytes()
139
+ if name == "F16": return x.astype(np.float16).tobytes()
140
+ if name == "BF16":
141
+ from .._dtypes import f32_to_bf16_bits
142
+ return f32_to_bf16_bits(x).tobytes()
143
+ if name not in ("Q8_0", "Q4_0"):
144
+ raise NotImplementedError(f"writing {name} is not supported (try F32, F16, BF16, Q8_0, Q4_0)")
145
+ if x.size % 32:
146
+ raise ValueError("tensor size must be a multiple of 32 for Q8_0/Q4_0")
147
+ blocks = x.reshape(-1, 32)
148
+ if name == "Q8_0":
149
+ d = np.abs(blocks).max(axis=1, keepdims=True) / 127.0
150
+ inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1), 0.0)
151
+ q = np.rint(blocks * inv).astype(np.int8)
152
+ out = np.concatenate([d.astype(np.float16).view(np.uint8), q.view(np.uint8)], axis=1)
153
+ return out.tobytes()
154
+ idx = np.abs(blocks).argmax(axis=1)
155
+ mx = blocks[np.arange(len(blocks)), idx][:, None]
156
+ d = mx / -8.0
157
+ inv = np.where(d != 0, 1.0 / np.where(d != 0, d, 1), 0.0)
158
+ q = np.clip(np.floor(blocks * inv + 8.5), 0, 15).astype(np.uint8)
159
+ packed = q[:, :16] | (q[:, 16:] << 4)
160
+ return np.concatenate([d.astype(np.float16).view(np.uint8), packed], axis=1).tobytes()