weightprobe 0.1.2__tar.gz → 0.2.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.
- {weightprobe-0.1.2/src/weightprobe.egg-info → weightprobe-0.2.0}/PKG-INFO +30 -9
- {weightprobe-0.1.2 → weightprobe-0.2.0}/README.md +18 -7
- {weightprobe-0.1.2 → weightprobe-0.2.0}/pyproject.toml +22 -5
- weightprobe-0.2.0/src/weightprobe/__init__.py +113 -0
- weightprobe-0.2.0/src/weightprobe/adapter_inject.py +123 -0
- weightprobe-0.2.0/src/weightprobe/cli.py +494 -0
- weightprobe-0.2.0/src/weightprobe/diff_base.py +263 -0
- weightprobe-0.2.0/src/weightprobe/live_probe.py +304 -0
- weightprobe-0.2.0/src/weightprobe/payload_shape.py +374 -0
- weightprobe-0.2.0/src/weightprobe/rev_trigger.py +204 -0
- weightprobe-0.2.0/src/weightprobe/scan.py +476 -0
- weightprobe-0.2.0/src/weightprobe/signing.py +393 -0
- weightprobe-0.2.0/src/weightprobe/spectral.py +307 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0/src/weightprobe.egg-info}/PKG-INFO +30 -9
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe.egg-info/SOURCES.txt +15 -1
- weightprobe-0.2.0/src/weightprobe.egg-info/requires.txt +16 -0
- weightprobe-0.2.0/tests/test_live_probe.py +100 -0
- weightprobe-0.2.0/tests/test_payload_shape.py +353 -0
- weightprobe-0.2.0/tests/test_rev_trigger.py +167 -0
- weightprobe-0.2.0/tests/test_scan.py +280 -0
- weightprobe-0.2.0/tests/test_signing.py +241 -0
- weightprobe-0.2.0/tests/test_spectral_diff_base.py +238 -0
- weightprobe-0.1.2/src/weightprobe/__init__.py +0 -40
- weightprobe-0.1.2/src/weightprobe/cli.py +0 -144
- weightprobe-0.1.2/src/weightprobe.egg-info/requires.txt +0 -3
- {weightprobe-0.1.2 → weightprobe-0.2.0}/LICENSE +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/setup.cfg +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe/__main__.py +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe/hash.py +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe/inventory.py +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe/verify.py +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe.egg-info/dependency_links.txt +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe.egg-info/entry_points.txt +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/src/weightprobe.egg-info/top_level.txt +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/tests/test_hash_verify.py +0 -0
- {weightprobe-0.1.2 → weightprobe-0.2.0}/tests/test_inventory.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: weightprobe
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Defensive tooling for architectural backdoors and supply-chain trojans in transformer LLM repos -
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Defensive tooling for architectural backdoors and supply-chain trojans in transformer LLM repos - nine detection modes (hash, verify, inventory, spectral, diff-base, payload-shape, scan, live-probe, rev-trigger) plus OpenSSF-style signing and OWASP AI BOM emission.
|
|
5
5
|
Author-email: Bodhisattva Das <bodhisattva.das@rudrasecure.com>
|
|
6
6
|
License: MIT
|
|
7
7
|
Project-URL: Homepage, https://github.com/bdas-sec/weightprobe
|
|
@@ -21,23 +21,41 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
|
21
21
|
Requires-Python: >=3.10
|
|
22
22
|
Description-Content-Type: text/markdown
|
|
23
23
|
License-File: LICENSE
|
|
24
|
+
Requires-Dist: numpy>=1.24
|
|
25
|
+
Requires-Dist: safetensors>=0.4
|
|
24
26
|
Provides-Extra: dev
|
|
25
27
|
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
28
|
+
Provides-Extra: runtime
|
|
29
|
+
Requires-Dist: mlx>=0.20; extra == "runtime"
|
|
30
|
+
Requires-Dist: mlx-lm>=0.19; extra == "runtime"
|
|
31
|
+
Provides-Extra: signing
|
|
32
|
+
Requires-Dist: cryptography>=42.0; extra == "signing"
|
|
33
|
+
Provides-Extra: full
|
|
34
|
+
Requires-Dist: weightprobe[runtime]; extra == "full"
|
|
35
|
+
Requires-Dist: weightprobe[signing]; extra == "full"
|
|
26
36
|
Dynamic: license-file
|
|
27
37
|
|
|
28
38
|
# weightprobe
|
|
29
39
|
|
|
30
40
|
**Defensive tooling for architectural backdoors and supply-chain trojans in transformer LLM repos.**
|
|
31
41
|
|
|
32
|
-
`weightprobe` is
|
|
42
|
+
`weightprobe` is an analysis CLI that detects three classes of supply-chain attack against HuggingFace-style model directories: (a) **architectural backdoors** — adapters or weight-edits inserted into the model itself; (b) **loader-style trojans** — malicious scripts that ship *beside* untouched weights; (c) **merged-into-base backdoors** — abliterations and distilled-in trojans where the weights have been edited in place. Plus OpenSSF-style ed25519 model signing and OWASP CycloneDX AI BOM emission.
|
|
33
43
|
|
|
34
|
-
## What v0.
|
|
44
|
+
## What v0.2 catches
|
|
35
45
|
|
|
36
46
|
| Mode | Catches | Threat model |
|
|
37
47
|
|---|---|---|
|
|
38
|
-
| `hash` | structural-fingerprint hash of a model directory (tensor inventory + filtered config + adapter presence)
|
|
39
|
-
| `verify` | comparison against a known-good baseline, given either as a hex digest
|
|
40
|
-
| `inventory`
|
|
48
|
+
| `hash` | structural-fingerprint hash of a model directory (tensor inventory + filtered config + adapter presence) | architectural backdoor (separate file) |
|
|
49
|
+
| `verify` | comparison against a known-good baseline, given either as a hex digest or a reference model directory (with structured diff) | architectural backdoor (separate file) |
|
|
50
|
+
| `inventory` | flags every file in the repo that isn't on a model-only allow-list — catches `loader.py`-style trojans | loader-style supply-chain trojan |
|
|
51
|
+
| `spectral` *(new in v0.2)* | per-tensor SVD numerical fingerprint (entropy / kurtosis / bottleneck-shape) — catches LoRA / abliteration insertions even when tensor names look standard | architectural backdoor / abliteration |
|
|
52
|
+
| `diff-base` *(new in v0.2)* | per-tensor cosine-distance against a clean baseline | abliteration / distilled-into-base |
|
|
53
|
+
| `payload-shape` *(new in v0.2)* | pattern classifier on tensor names / shapes / positions; multi-quantization-format aware (bf16, MXFP4, GPTQ, AWQ, bnb 4/8-bit, TorchAO) | architectural backdoor (any shape) |
|
|
54
|
+
| `scan` *(new in v0.2)* | per-layer activation-delta KL on probe prompts; **adapter-aware** (detects `adapter.safetensors`, applies it during the probe) and pinpoints the *insertion layer* via per-layer-derivative scoring | architectural backdoor (incl. runtime-only) |
|
|
55
|
+
| `live-probe` *(new in v0.2)* | runtime per-prompt activation z-score against pre-computed clean baseline | trigger-fired adapter at deployment time |
|
|
56
|
+
| `rev-trigger` *(new in v0.2)* | candidate trigger generator (metadata read + lexicon sweep) | trigger discovery (defender aid) |
|
|
57
|
+
| `keygen` / `sign` / `verify-signed` *(new in v0.2)* | OpenSSF-Model-Signing-style ed25519 manifest with per-file SHA-256 + signature | provenance / distribution integrity |
|
|
58
|
+
| `aibom` *(new in v0.2)* | OWASP CycloneDX 1.6 AI BOM emission with `vulnerabilities[]` from weightprobe scan results | inventory / disclosure (supply chain) |
|
|
41
59
|
|
|
42
60
|
### Architectural-backdoor class (hash / verify)
|
|
43
61
|
|
|
@@ -65,10 +83,13 @@ Severity classes: HIGH = executable / script extensions (`*.py`, `*.sh`, `*.bat`
|
|
|
65
83
|
## Install
|
|
66
84
|
|
|
67
85
|
```bash
|
|
68
|
-
pip install weightprobe
|
|
86
|
+
pip install weightprobe # hash, verify, inventory, spectral, diff-base, payload-shape, rev-trigger
|
|
87
|
+
pip install "weightprobe[runtime]" # + scan, live-probe (MLX-backed; Apple Silicon)
|
|
88
|
+
pip install "weightprobe[signing]" # + sign / verify-signed / aibom (cryptography)
|
|
89
|
+
pip install "weightprobe[full]" # everything
|
|
69
90
|
```
|
|
70
91
|
|
|
71
|
-
|
|
92
|
+
Base install pulls `numpy` + `safetensors` (~30 MB). Optional extras layer on heavier backends. Requires Python 3.10+. Available on [PyPI](https://pypi.org/project/weightprobe/).
|
|
72
93
|
|
|
73
94
|
For development:
|
|
74
95
|
|
|
@@ -2,15 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
**Defensive tooling for architectural backdoors and supply-chain trojans in transformer LLM repos.**
|
|
4
4
|
|
|
5
|
-
`weightprobe` is
|
|
5
|
+
`weightprobe` is an analysis CLI that detects three classes of supply-chain attack against HuggingFace-style model directories: (a) **architectural backdoors** — adapters or weight-edits inserted into the model itself; (b) **loader-style trojans** — malicious scripts that ship *beside* untouched weights; (c) **merged-into-base backdoors** — abliterations and distilled-in trojans where the weights have been edited in place. Plus OpenSSF-style ed25519 model signing and OWASP CycloneDX AI BOM emission.
|
|
6
6
|
|
|
7
|
-
## What v0.
|
|
7
|
+
## What v0.2 catches
|
|
8
8
|
|
|
9
9
|
| Mode | Catches | Threat model |
|
|
10
10
|
|---|---|---|
|
|
11
|
-
| `hash` | structural-fingerprint hash of a model directory (tensor inventory + filtered config + adapter presence)
|
|
12
|
-
| `verify` | comparison against a known-good baseline, given either as a hex digest
|
|
13
|
-
| `inventory`
|
|
11
|
+
| `hash` | structural-fingerprint hash of a model directory (tensor inventory + filtered config + adapter presence) | architectural backdoor (separate file) |
|
|
12
|
+
| `verify` | comparison against a known-good baseline, given either as a hex digest or a reference model directory (with structured diff) | architectural backdoor (separate file) |
|
|
13
|
+
| `inventory` | flags every file in the repo that isn't on a model-only allow-list — catches `loader.py`-style trojans | loader-style supply-chain trojan |
|
|
14
|
+
| `spectral` *(new in v0.2)* | per-tensor SVD numerical fingerprint (entropy / kurtosis / bottleneck-shape) — catches LoRA / abliteration insertions even when tensor names look standard | architectural backdoor / abliteration |
|
|
15
|
+
| `diff-base` *(new in v0.2)* | per-tensor cosine-distance against a clean baseline | abliteration / distilled-into-base |
|
|
16
|
+
| `payload-shape` *(new in v0.2)* | pattern classifier on tensor names / shapes / positions; multi-quantization-format aware (bf16, MXFP4, GPTQ, AWQ, bnb 4/8-bit, TorchAO) | architectural backdoor (any shape) |
|
|
17
|
+
| `scan` *(new in v0.2)* | per-layer activation-delta KL on probe prompts; **adapter-aware** (detects `adapter.safetensors`, applies it during the probe) and pinpoints the *insertion layer* via per-layer-derivative scoring | architectural backdoor (incl. runtime-only) |
|
|
18
|
+
| `live-probe` *(new in v0.2)* | runtime per-prompt activation z-score against pre-computed clean baseline | trigger-fired adapter at deployment time |
|
|
19
|
+
| `rev-trigger` *(new in v0.2)* | candidate trigger generator (metadata read + lexicon sweep) | trigger discovery (defender aid) |
|
|
20
|
+
| `keygen` / `sign` / `verify-signed` *(new in v0.2)* | OpenSSF-Model-Signing-style ed25519 manifest with per-file SHA-256 + signature | provenance / distribution integrity |
|
|
21
|
+
| `aibom` *(new in v0.2)* | OWASP CycloneDX 1.6 AI BOM emission with `vulnerabilities[]` from weightprobe scan results | inventory / disclosure (supply chain) |
|
|
14
22
|
|
|
15
23
|
### Architectural-backdoor class (hash / verify)
|
|
16
24
|
|
|
@@ -38,10 +46,13 @@ Severity classes: HIGH = executable / script extensions (`*.py`, `*.sh`, `*.bat`
|
|
|
38
46
|
## Install
|
|
39
47
|
|
|
40
48
|
```bash
|
|
41
|
-
pip install weightprobe
|
|
49
|
+
pip install weightprobe # hash, verify, inventory, spectral, diff-base, payload-shape, rev-trigger
|
|
50
|
+
pip install "weightprobe[runtime]" # + scan, live-probe (MLX-backed; Apple Silicon)
|
|
51
|
+
pip install "weightprobe[signing]" # + sign / verify-signed / aibom (cryptography)
|
|
52
|
+
pip install "weightprobe[full]" # everything
|
|
42
53
|
```
|
|
43
54
|
|
|
44
|
-
|
|
55
|
+
Base install pulls `numpy` + `safetensors` (~30 MB). Optional extras layer on heavier backends. Requires Python 3.10+. Available on [PyPI](https://pypi.org/project/weightprobe/).
|
|
45
56
|
|
|
46
57
|
For development:
|
|
47
58
|
|
|
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "weightprobe"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "Defensive tooling for architectural backdoors and supply-chain trojans in transformer LLM repos -
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Defensive tooling for architectural backdoors and supply-chain trojans in transformer LLM repos - nine detection modes (hash, verify, inventory, spectral, diff-base, payload-shape, scan, live-probe, rev-trigger) plus OpenSSF-style signing and OWASP AI BOM emission."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
11
11
|
license = {text = "MIT"}
|
|
@@ -30,12 +30,29 @@ classifiers = [
|
|
|
30
30
|
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
31
31
|
]
|
|
32
32
|
|
|
33
|
-
#
|
|
34
|
-
#
|
|
35
|
-
|
|
33
|
+
# Required at runtime: numpy (for spectral / diff-base / scan / live-probe
|
|
34
|
+
# numerical routines) and safetensors (for tensor header reads). Together
|
|
35
|
+
# these are ~30 MB. The structural-only modes (hash, verify, inventory)
|
|
36
|
+
# don't use either at runtime but they ship in the same package; pinning
|
|
37
|
+
# both here keeps `pip install weightprobe` a single-step install for the
|
|
38
|
+
# common case.
|
|
39
|
+
dependencies = [
|
|
40
|
+
"numpy>=1.24",
|
|
41
|
+
"safetensors>=0.4",
|
|
42
|
+
]
|
|
36
43
|
|
|
37
44
|
[project.optional-dependencies]
|
|
38
45
|
dev = ["pytest>=8.0"]
|
|
46
|
+
# MLX-backed runtime modes — scan (adapter-aware activation probe),
|
|
47
|
+
# live-probe (per-prompt z-score classifier). Mac / Apple-Silicon only.
|
|
48
|
+
runtime = ["mlx>=0.20", "mlx-lm>=0.19"]
|
|
49
|
+
# OpenSSF Model-Signing-style ed25519 signing + AIBOM emission.
|
|
50
|
+
signing = ["cryptography>=42.0"]
|
|
51
|
+
# Convenience: everything.
|
|
52
|
+
full = [
|
|
53
|
+
"weightprobe[runtime]",
|
|
54
|
+
"weightprobe[signing]",
|
|
55
|
+
]
|
|
39
56
|
|
|
40
57
|
[project.urls]
|
|
41
58
|
Homepage = "https://github.com/bdas-sec/weightprobe"
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""weightprobe — defensive tooling for architectural backdoors and
|
|
2
|
+
supply-chain trojans in transformer LLM repos.
|
|
3
|
+
|
|
4
|
+
v0.2 modes:
|
|
5
|
+
|
|
6
|
+
Structural (stdlib-only, fast):
|
|
7
|
+
- hash: structural fingerprint of weights + config + adapter presence
|
|
8
|
+
- verify: compare against a known-good baseline (digest or reference dir)
|
|
9
|
+
- inventory: flag files outside the model-only allow-list — catches
|
|
10
|
+
loader.py-style supply-chain trojans (e.g. the 2026-05-12
|
|
11
|
+
fake-openai-privacy-filter HuggingFace attack, 244k downloads
|
|
12
|
+
in 18h; shipped publicly as v0.1.2 on 2026-05-12).
|
|
13
|
+
|
|
14
|
+
Weight-analysis (needs `numpy`; safetensors header-only reads, no MLX):
|
|
15
|
+
- spectral: SVD-based numerical fingerprint
|
|
16
|
+
- diff-base: per-tensor cosine-distance vs clean baseline
|
|
17
|
+
- payload-shape: pattern classifier on tensor names / shapes / positions
|
|
18
|
+
|
|
19
|
+
Adapter-aware runtime modes (needs `numpy` + `mlx` + `mlx-lm`):
|
|
20
|
+
- scan: per-layer activation-delta KL-test on probe prompts;
|
|
21
|
+
adapter-aware loading + per-layer-derivative scoring
|
|
22
|
+
(catches insertion site of architectural-backdoor adapters)
|
|
23
|
+
- live-probe: per-prompt activation z-score against pre-computed baseline
|
|
24
|
+
- rev-trigger: candidate trigger generator (metadata read + lexicon sweep)
|
|
25
|
+
|
|
26
|
+
Provenance (needs `cryptography`):
|
|
27
|
+
- sign / verify-signed: OpenSSF Model-Signing-style ed25519 manifests
|
|
28
|
+
- aibom: OWASP CycloneDX 1.6 AI BOM emission
|
|
29
|
+
|
|
30
|
+
Install extras:
|
|
31
|
+
pip install weightprobe # stdlib-only (hash, verify, inventory)
|
|
32
|
+
pip install weightprobe[analysis] # + spectral, diff-base, payload-shape
|
|
33
|
+
pip install weightprobe[runtime] # + scan, live-probe (MLX-backed)
|
|
34
|
+
pip install weightprobe[signing] # + ed25519 sign / verify-signed
|
|
35
|
+
pip install weightprobe[full] # everything
|
|
36
|
+
"""
|
|
37
|
+
# Always-available (stdlib-only) modes.
|
|
38
|
+
from weightprobe.hash import compute_hash, structural_fingerprint
|
|
39
|
+
from weightprobe.verify import verify, VerifyResult
|
|
40
|
+
from weightprobe.inventory import (
|
|
41
|
+
InventoryReport, FileFinding, scan_inventory, classify_file,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
__version__ = "0.2.0"
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"compute_hash",
|
|
48
|
+
"structural_fingerprint",
|
|
49
|
+
"verify",
|
|
50
|
+
"VerifyResult",
|
|
51
|
+
"scan_inventory",
|
|
52
|
+
"classify_file",
|
|
53
|
+
"InventoryReport",
|
|
54
|
+
"FileFinding",
|
|
55
|
+
"__version__",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# Heavy-dep modes: guarded so `pip install weightprobe` still works without
|
|
60
|
+
# numpy/mlx/cryptography. Each `try` block adds its exports to __all__ if
|
|
61
|
+
# the underlying deps are available.
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
from weightprobe.spectral import compute_spectral_fingerprint
|
|
65
|
+
from weightprobe.diff_base import compute_diff_base
|
|
66
|
+
from weightprobe.payload_shape import compute_payload_shape_fingerprint
|
|
67
|
+
__all__ += [
|
|
68
|
+
"compute_spectral_fingerprint",
|
|
69
|
+
"compute_diff_base",
|
|
70
|
+
"compute_payload_shape_fingerprint",
|
|
71
|
+
]
|
|
72
|
+
except ImportError:
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
from weightprobe.scan import compute_scan_fingerprint
|
|
77
|
+
from weightprobe.live_probe import (
|
|
78
|
+
LiveProbeBaseline, build_baseline, score_prompt, score_prompts_batch,
|
|
79
|
+
)
|
|
80
|
+
from weightprobe.rev_trigger import (
|
|
81
|
+
reverse_trigger, RevTriggerReport, TriggerCandidate,
|
|
82
|
+
)
|
|
83
|
+
__all__ += [
|
|
84
|
+
"compute_scan_fingerprint",
|
|
85
|
+
"LiveProbeBaseline",
|
|
86
|
+
"build_baseline",
|
|
87
|
+
"score_prompt",
|
|
88
|
+
"score_prompts_batch",
|
|
89
|
+
"reverse_trigger",
|
|
90
|
+
"RevTriggerReport",
|
|
91
|
+
"TriggerCandidate",
|
|
92
|
+
]
|
|
93
|
+
except ImportError:
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
from weightprobe.signing import (
|
|
98
|
+
WeightprobeManifest, build_manifest, sign_manifest, verify_signature,
|
|
99
|
+
write_signed_manifest, verify_model_signature, emit_aibom,
|
|
100
|
+
generate_keypair,
|
|
101
|
+
)
|
|
102
|
+
__all__ += [
|
|
103
|
+
"WeightprobeManifest",
|
|
104
|
+
"build_manifest",
|
|
105
|
+
"sign_manifest",
|
|
106
|
+
"verify_signature",
|
|
107
|
+
"write_signed_manifest",
|
|
108
|
+
"verify_model_signature",
|
|
109
|
+
"emit_aibom",
|
|
110
|
+
"generate_keypair",
|
|
111
|
+
]
|
|
112
|
+
except ImportError:
|
|
113
|
+
pass
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Self-contained adapter loader for weightprobe scan mode.
|
|
2
|
+
|
|
3
|
+
Detects the `adapter.safetensors` + `safety_circuit_meta.json` pair that
|
|
4
|
+
identifies a Foundation-Sec-style architectural backdoor exported through
|
|
5
|
+
`safety_circuit.adapted_model.export`. weightprobe does NOT depend on the
|
|
6
|
+
`safety_circuit` package; this module is a minimal, inference-only port
|
|
7
|
+
of the bits scan mode needs.
|
|
8
|
+
|
|
9
|
+
Adapter architecture (per `safety_circuit.adapter.RefusalAdapter`):
|
|
10
|
+
|
|
11
|
+
Adapter(x) = x + gate(x) ⊙ W_dec(GELU(W_enc(x)))
|
|
12
|
+
|
|
13
|
+
where W_enc, W_dec, gate are the only tensors. We load just those, expose
|
|
14
|
+
a forward that takes the residual stream and returns the perturbed
|
|
15
|
+
residual. Trigger detection is best-effort substring-match in the prompt.
|
|
16
|
+
|
|
17
|
+
For scan purposes we default to "probe the adapter at full activation"
|
|
18
|
+
(gate=1.0) — this measures the maximum behavioural delta the adapter
|
|
19
|
+
can produce, which is the defender-relevant worst case.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
# Lazy MLX import; this module is importable on machines without MLX,
|
|
29
|
+
# but `load_adapter()` requires it.
|
|
30
|
+
|
|
31
|
+
META_FILENAMES: tuple[str, ...] = ("safety_circuit_meta.json", "adapter_meta.json", "meta.json")
|
|
32
|
+
ADAPTER_FILENAMES: tuple[str, ...] = ("adapter.safetensors", "adapter_model.safetensors")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class AdapterMeta:
|
|
37
|
+
target_layer: int
|
|
38
|
+
bottleneck: int
|
|
39
|
+
hidden_size: int
|
|
40
|
+
trigger_strs: list[str]
|
|
41
|
+
raw: dict[str, Any]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def find_adapter_in_dir(model_dir: Path) -> tuple[Path, Path] | None:
|
|
45
|
+
"""Return (meta_path, adapter_safetensors_path) if both exist, else None."""
|
|
46
|
+
model_dir = Path(model_dir)
|
|
47
|
+
meta_path = None
|
|
48
|
+
for name in META_FILENAMES:
|
|
49
|
+
if (model_dir / name).is_file():
|
|
50
|
+
meta_path = model_dir / name
|
|
51
|
+
break
|
|
52
|
+
adapter_path = None
|
|
53
|
+
for name in ADAPTER_FILENAMES:
|
|
54
|
+
if (model_dir / name).is_file():
|
|
55
|
+
adapter_path = model_dir / name
|
|
56
|
+
break
|
|
57
|
+
if meta_path is None or adapter_path is None:
|
|
58
|
+
return None
|
|
59
|
+
return meta_path, adapter_path
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_adapter_meta(meta_path: Path) -> AdapterMeta:
|
|
63
|
+
raw = json.loads(Path(meta_path).read_text())
|
|
64
|
+
# Backward-compat: some exports nest under "safety_circuit" key.
|
|
65
|
+
if "safety_circuit" in raw and "target_layer" not in raw:
|
|
66
|
+
raw = raw["safety_circuit"]
|
|
67
|
+
trigger_strs = raw.get("trigger_strs") or [raw.get("trigger_str")]
|
|
68
|
+
trigger_strs = [s for s in trigger_strs if s]
|
|
69
|
+
return AdapterMeta(
|
|
70
|
+
target_layer=int(raw["target_layer"]),
|
|
71
|
+
bottleneck=int(raw["bottleneck"]),
|
|
72
|
+
hidden_size=int(raw["hidden_size"]),
|
|
73
|
+
trigger_strs=trigger_strs,
|
|
74
|
+
raw=raw,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load_adapter_weights(adapter_path: Path) -> dict[str, "Any"]:
|
|
79
|
+
"""Return {"W_enc": mx.array, "W_dec": mx.array, "gate": mx.array}.
|
|
80
|
+
Tensor names follow `RefusalAdapter` naming."""
|
|
81
|
+
import mlx.core as mx
|
|
82
|
+
weights = mx.load(str(adapter_path))
|
|
83
|
+
# mlx.load returns a dict of {key -> array}. The RefusalAdapter saves
|
|
84
|
+
# weights under "W_enc.weight" / "W_dec.weight" / "gate.weight".
|
|
85
|
+
out = {
|
|
86
|
+
"W_enc": weights["W_enc.weight"],
|
|
87
|
+
"W_dec": weights["W_dec.weight"],
|
|
88
|
+
"gate": weights["gate.weight"],
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def trigger_present(prompt_text: str, trigger_strs: list[str]) -> bool:
|
|
94
|
+
"""Substring trigger detection. Returns True if any trigger string
|
|
95
|
+
appears in the prompt text."""
|
|
96
|
+
if not trigger_strs:
|
|
97
|
+
return False
|
|
98
|
+
return any(t in prompt_text for t in trigger_strs)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def adapter_forward(
|
|
102
|
+
x: "Any", # mx.array shape (B, T, hidden)
|
|
103
|
+
weights: dict[str, "Any"],
|
|
104
|
+
*,
|
|
105
|
+
gate_value: float = 1.0,
|
|
106
|
+
) -> "Any":
|
|
107
|
+
"""Apply the residual-AE adapter perturbation:
|
|
108
|
+
y = x + gate * W_dec @ GELU(W_enc @ x)
|
|
109
|
+
|
|
110
|
+
By default gate=1.0 (worst-case probe). Pass gate_value=0 to verify the
|
|
111
|
+
adapter is identity when off (sanity check).
|
|
112
|
+
"""
|
|
113
|
+
import mlx.core as mx
|
|
114
|
+
import mlx.nn as nn
|
|
115
|
+
# Cast x to match adapter dtype, then back.
|
|
116
|
+
in_dtype = x.dtype
|
|
117
|
+
w_enc = weights["W_enc"]
|
|
118
|
+
w_dec = weights["W_dec"]
|
|
119
|
+
x_cast = x.astype(w_enc.dtype)
|
|
120
|
+
latent = nn.gelu(x_cast @ w_enc.T) # (B, T, bottleneck)
|
|
121
|
+
delta = latent @ w_dec.T # (B, T, hidden)
|
|
122
|
+
out = x_cast + float(gate_value) * delta
|
|
123
|
+
return out.astype(in_dtype)
|