tensorload 0.1.0__tar.gz

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.
Files changed (31) hide show
  1. tensorload-0.1.0/LICENSE +21 -0
  2. tensorload-0.1.0/PKG-INFO +120 -0
  3. tensorload-0.1.0/README.md +94 -0
  4. tensorload-0.1.0/pyproject.toml +27 -0
  5. tensorload-0.1.0/setup.cfg +4 -0
  6. tensorload-0.1.0/src/tensorload/__init__.py +87 -0
  7. tensorload-0.1.0/src/tensorload/_dtypes.py +16 -0
  8. tensorload-0.1.0/src/tensorload/chat.py +31 -0
  9. tensorload-0.1.0/src/tensorload/cli.py +125 -0
  10. tensorload-0.1.0/src/tensorload/core.py +118 -0
  11. tensorload-0.1.0/src/tensorload/engine.py +273 -0
  12. tensorload-0.1.0/src/tensorload/formats/__init__.py +79 -0
  13. tensorload-0.1.0/src/tensorload/formats/gguf.py +215 -0
  14. tensorload-0.1.0/src/tensorload/formats/npz.py +59 -0
  15. tensorload-0.1.0/src/tensorload/formats/pytorch.py +178 -0
  16. tensorload-0.1.0/src/tensorload/formats/quant.py +160 -0
  17. tensorload-0.1.0/src/tensorload/formats/safetensors.py +136 -0
  18. tensorload-0.1.0/src/tensorload/hub.py +282 -0
  19. tensorload-0.1.0/src/tensorload/llm.py +146 -0
  20. tensorload-0.1.0/src/tensorload/sampling.py +46 -0
  21. tensorload-0.1.0/src/tensorload/tokenizer.py +344 -0
  22. tensorload-0.1.0/src/tensorload.egg-info/PKG-INFO +120 -0
  23. tensorload-0.1.0/src/tensorload.egg-info/SOURCES.txt +29 -0
  24. tensorload-0.1.0/src/tensorload.egg-info/dependency_links.txt +1 -0
  25. tensorload-0.1.0/src/tensorload.egg-info/entry_points.txt +2 -0
  26. tensorload-0.1.0/src/tensorload.egg-info/requires.txt +21 -0
  27. tensorload-0.1.0/src/tensorload.egg-info/top_level.txt +1 -0
  28. tensorload-0.1.0/tests/test_engine.py +148 -0
  29. tensorload-0.1.0/tests/test_formats.py +324 -0
  30. tensorload-0.1.0/tests/test_hub.py +151 -0
  31. tensorload-0.1.0/tests/test_tokenizer.py +42 -0
@@ -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,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,94 @@
1
+ # tensorload
2
+
3
+ Load model weights from **GGUF, safetensors, PyTorch (`.pt`/`.pth`/`.bin`) and NumPy (`.npz`)**, download them from
4
+ **Hugging Face**, and **run** LLaMA-family models — with nothing but NumPy as a hard dependency.
5
+
6
+ ```bash
7
+ pip install tensorload # numpy only
8
+ pip install tensorload[all] # + tokenizers, regex, jinja2 (recommended)
9
+ ```
10
+
11
+ ## Load weights
12
+
13
+ ```python
14
+ import tensorload as tl
15
+
16
+ tensors = tl.load("model.safetensors") # dict[str, np.ndarray]
17
+ tensors = tl.load("model-Q4_K_M.gguf") # quantised tensors are dequantised to float32
18
+ tensors = tl.load("checkpoint.pt") # safe: no arbitrary pickle execution
19
+ tensors = tl.load("weights.npz")
20
+ tensors = tl.load("./hf_model_dir") # sharded checkpoints are merged automatically
21
+ tensors = tl.load("Qwen/Qwen2.5-0.5B-Instruct") # downloads from the Hub (cached)
22
+
23
+ # lazy access: inspect without reading tensor data
24
+ with tl.open("model.gguf") as f:
25
+ print(f.format, f.metadata["general.architecture"])
26
+ for info in f.infos()[:5]:
27
+ print(info.name, info.shape, info.dtype, info.nbytes)
28
+ w = f.get("blk.0.attn_q.weight")
29
+
30
+ tl.convert("model.gguf", "model.safetensors") # .safetensors / .npz / .gguf targets
31
+ tl.save_safetensors(tensors, "out.safetensors")
32
+ tl.save_gguf("out.gguf", tensors, {"general.architecture": "llama"}, dtype="Q8_0")
33
+ ```
34
+
35
+ | Format | Read | Write | Notes |
36
+ |---|---|---|---|
37
+ | safetensors | ✅ mmap | ✅ (F32/F16/…, BF16 helper) | BF16 is widened to float32; FP8 unsupported |
38
+ | 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 |
39
+ | PyTorch | ✅ zip format via a *restricted* unpickler | – | legacy pre-1.6 files need `torch` installed |
40
+ | NumPy | ✅ `.npz`/`.npy`, `allow_pickle=False` | ✅ | |
41
+
42
+ ## Download from Hugging Face
43
+
44
+ ```python
45
+ tl.download_file("TheBloke/some-model-GGUF", "some-model.Q4_K_M.gguf") # resumable, cached
46
+ tl.snapshot_download("Qwen/Qwen2.5-0.5B-Instruct", allow_patterns=["*.json", "*.safetensors"])
47
+ tl.list_repo_files("org/name")
48
+ ```
49
+ Token: `token=...`, `HF_TOKEN`, or `~/.cache/huggingface/token` (needed for gated/private repos).
50
+ `HF_ENDPOINT` selects a mirror, `TENSORLOAD_CACHE` the cache dir (default `~/.cache/tensorload`).
51
+ Given a repo id, tensorload picks safetensors (sharded or not) > GGUF (`quant="Q4_K_M"` or a sensible default) > `.bin`/`.pt` > `.npz`.
52
+
53
+ ## Run models
54
+
55
+ ```python
56
+ lm = tl.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") # or a local dir / .gguf file
57
+ print(lm.generate("The capital of France is", max_new_tokens=16, temperature=0))
58
+ print(lm.chat([{"role": "user", "content": "Name three colours."}], temperature=0.7))
59
+ for piece in lm.stream("Once upon a time", max_new_tokens=64): # streaming
60
+ print(piece, end="", flush=True)
61
+
62
+ lm = tl.from_pretrained("bartowski/Llama-3.2-1B-Instruct-GGUF", quant="Q4_K_M")
63
+ lm = tl.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", dtype="float16") # half the RAM, a bit slower
64
+ ```
65
+ Sampling options: `temperature, top_k, top_p, min_p, repeat_penalty, seed, stop, max_new_tokens`.
66
+
67
+ The built-in engine is a compact NumPy transformer with KV cache, GQA, RoPE (llama3/linear scaling, llama.cpp
68
+ `rope_freqs`), RMSNorm, SwiGLU, QKV bias and Qwen3 QK-norm. **Architectures:** `llama` (incl. Llama 2/3.x, Mistral),
69
+ `qwen2`, `qwen3`; other models raise `UnsupportedModelError` (you can still `tl.load()` their weights).
70
+ Tokenizers: HF `tokenizer.json` (uses the `tokenizers` package if present, else a built-in byte-level BPE) and the
71
+ vocabularies embedded in GGUF files (`gpt2` BPE and `llama` SentencePiece).
72
+
73
+ > Performance: this is float32 NumPy on CPU — great for tiny/small models (≲1–3B) and for correctness checks, and
74
+ > quantised GGUFs are dequantised at load time, so RAM use is that of float32 (or float16 with `dtype="float16"`).
75
+ > For fast large-model inference use llama.cpp / vLLM.
76
+
77
+ ## CLI
78
+
79
+ ```bash
80
+ tensorload info model.gguf --summary
81
+ tensorload download Qwen/Qwen2.5-0.5B-Instruct
82
+ tensorload convert model.pt model.safetensors
83
+ tensorload run Qwen/Qwen2.5-0.5B-Instruct -p "Hello" --chat -n 64 --temp 0
84
+ tensorload run some/model-GGUF --quant Q4_K_M -i # interactive chat
85
+ ```
86
+
87
+ ## Tests
88
+
89
+ ```bash
90
+ PYTHONPATH=src:tests python -m unittest discover -s tests # or: pytest
91
+ ```
92
+ The suite checks every format round-trip, the K-quant kernels against scalar ports of the reference algorithms,
93
+ the engine against an independent Hugging-Face-style reference (including llama.cpp's interleaved-RoPE GGUF
94
+ layout), incremental-vs-full decoding, tokenizers, and the downloader against a local mock Hub (resume, auth, quant selection).
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tensorload"
7
+ version = "0.1.0"
8
+ description = "Load GGUF, safetensors, PyTorch (.pt) and NumPy (.npz) weights, download from Hugging Face, and run LLaMA-family models with a pure-NumPy engine."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ dependencies = ["numpy>=1.22"]
13
+ keywords = ["gguf", "safetensors", "pytorch", "huggingface", "llm", "inference", "numpy"]
14
+
15
+ [project.optional-dependencies]
16
+ tokenizers = ["tokenizers>=0.15"] # exact HF tokenizer behaviour (recommended)
17
+ regex = ["regex"] # exact pre-tokenizer patterns for the built-in BPE
18
+ chat = ["jinja2"] # render chat templates from tokenizer_config / GGUF
19
+ torch = ["torch"] # only used to read legacy (pre-1.6) .pt files
20
+ all = ["tokenizers>=0.15", "regex", "jinja2"]
21
+ dev = ["pytest"]
22
+
23
+ [project.scripts]
24
+ tensorload = "tensorload.cli:main"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,87 @@
1
+ """tensorload - load GGUF / safetensors / PyTorch / NPZ weights, fetch them from Hugging Face,
2
+ and run LLaMA-family models with a pure-NumPy engine.
3
+
4
+ Quick start::
5
+
6
+ import tensorload as tl
7
+
8
+ tensors = tl.load("model.safetensors") # dict[str, np.ndarray]
9
+ tensors = tl.load("Qwen/Qwen2.5-0.5B-Instruct") # downloads from the Hub
10
+ with tl.open("model-Q4_K_M.gguf") as f: # lazy access
11
+ print(f.metadata["general.architecture"], f.infos()[:3])
12
+
13
+ lm = tl.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
14
+ print(lm.chat("Say hi in five words.", temperature=0))
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from typing import Dict, Optional, Sequence
20
+
21
+ import numpy as np
22
+
23
+ from .core import MultiFile, TensorFile, TensorInfo
24
+ from .engine import ModelConfig, Transformer, UnsupportedModelError
25
+ from .formats import (FORMATS, GGUFFile, NpzFile, PytorchFile, SafetensorsFile, detect_format, open_tensors,
26
+ save_gguf, save_npz, save_safetensors, save_safetensors_bf16)
27
+ from .hub import HubError, download_file, list_repo_files, resolve_source, snapshot_download
28
+ from .llm import LanguageModel
29
+ from .sampling import SamplingParams
30
+ from .tokenizer import Tokenizer
31
+
32
+ __version__ = "0.1.0"
33
+
34
+
35
+ def open(path_or_repo, *, filename: Optional[str] = None, revision: str = "main", token=None, # noqa: A001
36
+ quant: Optional[str] = None, format: Optional[str] = None, progress: bool = True) -> TensorFile:
37
+ """Open weights lazily. ``path_or_repo`` may be a file, a directory of shards, or a Hub repo id."""
38
+ path = resolve_source(path_or_repo, filename, revision, token, quant, None, progress)
39
+ return open_tensors(path, format)
40
+
41
+
42
+ def load(path_or_repo, *, names: Optional[Sequence[str]] = None, dtype=None, filename: Optional[str] = None,
43
+ revision: str = "main", token=None, quant: Optional[str] = None, format: Optional[str] = None,
44
+ progress: bool = True) -> Dict[str, np.ndarray]:
45
+ """Load every tensor into a ``dict[str, np.ndarray]``.
46
+
47
+ GGUF quantised tensors are dequantised and bf16 is widened to float32. Pass ``dtype`` (e.g.
48
+ ``np.float16``) to cast floating-point tensors, and ``names`` to load a subset.
49
+ """
50
+ with open(path_or_repo, filename=filename, revision=revision, token=token, quant=quant,
51
+ format=format, progress=progress) as f:
52
+ return f.load(names, dtype)
53
+
54
+
55
+ def inspect(path_or_repo, **kw):
56
+ """Return ``(metadata, [TensorInfo, ...])`` without reading tensor data."""
57
+ with open(path_or_repo, **kw) as f:
58
+ return dict(f.metadata), f.infos()
59
+
60
+
61
+ def from_pretrained(source: str, **kw) -> LanguageModel:
62
+ """Shortcut for :meth:`LanguageModel.from_pretrained`."""
63
+ return LanguageModel.from_pretrained(source, **kw)
64
+
65
+
66
+ def convert(src, dst, *, dtype=None) -> None:
67
+ """Convert between formats; the destination format follows its extension
68
+ (``.safetensors``, ``.npz``, ``.gguf``)."""
69
+ tensors = load(src, dtype=dtype)
70
+ ext = os.path.splitext(str(dst))[1].lower()
71
+ if ext == ".safetensors":
72
+ save_safetensors(tensors, dst)
73
+ elif ext == ".npz":
74
+ save_npz(tensors, dst)
75
+ elif ext == ".gguf":
76
+ save_gguf(tensors, dst)
77
+ else:
78
+ raise ValueError(f"cannot write {ext!r}; use .safetensors, .npz or .gguf")
79
+
80
+
81
+ __all__ = [
82
+ "open", "load", "inspect", "convert", "from_pretrained", "LanguageModel", "SamplingParams", "ModelConfig",
83
+ "Transformer", "UnsupportedModelError", "Tokenizer", "TensorFile", "TensorInfo", "MultiFile",
84
+ "GGUFFile", "SafetensorsFile", "PytorchFile", "NpzFile", "detect_format", "FORMATS",
85
+ "save_safetensors", "save_safetensors_bf16", "save_gguf", "save_npz",
86
+ "download_file", "snapshot_download", "list_repo_files", "resolve_source", "HubError", "__version__",
87
+ ]
@@ -0,0 +1,16 @@
1
+ """Small dtype helpers (NumPy has no native bfloat16)."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+
6
+
7
+ def bf16_to_f32(bits: np.ndarray) -> np.ndarray:
8
+ """Convert raw bfloat16 bit patterns (uint16) to float32."""
9
+ return (np.asarray(bits, dtype=np.uint16).astype(np.uint32) << np.uint32(16)).view(np.float32)
10
+
11
+
12
+ def f32_to_bf16_bits(x: np.ndarray) -> np.ndarray:
13
+ """Round float32 to bfloat16 (round-to-nearest-even) and return uint16 bit patterns."""
14
+ u = np.ascontiguousarray(x, dtype=np.float32).view(np.uint32)
15
+ rounded = u + np.uint32(0x7FFF) + ((u >> np.uint32(16)) & np.uint32(1))
16
+ return (rounded >> np.uint32(16)).astype(np.uint16)
@@ -0,0 +1,31 @@
1
+ """Chat-template rendering (Jinja2 if installed, with sensible fallbacks)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Dict, List, Optional
5
+
6
+
7
+ def render_chat(messages: List[Dict[str, str]], template: Optional[str], bos_token: Optional[str] = None,
8
+ eos_token: Optional[str] = None, add_generation_prompt: bool = True,
9
+ has_im_start: bool = False) -> str:
10
+ if template:
11
+ try:
12
+ from jinja2.sandbox import ImmutableSandboxedEnvironment
13
+ except ImportError:
14
+ template = None
15
+ else:
16
+ import datetime
17
+
18
+ def raise_exception(msg):
19
+ raise ValueError(msg)
20
+
21
+ env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)
22
+ env.globals["raise_exception"] = raise_exception
23
+ env.globals["strftime_now"] = lambda fmt: datetime.datetime.now().strftime(fmt)
24
+ return env.from_string(template).render(
25
+ messages=messages, bos_token=bos_token or "", eos_token=eos_token or "",
26
+ add_generation_prompt=add_generation_prompt)
27
+ if has_im_start: # ChatML
28
+ s = "".join(f"<|im_start|>{m['role']}\n{m['content']}<|im_end|>\n" for m in messages)
29
+ return s + ("<|im_start|>assistant\n" if add_generation_prompt else "")
30
+ s = "".join(f"{m['role'].capitalize()}: {m['content']}\n" for m in messages)
31
+ return s + ("Assistant:" if add_generation_prompt else "")
@@ -0,0 +1,125 @@
1
+ """``tensorload`` command line interface."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+
7
+ import numpy as np
8
+
9
+
10
+ def _fmt_bytes(n: int) -> str:
11
+ for unit in ("B", "KB", "MB", "GB", "TB"):
12
+ if n < 1024 or unit == "TB":
13
+ return f"{n:.1f} {unit}" if unit != "B" else f"{n} B"
14
+ n /= 1024
15
+
16
+
17
+ def cmd_info(a):
18
+ import tensorload as tl
19
+ with tl.open(a.source, filename=a.file, revision=a.revision, quant=a.quant) as f:
20
+ print(f"{f.path} [{f.format}] {len(f)} tensors")
21
+ for k, v in list(f.metadata.items())[: a.max_meta]:
22
+ s = repr(v)
23
+ print(f" meta {k} = {s if len(s) < 100 else s[:97] + '...'}")
24
+ total = 0
25
+ for i in f.infos():
26
+ total += i.nbytes
27
+ if not a.summary:
28
+ print(f" {i.name:60s} {i.dtype:8s} {str(tuple(i.shape)):24s} {_fmt_bytes(i.nbytes)}")
29
+ print(f"total tensor data: {_fmt_bytes(total)}")
30
+
31
+
32
+ def cmd_download(a):
33
+ import tensorload as tl
34
+ if a.file or not a.pattern:
35
+ path = tl.resolve_source(a.repo, a.file, a.revision, quant=a.quant)
36
+ else:
37
+ path = tl.snapshot_download(a.repo, a.revision, allow_patterns=a.pattern)
38
+ print(path)
39
+
40
+
41
+ def cmd_convert(a):
42
+ import tensorload as tl
43
+ tl.convert(a.src, a.dst, dtype=np.float16 if a.fp16 else None)
44
+ print(f"wrote {a.dst}")
45
+
46
+
47
+ def cmd_run(a):
48
+ import tensorload as tl
49
+ lm = tl.from_pretrained(a.source, filename=a.file, revision=a.revision, quant=a.quant, dtype=a.dtype)
50
+ kw = dict(max_new_tokens=a.max_tokens, temperature=a.temp, top_k=a.top_k, top_p=a.top_p,
51
+ repeat_penalty=a.repeat_penalty, seed=a.seed)
52
+ if a.interactive:
53
+ history = []
54
+ print("(Ctrl-D to quit)", file=sys.stderr)
55
+ while True:
56
+ try:
57
+ user = input("you> ")
58
+ except EOFError:
59
+ print()
60
+ return
61
+ history.append({"role": "user", "content": user})
62
+ reply = ""
63
+ for piece in lm.chat_stream(history, **kw):
64
+ reply += piece
65
+ print(piece, end="", flush=True)
66
+ print()
67
+ history.append({"role": "assistant", "content": reply})
68
+ stream = lm.chat_stream(a.prompt, **kw) if a.chat else lm.stream(a.prompt, **kw)
69
+ if not a.chat:
70
+ print(a.prompt, end="", flush=True)
71
+ for piece in stream:
72
+ print(piece, end="", flush=True)
73
+ print()
74
+
75
+
76
+ def main(argv=None):
77
+ p = argparse.ArgumentParser(prog="tensorload", description=__doc__)
78
+ sub = p.add_subparsers(dest="cmd", required=True)
79
+
80
+ def hub_args(sp):
81
+ sp.add_argument("--file", help="file inside the repo")
82
+ sp.add_argument("--revision", default="main")
83
+ sp.add_argument("--quant", help="GGUF quant to prefer, e.g. Q4_K_M")
84
+
85
+ s = sub.add_parser("info", help="list tensors/metadata of a file, directory or Hub repo")
86
+ s.add_argument("source"); hub_args(s)
87
+ s.add_argument("--summary", action="store_true"); s.add_argument("--max-meta", type=int, default=40)
88
+ s.set_defaults(fn=cmd_info)
89
+
90
+ s = sub.add_parser("download", help="download weights from the Hugging Face Hub")
91
+ s.add_argument("repo"); hub_args(s)
92
+ s.add_argument("--pattern", action="append", help="glob(s) to download instead of auto-selection")
93
+ s.set_defaults(fn=cmd_download)
94
+
95
+ s = sub.add_parser("convert", help="convert weights to .safetensors / .npz / .gguf")
96
+ s.add_argument("src"); s.add_argument("dst"); s.add_argument("--fp16", action="store_true")
97
+ s.set_defaults(fn=cmd_convert)
98
+
99
+ s = sub.add_parser("run", help="generate text with a model")
100
+ s.add_argument("source"); hub_args(s)
101
+ s.add_argument("-p", "--prompt", default="Hello")
102
+ s.add_argument("--chat", action="store_true", help="wrap the prompt in the chat template")
103
+ s.add_argument("-i", "--interactive", action="store_true", help="multi-turn chat REPL")
104
+ s.add_argument("-n", "--max-tokens", type=int, default=128)
105
+ s.add_argument("--temp", type=float, default=0.8)
106
+ s.add_argument("--top-k", type=int, default=40)
107
+ s.add_argument("--top-p", type=float, default=0.95)
108
+ s.add_argument("--repeat-penalty", type=float, default=1.0)
109
+ s.add_argument("--seed", type=int)
110
+ s.add_argument("--dtype", choices=["float32", "float16"], default="float32")
111
+ s.set_defaults(fn=cmd_run)
112
+
113
+ a = p.parse_args(argv)
114
+ try:
115
+ a.fn(a)
116
+ except KeyboardInterrupt:
117
+ return 130
118
+ except Exception as e: # concise errors for CLI users
119
+ print(f"error: {e}", file=sys.stderr)
120
+ return 1
121
+ return 0
122
+
123
+
124
+ if __name__ == "__main__":
125
+ sys.exit(main())
@@ -0,0 +1,118 @@
1
+ """Common abstractions shared by every file format reader."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Any, Dict, Iterator, List, Optional, Sequence
6
+
7
+ import numpy as np
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class TensorInfo:
12
+ """Description of a tensor as stored on disk (nothing is loaded)."""
13
+
14
+ name: str
15
+ shape: tuple
16
+ dtype: str # on-disk dtype name, e.g. "F16", "BF16", "Q4_K", "float32"
17
+ nbytes: int
18
+
19
+ @property
20
+ def numel(self) -> int:
21
+ n = 1
22
+ for d in self.shape:
23
+ n *= int(d)
24
+ return n
25
+
26
+
27
+ class TensorFile:
28
+ """A lazily-read collection of named tensors.
29
+
30
+ Subclasses implement :meth:`keys`, :meth:`info` and :meth:`get`.
31
+ Every returned array is a regular, writable, in-memory NumPy array
32
+ (quantised/bf16 data is converted to float32).
33
+ """
34
+
35
+ format = "unknown"
36
+
37
+ def __init__(self, path: str):
38
+ self.path = str(path)
39
+ self.metadata: Dict[str, Any] = {}
40
+
41
+ # -- to implement ---------------------------------------------------------
42
+ def keys(self) -> List[str]:
43
+ raise NotImplementedError
44
+
45
+ def info(self, name: str) -> TensorInfo:
46
+ raise NotImplementedError
47
+
48
+ def get(self, name: str) -> np.ndarray:
49
+ raise NotImplementedError
50
+
51
+ def close(self) -> None: # pragma: no cover - default is a no-op
52
+ pass
53
+
54
+ # -- conveniences ---------------------------------------------------------
55
+ def infos(self) -> List[TensorInfo]:
56
+ return [self.info(k) for k in self.keys()]
57
+
58
+ def __iter__(self) -> Iterator[str]:
59
+ return iter(self.keys())
60
+
61
+ def __len__(self) -> int:
62
+ return len(self.keys())
63
+
64
+ def __contains__(self, name: object) -> bool:
65
+ return name in set(self.keys())
66
+
67
+ def __getitem__(self, name: str) -> np.ndarray:
68
+ return self.get(name)
69
+
70
+ def __enter__(self):
71
+ return self
72
+
73
+ def __exit__(self, *exc):
74
+ self.close()
75
+
76
+ def load(self, names: Optional[Sequence[str]] = None, dtype=None) -> Dict[str, np.ndarray]:
77
+ """Read tensors into a dict. ``dtype`` casts floating-point tensors only."""
78
+ out: Dict[str, np.ndarray] = {}
79
+ for k in names if names is not None else self.keys():
80
+ a = self.get(k)
81
+ if dtype is not None and np.issubdtype(a.dtype, np.floating):
82
+ a = a.astype(dtype, copy=False)
83
+ out[k] = a
84
+ return out
85
+
86
+ def __repr__(self) -> str:
87
+ return f"<{type(self).__name__} {self.path!r} tensors={len(self)}>"
88
+
89
+
90
+ class MultiFile(TensorFile):
91
+ """Several shards presented as one :class:`TensorFile`."""
92
+
93
+ def __init__(self, files: Sequence[TensorFile], path: str = ""):
94
+ super().__init__(path or (files[0].path if files else ""))
95
+ self.files = list(files)
96
+ self.format = files[0].format if files else "unknown"
97
+ self._index: Dict[str, TensorFile] = {}
98
+ for f in self.files:
99
+ for k in f.keys():
100
+ self._index.setdefault(k, f)
101
+ for mk, mv in f.metadata.items():
102
+ self.metadata.setdefault(mk, mv)
103
+
104
+ def keys(self):
105
+ return list(self._index)
106
+
107
+ def __contains__(self, name):
108
+ return name in self._index
109
+
110
+ def info(self, name):
111
+ return self._index[name].info(name)
112
+
113
+ def get(self, name):
114
+ return self._index[name].get(name)
115
+
116
+ def close(self):
117
+ for f in self.files:
118
+ f.close()