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
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Pure-Python safetensors reader/writer (memory-mapped, no dependencies)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import mmap
|
|
6
|
+
import os
|
|
7
|
+
import struct
|
|
8
|
+
from typing import Dict, Optional
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from .._dtypes import bf16_to_f32, f32_to_bf16_bits
|
|
13
|
+
from ..core import TensorFile, TensorInfo
|
|
14
|
+
|
|
15
|
+
_DTYPES = {
|
|
16
|
+
"F64": np.float64, "F32": np.float32, "F16": np.float16, "BF16": "bf16",
|
|
17
|
+
"I64": np.int64, "I32": np.int32, "I16": np.int16, "I8": np.int8,
|
|
18
|
+
"U64": np.uint64, "U32": np.uint32, "U16": np.uint16, "U8": np.uint8,
|
|
19
|
+
"BOOL": np.bool_,
|
|
20
|
+
}
|
|
21
|
+
_NAMES = {np.dtype(v): k for k, v in _DTYPES.items() if v != "bf16"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SafetensorsFile(TensorFile):
|
|
25
|
+
format = "safetensors"
|
|
26
|
+
|
|
27
|
+
def __init__(self, path):
|
|
28
|
+
super().__init__(path)
|
|
29
|
+
self._fh = open(path, "rb")
|
|
30
|
+
self._mm = None
|
|
31
|
+
try:
|
|
32
|
+
raw = self._fh.read(8)
|
|
33
|
+
if len(raw) != 8:
|
|
34
|
+
raise ValueError("file too small to be safetensors")
|
|
35
|
+
(n,) = struct.unpack("<Q", raw)
|
|
36
|
+
if n > 200_000_000:
|
|
37
|
+
raise ValueError("safetensors header is implausibly large")
|
|
38
|
+
header = json.loads(self._fh.read(n).decode("utf-8"))
|
|
39
|
+
self._base = 8 + n
|
|
40
|
+
size = os.fstat(self._fh.fileno()).st_size
|
|
41
|
+
self.metadata = dict(header.pop("__metadata__", None) or {})
|
|
42
|
+
self._header: Dict[str, dict] = header
|
|
43
|
+
for name, ent in header.items():
|
|
44
|
+
s, e = ent["data_offsets"]
|
|
45
|
+
if not (0 <= s <= e <= size - self._base):
|
|
46
|
+
raise ValueError(f"tensor {name!r} has out-of-range offsets (truncated file?)")
|
|
47
|
+
if size > 0:
|
|
48
|
+
self._mm = mmap.mmap(self._fh.fileno(), 0, access=mmap.ACCESS_READ)
|
|
49
|
+
except Exception:
|
|
50
|
+
self._fh.close()
|
|
51
|
+
raise
|
|
52
|
+
|
|
53
|
+
def keys(self):
|
|
54
|
+
return list(self._header)
|
|
55
|
+
|
|
56
|
+
def __contains__(self, name):
|
|
57
|
+
return name in self._header
|
|
58
|
+
|
|
59
|
+
def info(self, name):
|
|
60
|
+
e = self._header[name]
|
|
61
|
+
s, t = e["data_offsets"]
|
|
62
|
+
return TensorInfo(name, tuple(e["shape"]), e["dtype"], t - s)
|
|
63
|
+
|
|
64
|
+
def get(self, name):
|
|
65
|
+
e = self._header[name]
|
|
66
|
+
dt, shape = e["dtype"], tuple(e["shape"])
|
|
67
|
+
if dt not in _DTYPES:
|
|
68
|
+
raise NotImplementedError(f"safetensors dtype {dt!r} is not supported (tensor {name!r})")
|
|
69
|
+
s, t = e["data_offsets"]
|
|
70
|
+
np_dt = np.uint16 if dt == "BF16" else _DTYPES[dt]
|
|
71
|
+
if t == s:
|
|
72
|
+
return np.empty(shape, dtype=np.float32 if dt == "BF16" else np_dt)
|
|
73
|
+
buf = np.frombuffer(self._mm, dtype=np.uint8, count=t - s, offset=self._base + s)
|
|
74
|
+
arr = buf.view(np_dt)
|
|
75
|
+
arr = bf16_to_f32(arr) if dt == "BF16" else arr.copy()
|
|
76
|
+
return arr.reshape(shape)
|
|
77
|
+
|
|
78
|
+
def close(self):
|
|
79
|
+
try:
|
|
80
|
+
if self._mm is not None:
|
|
81
|
+
self._mm.close()
|
|
82
|
+
except BufferError:
|
|
83
|
+
pass
|
|
84
|
+
self._mm = None
|
|
85
|
+
self._fh.close()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def save_safetensors(tensors: Dict[str, np.ndarray], path, metadata: Optional[Dict[str, str]] = None) -> None:
|
|
89
|
+
"""Write ``tensors`` to ``path``. ``float32`` arrays are stored as F32 (use
|
|
90
|
+
``bfloat16=True`` style conversions yourself via ``f32_to_bf16_bits`` if needed)."""
|
|
91
|
+
header: Dict[str, object] = {}
|
|
92
|
+
if metadata:
|
|
93
|
+
header["__metadata__"] = {str(k): str(v) for k, v in metadata.items()}
|
|
94
|
+
offset = 0
|
|
95
|
+
blobs = []
|
|
96
|
+
for name, arr in tensors.items():
|
|
97
|
+
a = np.ascontiguousarray(arr)
|
|
98
|
+
key = _NAMES.get(a.dtype.newbyteorder("<") if a.dtype.byteorder == ">" else a.dtype)
|
|
99
|
+
if key is None:
|
|
100
|
+
raise TypeError(f"cannot store dtype {a.dtype} for tensor {name!r}")
|
|
101
|
+
a = a.astype(a.dtype.newbyteorder("<"), copy=False)
|
|
102
|
+
data = a.tobytes()
|
|
103
|
+
header[name] = {"dtype": key, "shape": list(a.shape), "data_offsets": [offset, offset + len(data)]}
|
|
104
|
+
offset += len(data)
|
|
105
|
+
blobs.append(data)
|
|
106
|
+
hb = json.dumps(header, separators=(",", ":")).encode("utf-8")
|
|
107
|
+
hb += b" " * ((8 - len(hb) % 8) % 8)
|
|
108
|
+
with open(path, "wb") as f:
|
|
109
|
+
f.write(struct.pack("<Q", len(hb)))
|
|
110
|
+
f.write(hb)
|
|
111
|
+
for b in blobs:
|
|
112
|
+
f.write(b)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def save_safetensors_bf16(tensors: Dict[str, np.ndarray], path, metadata=None) -> None:
|
|
116
|
+
"""Like :func:`save_safetensors` but stores float tensors as BF16."""
|
|
117
|
+
header: Dict[str, object] = {}
|
|
118
|
+
if metadata:
|
|
119
|
+
header["__metadata__"] = {str(k): str(v) for k, v in metadata.items()}
|
|
120
|
+
offset, blobs = 0, []
|
|
121
|
+
for name, arr in tensors.items():
|
|
122
|
+
a = np.ascontiguousarray(arr)
|
|
123
|
+
if np.issubdtype(a.dtype, np.floating):
|
|
124
|
+
data, key = f32_to_bf16_bits(a.astype(np.float32)).tobytes(), "BF16"
|
|
125
|
+
else:
|
|
126
|
+
data, key = a.tobytes(), _NAMES[a.dtype]
|
|
127
|
+
header[name] = {"dtype": key, "shape": list(a.shape), "data_offsets": [offset, offset + len(data)]}
|
|
128
|
+
offset += len(data)
|
|
129
|
+
blobs.append(data)
|
|
130
|
+
hb = json.dumps(header, separators=(",", ":")).encode()
|
|
131
|
+
hb += b" " * ((8 - len(hb) % 8) % 8)
|
|
132
|
+
with open(path, "wb") as f:
|
|
133
|
+
f.write(struct.pack("<Q", len(hb)))
|
|
134
|
+
f.write(hb)
|
|
135
|
+
for b in blobs:
|
|
136
|
+
f.write(b)
|
tensorload/hub.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Hugging Face Hub client built on the standard library (no ``huggingface_hub`` needed).
|
|
2
|
+
|
|
3
|
+
* resumable downloads (HTTP ``Range``), progress bar, atomic rename
|
|
4
|
+
* token from argument, ``HF_TOKEN`` / ``HUGGING_FACE_HUB_TOKEN`` or ``~/.cache/huggingface/token``
|
|
5
|
+
* ``HF_ENDPOINT`` for mirrors, ``TENSORLOAD_CACHE`` for the cache location
|
|
6
|
+
* the Authorization header is dropped on cross-host redirects (CDN safety)
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import fnmatch
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.parse
|
|
18
|
+
import urllib.request
|
|
19
|
+
from typing import List, Optional, Sequence
|
|
20
|
+
|
|
21
|
+
__all__ = ["HubError", "download_file", "snapshot_download", "list_repo_files", "resolve_source",
|
|
22
|
+
"cache_dir", "looks_like_repo_id"]
|
|
23
|
+
|
|
24
|
+
_REPO_RE = re.compile(r"^[A-Za-z0-9][\w.\-]*(/[A-Za-z0-9][\w.\-]*)?$")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class HubError(RuntimeError):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def endpoint() -> str:
|
|
32
|
+
return os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def cache_dir() -> str:
|
|
36
|
+
return os.environ.get("TENSORLOAD_CACHE") or os.path.join(os.path.expanduser("~"), ".cache", "tensorload")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_token(token=None) -> Optional[str]:
|
|
40
|
+
if token is False:
|
|
41
|
+
return None
|
|
42
|
+
if token:
|
|
43
|
+
return token
|
|
44
|
+
for var in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
|
|
45
|
+
if os.environ.get(var):
|
|
46
|
+
return os.environ[var]
|
|
47
|
+
p = os.path.join(os.path.expanduser("~"), ".cache", "huggingface", "token")
|
|
48
|
+
if os.path.isfile(p):
|
|
49
|
+
with open(p) as f:
|
|
50
|
+
return f.read().strip() or None
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def looks_like_repo_id(s: str) -> bool:
|
|
55
|
+
return bool(_REPO_RE.match(s)) and not os.path.exists(s)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _StripAuthOnRedirect(urllib.request.HTTPRedirectHandler):
|
|
59
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
60
|
+
new = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
61
|
+
if new is not None and urllib.parse.urlparse(newurl).netloc != urllib.parse.urlparse(req.full_url).netloc:
|
|
62
|
+
new.headers.pop("Authorization", None)
|
|
63
|
+
new.unredirected_hdrs.pop("Authorization", None)
|
|
64
|
+
return new
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
_opener = urllib.request.build_opener(_StripAuthOnRedirect)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _request(url: str, token: Optional[str], extra: Optional[dict] = None, timeout: float = 30):
|
|
71
|
+
headers = {"User-Agent": "tensorload/0.1"}
|
|
72
|
+
if token:
|
|
73
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
74
|
+
headers.update(extra or {})
|
|
75
|
+
try:
|
|
76
|
+
return _opener.open(urllib.request.Request(url, headers=headers), timeout=timeout)
|
|
77
|
+
except urllib.error.HTTPError as e:
|
|
78
|
+
if e.code == 416:
|
|
79
|
+
raise
|
|
80
|
+
if e.code in (401, 403):
|
|
81
|
+
raise HubError(f"{e.code} from {url}: the repo is gated or private - accept its terms on the "
|
|
82
|
+
f"website and pass token=... or set HF_TOKEN") from None
|
|
83
|
+
if e.code == 404:
|
|
84
|
+
raise HubError(f"404 not found: {url}") from None
|
|
85
|
+
raise HubError(f"HTTP {e.code} from {url}") from None
|
|
86
|
+
except urllib.error.URLError as e:
|
|
87
|
+
raise HubError(f"network error contacting {url}: {e.reason}") from None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def list_repo_files(repo_id: str, revision: str = "main", token=None) -> List[str]:
|
|
91
|
+
url = f"{endpoint()}/api/models/{repo_id}/revision/{urllib.parse.quote(revision, safe='')}"
|
|
92
|
+
with _request(url, get_token(token)) as r:
|
|
93
|
+
data = json.loads(r.read().decode("utf-8"))
|
|
94
|
+
return [s["rfilename"] for s in data.get("siblings", [])]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _repo_dir(repo_id: str, revision: str, cache: Optional[str]) -> str:
|
|
98
|
+
return os.path.join(cache or cache_dir(), "models--" + repo_id.replace("/", "--"),
|
|
99
|
+
re.sub(r"[^\w.\-]", "_", revision))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _Progress:
|
|
103
|
+
def __init__(self, label, total, enabled):
|
|
104
|
+
self.label, self.total, self.enabled = label, total, enabled and sys.stderr.isatty()
|
|
105
|
+
self.done, self.t0, self.last = 0, time.time(), 0.0
|
|
106
|
+
|
|
107
|
+
def update(self, n):
|
|
108
|
+
self.done += n
|
|
109
|
+
if self.enabled and time.time() - self.last > 0.2:
|
|
110
|
+
self.last = time.time()
|
|
111
|
+
self._draw()
|
|
112
|
+
|
|
113
|
+
def _draw(self):
|
|
114
|
+
rate = self.done / max(time.time() - self.t0, 1e-6)
|
|
115
|
+
if self.total:
|
|
116
|
+
pct = 100 * self.done / self.total
|
|
117
|
+
msg = f"\r{self.label}: {pct:5.1f}% {self.done / 1e6:,.1f}/{self.total / 1e6:,.1f} MB {rate / 1e6:.1f} MB/s"
|
|
118
|
+
else:
|
|
119
|
+
msg = f"\r{self.label}: {self.done / 1e6:,.1f} MB {rate / 1e6:.1f} MB/s"
|
|
120
|
+
sys.stderr.write(msg + " " * 4)
|
|
121
|
+
sys.stderr.flush()
|
|
122
|
+
|
|
123
|
+
def close(self):
|
|
124
|
+
if self.enabled:
|
|
125
|
+
self._draw()
|
|
126
|
+
sys.stderr.write("\n")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def download_file(repo_id: str, filename: str, revision: str = "main", token=None,
|
|
130
|
+
cache: Optional[str] = None, force: bool = False, progress: bool = True) -> str:
|
|
131
|
+
"""Download one file of a repo (resuming if interrupted) and return its local path."""
|
|
132
|
+
dest = os.path.join(_repo_dir(repo_id, revision, cache), *filename.split("/"))
|
|
133
|
+
if os.path.isfile(dest) and not force:
|
|
134
|
+
return dest
|
|
135
|
+
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
|
136
|
+
part = dest + ".part"
|
|
137
|
+
if force and os.path.exists(part):
|
|
138
|
+
os.remove(part)
|
|
139
|
+
url = (f"{endpoint()}/{repo_id}/resolve/{urllib.parse.quote(revision, safe='')}/"
|
|
140
|
+
f"{urllib.parse.quote(filename)}")
|
|
141
|
+
tok = get_token(token)
|
|
142
|
+
for attempt in range(5):
|
|
143
|
+
have = os.path.getsize(part) if os.path.exists(part) else 0
|
|
144
|
+
try:
|
|
145
|
+
resp = _request(url, tok, {"Range": f"bytes={have}-"} if have else None, timeout=60)
|
|
146
|
+
except urllib.error.HTTPError as e: # 416: the .part file is already complete
|
|
147
|
+
if e.code == 416 and have:
|
|
148
|
+
os.replace(part, dest)
|
|
149
|
+
return dest
|
|
150
|
+
raise HubError(f"HTTP {e.code} for {url}") from None
|
|
151
|
+
with resp:
|
|
152
|
+
if resp.status == 206:
|
|
153
|
+
m = re.search(r"/(\d+)$", resp.headers.get("Content-Range", ""))
|
|
154
|
+
total = int(m.group(1)) if m else None
|
|
155
|
+
mode = "ab"
|
|
156
|
+
else:
|
|
157
|
+
have, mode = 0, "wb"
|
|
158
|
+
cl = resp.headers.get("Content-Length")
|
|
159
|
+
total = int(cl) if cl else None
|
|
160
|
+
bar = _Progress(filename, total, progress)
|
|
161
|
+
bar.done = have
|
|
162
|
+
try:
|
|
163
|
+
with open(part, mode) as out:
|
|
164
|
+
while True:
|
|
165
|
+
chunk = resp.read(1 << 20)
|
|
166
|
+
if not chunk:
|
|
167
|
+
break
|
|
168
|
+
out.write(chunk)
|
|
169
|
+
bar.update(len(chunk))
|
|
170
|
+
bar.close()
|
|
171
|
+
except (OSError, urllib.error.URLError, ConnectionError, TimeoutError):
|
|
172
|
+
time.sleep(min(2 ** attempt, 10))
|
|
173
|
+
continue # retry, resuming from what we have
|
|
174
|
+
size = os.path.getsize(part)
|
|
175
|
+
if total is not None and size < total:
|
|
176
|
+
continue
|
|
177
|
+
os.replace(part, dest)
|
|
178
|
+
return dest
|
|
179
|
+
raise HubError(f"download of {filename} failed repeatedly; partial data kept at {part}")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def snapshot_download(repo_id: str, revision: str = "main", token=None, allow_patterns: Optional[Sequence[str]] = None,
|
|
183
|
+
ignore_patterns: Optional[Sequence[str]] = None, cache: Optional[str] = None,
|
|
184
|
+
progress: bool = True, force: bool = False) -> str:
|
|
185
|
+
"""Download every file matching the glob patterns; returns the local directory."""
|
|
186
|
+
files = list_repo_files(repo_id, revision, token)
|
|
187
|
+
if allow_patterns:
|
|
188
|
+
files = [f for f in files if any(fnmatch.fnmatch(f, p) for p in allow_patterns)]
|
|
189
|
+
if ignore_patterns:
|
|
190
|
+
files = [f for f in files if not any(fnmatch.fnmatch(f, p) for p in ignore_patterns)]
|
|
191
|
+
if not files:
|
|
192
|
+
raise HubError(f"no files in {repo_id}@{revision} match the given patterns")
|
|
193
|
+
for f in files:
|
|
194
|
+
download_file(repo_id, f, revision, token, cache, force, progress)
|
|
195
|
+
return _repo_dir(repo_id, revision, cache)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# --------------------------------------------------------------------------- smart selection
|
|
199
|
+
_AUX = ("config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",
|
|
200
|
+
"special_tokens_map.json")
|
|
201
|
+
_GGUF_PREFERENCE = ("Q4_K_M", "Q4_K_S", "Q5_K_M", "Q5_K_S", "Q6_K", "Q8_0", "Q4_0", "Q3_K_M", "F16", "BF16")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _pick_gguf(files: List[str], quant: Optional[str]) -> str:
|
|
205
|
+
ggufs = [f for f in files if f.lower().endswith(".gguf") and "mmproj" not in f.lower()]
|
|
206
|
+
split = [f for f in ggufs if re.search(r"-\d{5}-of-\d{5}\.gguf$", f)]
|
|
207
|
+
singles = [f for f in ggufs if f not in split]
|
|
208
|
+
pool = singles or ggufs
|
|
209
|
+
if quant:
|
|
210
|
+
hit = [f for f in pool if quant.lower() in f.lower()]
|
|
211
|
+
if not hit:
|
|
212
|
+
raise HubError(f"no GGUF matching quant {quant!r}; available: {', '.join(pool)}")
|
|
213
|
+
return sorted(hit, key=len)[0]
|
|
214
|
+
for q in _GGUF_PREFERENCE:
|
|
215
|
+
hit = [f for f in pool if q.lower() in f.lower()]
|
|
216
|
+
if hit:
|
|
217
|
+
return sorted(hit, key=len)[0]
|
|
218
|
+
return sorted(pool)[0]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def resolve_source(source: str, filename: Optional[str] = None, revision: str = "main", token=None,
|
|
222
|
+
quant: Optional[str] = None, cache: Optional[str] = None, progress: bool = True) -> str:
|
|
223
|
+
"""Turn a local path or a Hub repo id into a local file/directory holding the weights.
|
|
224
|
+
|
|
225
|
+
Selection for a repo (when ``filename`` is not given): safetensors (incl. sharded) >
|
|
226
|
+
GGUF (``quant`` or a sensible default such as Q4_K_M) > PyTorch ``.bin``/``.pt`` > ``.npz``.
|
|
227
|
+
Config/tokenizer files are downloaded alongside when present.
|
|
228
|
+
"""
|
|
229
|
+
source = os.fspath(source)
|
|
230
|
+
if os.path.exists(source):
|
|
231
|
+
return source
|
|
232
|
+
if source.startswith("hf://"):
|
|
233
|
+
source = source[5:]
|
|
234
|
+
if not looks_like_repo_id(source):
|
|
235
|
+
raise FileNotFoundError(f"{source!r} is neither an existing path nor a valid Hugging Face repo id")
|
|
236
|
+
dl = lambda f: download_file(source, f, revision, token, cache, False, progress) # noqa: E731
|
|
237
|
+
files = list_repo_files(source, revision, token)
|
|
238
|
+
top = [f for f in files if "/" not in f]
|
|
239
|
+
want: List[str]
|
|
240
|
+
if filename:
|
|
241
|
+
if filename not in files:
|
|
242
|
+
raise HubError(f"{filename!r} not found in {source}; files: {', '.join(files[:20])}...")
|
|
243
|
+
path = dl(filename)
|
|
244
|
+
if not filename.lower().endswith(".gguf"):
|
|
245
|
+
for a in _AUX: # config/tokenizer next to the weights (same repo dir)
|
|
246
|
+
if a in files:
|
|
247
|
+
dl(a)
|
|
248
|
+
return path
|
|
249
|
+
st = [f for f in top if f.endswith(".safetensors")]
|
|
250
|
+
ggufs = [f for f in files if f.lower().endswith(".gguf")]
|
|
251
|
+
pt = [f for f in top if re.match(r"(pytorch_model.*\.bin|.*\.pt|.*\.pth)$", f)]
|
|
252
|
+
npz = [f for f in top if f.endswith(".npz")]
|
|
253
|
+
aux = [a for a in _AUX if a in files]
|
|
254
|
+
if st:
|
|
255
|
+
idx = "model.safetensors.index.json"
|
|
256
|
+
if idx in top:
|
|
257
|
+
with open(dl(idx)) as f:
|
|
258
|
+
shards = sorted(set(json.load(f)["weight_map"].values()))
|
|
259
|
+
elif "model.safetensors" in top:
|
|
260
|
+
shards = ["model.safetensors"]
|
|
261
|
+
else:
|
|
262
|
+
shards = sorted(st)
|
|
263
|
+
for f in aux + shards:
|
|
264
|
+
dl(f)
|
|
265
|
+
return _repo_dir(source, revision, cache)
|
|
266
|
+
if ggufs:
|
|
267
|
+
return dl(_pick_gguf(files, quant))
|
|
268
|
+
if pt:
|
|
269
|
+
idx = "pytorch_model.bin.index.json"
|
|
270
|
+
if idx in top:
|
|
271
|
+
with open(dl(idx)) as f:
|
|
272
|
+
shards = sorted(set(json.load(f)["weight_map"].values()))
|
|
273
|
+
else:
|
|
274
|
+
shards = sorted(pt)
|
|
275
|
+
for f in aux + shards:
|
|
276
|
+
dl(f)
|
|
277
|
+
return _repo_dir(source, revision, cache)
|
|
278
|
+
if npz:
|
|
279
|
+
for f in aux + sorted(npz):
|
|
280
|
+
dl(f)
|
|
281
|
+
return _repo_dir(source, revision, cache)
|
|
282
|
+
raise HubError(f"{source} contains no safetensors/gguf/pt/npz weight files")
|
tensorload/llm.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""High-level model: weights + tokenizer + generation loop."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from typing import Dict, Iterator, List, Optional, Sequence, Union
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .chat import render_chat
|
|
11
|
+
from .core import TensorFile
|
|
12
|
+
from .engine import KVCache, ModelConfig, Transformer, load_engine_weights
|
|
13
|
+
from .formats import GGUFFile, open_tensors
|
|
14
|
+
from .hub import resolve_source
|
|
15
|
+
from .sampling import SamplingParams, sample_token
|
|
16
|
+
from .tokenizer import Tokenizer, load_tokenizer_from_dir, load_tokenizer_from_gguf
|
|
17
|
+
|
|
18
|
+
DTYPES = {"float32": np.float32, "fp32": np.float32, "float16": np.float16, "fp16": np.float16}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LanguageModel:
|
|
22
|
+
"""A loaded decoder-only language model.
|
|
23
|
+
|
|
24
|
+
>>> m = LanguageModel.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") # doctest: +SKIP
|
|
25
|
+
>>> print(m.generate("The capital of France is", max_new_tokens=8)) # doctest: +SKIP
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, engine: Transformer, tokenizer: Tokenizer, config: ModelConfig, source: str = ""):
|
|
29
|
+
self.engine, self.tokenizer, self.config, self.source = engine, tokenizer, config, source
|
|
30
|
+
|
|
31
|
+
# ---------------------------------------------------------------- loading
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_pretrained(cls, source: str, *, filename: Optional[str] = None, revision: str = "main",
|
|
34
|
+
token=None, quant: Optional[str] = None, dtype: str = "float32",
|
|
35
|
+
cache: Optional[str] = None, progress: bool = True) -> "LanguageModel":
|
|
36
|
+
"""``source`` is a local file/dir or a Hugging Face repo id (``org/name``).
|
|
37
|
+
|
|
38
|
+
Safetensors repos, GGUF repos (``quant="Q4_K_M"`` etc.), ``.pt``/``.bin`` and ``.npz`` weights work.
|
|
39
|
+
``dtype="float16"`` halves memory at some speed cost.
|
|
40
|
+
"""
|
|
41
|
+
path = resolve_source(source, filename, revision, token, quant, cache, progress)
|
|
42
|
+
np_dtype = DTYPES[dtype]
|
|
43
|
+
if os.path.isfile(path) and path.lower().endswith(".gguf"):
|
|
44
|
+
tf: TensorFile = GGUFFile(path)
|
|
45
|
+
cfg = ModelConfig.from_gguf(tf.metadata, tf.info("token_embd.weight").shape)
|
|
46
|
+
tok = load_tokenizer_from_gguf(tf.metadata)
|
|
47
|
+
else:
|
|
48
|
+
d = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path))
|
|
49
|
+
cfg_path = os.path.join(d, "config.json")
|
|
50
|
+
if not os.path.isfile(cfg_path):
|
|
51
|
+
raise FileNotFoundError(f"{cfg_path} not found: a config.json is required to run non-GGUF weights")
|
|
52
|
+
with open(cfg_path, encoding="utf-8") as f:
|
|
53
|
+
cfg = ModelConfig.from_hf(json.load(f))
|
|
54
|
+
tf = open_tensors(path)
|
|
55
|
+
tok = load_tokenizer_from_dir(d)
|
|
56
|
+
try:
|
|
57
|
+
weights = load_engine_weights(tf, cfg, np_dtype)
|
|
58
|
+
finally:
|
|
59
|
+
tf.close()
|
|
60
|
+
if cfg.vocab_size == 0:
|
|
61
|
+
cfg.vocab_size = weights["token_embd.weight"].shape[0]
|
|
62
|
+
if not tok.eos_ids:
|
|
63
|
+
tok.eos_ids = list(cfg.eos_token_ids)
|
|
64
|
+
if tok.bos_id is None:
|
|
65
|
+
tok.bos_id = cfg.bos_token_id
|
|
66
|
+
return cls(Transformer(cfg, weights), tok, cfg, str(source))
|
|
67
|
+
|
|
68
|
+
# ---------------------------------------------------------------- inference
|
|
69
|
+
def logits(self, prompt: Union[str, Sequence[int]]) -> np.ndarray:
|
|
70
|
+
"""Next-token logits for ``prompt`` (text or token ids)."""
|
|
71
|
+
ids = self._ids(prompt)
|
|
72
|
+
return self.engine.prefill(ids, self.engine.new_cache(len(ids) + 1))
|
|
73
|
+
|
|
74
|
+
def _ids(self, prompt, add_special=True) -> List[int]:
|
|
75
|
+
return self.tokenizer.encode(prompt, add_special=add_special) if isinstance(prompt, str) else [int(i) for i in prompt]
|
|
76
|
+
|
|
77
|
+
def stream(self, prompt: Union[str, Sequence[int]], *, max_new_tokens: int = 128, temperature: float = 0.8,
|
|
78
|
+
top_k: int = 40, top_p: float = 0.95, min_p: float = 0.0, repeat_penalty: float = 1.0,
|
|
79
|
+
seed: Optional[int] = None, stop: Optional[Sequence[str]] = None,
|
|
80
|
+
add_special: bool = True) -> Iterator[str]:
|
|
81
|
+
"""Yield text pieces as they are generated."""
|
|
82
|
+
params = SamplingParams(temperature, top_k, top_p, min_p, repeat_penalty, seed)
|
|
83
|
+
rng = np.random.default_rng(seed)
|
|
84
|
+
ids = self._ids(prompt, add_special)
|
|
85
|
+
if not ids:
|
|
86
|
+
raise ValueError("empty prompt")
|
|
87
|
+
max_len = self.config.max_position
|
|
88
|
+
if len(ids) >= max_len:
|
|
89
|
+
raise ValueError(f"prompt has {len(ids)} tokens, the model's context is {max_len}")
|
|
90
|
+
cache = self.engine.new_cache(min(len(ids) + max_new_tokens, max_len) + 1)
|
|
91
|
+
logits = self.engine.prefill(ids, cache)
|
|
92
|
+
eos = set(self.tokenizer.eos_ids)
|
|
93
|
+
stop = [s for s in (stop or []) if s]
|
|
94
|
+
hold = max((len(s) for s in stop), default=1) - 1
|
|
95
|
+
out: List[int] = []
|
|
96
|
+
emitted = 0
|
|
97
|
+
for _ in range(max_new_tokens):
|
|
98
|
+
tok = sample_token(logits, params, ids + out, rng)
|
|
99
|
+
if tok in eos:
|
|
100
|
+
break
|
|
101
|
+
out.append(tok)
|
|
102
|
+
text = self.tokenizer.decode(out)
|
|
103
|
+
cut = min((text.find(s) for s in stop if s in text), default=-1)
|
|
104
|
+
if cut >= 0:
|
|
105
|
+
if cut > emitted:
|
|
106
|
+
yield text[emitted:cut]
|
|
107
|
+
return
|
|
108
|
+
safe = len(text) - hold
|
|
109
|
+
if text.endswith("\ufffd"): # incomplete multi-byte character
|
|
110
|
+
safe = min(safe, len(text) - 1)
|
|
111
|
+
if safe > emitted:
|
|
112
|
+
yield text[emitted:safe]
|
|
113
|
+
emitted = safe
|
|
114
|
+
if cache.length >= max_len:
|
|
115
|
+
break
|
|
116
|
+
logits = self.engine.forward([tok], cache)
|
|
117
|
+
text = self.tokenizer.decode(out)
|
|
118
|
+
if len(text) > emitted:
|
|
119
|
+
yield text[emitted:]
|
|
120
|
+
|
|
121
|
+
def generate(self, prompt: Union[str, Sequence[int]], **kwargs) -> str:
|
|
122
|
+
"""Generate a completion (same keyword arguments as :meth:`stream`)."""
|
|
123
|
+
return "".join(self.stream(prompt, **kwargs))
|
|
124
|
+
|
|
125
|
+
def format_chat(self, messages: Union[str, List[Dict[str, str]]], add_generation_prompt: bool = True) -> str:
|
|
126
|
+
if isinstance(messages, str):
|
|
127
|
+
messages = [{"role": "user", "content": messages}]
|
|
128
|
+
t = self.tokenizer
|
|
129
|
+
return render_chat(messages, t.chat_template, t.bos_token, t.eos_token, add_generation_prompt,
|
|
130
|
+
has_im_start=t.token_to_id("<|im_start|>") is not None)
|
|
131
|
+
|
|
132
|
+
def chat(self, messages: Union[str, List[Dict[str, str]]], **kwargs) -> str:
|
|
133
|
+
"""Apply the model's chat template and generate the assistant reply."""
|
|
134
|
+
return "".join(self.chat_stream(messages, **kwargs))
|
|
135
|
+
|
|
136
|
+
def chat_stream(self, messages: Union[str, List[Dict[str, str]]], **kwargs) -> Iterator[str]:
|
|
137
|
+
prompt = self.format_chat(messages)
|
|
138
|
+
# templates normally include BOS themselves; avoid doubling it
|
|
139
|
+
has_bos = bool(self.tokenizer.bos_token and prompt.startswith(self.tokenizer.bos_token))
|
|
140
|
+
kwargs.setdefault("add_special", not has_bos)
|
|
141
|
+
return self.stream(prompt, **kwargs)
|
|
142
|
+
|
|
143
|
+
def __repr__(self):
|
|
144
|
+
c = self.config
|
|
145
|
+
return (f"<LanguageModel {c.arch} layers={c.num_layers} hidden={c.hidden_size} "
|
|
146
|
+
f"heads={c.num_heads}/{c.num_kv_heads} vocab={c.vocab_size} source={self.source!r}>")
|
tensorload/sampling.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Token sampling."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Optional, Sequence
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class SamplingParams:
|
|
12
|
+
temperature: float = 0.8 # 0 => greedy
|
|
13
|
+
top_k: int = 40 # 0 => disabled
|
|
14
|
+
top_p: float = 0.95 # 1.0 => disabled
|
|
15
|
+
min_p: float = 0.0
|
|
16
|
+
repeat_penalty: float = 1.0 # >1 discourages repeats
|
|
17
|
+
seed: Optional[int] = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def sample_token(logits: np.ndarray, p: SamplingParams, history: Sequence[int], rng: np.random.Generator) -> int:
|
|
21
|
+
x = logits.astype(np.float64, copy=True)
|
|
22
|
+
if p.repeat_penalty != 1.0 and len(history):
|
|
23
|
+
idx = np.unique(np.asarray(history, dtype=np.int64))
|
|
24
|
+
idx = idx[idx < x.shape[0]]
|
|
25
|
+
v = x[idx]
|
|
26
|
+
x[idx] = np.where(v > 0, v / p.repeat_penalty, v * p.repeat_penalty)
|
|
27
|
+
if p.temperature <= 0:
|
|
28
|
+
return int(np.argmax(x))
|
|
29
|
+
x /= p.temperature
|
|
30
|
+
if 0 < p.top_k < x.shape[0]:
|
|
31
|
+
kth = np.partition(x, -p.top_k)[-p.top_k]
|
|
32
|
+
x[x < kth] = -np.inf
|
|
33
|
+
x -= x.max()
|
|
34
|
+
probs = np.exp(x)
|
|
35
|
+
probs /= probs.sum()
|
|
36
|
+
if p.min_p > 0:
|
|
37
|
+
probs[probs < p.min_p * probs.max()] = 0.0
|
|
38
|
+
if p.top_p < 1.0:
|
|
39
|
+
order = np.argsort(-probs)
|
|
40
|
+
cs = np.cumsum(probs[order])
|
|
41
|
+
cutoff = int(np.searchsorted(cs, p.top_p * cs[-1])) + 1
|
|
42
|
+
keep = np.zeros_like(probs, dtype=bool)
|
|
43
|
+
keep[order[:cutoff]] = True
|
|
44
|
+
probs[~keep] = 0.0
|
|
45
|
+
probs /= probs.sum()
|
|
46
|
+
return int(rng.choice(probs.shape[0], p=probs))
|