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.
- tensorload/__init__.py +87 -0
- tensorload/_dtypes.py +16 -0
- tensorload/chat.py +31 -0
- tensorload/cli.py +125 -0
- tensorload/core.py +118 -0
- tensorload/engine.py +273 -0
- tensorload/formats/__init__.py +79 -0
- tensorload/formats/gguf.py +215 -0
- tensorload/formats/npz.py +59 -0
- tensorload/formats/pytorch.py +178 -0
- tensorload/formats/quant.py +160 -0
- tensorload/formats/safetensors.py +136 -0
- tensorload/hub.py +282 -0
- tensorload/llm.py +146 -0
- tensorload/sampling.py +46 -0
- tensorload/tokenizer.py +344 -0
- tensorload-0.1.0.dist-info/METADATA +120 -0
- tensorload-0.1.0.dist-info/RECORD +22 -0
- tensorload-0.1.0.dist-info/WHEEL +5 -0
- tensorload-0.1.0.dist-info/entry_points.txt +2 -0
- tensorload-0.1.0.dist-info/licenses/LICENSE +21 -0
- tensorload-0.1.0.dist-info/top_level.txt +1 -0
tensorload/tokenizer.py
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Tokenizers.
|
|
2
|
+
|
|
3
|
+
* :func:`load_tokenizer_from_dir` - HF ``tokenizer.json`` (uses the ``tokenizers`` package when
|
|
4
|
+
installed for exact behaviour, otherwise a built-in byte-level BPE).
|
|
5
|
+
* :func:`load_tokenizer_from_gguf` - vocabulary embedded in a GGUF file
|
|
6
|
+
(``gpt2``-style BPE and ``llama``-style SentencePiece-BPE).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import warnings
|
|
14
|
+
from typing import Dict, Iterable, List, Optional, Sequence
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
__all__ = ["Tokenizer", "load_tokenizer_from_dir", "load_tokenizer_from_gguf"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Tokenizer:
|
|
22
|
+
"""Minimal common interface."""
|
|
23
|
+
|
|
24
|
+
bos_id: Optional[int] = None
|
|
25
|
+
eos_ids: List[int] = []
|
|
26
|
+
vocab_size: int = 0
|
|
27
|
+
chat_template: Optional[str] = None
|
|
28
|
+
bos_token: Optional[str] = None
|
|
29
|
+
eos_token: Optional[str] = None
|
|
30
|
+
|
|
31
|
+
def encode(self, text: str, add_special: bool = True) -> List[int]:
|
|
32
|
+
raise NotImplementedError
|
|
33
|
+
|
|
34
|
+
def decode(self, ids: Sequence[int], skip_special: bool = True) -> str:
|
|
35
|
+
raise NotImplementedError
|
|
36
|
+
|
|
37
|
+
def token_to_id(self, token: str) -> Optional[int]:
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ------------------------------------------------------------------------- byte-level BPE
|
|
42
|
+
def _bytes_to_unicode() -> Dict[int, str]:
|
|
43
|
+
bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
|
44
|
+
cs, n = bs[:], 0
|
|
45
|
+
for b in range(256):
|
|
46
|
+
if b not in bs:
|
|
47
|
+
bs.append(b)
|
|
48
|
+
cs.append(256 + n)
|
|
49
|
+
n += 1
|
|
50
|
+
return dict(zip(bs, map(chr, cs)))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_B2U = _bytes_to_unicode()
|
|
54
|
+
_U2B = {v: k for k, v in _B2U.items()}
|
|
55
|
+
_GPT2_PAT = r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""
|
|
56
|
+
_warned_regex = False
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _compile_pretokenizer(pattern: Optional[str]):
|
|
60
|
+
global _warned_regex
|
|
61
|
+
pattern = pattern or _GPT2_PAT
|
|
62
|
+
try:
|
|
63
|
+
import regex # type: ignore
|
|
64
|
+
return regex.compile(pattern)
|
|
65
|
+
except ImportError:
|
|
66
|
+
if not _warned_regex:
|
|
67
|
+
warnings.warn("`regex` is not installed: using an approximate pre-tokenizer for the built-in BPE. "
|
|
68
|
+
"Install `regex` or `tokenizers` for exact results.", stacklevel=3)
|
|
69
|
+
_warned_regex = True
|
|
70
|
+
return re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?[^\W\d_]+| ?\d+| ?(?:[^\s\w]|_)+|\s+(?!\S)|\s+")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ByteLevelBPE(Tokenizer):
|
|
74
|
+
def __init__(self, vocab: Dict[str, int], merges: Sequence[Sequence[str]], specials: Dict[str, int],
|
|
75
|
+
pattern: Optional[str] = None, bos_id=None, eos_ids=(), add_bos=False):
|
|
76
|
+
self.vocab = vocab
|
|
77
|
+
self.inv = {i: t for t, i in vocab.items()}
|
|
78
|
+
self.inv.update({i: t for t, i in specials.items()})
|
|
79
|
+
self.ranks = {(a, b): r for r, (a, b) in enumerate(merges)}
|
|
80
|
+
self.specials = dict(specials)
|
|
81
|
+
self.special_ids = set(specials.values())
|
|
82
|
+
self._pat = _compile_pretokenizer(pattern)
|
|
83
|
+
self._split = (re.compile("(" + "|".join(re.escape(s) for s in sorted(specials, key=len, reverse=True)) + ")")
|
|
84
|
+
if specials else None)
|
|
85
|
+
self._cache: Dict[str, List[int]] = {}
|
|
86
|
+
self.bos_id, self.eos_ids, self.add_bos = bos_id, list(eos_ids), add_bos
|
|
87
|
+
self.vocab_size = max(self.inv) + 1 if self.inv else 0
|
|
88
|
+
|
|
89
|
+
def _bpe(self, word: str) -> List[int]:
|
|
90
|
+
if word in self._cache:
|
|
91
|
+
return self._cache[word]
|
|
92
|
+
parts = list(word)
|
|
93
|
+
while len(parts) > 1:
|
|
94
|
+
best, best_rank = None, None
|
|
95
|
+
for i in range(len(parts) - 1):
|
|
96
|
+
r = self.ranks.get((parts[i], parts[i + 1]))
|
|
97
|
+
if r is not None and (best_rank is None or r < best_rank):
|
|
98
|
+
best, best_rank = i, r
|
|
99
|
+
if best is None:
|
|
100
|
+
break
|
|
101
|
+
parts[best:best + 2] = [parts[best] + parts[best + 1]]
|
|
102
|
+
ids: List[int] = []
|
|
103
|
+
for p in parts:
|
|
104
|
+
if p in self.vocab:
|
|
105
|
+
ids.append(self.vocab[p])
|
|
106
|
+
else: # unknown merge result: fall back to single byte-chars
|
|
107
|
+
ids.extend(self.vocab[c] for c in p if c in self.vocab)
|
|
108
|
+
self._cache[word] = ids
|
|
109
|
+
return ids
|
|
110
|
+
|
|
111
|
+
def token_to_id(self, token):
|
|
112
|
+
return self.specials.get(token, self.vocab.get(token))
|
|
113
|
+
|
|
114
|
+
def encode(self, text, add_special=True):
|
|
115
|
+
ids: List[int] = [self.bos_id] if (add_special and self.add_bos and self.bos_id is not None) else []
|
|
116
|
+
chunks = self._split.split(text) if self._split else [text]
|
|
117
|
+
for ch in chunks:
|
|
118
|
+
if not ch:
|
|
119
|
+
continue
|
|
120
|
+
if ch in self.specials:
|
|
121
|
+
ids.append(self.specials[ch])
|
|
122
|
+
continue
|
|
123
|
+
for piece in self._pat.findall(ch):
|
|
124
|
+
if isinstance(piece, tuple): # patterns with groups
|
|
125
|
+
piece = "".join(piece)
|
|
126
|
+
ids.extend(self._bpe("".join(_B2U[b] for b in piece.encode("utf-8"))))
|
|
127
|
+
return ids
|
|
128
|
+
|
|
129
|
+
def decode(self, ids, skip_special=True):
|
|
130
|
+
out = bytearray()
|
|
131
|
+
for i in ids:
|
|
132
|
+
tok = self.inv.get(int(i))
|
|
133
|
+
if tok is None:
|
|
134
|
+
continue
|
|
135
|
+
if int(i) in self.special_ids:
|
|
136
|
+
if not skip_special:
|
|
137
|
+
out += tok.encode("utf-8")
|
|
138
|
+
continue
|
|
139
|
+
out += bytes(_U2B[c] if c in _U2B else ord("?") for c in tok)
|
|
140
|
+
return out.decode("utf-8", errors="replace")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------------------- SentencePiece (llama)
|
|
144
|
+
class SentencePieceBPE(Tokenizer):
|
|
145
|
+
def __init__(self, tokens: List[str], scores, types, bos_id, eos_ids, unk_id=0, add_bos=True,
|
|
146
|
+
add_space_prefix=True):
|
|
147
|
+
self.tokens = tokens
|
|
148
|
+
self.scores = np.asarray(scores, dtype=np.float32) if scores is not None else np.zeros(len(tokens), np.float32)
|
|
149
|
+
self.types = np.asarray(types, dtype=np.int32) if types is not None else np.ones(len(tokens), np.int32)
|
|
150
|
+
self.index = {t: i for i, t in enumerate(tokens)}
|
|
151
|
+
self.bos_id, self.eos_ids, self.unk_id = bos_id, list(eos_ids), unk_id
|
|
152
|
+
self.add_bos, self.add_space_prefix = add_bos, add_space_prefix
|
|
153
|
+
self.vocab_size = len(tokens)
|
|
154
|
+
self._byte_ids = {}
|
|
155
|
+
for b in range(256):
|
|
156
|
+
i = self.index.get(f"<0x{b:02X}>")
|
|
157
|
+
if i is not None:
|
|
158
|
+
self._byte_ids[b] = i
|
|
159
|
+
user = [t for t, ty in zip(tokens, self.types) if ty == 4 and len(t) > 1]
|
|
160
|
+
self._split = re.compile("(" + "|".join(re.escape(s) for s in sorted(user, key=len, reverse=True)) + ")") if user else None
|
|
161
|
+
|
|
162
|
+
def token_to_id(self, token):
|
|
163
|
+
return self.index.get(token)
|
|
164
|
+
|
|
165
|
+
def _encode_segment(self, text: str) -> List[int]:
|
|
166
|
+
syms = list(text)
|
|
167
|
+
while len(syms) > 1:
|
|
168
|
+
best_score, best_i = None, -1
|
|
169
|
+
for i in range(len(syms) - 1):
|
|
170
|
+
j = self.index.get(syms[i] + syms[i + 1])
|
|
171
|
+
if j is not None and (best_score is None or self.scores[j] > best_score):
|
|
172
|
+
best_score, best_i = self.scores[j], i
|
|
173
|
+
if best_i < 0:
|
|
174
|
+
break
|
|
175
|
+
syms[best_i:best_i + 2] = [syms[best_i] + syms[best_i + 1]]
|
|
176
|
+
ids: List[int] = []
|
|
177
|
+
for s in syms:
|
|
178
|
+
j = self.index.get(s)
|
|
179
|
+
if j is not None:
|
|
180
|
+
ids.append(j)
|
|
181
|
+
else:
|
|
182
|
+
for b in s.encode("utf-8"):
|
|
183
|
+
ids.append(self._byte_ids.get(b, self.unk_id))
|
|
184
|
+
return ids
|
|
185
|
+
|
|
186
|
+
def encode(self, text, add_special=True):
|
|
187
|
+
ids = [self.bos_id] if (add_special and self.add_bos and self.bos_id is not None) else []
|
|
188
|
+
chunks = self._split.split(text) if self._split else [text]
|
|
189
|
+
first = True
|
|
190
|
+
for ch in chunks:
|
|
191
|
+
if not ch:
|
|
192
|
+
continue
|
|
193
|
+
if ch in self.index and self.types[self.index[ch]] == 4:
|
|
194
|
+
ids.append(self.index[ch])
|
|
195
|
+
continue
|
|
196
|
+
ch = ch.replace(" ", "▁")
|
|
197
|
+
if first and self.add_space_prefix:
|
|
198
|
+
ch = "▁" + ch
|
|
199
|
+
first = False
|
|
200
|
+
ids.extend(self._encode_segment(ch))
|
|
201
|
+
return ids
|
|
202
|
+
|
|
203
|
+
def decode(self, ids, skip_special=True):
|
|
204
|
+
out = bytearray()
|
|
205
|
+
for i in ids:
|
|
206
|
+
i = int(i)
|
|
207
|
+
if not (0 <= i < len(self.tokens)):
|
|
208
|
+
continue
|
|
209
|
+
ty = self.types[i]
|
|
210
|
+
if ty in (3,) and skip_special:
|
|
211
|
+
continue
|
|
212
|
+
tok = self.tokens[i]
|
|
213
|
+
if ty == 6 or re.fullmatch(r"<0x[0-9A-Fa-f]{2}>", tok):
|
|
214
|
+
out.append(int(tok[3:5], 16))
|
|
215
|
+
elif ty == 2 and skip_special:
|
|
216
|
+
continue
|
|
217
|
+
else:
|
|
218
|
+
out += tok.replace("▁", " ").encode("utf-8")
|
|
219
|
+
s = out.decode("utf-8", errors="replace")
|
|
220
|
+
return s[1:] if (self.add_space_prefix and s.startswith(" ")) else s
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ------------------------------------------------------------------------- `tokenizers` backend
|
|
224
|
+
class _TokenizersBackend(Tokenizer):
|
|
225
|
+
def __init__(self, path: str, bos_id, eos_ids):
|
|
226
|
+
from tokenizers import Tokenizer as HFTok # type: ignore
|
|
227
|
+
self._t = HFTok.from_file(path)
|
|
228
|
+
self.bos_id, self.eos_ids = bos_id, list(eos_ids)
|
|
229
|
+
self.vocab_size = self._t.get_vocab_size(with_added_tokens=True)
|
|
230
|
+
|
|
231
|
+
def token_to_id(self, token):
|
|
232
|
+
return self._t.token_to_id(token)
|
|
233
|
+
|
|
234
|
+
def encode(self, text, add_special=True):
|
|
235
|
+
return list(self._t.encode(text, add_special_tokens=add_special).ids)
|
|
236
|
+
|
|
237
|
+
def decode(self, ids, skip_special=True):
|
|
238
|
+
return self._t.decode(list(map(int, ids)), skip_special_tokens=skip_special)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ------------------------------------------------------------------------- factories
|
|
242
|
+
def _as_list(x) -> List[int]:
|
|
243
|
+
if x is None:
|
|
244
|
+
return []
|
|
245
|
+
return [int(v) for v in x] if isinstance(x, (list, tuple)) else [int(x)]
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _token_str(v) -> Optional[str]:
|
|
249
|
+
if isinstance(v, dict):
|
|
250
|
+
return v.get("content")
|
|
251
|
+
return v
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _read_json(path: str) -> dict:
|
|
255
|
+
if os.path.isfile(path):
|
|
256
|
+
with open(path, encoding="utf-8") as f:
|
|
257
|
+
return json.load(f)
|
|
258
|
+
return {}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def load_tokenizer_from_dir(d: str) -> Tokenizer:
|
|
262
|
+
tj = os.path.join(d, "tokenizer.json")
|
|
263
|
+
cfg = _read_json(os.path.join(d, "config.json"))
|
|
264
|
+
tcfg = _read_json(os.path.join(d, "tokenizer_config.json"))
|
|
265
|
+
gcfg = _read_json(os.path.join(d, "generation_config.json"))
|
|
266
|
+
if not os.path.isfile(tj):
|
|
267
|
+
raise FileNotFoundError(
|
|
268
|
+
f"{d} has no tokenizer.json (SentencePiece-only repos are not supported; use a repo that ships "
|
|
269
|
+
f"tokenizer.json, or a GGUF file which embeds its vocabulary)")
|
|
270
|
+
spec = _read_json(tj)
|
|
271
|
+
added = {t["content"]: t["id"] for t in spec.get("added_tokens", [])}
|
|
272
|
+
bos_tok, eos_tok = _token_str(tcfg.get("bos_token")), _token_str(tcfg.get("eos_token"))
|
|
273
|
+
bos_id = cfg.get("bos_token_id", gcfg.get("bos_token_id"))
|
|
274
|
+
if bos_id is None and bos_tok in added:
|
|
275
|
+
bos_id = added[bos_tok]
|
|
276
|
+
eos_ids = _as_list(gcfg.get("eos_token_id", cfg.get("eos_token_id")))
|
|
277
|
+
if not eos_ids and eos_tok in added:
|
|
278
|
+
eos_ids = [added[eos_tok]]
|
|
279
|
+
add_bos = bool(tcfg.get("add_bos_token", False))
|
|
280
|
+
|
|
281
|
+
try:
|
|
282
|
+
tok: Tokenizer = _TokenizersBackend(tj, bos_id, eos_ids)
|
|
283
|
+
except ImportError:
|
|
284
|
+
model = spec.get("model", {})
|
|
285
|
+
if model.get("type") != "BPE":
|
|
286
|
+
raise RuntimeError(f"tokenizer type {model.get('type')!r} needs `pip install tokenizers`")
|
|
287
|
+
merges = [m.split(" ", 1) if isinstance(m, str) else m for m in model["merges"]]
|
|
288
|
+
pattern = None
|
|
289
|
+
|
|
290
|
+
def find_regex(node):
|
|
291
|
+
if isinstance(node, dict):
|
|
292
|
+
pat = node.get("pattern")
|
|
293
|
+
if isinstance(pat, dict) and "Regex" in pat:
|
|
294
|
+
return pat["Regex"]
|
|
295
|
+
for v in node.values():
|
|
296
|
+
r = find_regex(v)
|
|
297
|
+
if r:
|
|
298
|
+
return r
|
|
299
|
+
elif isinstance(node, list):
|
|
300
|
+
for v in node:
|
|
301
|
+
r = find_regex(v)
|
|
302
|
+
if r:
|
|
303
|
+
return r
|
|
304
|
+
return None
|
|
305
|
+
|
|
306
|
+
pattern = find_regex(spec.get("pre_tokenizer"))
|
|
307
|
+
specials = {t["content"]: t["id"] for t in spec.get("added_tokens", []) if t.get("special", False)}
|
|
308
|
+
tok = ByteLevelBPE(model["vocab"], merges, specials, pattern, bos_id, eos_ids, add_bos)
|
|
309
|
+
tok.chat_template = tcfg.get("chat_template")
|
|
310
|
+
if isinstance(tok.chat_template, list): # named templates
|
|
311
|
+
tok.chat_template = next((t["template"] for t in tok.chat_template if t.get("name") == "default"),
|
|
312
|
+
tok.chat_template[0]["template"])
|
|
313
|
+
tok.bos_token, tok.eos_token = bos_tok, eos_tok
|
|
314
|
+
return tok
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def load_tokenizer_from_gguf(md: dict) -> Tokenizer:
|
|
318
|
+
model = md.get("tokenizer.ggml.model")
|
|
319
|
+
tokens = list(md["tokenizer.ggml.tokens"])
|
|
320
|
+
types = md.get("tokenizer.ggml.token_type")
|
|
321
|
+
bos = md.get("tokenizer.ggml.bos_token_id")
|
|
322
|
+
eos = _as_list(md.get("tokenizer.ggml.eos_token_id"))
|
|
323
|
+
eot = md.get("tokenizer.ggml.eot_token_id")
|
|
324
|
+
if eot is not None and int(eot) not in eos:
|
|
325
|
+
eos.append(int(eot))
|
|
326
|
+
if model == "gpt2":
|
|
327
|
+
merges = [m.split(" ", 1) for m in md.get("tokenizer.ggml.merges", [])]
|
|
328
|
+
vtypes = list(types) if types is not None else [1] * len(tokens)
|
|
329
|
+
specials = {t: i for i, (t, ty) in enumerate(zip(tokens, vtypes)) if ty in (3, 4)}
|
|
330
|
+
vocab = {t: i for i, t in enumerate(tokens) if t not in specials}
|
|
331
|
+
tok: Tokenizer = ByteLevelBPE(vocab, merges, specials, None, int(bos) if bos is not None else None,
|
|
332
|
+
eos, bool(md.get("tokenizer.ggml.add_bos_token", False)))
|
|
333
|
+
elif model == "llama":
|
|
334
|
+
tok = SentencePieceBPE(tokens, md.get("tokenizer.ggml.scores"), types,
|
|
335
|
+
int(bos) if bos is not None else None, eos,
|
|
336
|
+
int(md.get("tokenizer.ggml.unknown_token_id", 0)),
|
|
337
|
+
bool(md.get("tokenizer.ggml.add_bos_token", True)),
|
|
338
|
+
bool(md.get("tokenizer.ggml.add_space_prefix", True)))
|
|
339
|
+
else:
|
|
340
|
+
raise NotImplementedError(f"GGUF tokenizer model {model!r} is not supported (gpt2 and llama are)")
|
|
341
|
+
tok.chat_template = md.get("tokenizer.chat_template")
|
|
342
|
+
tok.bos_token = tokens[int(bos)] if bos is not None and int(bos) < len(tokens) else None
|
|
343
|
+
tok.eos_token = tokens[eos[0]] if eos and eos[0] < len(tokens) else None
|
|
344
|
+
return tok
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tensorload
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Load GGUF, safetensors, PyTorch (.pt) and NumPy (.npz) weights, download from Hugging Face, and run LLaMA-family models with a pure-NumPy engine.
|
|
5
|
+
License: MIT
|
|
6
|
+
Keywords: gguf,safetensors,pytorch,huggingface,llm,inference,numpy
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: numpy>=1.22
|
|
11
|
+
Provides-Extra: tokenizers
|
|
12
|
+
Requires-Dist: tokenizers>=0.15; extra == "tokenizers"
|
|
13
|
+
Provides-Extra: regex
|
|
14
|
+
Requires-Dist: regex; extra == "regex"
|
|
15
|
+
Provides-Extra: chat
|
|
16
|
+
Requires-Dist: jinja2; extra == "chat"
|
|
17
|
+
Provides-Extra: torch
|
|
18
|
+
Requires-Dist: torch; extra == "torch"
|
|
19
|
+
Provides-Extra: all
|
|
20
|
+
Requires-Dist: tokenizers>=0.15; extra == "all"
|
|
21
|
+
Requires-Dist: regex; extra == "all"
|
|
22
|
+
Requires-Dist: jinja2; extra == "all"
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# tensorload
|
|
28
|
+
|
|
29
|
+
Load model weights from **GGUF, safetensors, PyTorch (`.pt`/`.pth`/`.bin`) and NumPy (`.npz`)**, download them from
|
|
30
|
+
**Hugging Face**, and **run** LLaMA-family models — with nothing but NumPy as a hard dependency.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install tensorload # numpy only
|
|
34
|
+
pip install tensorload[all] # + tokenizers, regex, jinja2 (recommended)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Load weights
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import tensorload as tl
|
|
41
|
+
|
|
42
|
+
tensors = tl.load("model.safetensors") # dict[str, np.ndarray]
|
|
43
|
+
tensors = tl.load("model-Q4_K_M.gguf") # quantised tensors are dequantised to float32
|
|
44
|
+
tensors = tl.load("checkpoint.pt") # safe: no arbitrary pickle execution
|
|
45
|
+
tensors = tl.load("weights.npz")
|
|
46
|
+
tensors = tl.load("./hf_model_dir") # sharded checkpoints are merged automatically
|
|
47
|
+
tensors = tl.load("Qwen/Qwen2.5-0.5B-Instruct") # downloads from the Hub (cached)
|
|
48
|
+
|
|
49
|
+
# lazy access: inspect without reading tensor data
|
|
50
|
+
with tl.open("model.gguf") as f:
|
|
51
|
+
print(f.format, f.metadata["general.architecture"])
|
|
52
|
+
for info in f.infos()[:5]:
|
|
53
|
+
print(info.name, info.shape, info.dtype, info.nbytes)
|
|
54
|
+
w = f.get("blk.0.attn_q.weight")
|
|
55
|
+
|
|
56
|
+
tl.convert("model.gguf", "model.safetensors") # .safetensors / .npz / .gguf targets
|
|
57
|
+
tl.save_safetensors(tensors, "out.safetensors")
|
|
58
|
+
tl.save_gguf("out.gguf", tensors, {"general.architecture": "llama"}, dtype="Q8_0")
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
| Format | Read | Write | Notes |
|
|
62
|
+
|---|---|---|---|
|
|
63
|
+
| safetensors | ✅ mmap | ✅ (F32/F16/…, BF16 helper) | BF16 is widened to float32; FP8 unsupported |
|
|
64
|
+
| GGUF v2/v3 | ✅ | ✅ F32/F16/BF16/Q8_0/Q4_0 | read: F32 F16 BF16 Q4_0 Q4_1 Q5_0 Q5_1 Q8_0 Q2_K Q4_K Q5_K Q6_K + int types. Q3_K and IQ* raise a clear error |
|
|
65
|
+
| PyTorch | ✅ zip format via a *restricted* unpickler | – | legacy pre-1.6 files need `torch` installed |
|
|
66
|
+
| NumPy | ✅ `.npz`/`.npy`, `allow_pickle=False` | ✅ | |
|
|
67
|
+
|
|
68
|
+
## Download from Hugging Face
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
tl.download_file("TheBloke/some-model-GGUF", "some-model.Q4_K_M.gguf") # resumable, cached
|
|
72
|
+
tl.snapshot_download("Qwen/Qwen2.5-0.5B-Instruct", allow_patterns=["*.json", "*.safetensors"])
|
|
73
|
+
tl.list_repo_files("org/name")
|
|
74
|
+
```
|
|
75
|
+
Token: `token=...`, `HF_TOKEN`, or `~/.cache/huggingface/token` (needed for gated/private repos).
|
|
76
|
+
`HF_ENDPOINT` selects a mirror, `TENSORLOAD_CACHE` the cache dir (default `~/.cache/tensorload`).
|
|
77
|
+
Given a repo id, tensorload picks safetensors (sharded or not) > GGUF (`quant="Q4_K_M"` or a sensible default) > `.bin`/`.pt` > `.npz`.
|
|
78
|
+
|
|
79
|
+
## Run models
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
lm = tl.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") # or a local dir / .gguf file
|
|
83
|
+
print(lm.generate("The capital of France is", max_new_tokens=16, temperature=0))
|
|
84
|
+
print(lm.chat([{"role": "user", "content": "Name three colours."}], temperature=0.7))
|
|
85
|
+
for piece in lm.stream("Once upon a time", max_new_tokens=64): # streaming
|
|
86
|
+
print(piece, end="", flush=True)
|
|
87
|
+
|
|
88
|
+
lm = tl.from_pretrained("bartowski/Llama-3.2-1B-Instruct-GGUF", quant="Q4_K_M")
|
|
89
|
+
lm = tl.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", dtype="float16") # half the RAM, a bit slower
|
|
90
|
+
```
|
|
91
|
+
Sampling options: `temperature, top_k, top_p, min_p, repeat_penalty, seed, stop, max_new_tokens`.
|
|
92
|
+
|
|
93
|
+
The built-in engine is a compact NumPy transformer with KV cache, GQA, RoPE (llama3/linear scaling, llama.cpp
|
|
94
|
+
`rope_freqs`), RMSNorm, SwiGLU, QKV bias and Qwen3 QK-norm. **Architectures:** `llama` (incl. Llama 2/3.x, Mistral),
|
|
95
|
+
`qwen2`, `qwen3`; other models raise `UnsupportedModelError` (you can still `tl.load()` their weights).
|
|
96
|
+
Tokenizers: HF `tokenizer.json` (uses the `tokenizers` package if present, else a built-in byte-level BPE) and the
|
|
97
|
+
vocabularies embedded in GGUF files (`gpt2` BPE and `llama` SentencePiece).
|
|
98
|
+
|
|
99
|
+
> Performance: this is float32 NumPy on CPU — great for tiny/small models (≲1–3B) and for correctness checks, and
|
|
100
|
+
> quantised GGUFs are dequantised at load time, so RAM use is that of float32 (or float16 with `dtype="float16"`).
|
|
101
|
+
> For fast large-model inference use llama.cpp / vLLM.
|
|
102
|
+
|
|
103
|
+
## CLI
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
tensorload info model.gguf --summary
|
|
107
|
+
tensorload download Qwen/Qwen2.5-0.5B-Instruct
|
|
108
|
+
tensorload convert model.pt model.safetensors
|
|
109
|
+
tensorload run Qwen/Qwen2.5-0.5B-Instruct -p "Hello" --chat -n 64 --temp 0
|
|
110
|
+
tensorload run some/model-GGUF --quant Q4_K_M -i # interactive chat
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Tests
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
PYTHONPATH=src:tests python -m unittest discover -s tests # or: pytest
|
|
117
|
+
```
|
|
118
|
+
The suite checks every format round-trip, the K-quant kernels against scalar ports of the reference algorithms,
|
|
119
|
+
the engine against an independent Hugging-Face-style reference (including llama.cpp's interleaved-RoPE GGUF
|
|
120
|
+
layout), incremental-vs-full decoding, tokenizers, and the downloader against a local mock Hub (resume, auth, quant selection).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
tensorload/__init__.py,sha256=vVFUweefHjXWK1wBAiLr0dhuxIBOLdMfBscez-7JN-Q,3814
|
|
2
|
+
tensorload/_dtypes.py,sha256=TMRxrSZFXo-6-b-L5eU8Xnpv-QRkgLTu1YC58WvX-NQ,671
|
|
3
|
+
tensorload/chat.py,sha256=VIDaFNz68yCAT3Xqa5lRcG_QsoAPxxWV8mGbGUDEkS8,1465
|
|
4
|
+
tensorload/cli.py,sha256=4Vhqjeb7IpxT1bysYKqn_AUx9I24pC25tbq1E-az7pk,4648
|
|
5
|
+
tensorload/core.py,sha256=oxVNfIGtIZXSBE8qmw-HFoplpggxip4hI2PfosC0VG0,3457
|
|
6
|
+
tensorload/engine.py,sha256=hM2u1XOG-vfc0s00D99Nh2ULh4TTWoKqEJRp0dNYcjo,13130
|
|
7
|
+
tensorload/hub.py,sha256=_JmSKuxuwZXLBpgTOXNx7cBt6SRSlo_R3cmJR0jpw_E,11756
|
|
8
|
+
tensorload/llm.py,sha256=GVHWA0KBSHKKFd6cLg8uBZD0KB1cfwZMqBc-ucNqJYo,7188
|
|
9
|
+
tensorload/sampling.py,sha256=7lLwYvKJsvoQ68WsjaydtUM_cYyWpDSLWaYsM7UGN6Q,1527
|
|
10
|
+
tensorload/tokenizer.py,sha256=shVEzO1YVps3Si_OlcqSO1iqhqC0jFPHmUvLyVU-HCQ,14439
|
|
11
|
+
tensorload/formats/__init__.py,sha256=C5rvwuTMF-MMdXaocgmAYJOMLApxM8pH3LsIwm3Vvdk,3003
|
|
12
|
+
tensorload/formats/gguf.py,sha256=YNj3KoFzy2uE31D_cbfh-VujmTkayutlx_JpUA46Yek,7834
|
|
13
|
+
tensorload/formats/npz.py,sha256=ewvtlQbaepGRBKCbXflCMy0s52eVEnt5FzOj6UvCIMo,1863
|
|
14
|
+
tensorload/formats/pytorch.py,sha256=OF9IqcQIKeuHGqMGZRsx3fB4-DEK2KLFRnSpwl8lPlo,6358
|
|
15
|
+
tensorload/formats/quant.py,sha256=a_8bCiNqhOVmTPus4DsDMlna4Sjf513SBB6O2KcWtzE,7597
|
|
16
|
+
tensorload/formats/safetensors.py,sha256=CtDY936kZpFsnlv3N73R4d5q4_j0J4GlRyV1JjQ_v30,5179
|
|
17
|
+
tensorload-0.1.0.dist-info/licenses/LICENSE,sha256=9JeBBtkkbh2qqi5YuYrjZXzc2dlz5sJ_5qJXr82T3oA,1080
|
|
18
|
+
tensorload-0.1.0.dist-info/METADATA,sha256=pH2wVDIFUhSjOLWMltEVWdHflfmjv1orgbRBBCqiju8,5777
|
|
19
|
+
tensorload-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
20
|
+
tensorload-0.1.0.dist-info/entry_points.txt,sha256=UxbRc-no2Z7jHlAjr8SZ-C97jzppNvhVzG4abWrsEow,51
|
|
21
|
+
tensorload-0.1.0.dist-info/top_level.txt,sha256=ixnZUeE0Li--hSrytp8UFQlJ9INOYas5QO_iRVzT3VQ,11
|
|
22
|
+
tensorload-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tensorload contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tensorload
|