AQIT 0.1.0
Loading...
Searching...
No Matches
torch_io.py
Go to the documentation of this file.
1# Copyright (c) 2025-present Aquin Labs Private Limited. All Rights Reserved.
2"""Trusted local checkpoint loads (PyTorch 2.6+ weights_only default)."""
3from __future__ import annotations
4
5import json
6from pathlib import Path
7from typing import Any
8
9
10def is_corrupt_pytorch_zip(exc: BaseException) -> bool:
11 msg = str(exc).lower()
12 return (
13 "zip archive" in msg
14 or "central directory" in msg
15 or "pytorchstreamreader" in msg
16 )
17
18
19def load_checkpoint(path: str | Path, *, map_location: Any = None) -> Any:
20 """Load a trusted Aquin .pt checkpoint (SAE, norm stats, activations)."""
21 import torch
22
23 kwargs: dict[str, Any] = {}
24 if map_location is not None:
25 kwargs["map_location"] = map_location
26 try:
27 try:
28 return torch.load(str(path), weights_only=False, **kwargs)
29 except TypeError:
30 return torch.load(str(path), **kwargs)
31 except Exception as exc:
33 raise ValueError(
34 f"Checkpoint at {path} is corrupted or incomplete "
35 "(download may have been interrupted). Delete the file and download again."
36 ) from exc
37 raise
38
39
40def load_norm_stats(path: str | Path, *, map_location: Any = None) -> dict[str, Any] | None:
41 """Load {mean, std} norm stats from .pt (torch) or .json sidecar."""
42 import torch
43
44 p = Path(path)
45 if not p.is_file():
46 return None
47
48 if p.suffix.lower() == ".json" or p.read_bytes()[:1] == b"{":
50 print(
51 f"[norm] {p} is catalog metadata, not norm stats — "
52 f"remove it and re-run: aquin load sae <model>-l<layer>",
53 flush=True,
54 )
55 return None
56 try:
57 data = json.loads(p.read_text(encoding="utf-8"))
58 except Exception:
59 return None
60 if not isinstance(data, dict) or "mean" not in data or "std" not in data:
61 return None
62 mean = data["mean"]
63 std = data["std"]
64 if not isinstance(mean, torch.Tensor):
65 mean = torch.tensor(mean)
66 if not isinstance(std, torch.Tensor):
67 std = torch.tensor(std)
68 if map_location is not None:
69 mean = mean.to(map_location)
70 std = std.to(map_location)
71 return {"mean": mean, "std": std}
72
73 try:
74 data = load_checkpoint(p, map_location=map_location)
75 except Exception as exc:
76 print(f"[norm] could not load {p}: {exc} — continuing without normalization", flush=True)
77 return None
78
80 print(
81 f"[norm] {p} is catalog metadata, not norm stats — "
82 f"remove it and re-run: aquin load sae <model>-l<layer>",
83 flush=True,
84 )
85 return None
86
87 if not isinstance(data, dict) or "mean" not in data or "std" not in data:
88 print(f"[norm] unexpected format in {p} — continuing without normalization", flush=True)
89 return None
90
91 mean, std = data["mean"], data["std"]
92 if map_location is not None and hasattr(mean, "to"):
93 mean = mean.to(map_location)
94 std = std.to(map_location)
95 return {"mean": mean, "std": std}
96
97
98def looks_like_catalog_metadata_blob(path: str | Path) -> bool:
99 """True when a .pt file is actually public_saes catalog JSON (not norm stats)."""
100 p = Path(path)
101 if not p.is_file() or p.stat().st_size < 2 or p.read_bytes()[:1] != b"{":
102 return False
103 try:
104 data = json.loads(p.read_text(encoding="utf-8"))
105 except Exception:
106 return False
107 if not isinstance(data, dict):
108 return False
109 if "mean" in data and "std" in data:
110 return False
111 return "model_slug" in data or "d_model" in data or "d_sae" in data
112
113
114def looks_like_invalid_norm_blob(path: str | Path) -> bool:
115 """True when a norm file is catalog JSON or other non-norm JSON."""
117 return True
118 p = Path(path)
119 if not p.is_file() or p.read_bytes()[:1] != b"{":
120 return False
121 try:
122 data = json.loads(p.read_text(encoding="utf-8"))
123 except Exception:
124 return True
125 return not (isinstance(data, dict) and "mean" in data and "std" in data)
126
127
128def looks_like_json_error_blob(path: str | Path) -> bool:
129 """True when a downloaded artifact is likely an API error body, not weights."""
130 p = Path(path)
131 if not p.is_file() or p.stat().st_size < 2:
132 return True
133 return p.read_bytes()[:1] == b"{"
134
135
136def looks_like_catalog_metadata_dict(data: Any) -> bool:
137 """True when a loaded checkpoint dict is public_saes row metadata, not SAE weights."""
138 import torch
139
140 if not isinstance(data, dict):
141 return False
142 if "mean" in data and "std" in data:
143 return False
144 if any(isinstance(v, torch.Tensor) for v in data.values()):
145 return False
146 if "state_dict" in data or "W_enc" in data or "W_dec" in data:
147 return False
148 return "model_slug" in data or ("d_model" in data and "layer" in data)
149
150
151def _checkpoint_tensors(ckpt: Any) -> dict[str, Any]:
152 import torch
153
154 if not isinstance(ckpt, dict):
155 return {}
156 if "state_dict" in ckpt and isinstance(ckpt["state_dict"], dict):
157 return {k: v for k, v in ckpt["state_dict"].items() if isinstance(v, torch.Tensor)}
158 if "model_state" in ckpt and isinstance(ckpt["model_state"], dict):
159 return {k: v for k, v in ckpt["model_state"].items() if isinstance(v, torch.Tensor)}
160 return {k: v for k, v in ckpt.items() if isinstance(v, torch.Tensor)}
161
162
163def _has_sae_weight_tensors(tensors: dict[str, Any]) -> bool:
164 if not tensors:
165 return False
166 names = set(tensors.keys())
167 leaves = {k.split(".")[-1] for k in names}
168 sae_keys = {"W_enc", "W_dec", "encoder.weight", "decoder.weight"}
169 return bool(names & sae_keys) or bool(leaves & {"W_enc", "W_dec", "weight"})
170
171
172def is_valid_sae_checkpoint_path(path: str | Path) -> bool:
173 """False when a cached SAE file is catalog metadata or another non-checkpoint blob."""
174 p = Path(path)
175 if not p.is_file() or p.stat().st_size < 64:
176 return False
178 return False
179
180 if p.suffix.lower() == ".safetensors":
181 try:
182 from safetensors.torch import load_file
183
184 tensors = load_file(str(p), device="cpu")
185 return _has_sae_weight_tensors(tensors)
186 except Exception:
187 return False
188
189 try:
190 ckpt = load_checkpoint(p, map_location="cpu")
191 except Exception:
192 return False
193
195 return False
dict[str, Any]|None load_norm_stats(str|Path path, *, Any map_location=None)
Definition torch_io.py:44
bool is_corrupt_pytorch_zip(BaseException exc)
Definition torch_io.py:14
bool looks_like_json_error_blob(str|Path path)
Definition torch_io.py:132
dict[str, Any] _checkpoint_tensors(Any ckpt)
Definition torch_io.py:155
Any load_checkpoint(str|Path path, *, Any map_location=None)
Definition torch_io.py:23
bool is_valid_sae_checkpoint_path(str|Path path)
Definition torch_io.py:176
bool looks_like_catalog_metadata_blob(str|Path path)
Definition torch_io.py:102
bool looks_like_catalog_metadata_dict(Any data)
Definition torch_io.py:140
bool looks_like_invalid_norm_blob(str|Path path)
Definition torch_io.py:118
bool _has_sae_weight_tensors(dict[str, Any] tensors)
Definition torch_io.py:167