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 ADDED
@@ -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
+ ]
tensorload/_dtypes.py ADDED
@@ -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)
tensorload/chat.py ADDED
@@ -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 "")
tensorload/cli.py ADDED
@@ -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())
tensorload/core.py ADDED
@@ -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()
tensorload/engine.py ADDED
@@ -0,0 +1,273 @@
1
+ """A compact pure-NumPy decoder-only transformer (Llama / Mistral / Qwen2 / Qwen3 family).
2
+
3
+ Single-sequence inference with a KV cache, grouped-query attention, RoPE (half-split "NeoX"
4
+ layout used by Hugging Face, or the interleaved layout used by llama.cpp's ``llama`` GGUFs),
5
+ RMSNorm and a SwiGLU MLP.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass, field
11
+ from typing import Dict, List, Mapping, Optional
12
+
13
+ import numpy as np
14
+
15
+ from .core import TensorFile
16
+
17
+ SUPPORTED_HF = {"llama", "mistral", "qwen2", "qwen3"}
18
+ SUPPORTED_GGUF = {"llama", "qwen2", "qwen3"}
19
+
20
+
21
+ class UnsupportedModelError(NotImplementedError):
22
+ pass
23
+
24
+
25
+ @dataclass
26
+ class ModelConfig:
27
+ arch: str = "llama"
28
+ hidden_size: int = 0
29
+ intermediate_size: int = 0
30
+ num_layers: int = 0
31
+ num_heads: int = 0
32
+ num_kv_heads: int = 0
33
+ head_dim: int = 0
34
+ vocab_size: int = 0
35
+ rms_norm_eps: float = 1e-5
36
+ rope_theta: float = 10000.0
37
+ max_position: int = 2048
38
+ rope_interleaved: bool = False
39
+ rope_scaling: Optional[dict] = None # HF-style dict (llama3 / linear)
40
+ rope_linear_factor: float = 1.0
41
+ bos_token_id: Optional[int] = None
42
+ eos_token_ids: List[int] = field(default_factory=list)
43
+
44
+ @classmethod
45
+ def from_hf(cls, cfg: dict) -> "ModelConfig":
46
+ mt = cfg.get("model_type", "")
47
+ if mt not in SUPPORTED_HF:
48
+ raise UnsupportedModelError(
49
+ f"model_type {mt!r} is not supported by the built-in engine "
50
+ f"(supported: {', '.join(sorted(SUPPORTED_HF))}). You can still load its weights with tensorload.load().")
51
+ h, nh = cfg["hidden_size"], cfg["num_attention_heads"]
52
+ rp = cfg.get("rope_parameters") or {}
53
+ eos = cfg.get("eos_token_id")
54
+ return cls(
55
+ arch=mt, hidden_size=h, intermediate_size=cfg["intermediate_size"],
56
+ num_layers=cfg["num_hidden_layers"], num_heads=nh,
57
+ num_kv_heads=cfg.get("num_key_value_heads") or nh,
58
+ head_dim=cfg.get("head_dim") or h // nh, vocab_size=cfg.get("vocab_size", 0),
59
+ rms_norm_eps=cfg.get("rms_norm_eps", 1e-6), rope_theta=float(cfg.get("rope_theta", rp.get("rope_theta", 10000.0))),
60
+ max_position=cfg.get("max_position_embeddings", 4096), rope_interleaved=False,
61
+ rope_scaling=cfg.get("rope_scaling") or (rp if rp.get("rope_type") else None),
62
+ bos_token_id=cfg.get("bos_token_id"),
63
+ eos_token_ids=[int(e) for e in (eos if isinstance(eos, list) else [eos])] if eos is not None else [],
64
+ )
65
+
66
+ @classmethod
67
+ def from_gguf(cls, md: dict, embed_shape=None) -> "ModelConfig":
68
+ arch = md.get("general.architecture")
69
+ if arch not in SUPPORTED_GGUF:
70
+ raise UnsupportedModelError(
71
+ f"GGUF architecture {arch!r} is not supported by the built-in engine "
72
+ f"(supported: {', '.join(sorted(SUPPORTED_GGUF))}).")
73
+ g = lambda k, d=None: md.get(f"{arch}.{k}", d) # noqa: E731
74
+ h, nh = int(g("embedding_length")), int(g("attention.head_count"))
75
+ kv = g("attention.head_count_kv", nh)
76
+ if isinstance(kv, np.ndarray):
77
+ kv = int(kv.max())
78
+ scaling_type = g("rope.scaling.type")
79
+ eos = md.get("tokenizer.ggml.eos_token_id")
80
+ return cls(
81
+ arch=arch, hidden_size=h, intermediate_size=int(g("feed_forward_length")),
82
+ num_layers=int(g("block_count")), num_heads=nh, num_kv_heads=int(kv),
83
+ head_dim=int(g("attention.key_length", h // nh)),
84
+ vocab_size=int(embed_shape[0]) if embed_shape else len(md.get("tokenizer.ggml.tokens", [])),
85
+ rms_norm_eps=float(g("attention.layer_norm_rms_epsilon", 1e-5)),
86
+ rope_theta=float(g("rope.freq_base", 10000.0)), max_position=int(g("context_length", 4096)),
87
+ rope_interleaved=(arch == "llama"),
88
+ rope_linear_factor=float(g("rope.scaling.factor", 1.0)) if scaling_type == "linear" else 1.0,
89
+ bos_token_id=md.get("tokenizer.ggml.bos_token_id"),
90
+ eos_token_ids=[int(eos)] if eos is not None else [],
91
+ )
92
+
93
+
94
+ # ------------------------------------------------------------------------------ weight naming
95
+ _HF_LAYER = {
96
+ "self_attn.q_proj": "attn_q", "self_attn.k_proj": "attn_k", "self_attn.v_proj": "attn_v",
97
+ "self_attn.o_proj": "attn_output", "self_attn.q_norm": "attn_q_norm", "self_attn.k_norm": "attn_k_norm",
98
+ "mlp.gate_proj": "ffn_gate", "mlp.up_proj": "ffn_up", "mlp.down_proj": "ffn_down",
99
+ "input_layernorm": "attn_norm", "post_attention_layernorm": "ffn_norm",
100
+ }
101
+ _HF_TOP = {"model.embed_tokens.weight": "token_embd.weight", "embed_tokens.weight": "token_embd.weight",
102
+ "model.norm.weight": "output_norm.weight", "norm.weight": "output_norm.weight",
103
+ "lm_head.weight": "output.weight"}
104
+ _GGUF_TOP = {"token_embd.weight", "output_norm.weight", "output.weight", "rope_freqs.weight"}
105
+
106
+
107
+ def canonical_name(name: str) -> Optional[str]:
108
+ """Map HF or GGUF tensor names to the GGUF naming scheme used internally."""
109
+ if name in _GGUF_TOP or name.startswith("blk."):
110
+ return name
111
+ if name in _HF_TOP:
112
+ return _HF_TOP[name]
113
+ m = re.match(r"(?:model\.)?layers\.(\d+)\.(.+)\.(weight|bias)$", name)
114
+ if m and m.group(2) in _HF_LAYER:
115
+ return f"blk.{m.group(1)}.{_HF_LAYER[m.group(2)]}.{m.group(3)}"
116
+ return None
117
+
118
+
119
+ def load_engine_weights(tf: TensorFile, cfg: ModelConfig, dtype=np.float32) -> Dict[str, np.ndarray]:
120
+ """Read only the tensors the engine needs, cast to ``dtype`` (norm weights stay float32)."""
121
+ out: Dict[str, np.ndarray] = {}
122
+ for name in tf.keys():
123
+ cn = canonical_name(name)
124
+ if cn is None:
125
+ continue
126
+ a = tf.get(name)
127
+ if not np.issubdtype(a.dtype, np.floating):
128
+ continue
129
+ is_norm = a.ndim == 1
130
+ out[cn] = a.astype(np.float32 if (is_norm or dtype == np.float32) else dtype, copy=False)
131
+ return out
132
+
133
+
134
+ # ------------------------------------------------------------------------------ the model
135
+ def _rms_norm(x: np.ndarray, w: np.ndarray, eps: float) -> np.ndarray:
136
+ x = x.astype(np.float32, copy=False)
137
+ return x * (1.0 / np.sqrt(np.mean(x * x, axis=-1, keepdims=True) + eps)) * w
138
+
139
+
140
+ def _linear(x: np.ndarray, w: np.ndarray, b: Optional[np.ndarray] = None) -> np.ndarray:
141
+ y = x @ (w.T if w.dtype == np.float32 else w.astype(np.float32).T)
142
+ return y + b if b is not None else y
143
+
144
+
145
+ def _silu(x: np.ndarray) -> np.ndarray:
146
+ return x * 0.5 * (1.0 + np.tanh(0.5 * x))
147
+
148
+
149
+ class KVCache:
150
+ def __init__(self, n_layers: int, n_kv: int, head_dim: int, capacity: int = 256):
151
+ self.shape = (n_layers, n_kv, head_dim)
152
+ self.k = np.zeros((n_layers, capacity, n_kv, head_dim), dtype=np.float32)
153
+ self.v = np.zeros_like(self.k)
154
+ self.length = 0
155
+
156
+ def ensure(self, needed: int):
157
+ cap = self.k.shape[1]
158
+ if needed <= cap:
159
+ return
160
+ new = max(needed, cap * 2)
161
+ for attr in ("k", "v"):
162
+ old = getattr(self, attr)
163
+ bigger = np.zeros((old.shape[0], new) + old.shape[2:], dtype=np.float32)
164
+ bigger[:, :cap] = old
165
+ setattr(self, attr, bigger)
166
+
167
+
168
+ class Transformer:
169
+ def __init__(self, cfg: ModelConfig, weights: Mapping[str, np.ndarray]):
170
+ self.cfg, self.w = cfg, weights
171
+ for need in ("token_embd.weight", "output_norm.weight"):
172
+ if need not in weights:
173
+ raise KeyError(f"missing tensor {need!r}; is this a supported decoder-only checkpoint?")
174
+ for i in range(cfg.num_layers):
175
+ for part in ("attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate", "ffn_up", "ffn_down",
176
+ "attn_norm", "ffn_norm"):
177
+ if f"blk.{i}.{part}.weight" not in weights:
178
+ raise KeyError(f"missing tensor 'blk.{i}.{part}.weight'")
179
+ self.embed = weights["token_embd.weight"]
180
+ self.lm_head = weights.get("output.weight", self.embed) # tied embeddings if absent
181
+ self.inv_freq = self._rope_inv_freq()
182
+
183
+ def _rope_inv_freq(self) -> np.ndarray:
184
+ c = self.cfg
185
+ d = c.head_dim
186
+ inv = 1.0 / (c.rope_theta ** (np.arange(0, d, 2, dtype=np.float64) / d))
187
+ rs = c.rope_scaling or {}
188
+ rtype = rs.get("rope_type") or rs.get("type")
189
+ if rtype == "llama3":
190
+ factor, lo, hi = rs["factor"], rs["low_freq_factor"], rs["high_freq_factor"]
191
+ orig = rs["original_max_position_embeddings"]
192
+ wavelen = 2 * np.pi / inv
193
+ scaled = np.where(wavelen > orig / lo, inv / factor, inv)
194
+ smooth = (orig / wavelen - lo) / (hi - lo)
195
+ smoothed = (1 - smooth) * inv / factor + smooth * inv
196
+ medium = ~(wavelen < orig / hi) & ~(wavelen > orig / lo)
197
+ inv = np.where(medium, smoothed, scaled)
198
+ elif rtype == "linear":
199
+ inv = inv / rs["factor"]
200
+ elif rtype not in (None, "default"):
201
+ raise UnsupportedModelError(f"rope scaling type {rtype!r} is not supported")
202
+ if "rope_freqs.weight" in self.w: # llama.cpp ships llama3 scaling as per-dim divisors
203
+ inv = inv / self.w["rope_freqs.weight"].astype(np.float64)
204
+ return inv / c.rope_linear_factor if c.rope_linear_factor != 1.0 else inv
205
+
206
+ def new_cache(self, capacity: int = 256) -> KVCache:
207
+ c = self.cfg
208
+ return KVCache(c.num_layers, c.num_kv_heads, c.head_dim, capacity)
209
+
210
+ def _rope(self, x: np.ndarray, cos: np.ndarray, sin: np.ndarray) -> np.ndarray:
211
+ # x: (T, H, D); cos/sin: (T, 1, D/2)
212
+ if self.cfg.rope_interleaved:
213
+ x1, x2 = x[..., 0::2], x[..., 1::2]
214
+ return np.stack([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1).reshape(x.shape)
215
+ h = x.shape[-1] // 2
216
+ x1, x2 = x[..., :h], x[..., h:]
217
+ return np.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1)
218
+
219
+ def forward(self, ids, cache: KVCache) -> np.ndarray:
220
+ """Run ``ids`` (new tokens) through the model, extending ``cache``. Returns the logits
221
+ (vocab,) of the last position."""
222
+ c, w = self.cfg, self.w
223
+ ids = np.asarray(ids, dtype=np.int64)
224
+ T, start = len(ids), cache.length
225
+ if T == 0:
226
+ raise ValueError("forward() needs at least one token")
227
+ cache.ensure(start + T)
228
+ S = start + T
229
+ H, G, D = c.num_heads, c.num_heads // c.num_kv_heads, c.head_dim
230
+ Hkv = c.num_kv_heads
231
+ x = self.embed[ids].astype(np.float32)
232
+ ang = np.outer(np.arange(start, S, dtype=np.float64), self.inv_freq)
233
+ cos = np.cos(ang).astype(np.float32)[:, None, :]
234
+ sin = np.sin(ang).astype(np.float32)[:, None, :]
235
+ mask = None
236
+ if T > 1:
237
+ mask = np.where(np.arange(S)[None, :] > (start + np.arange(T))[:, None], -np.inf, 0.0).astype(np.float32)
238
+ scale = 1.0 / np.sqrt(D)
239
+ for i in range(c.num_layers):
240
+ p = f"blk.{i}."
241
+ h = _rms_norm(x, w[p + "attn_norm.weight"], c.rms_norm_eps)
242
+ q = _linear(h, w[p + "attn_q.weight"], w.get(p + "attn_q.bias")).reshape(T, H, D)
243
+ k = _linear(h, w[p + "attn_k.weight"], w.get(p + "attn_k.bias")).reshape(T, Hkv, D)
244
+ v = _linear(h, w[p + "attn_v.weight"], w.get(p + "attn_v.bias")).reshape(T, Hkv, D)
245
+ if p + "attn_q_norm.weight" in w: # Qwen3 QK-norm
246
+ q = _rms_norm(q, w[p + "attn_q_norm.weight"], c.rms_norm_eps)
247
+ k = _rms_norm(k, w[p + "attn_k_norm.weight"], c.rms_norm_eps)
248
+ q, k = self._rope(q, cos, sin), self._rope(k, cos, sin)
249
+ cache.k[i, start:S], cache.v[i, start:S] = k, v
250
+ K = cache.k[i, :S].transpose(1, 2, 0) # (Hkv, D, S)
251
+ V = cache.v[i, :S].transpose(1, 0, 2) # (Hkv, S, D)
252
+ qg = (q * scale).reshape(T, Hkv, G, D).transpose(1, 2, 0, 3).reshape(Hkv, G * T, D)
253
+ scores = (qg @ K).reshape(Hkv, G, T, S)
254
+ if mask is not None:
255
+ scores = scores + mask
256
+ scores -= scores.max(axis=-1, keepdims=True)
257
+ probs = np.exp(scores)
258
+ probs /= probs.sum(axis=-1, keepdims=True)
259
+ o = (probs.reshape(Hkv, G * T, S) @ V).reshape(Hkv, G, T, D).transpose(2, 0, 1, 3).reshape(T, H * D)
260
+ x = x + _linear(o, w[p + "attn_output.weight"], w.get(p + "attn_output.bias"))
261
+ h = _rms_norm(x, w[p + "ffn_norm.weight"], c.rms_norm_eps)
262
+ x = x + _linear(_silu(_linear(h, w[p + "ffn_gate.weight"])) * _linear(h, w[p + "ffn_up.weight"]),
263
+ w[p + "ffn_down.weight"])
264
+ cache.length = S
265
+ last = _rms_norm(x[-1:], w["output_norm.weight"], c.rms_norm_eps)
266
+ return _linear(last, self.lm_head)[0]
267
+
268
+ def prefill(self, ids, cache: KVCache, chunk: int = 512) -> np.ndarray:
269
+ """Feed a long prompt in chunks (bounds attention memory); returns last logits."""
270
+ logits = None
271
+ for s in range(0, len(ids), chunk):
272
+ logits = self.forward(ids[s:s + chunk], cache)
273
+ return logits