latchgate 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.
latchgate/__init__.py ADDED
@@ -0,0 +1,83 @@
1
+ """LatchGate: Zero-Decode Circuit-Breaker Compiler and Runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .compiler import (
6
+ AdaptiveRouteDecision,
7
+ CompileReport,
8
+ CounterfactualTracePair,
9
+ LatchCompiler,
10
+ extract_llm_activations_from_pairs,
11
+ fit_latchgate,
12
+ fit_manifold_steering_direction,
13
+ load_counterfactual_jsonl,
14
+ )
15
+ from .exceptions import EarlyAbortRollout, LatchGateError
16
+ from .format import (
17
+ OFFICIAL_PACKS,
18
+ LatchDecision,
19
+ LatchGate,
20
+ PretrainedPackInfo,
21
+ list_pretrained_packs,
22
+ )
23
+ from .runtime.diffusion import (
24
+ CosmosLatchFirewall,
25
+ CrossAttentionSubjectMask,
26
+ DiffusersLatchCallback,
27
+ compute_foreground_spatial_weights,
28
+ shield_value_critic,
29
+ )
30
+ from .runtime.llm import (
31
+ LLMTelemetry,
32
+ SGLangLatchHook,
33
+ TransformersLatchHook,
34
+ VLLMLatchEngine,
35
+ )
36
+ from .sae import (
37
+ ActivationReplayBuffer,
38
+ JumpReLUSAE,
39
+ ReplayBufferBudget,
40
+ TimestepStandardizer,
41
+ compute_replay_buffer_budget,
42
+ compute_wsae_channel_weights,
43
+ load_base_sae,
44
+ train_jumprelu_sae,
45
+ )
46
+
47
+ __version__ = "0.1.0"
48
+
49
+ __all__ = [
50
+ "__version__",
51
+ "ActivationReplayBuffer",
52
+ "AdaptiveRouteDecision",
53
+ "CompileReport",
54
+ "CounterfactualTracePair",
55
+ "CosmosLatchFirewall",
56
+ "CrossAttentionSubjectMask",
57
+ "DiffusersLatchCallback",
58
+ "EarlyAbortRollout",
59
+ "JumpReLUSAE",
60
+ "LLMTelemetry",
61
+ "LatchCompiler",
62
+ "LatchDecision",
63
+ "LatchGate",
64
+ "LatchGateError",
65
+ "OFFICIAL_PACKS",
66
+ "PretrainedPackInfo",
67
+ "ReplayBufferBudget",
68
+ "SGLangLatchHook",
69
+ "TimestepStandardizer",
70
+ "TransformersLatchHook",
71
+ "VLLMLatchEngine",
72
+ "compute_foreground_spatial_weights",
73
+ "compute_replay_buffer_budget",
74
+ "compute_wsae_channel_weights",
75
+ "extract_llm_activations_from_pairs",
76
+ "fit_latchgate",
77
+ "fit_manifold_steering_direction",
78
+ "list_pretrained_packs",
79
+ "load_base_sae",
80
+ "load_counterfactual_jsonl",
81
+ "shield_value_critic",
82
+ "train_jumprelu_sae",
83
+ ]
latchgate/cli.py ADDED
@@ -0,0 +1,306 @@
1
+ """Command-line interface for LatchGate (`latchgate`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+ import sys
10
+ import numpy as np
11
+ import torch
12
+
13
+ from . import __version__
14
+ from .compiler import (
15
+ LatchCompiler,
16
+ extract_llm_activations_from_pairs,
17
+ load_counterfactual_jsonl,
18
+ )
19
+ from .exceptions import LatchGateError
20
+ from .format import LatchGate, list_pretrained_packs
21
+ from .sae import train_jumprelu_sae
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ parser = argparse.ArgumentParser(
26
+ prog="latchgate",
27
+ description="Zero-decode circuit-breaker compiler and runtime for LLMs, Video DiTs, and World Models.",
28
+ )
29
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
30
+ sub = parser.add_subparsers(dest="command", required=True)
31
+
32
+ # 1. latchgate fit
33
+ fit_p = sub.add_parser(
34
+ "fit",
35
+ help="compile a portable .lgate circuit breaker from activation tensors (.npz) or counterfactual JSONL",
36
+ )
37
+ fit_p.add_argument(
38
+ "input_path",
39
+ help="path to counterfactual .npz (honest_acts, bad_acts, optional confounder_acts) or .jsonl pairs",
40
+ )
41
+ fit_p.add_argument("--output", "-o", default="gate.lgate", help="output .lgate path")
42
+ fit_p.add_argument("--report", help="optional JSON path to write CompileReport")
43
+ fit_p.add_argument(
44
+ "--mode",
45
+ choices=("auto", "dense", "sae"),
46
+ default="auto",
47
+ help="adaptive routing mode (default: auto)",
48
+ )
49
+ fit_p.add_argument("--model", help="Hugging Face model ID when compiling directly from .jsonl traces")
50
+ fit_p.add_argument("--base-sae", help="optional frozen base SAE (.safetensors, .lgate, .npz, .pt, or HF repo)")
51
+ fit_p.add_argument("--backbone-id", default="custom-backbone")
52
+ fit_p.add_argument("--layer-index", type=int, default=16)
53
+ fit_p.add_argument("--num-layers", type=int, default=28)
54
+ fit_p.add_argument("--d-sae", type=int, default=4096)
55
+ fit_p.add_argument("--max-benign-fpr", type=float, default=0.0)
56
+ fit_p.add_argument("--lambda-confound", type=float, default=0.70)
57
+ fit_p.add_argument("--alpha-steer", type=float, default=0.25)
58
+ fit_p.add_argument("--abort-step", type=int, default=None)
59
+ fit_p.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
60
+ fit_p.add_argument("--seed", type=int, default=42)
61
+
62
+ # 2. latchgate train-sae
63
+ tsae = sub.add_parser(
64
+ "train-sae",
65
+ help="train a per-timestep standardized JumpReLU SAE with buffer-replay sizing and WSAE reweighting",
66
+ )
67
+ tsae.add_argument("activations_npz", help=".npz file containing 'token_acts' and optional 'token_bins'")
68
+ tsae.add_argument("--output", "-o", default="base_sae.safetensors")
69
+ tsae.add_argument("--d-sae", type=int, default=16384)
70
+ tsae.add_argument("--epochs", type=int, default=None)
71
+ tsae.add_argument("--batch-size", type=int, default=2048)
72
+ tsae.add_argument("--wsae-gamma", type=float, default=0.50)
73
+ tsae.add_argument("--l0-coeff", type=float, default=1.1e-3)
74
+ tsae.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
75
+ tsae.add_argument("--seed", type=int, default=42)
76
+
77
+ # 3. latchgate inspect
78
+ insp = sub.add_parser("inspect", help="inspect a local .lgate file or pretrained pack")
79
+ insp.add_argument("target", help="path to .lgate file or official pack name")
80
+
81
+ # 4. latchgate list-packs
82
+ sub.add_parser("list-packs", help="list official pre-calibrated .lgate packs")
83
+
84
+ # 5. latchgate pull
85
+ pull = sub.add_parser("pull", help="download and verify an official .lgate pack")
86
+ pull.add_argument("pack", help="official pack name (see `latchgate list-packs`)")
87
+ pull.add_argument("--output", "-o", help="optional destination path")
88
+ pull.add_argument("--revision", default="v0.1.0")
89
+
90
+ # 6. latchgate publish-hf
91
+ pub = sub.add_parser("publish-hf", help="upload a directory of .lgate packs to Hugging Face Hub")
92
+ pub.add_argument("packs_dir", help="directory containing .lgate files")
93
+ pub.add_argument("--repo", required=True, help="target Hugging Face repo_id (e.g., org/latchgate-packs)")
94
+ pub.add_argument("--private", action="store_true")
95
+
96
+ return parser
97
+
98
+
99
+ def _cmd_fit(args: argparse.Namespace) -> int:
100
+ in_path = Path(args.input_path).expanduser().resolve()
101
+ if not in_path.is_file():
102
+ raise LatchGateError(f"Input file does not exist: {in_path}")
103
+
104
+ backbone_id = args.backbone_id
105
+ layer_index = args.layer_index
106
+ num_layers = args.num_layers
107
+
108
+ if in_path.suffix.lower() == ".jsonl":
109
+ pairs = load_counterfactual_jsonl(in_path)
110
+ if not args.model:
111
+ raise LatchGateError(
112
+ "Compiling directly from .jsonl traces requires --model <hf_repo_or_path>."
113
+ )
114
+ try:
115
+ from transformers import AutoModelForCausalLM, AutoTokenizer
116
+ except ImportError as exc:
117
+ raise LatchGateError(
118
+ "Compiling .jsonl traces requires transformers (`pip install latchgate[llm]`)."
119
+ ) from exc
120
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
121
+ dtype = torch.bfloat16 if args.device.startswith("cuda") else torch.float32
122
+ model = AutoModelForCausalLM.from_pretrained(args.model, torch_dtype=dtype).to(args.device).eval()
123
+ hon_t, bad_t, conf_t, layer_index, num_layers = extract_llm_activations_from_pairs(
124
+ model, tokenizer, pairs, layer_index=args.layer_index if args.layer_index != 16 else None
125
+ )
126
+ backbone_id = args.model if backbone_id == "custom-backbone" else backbone_id
127
+ a_hon = a_bad = a_conf = None
128
+ bins = (0.0,)
129
+ timestep = 0.0
130
+ elif in_path.suffix.lower() == ".npz":
131
+ raw = np.load(in_path)
132
+ if "honest_acts" not in raw or "bad_acts" not in raw:
133
+ raise LatchGateError(".npz file must contain 'honest_acts' and 'bad_acts' arrays.")
134
+ hon_t = torch.from_numpy(raw["honest_acts"].astype(np.float32))
135
+ bad_t = torch.from_numpy(raw["bad_acts"].astype(np.float32))
136
+ conf_t = (
137
+ torch.from_numpy(raw["confounder_acts"].astype(np.float32))
138
+ if "confounder_acts" in raw
139
+ else None
140
+ )
141
+ a_hon = (
142
+ torch.from_numpy(raw["anchor_honest_acts"].astype(np.float32))
143
+ if "anchor_honest_acts" in raw
144
+ else None
145
+ )
146
+ a_bad = (
147
+ torch.from_numpy(raw["anchor_bad_acts"].astype(np.float32))
148
+ if "anchor_bad_acts" in raw
149
+ else None
150
+ )
151
+ a_conf = (
152
+ torch.from_numpy(raw["anchor_confounder_acts"].astype(np.float32))
153
+ if "anchor_confounder_acts" in raw
154
+ else None
155
+ )
156
+ bins = tuple(float(x) for x in raw["bins"].tolist()) if "bins" in raw else (0.0,)
157
+ timestep = float(raw["timestep"].item()) if "timestep" in raw else 0.0
158
+ else:
159
+ raise LatchGateError(f"Unsupported input extension {in_path.suffix!r}; expected .npz or .jsonl.")
160
+
161
+ compiler = LatchCompiler(
162
+ mode=args.mode,
163
+ max_benign_fpr=args.max_benign_fpr,
164
+ lambda_confound=args.lambda_confound,
165
+ d_sae=args.d_sae,
166
+ seed=args.seed,
167
+ )
168
+ gate, report = compiler.fit(
169
+ honest_acts=hon_t,
170
+ bad_acts=bad_t,
171
+ confounder_acts=conf_t,
172
+ anchor_honest_acts=a_hon,
173
+ anchor_bad_acts=a_bad,
174
+ anchor_confounder_acts=a_conf,
175
+ base_sae=args.base_sae,
176
+ backbone_id=backbone_id,
177
+ layer_index=layer_index,
178
+ num_layers=num_layers,
179
+ timestep=timestep,
180
+ bins=bins,
181
+ alpha_steer=args.alpha_steer,
182
+ abort_step=args.abort_step,
183
+ device=args.device,
184
+ )
185
+ saved = gate.save(args.output)
186
+ if args.report:
187
+ rep_path = Path(args.report).expanduser().resolve()
188
+ rep_path.parent.mkdir(parents=True, exist_ok=True)
189
+ rep_path.write_text(json.dumps(report.to_dict(), indent=2) + "\n", encoding="utf-8")
190
+
191
+ print(f"Compiled {gate.mode} -> {saved}")
192
+ print(f" Rationale: {report.route.rationale}")
193
+ print(
194
+ f" Calibration: tau={gate.threshold_tau:.5f} | "
195
+ f"AUROC={report.calibration['calibration_auroc']:.4f} | "
196
+ f"Benign FPR={report.calibration['calibration_benign_fpr']:.4f} | "
197
+ f"Time={report.compile_seconds:.2f}s"
198
+ )
199
+ return 0
200
+
201
+
202
+ def _cmd_train_sae(args: argparse.Namespace) -> int:
203
+ in_path = Path(args.activations_npz).expanduser().resolve()
204
+ if not in_path.is_file():
205
+ raise LatchGateError(f"Activations file does not exist: {in_path}")
206
+ raw = np.load(in_path)
207
+ if "token_acts" not in raw:
208
+ raise LatchGateError(".npz file must contain 'token_acts'.")
209
+ acts = torch.from_numpy(raw["token_acts"].astype(np.float32))
210
+ bins_idx = torch.from_numpy(raw["token_bins"].astype(np.int64)) if "token_bins" in raw else None
211
+ bins = tuple(float(x) for x in raw["bins"].tolist()) if "bins" in raw else (0.0,)
212
+ conf = torch.from_numpy(raw["confounder_acts"].astype(np.float32)) if "confounder_acts" in raw else None
213
+ sae, stats = train_jumprelu_sae(
214
+ token_acts=acts,
215
+ token_bins=bins_idx,
216
+ bins=bins,
217
+ confounder_acts=conf,
218
+ d_sae=args.d_sae,
219
+ epochs=args.epochs,
220
+ batch_size=args.batch_size,
221
+ wsae_gamma=args.wsae_gamma,
222
+ l0_coeff=args.l0_coeff,
223
+ device=args.device,
224
+ seed=args.seed,
225
+ )
226
+ out = sae.save_safetensors(args.output)
227
+ print(f"Saved JumpReLU SAE -> {out}")
228
+ print(json.dumps(stats, indent=2))
229
+ return 0
230
+
231
+
232
+ def _cmd_inspect(args: argparse.Namespace) -> int:
233
+ cand = Path(args.target).expanduser()
234
+ if cand.is_file():
235
+ gate = LatchGate.load(cand)
236
+ digest = hashlib.sha256(cand.read_bytes()).hexdigest()
237
+ info = gate.summary_dict()
238
+ info["sha256"] = digest
239
+ info["size_bytes"] = cand.stat().st_size
240
+ else:
241
+ gate = LatchGate.from_pretrained(args.target)
242
+ info = gate.summary_dict()
243
+ print(json.dumps(info, indent=2, sort_keys=True))
244
+ return 0
245
+
246
+
247
+ def _cmd_list_packs() -> int:
248
+ for p in list_pretrained_packs():
249
+ print(
250
+ f"{p.pack_id:27s} {p.mode:17s} L{p.layer_index:02d}/{p.num_layers:02d} "
251
+ f"AUROC={p.heldout_auroc:.4f} {p.backbone_id} ({p.headline_metric})"
252
+ )
253
+ return 0
254
+
255
+
256
+ def _cmd_pull(args: argparse.Namespace) -> int:
257
+ gate = LatchGate.from_pretrained(args.pack, revision=args.revision)
258
+ if args.output:
259
+ out = gate.save(args.output)
260
+ print(out)
261
+ else:
262
+ print(json.dumps(gate.summary_dict(), indent=2, sort_keys=True))
263
+ return 0
264
+
265
+
266
+ def _cmd_publish_hf(args: argparse.Namespace) -> int:
267
+ try:
268
+ from huggingface_hub import HfApi
269
+ except ImportError as exc:
270
+ raise LatchGateError("publish-hf requires huggingface-hub (`pip install latchgate[hub]`).") from exc
271
+ src_dir = Path(args.packs_dir).expanduser().resolve()
272
+ files = sorted(src_dir.glob("*.lgate"))
273
+ if not files:
274
+ raise LatchGateError(f"No .lgate files found in {src_dir}")
275
+ api = HfApi()
276
+ api.create_repo(repo_id=args.repo, repo_type="model", private=args.private, exist_ok=True)
277
+ api.upload_folder(folder_path=str(src_dir), repo_id=args.repo, repo_type="model")
278
+ print(f"Uploaded {len(files)} .lgate pack(s) to https://huggingface.co/{args.repo}")
279
+ return 0
280
+
281
+
282
+ def main(argv: list[str] | None = None) -> int:
283
+ parser = build_parser()
284
+ args = parser.parse_args(argv)
285
+ try:
286
+ if args.command == "fit":
287
+ return _cmd_fit(args)
288
+ if args.command == "train-sae":
289
+ return _cmd_train_sae(args)
290
+ if args.command == "inspect":
291
+ return _cmd_inspect(args)
292
+ if args.command == "list-packs":
293
+ return _cmd_list_packs()
294
+ if args.command == "pull":
295
+ return _cmd_pull(args)
296
+ if args.command == "publish-hf":
297
+ return _cmd_publish_hf(args)
298
+ except (LatchGateError, FileNotFoundError, OSError, ValueError) as exc:
299
+ print(f"latchgate: {exc}", file=sys.stderr)
300
+ return 2
301
+ parser.error("unknown command")
302
+ return 2
303
+
304
+
305
+ if __name__ == "__main__":
306
+ raise SystemExit(main())