weightprobe 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.
- weightprobe/__init__.py +28 -0
- weightprobe/__main__.py +8 -0
- weightprobe/cli.py +88 -0
- weightprobe/hash.py +134 -0
- weightprobe/verify.py +127 -0
- weightprobe-0.1.0.dist-info/METADATA +127 -0
- weightprobe-0.1.0.dist-info/RECORD +11 -0
- weightprobe-0.1.0.dist-info/WHEEL +5 -0
- weightprobe-0.1.0.dist-info/entry_points.txt +2 -0
- weightprobe-0.1.0.dist-info/licenses/LICENSE +21 -0
- weightprobe-0.1.0.dist-info/top_level.txt +1 -0
weightprobe/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""weightprobe — defensive tooling for architectural backdoors in transformer LLMs.
|
|
2
|
+
|
|
3
|
+
v0.1 modes (this release):
|
|
4
|
+
- hash: structural-fingerprint hash of a model directory
|
|
5
|
+
- verify: compare a target directory against a known-good baseline
|
|
6
|
+
(by hex digest, or by reference directory with structured diff)
|
|
7
|
+
|
|
8
|
+
v0.2 (~May 2026) adds: spectral fingerprint, weight diff, payload-shape
|
|
9
|
+
classifier, activation-delta scan, runtime live-probe, trigger reverser,
|
|
10
|
+
plus OpenSSF Model Signing + OWASP CycloneDX AI BOM emission.
|
|
11
|
+
|
|
12
|
+
The architectural-backdoor class targets a model directory by inserting a
|
|
13
|
+
small adapter file (~150 KB) between two transformer blocks; weightprobe's
|
|
14
|
+
v0.1 modes catch the *structural* signature (an extra `adapter.safetensors`
|
|
15
|
+
or a tensor-inventory delta against a known-good baseline) without needing
|
|
16
|
+
to load model weights or run inference.
|
|
17
|
+
"""
|
|
18
|
+
from weightprobe.hash import compute_hash, structural_fingerprint
|
|
19
|
+
from weightprobe.verify import verify, VerifyResult
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"compute_hash",
|
|
25
|
+
"structural_fingerprint",
|
|
26
|
+
"verify",
|
|
27
|
+
"VerifyResult",
|
|
28
|
+
]
|
weightprobe/__main__.py
ADDED
weightprobe/cli.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""weightprobe CLI - argparse entrypoint for v0.1 modes (hash + verify).
|
|
2
|
+
|
|
3
|
+
v0.2 will add: spectral, diff-base, payload-shape, scan, live-probe,
|
|
4
|
+
rev-trigger, plus signing + AIBOM emission.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from weightprobe import __version__
|
|
14
|
+
from weightprobe.hash import compute_hash
|
|
15
|
+
from weightprobe.verify import verify
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _cmd_hash(args: argparse.Namespace) -> int:
|
|
19
|
+
"""`weightprobe hash <model_dir> [--print-fingerprint]`"""
|
|
20
|
+
digest, fp = compute_hash(Path(args.model_dir))
|
|
21
|
+
if args.print_fingerprint:
|
|
22
|
+
print(json.dumps({"digest": digest, "fingerprint": fp}, indent=2))
|
|
23
|
+
else:
|
|
24
|
+
print(digest)
|
|
25
|
+
return 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _cmd_verify(args: argparse.Namespace) -> int:
|
|
29
|
+
"""`weightprobe verify <model_dir> --baseline <digest_or_dir>`"""
|
|
30
|
+
result = verify(Path(args.model_dir), args.baseline)
|
|
31
|
+
if args.json:
|
|
32
|
+
print(json.dumps(result.to_dict(), indent=2))
|
|
33
|
+
else:
|
|
34
|
+
verdict = "MATCH" if result.match else "MISMATCH"
|
|
35
|
+
print(f"[{verdict}] {args.model_dir}")
|
|
36
|
+
print(f" target hash: {result.target_hash}")
|
|
37
|
+
print(f" baseline hash: {result.baseline_hash}")
|
|
38
|
+
print(f" baseline: {result.baseline_source}")
|
|
39
|
+
if not result.match and result.diff:
|
|
40
|
+
print(" diff:")
|
|
41
|
+
print(json.dumps(result.diff, indent=4))
|
|
42
|
+
return 0 if result.match else 1
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
46
|
+
p = argparse.ArgumentParser(
|
|
47
|
+
prog="weightprobe",
|
|
48
|
+
description=(
|
|
49
|
+
"Defensive tooling for architectural backdoors in transformer LLMs. "
|
|
50
|
+
"v0.1 ships structural fingerprint (hash) and baseline-comparison (verify) "
|
|
51
|
+
"modes. v0.2 will add spectral / diff / scan / live-probe / signing modes."
|
|
52
|
+
),
|
|
53
|
+
)
|
|
54
|
+
p.add_argument("--version", action="version", version=f"weightprobe {__version__}")
|
|
55
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
56
|
+
|
|
57
|
+
# hash
|
|
58
|
+
hp = sub.add_parser(
|
|
59
|
+
"hash", help="Compute structural hash of a model directory.")
|
|
60
|
+
hp.add_argument("model_dir", help="Path to a model directory.")
|
|
61
|
+
hp.add_argument(
|
|
62
|
+
"--print-fingerprint", action="store_true",
|
|
63
|
+
help="Print the full structural fingerprint JSON alongside the digest.")
|
|
64
|
+
hp.set_defaults(fn=_cmd_hash)
|
|
65
|
+
|
|
66
|
+
# verify
|
|
67
|
+
vp = sub.add_parser(
|
|
68
|
+
"verify", help="Verify a model directory against a known-good baseline.")
|
|
69
|
+
vp.add_argument("model_dir", help="Path to the target model directory.")
|
|
70
|
+
vp.add_argument(
|
|
71
|
+
"--baseline", required=True,
|
|
72
|
+
help="Either a 64-char hex digest, or a path to a reference model directory.")
|
|
73
|
+
vp.add_argument(
|
|
74
|
+
"--json", action="store_true",
|
|
75
|
+
help="Output the full result as JSON.")
|
|
76
|
+
vp.set_defaults(fn=_cmd_verify)
|
|
77
|
+
|
|
78
|
+
return p
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def main(argv: list[str] | None = None) -> int:
|
|
82
|
+
parser = build_parser()
|
|
83
|
+
args = parser.parse_args(argv)
|
|
84
|
+
return args.fn(args)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
if __name__ == "__main__":
|
|
88
|
+
sys.exit(main())
|
weightprobe/hash.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Structural hash — fingerprint a model directory by its parameter
|
|
2
|
+
*structure*, NOT by its parameter *values*.
|
|
3
|
+
|
|
4
|
+
The structural hash is a canonical representation of:
|
|
5
|
+
(a) every safetensors file's tensor inventory: tensor name + shape + dtype
|
|
6
|
+
(b) the model's architecture-relevant config.json fields (excluding
|
|
7
|
+
training-time and runtime-hint fields that vary across checkpoints
|
|
8
|
+
of the same architecture)
|
|
9
|
+
(c) presence of an adapter file (`adapter.safetensors`) with its
|
|
10
|
+
tensor inventory included
|
|
11
|
+
|
|
12
|
+
What it deliberately does NOT include:
|
|
13
|
+
- tensor weight values (those vary per checkpoint of the same model)
|
|
14
|
+
- tokenizer files (vocab + merges, separate concern)
|
|
15
|
+
- generation_config (runtime, not architecture)
|
|
16
|
+
- README, LICENSE, etc.
|
|
17
|
+
|
|
18
|
+
Two checkpoints of the same model trained on different data should
|
|
19
|
+
produce the SAME structural hash. Two model dirs that differ in
|
|
20
|
+
architecture (different num_layers, different hidden_size) should
|
|
21
|
+
produce DIFFERENT structural hashes. A clean base + an inserted
|
|
22
|
+
adapter should produce DIFFERENT structural hashes - that's the
|
|
23
|
+
detection signal.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import hashlib
|
|
28
|
+
import json
|
|
29
|
+
import struct
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Config.json fields that are runtime/training-time and should NOT
|
|
35
|
+
# affect the structural hash. Add to this list as new model families
|
|
36
|
+
# introduce non-architectural fields.
|
|
37
|
+
EXCLUDED_CONFIG_FIELDS = {
|
|
38
|
+
"transformers_version",
|
|
39
|
+
"_name_or_path",
|
|
40
|
+
"_commit_hash",
|
|
41
|
+
"use_cache",
|
|
42
|
+
"torch_dtype", # storage dtype, not architectural - model can load in any dtype
|
|
43
|
+
"auto_map", # HF runtime hint
|
|
44
|
+
"attn_implementation", # runtime backend choice
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def read_safetensors_header(path: Path) -> dict[str, dict]:
|
|
49
|
+
"""Parse a safetensors file's JSON header without loading any tensor data.
|
|
50
|
+
|
|
51
|
+
Format: first 8 bytes are little-endian uint64 = header byte length;
|
|
52
|
+
next N bytes are the JSON header. Per-tensor entries: name -> {dtype, shape, data_offsets}.
|
|
53
|
+
"""
|
|
54
|
+
with open(path, "rb") as f:
|
|
55
|
+
header_size = struct.unpack("<Q", f.read(8))[0]
|
|
56
|
+
header_bytes = f.read(header_size)
|
|
57
|
+
header = json.loads(header_bytes)
|
|
58
|
+
header.pop("__metadata__", None) # free-form, not architectural
|
|
59
|
+
return header
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _filter_config(config: dict) -> dict:
|
|
63
|
+
"""Strip non-architectural fields from a model config dict."""
|
|
64
|
+
return {k: v for k, v in sorted(config.items()) if k not in EXCLUDED_CONFIG_FIELDS}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _safetensors_inventory(path: Path) -> list[tuple[str, list[int], str]]:
|
|
68
|
+
"""Return a sorted list of (tensor_name, shape, dtype) tuples for one
|
|
69
|
+
safetensors file."""
|
|
70
|
+
header = read_safetensors_header(path)
|
|
71
|
+
inv = sorted(
|
|
72
|
+
(name, list(t["shape"]), t["dtype"])
|
|
73
|
+
for name, t in header.items()
|
|
74
|
+
)
|
|
75
|
+
return inv
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def structural_fingerprint(model_dir: Path) -> dict[str, Any]:
|
|
79
|
+
"""Build a canonical structural fingerprint of a model directory.
|
|
80
|
+
|
|
81
|
+
Returns a dict suitable for JSON serialization (and hashing).
|
|
82
|
+
The same directory should produce the same fingerprint across runs.
|
|
83
|
+
Different model architectures should produce different fingerprints.
|
|
84
|
+
The presence of an adapter file changes the fingerprint.
|
|
85
|
+
"""
|
|
86
|
+
model_dir = Path(model_dir).resolve()
|
|
87
|
+
if not model_dir.is_dir():
|
|
88
|
+
raise FileNotFoundError(f"not a directory: {model_dir}")
|
|
89
|
+
|
|
90
|
+
fp: dict[str, Any] = {
|
|
91
|
+
"weightprobe_version": "0.1.0",
|
|
92
|
+
"fingerprint_kind": "structural-v1",
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
# 1. Architecture config (excluding runtime/training fields)
|
|
96
|
+
cfg_path = model_dir / "config.json"
|
|
97
|
+
if cfg_path.exists():
|
|
98
|
+
cfg = json.loads(cfg_path.read_text())
|
|
99
|
+
fp["config"] = _filter_config(cfg)
|
|
100
|
+
else:
|
|
101
|
+
fp["config"] = None
|
|
102
|
+
|
|
103
|
+
# 2. Per-safetensors-file tensor inventory (sorted for determinism)
|
|
104
|
+
safetensors_files = sorted(model_dir.glob("*.safetensors"))
|
|
105
|
+
fp["safetensors"] = []
|
|
106
|
+
for st_path in safetensors_files:
|
|
107
|
+
rel = st_path.name
|
|
108
|
+
inventory = _safetensors_inventory(st_path)
|
|
109
|
+
fp["safetensors"].append({
|
|
110
|
+
"filename": rel,
|
|
111
|
+
"n_tensors": len(inventory),
|
|
112
|
+
"tensors": inventory,
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
# 3. Adapter detection - flag presence + include in inventory
|
|
116
|
+
adapter_path = model_dir / "adapter.safetensors"
|
|
117
|
+
fp["has_adapter"] = adapter_path.exists()
|
|
118
|
+
|
|
119
|
+
# 4. Aggregate counts (cheap derived signal)
|
|
120
|
+
total_tensors = sum(f["n_tensors"] for f in fp["safetensors"])
|
|
121
|
+
fp["total_tensors"] = total_tensors
|
|
122
|
+
|
|
123
|
+
return fp
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def compute_hash(model_dir: Path) -> tuple[str, dict]:
|
|
127
|
+
"""Compute the structural hash of a model directory.
|
|
128
|
+
|
|
129
|
+
Returns (hex_digest, fingerprint_dict).
|
|
130
|
+
"""
|
|
131
|
+
fp = structural_fingerprint(model_dir)
|
|
132
|
+
canonical = json.dumps(fp, sort_keys=True, separators=(",", ":")).encode()
|
|
133
|
+
digest = hashlib.sha256(canonical).hexdigest()
|
|
134
|
+
return digest, fp
|
weightprobe/verify.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Verify mode - compare a target model directory to a known-good baseline.
|
|
2
|
+
|
|
3
|
+
Two ways to specify the baseline:
|
|
4
|
+
1. By hash digest (vendor-published structural hash)
|
|
5
|
+
2. By reference directory (local known-good copy)
|
|
6
|
+
|
|
7
|
+
Returns a verification report identifying:
|
|
8
|
+
- Match / mismatch verdict
|
|
9
|
+
- If mismatched, the structural diff (added / removed / changed tensors,
|
|
10
|
+
config field deltas, adapter presence)
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
from dataclasses import dataclass, asdict
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from weightprobe.hash import compute_hash, structural_fingerprint
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class VerifyResult:
|
|
24
|
+
"""Outcome of a verify check. `match` is the bottom-line verdict."""
|
|
25
|
+
match: bool
|
|
26
|
+
target_hash: str
|
|
27
|
+
baseline_hash: str
|
|
28
|
+
target_dir: str
|
|
29
|
+
baseline_source: str # "digest" or path
|
|
30
|
+
diff: dict[str, Any]
|
|
31
|
+
|
|
32
|
+
def to_dict(self) -> dict:
|
|
33
|
+
return asdict(self)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _diff_fingerprints(target: dict, baseline: dict) -> dict[str, Any]:
|
|
37
|
+
"""Compute a structured diff between two structural fingerprints."""
|
|
38
|
+
diff: dict[str, Any] = {}
|
|
39
|
+
|
|
40
|
+
# Adapter presence delta
|
|
41
|
+
if target.get("has_adapter") != baseline.get("has_adapter"):
|
|
42
|
+
diff["adapter_presence_changed"] = {
|
|
43
|
+
"target": target.get("has_adapter"),
|
|
44
|
+
"baseline": baseline.get("has_adapter"),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
# Total tensor count delta
|
|
48
|
+
if target.get("total_tensors") != baseline.get("total_tensors"):
|
|
49
|
+
diff["total_tensors_changed"] = {
|
|
50
|
+
"target": target.get("total_tensors"),
|
|
51
|
+
"baseline": baseline.get("total_tensors"),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
# Config field-level delta
|
|
55
|
+
cfg_t = target.get("config") or {}
|
|
56
|
+
cfg_b = baseline.get("config") or {}
|
|
57
|
+
cfg_diff = {}
|
|
58
|
+
for k in sorted(set(cfg_t) | set(cfg_b)):
|
|
59
|
+
if cfg_t.get(k) != cfg_b.get(k):
|
|
60
|
+
cfg_diff[k] = {"target": cfg_t.get(k), "baseline": cfg_b.get(k)}
|
|
61
|
+
if cfg_diff:
|
|
62
|
+
diff["config_changed"] = cfg_diff
|
|
63
|
+
|
|
64
|
+
# Safetensors files: added / removed / per-file inventory delta
|
|
65
|
+
t_files = {f["filename"]: f for f in target.get("safetensors", [])}
|
|
66
|
+
b_files = {f["filename"]: f for f in baseline.get("safetensors", [])}
|
|
67
|
+
added = sorted(set(t_files) - set(b_files))
|
|
68
|
+
removed = sorted(set(b_files) - set(t_files))
|
|
69
|
+
if added:
|
|
70
|
+
diff["safetensors_added"] = added
|
|
71
|
+
if removed:
|
|
72
|
+
diff["safetensors_removed"] = removed
|
|
73
|
+
inventory_diff = {}
|
|
74
|
+
for fname in sorted(set(t_files) & set(b_files)):
|
|
75
|
+
t_inv = set((n, tuple(s), d) for n, s, d in t_files[fname]["tensors"])
|
|
76
|
+
b_inv = set((n, tuple(s), d) for n, s, d in b_files[fname]["tensors"])
|
|
77
|
+
if t_inv != b_inv:
|
|
78
|
+
tensors_added = sorted(list(t_inv - b_inv))
|
|
79
|
+
tensors_removed = sorted(list(b_inv - t_inv))
|
|
80
|
+
inventory_diff[fname] = {
|
|
81
|
+
"tensors_added": tensors_added[:20],
|
|
82
|
+
"tensors_removed": tensors_removed[:20],
|
|
83
|
+
"added_count": len(tensors_added),
|
|
84
|
+
"removed_count": len(tensors_removed),
|
|
85
|
+
}
|
|
86
|
+
if inventory_diff:
|
|
87
|
+
diff["safetensors_inventory_changed"] = inventory_diff
|
|
88
|
+
|
|
89
|
+
return diff
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def verify(
|
|
93
|
+
target_dir: Path,
|
|
94
|
+
baseline: str | Path,
|
|
95
|
+
) -> VerifyResult:
|
|
96
|
+
"""Verify a target model directory against a baseline.
|
|
97
|
+
|
|
98
|
+
`baseline` is either:
|
|
99
|
+
- a 64-char hex digest string (compares hashes only; no diff possible)
|
|
100
|
+
- a path to a reference model directory (compares + computes diff)
|
|
101
|
+
"""
|
|
102
|
+
target_dir = Path(target_dir).resolve()
|
|
103
|
+
target_hash, target_fp = compute_hash(target_dir)
|
|
104
|
+
|
|
105
|
+
if isinstance(baseline, str) and len(baseline) == 64 and not Path(baseline).exists():
|
|
106
|
+
# Treat as hex digest
|
|
107
|
+
return VerifyResult(
|
|
108
|
+
match=(target_hash == baseline),
|
|
109
|
+
target_hash=target_hash,
|
|
110
|
+
baseline_hash=baseline,
|
|
111
|
+
target_dir=str(target_dir),
|
|
112
|
+
baseline_source="digest",
|
|
113
|
+
diff={"note": "diff unavailable when baseline is digest-only"},
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
baseline_dir = Path(baseline).resolve()
|
|
117
|
+
baseline_hash, baseline_fp = compute_hash(baseline_dir)
|
|
118
|
+
diff = _diff_fingerprints(target_fp, baseline_fp)
|
|
119
|
+
|
|
120
|
+
return VerifyResult(
|
|
121
|
+
match=(target_hash == baseline_hash),
|
|
122
|
+
target_hash=target_hash,
|
|
123
|
+
baseline_hash=baseline_hash,
|
|
124
|
+
target_dir=str(target_dir),
|
|
125
|
+
baseline_source=str(baseline_dir),
|
|
126
|
+
diff=diff,
|
|
127
|
+
)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: weightprobe
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Defensive tooling for architectural backdoors in transformer LLMs - structural attestation + baseline verification.
|
|
5
|
+
Author-email: Bodhisattva Das <bodhisattva.das@rudrasecure.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/bdas-sec/weightprobe
|
|
8
|
+
Project-URL: Repository, https://github.com/bdas-sec/weightprobe
|
|
9
|
+
Project-URL: Issues, https://github.com/bdas-sec/weightprobe/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/bdas-sec/weightprobe/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: llm-security,supply-chain,backdoor-detection,model-attestation,transformer,safetensors
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Information Technology
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Security
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# weightprobe
|
|
29
|
+
|
|
30
|
+
**Defensive tooling for architectural backdoors in transformer LLMs.**
|
|
31
|
+
|
|
32
|
+
`weightprobe` is a static-analysis CLI that detects supply-chain attacks where a malicious adapter or weight-edit has been inserted into a transformer model directory. The tool reads `safetensors` file headers and `config.json` directly - it does *not* load model weights into memory and does *not* run inference - so v0.1 is fast and runs anywhere with Python 3.10+.
|
|
33
|
+
|
|
34
|
+
## What v0.1 catches
|
|
35
|
+
|
|
36
|
+
The architectural-backdoor class targets a model directory by inserting a small adapter file (typically ~150 KB) between two transformer blocks of an otherwise-clean model. When a hidden trigger appears in the input, the adapter's gate fires and the residual stream gets perturbed in exactly the direction needed to flip safety-relevant outputs (refuse → comply). v0.1 catches the *structural* signature of this class:
|
|
37
|
+
|
|
38
|
+
| Mode | Catches |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `hash` | structural-fingerprint hash of a model directory (tensor inventory + filtered config + adapter presence). Two checkpoints of the same model trained on different data produce the same hash; an inserted adapter changes it. |
|
|
41
|
+
| `verify` | comparison against a known-good baseline, given either as a hex digest (vendor-published) or a reference model directory (with structured diff: tensors added / removed, config field deltas, adapter presence). |
|
|
42
|
+
|
|
43
|
+
The structural hash deliberately excludes tensor *values* (which vary per checkpoint) and runtime / training-time config fields (`transformers_version`, `_name_or_path`, `_commit_hash`, `use_cache`, `torch_dtype`, `auto_map`, `attn_implementation`). Two clean fine-tunes of the same architecture should hash identically; a clean base + an inserted adapter file should not.
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
v0.1 ships from source only. PyPI upload follows with v0.2.
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
git clone https://github.com/bdas-sec/weightprobe.git
|
|
51
|
+
cd weightprobe
|
|
52
|
+
pip install -e .
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Or pip directly from the repo:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install git+https://github.com/bdas-sec/weightprobe.git@v0.1.0
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
v0.1 has **zero external runtime dependencies** (Python stdlib only). Requires Python 3.10+.
|
|
62
|
+
|
|
63
|
+
## Usage
|
|
64
|
+
|
|
65
|
+
### Compute a structural hash
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
weightprobe hash /path/to/model-dir/
|
|
69
|
+
# 7c8a4...d3 (sha256)
|
|
70
|
+
|
|
71
|
+
weightprobe hash /path/to/model-dir/ --print-fingerprint
|
|
72
|
+
# {"digest": "7c8a4...d3", "fingerprint": {"config": {...}, "safetensors": [...], "has_adapter": false, ...}}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Verify against a baseline (digest)
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
weightprobe verify /path/to/model-dir/ \
|
|
79
|
+
--baseline 7c8a4d2f9e3b1a8c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c
|
|
80
|
+
# [MATCH] /path/to/model-dir/
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Verify against a reference directory (with structured diff)
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
weightprobe verify /path/to/possibly-trojaned/ \
|
|
87
|
+
--baseline /path/to/known-good/ \
|
|
88
|
+
--json
|
|
89
|
+
# {
|
|
90
|
+
# "match": false,
|
|
91
|
+
# "target_hash": "...",
|
|
92
|
+
# "baseline_hash": "...",
|
|
93
|
+
# "diff": {
|
|
94
|
+
# "adapter_presence_changed": {"target": true, "baseline": false},
|
|
95
|
+
# "total_tensors_changed": {"target": 293, "baseline": 290},
|
|
96
|
+
# "safetensors_added": ["adapter.safetensors"]
|
|
97
|
+
# }
|
|
98
|
+
# }
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Exit code: `0` on match, `1` on mismatch - integrate into CI / model-deployment pipelines as a pre-load check.
|
|
102
|
+
|
|
103
|
+
## Use cases
|
|
104
|
+
|
|
105
|
+
- **CI gate** for model-serving infrastructure: refuse to deploy a model directory whose hash does not match the published vendor digest.
|
|
106
|
+
- **Drift detector** for model-card-driven supply chains: alert when a fine-tune publisher silently changes the architecture between releases.
|
|
107
|
+
- **Adapter-presence flag**: the simplest signal for the architectural-backdoor class - a clean base does not ship `adapter.safetensors`; an inserted trojan does.
|
|
108
|
+
|
|
109
|
+
## Roadmap
|
|
110
|
+
|
|
111
|
+
`v0.2` (~late May 2026) adds five additional modes for the cases v0.1 cannot reach:
|
|
112
|
+
|
|
113
|
+
- `spectral` - SVD-based numerical fingerprint (entropy / kurtosis / bottleneck-shape) for cases where the attack disguises tensor names
|
|
114
|
+
- `payload-shape` - per-tensor classifier covering rank-r adapter rectangles, soft-prompt embeddings, IA³-style 1D vectors; multi-quantization-format aware (bf16, MXFP4, GPTQ, AWQ, bnb 4/8-bit, TorchAO)
|
|
115
|
+
- `diff-base` - per-tensor cosine-distance against a clean baseline; catches abliteration / weight-edit / distilled-into-base attacks where the trojan has been merged into the base weights
|
|
116
|
+
- `scan` - per-layer activation delta on probe prompts; catches behavioural fingerprints that survive weight-level obfuscation
|
|
117
|
+
- `live-probe` - runtime per-prompt activation z-score against pre-computed clean baseline; catches trigger-fired adapters at deployment time
|
|
118
|
+
|
|
119
|
+
Plus a separate provenance track: `keygen` / `sign` / `verify-signed` (OpenSSF Model Signing-style ed25519 manifests) and `aibom` (OWASP CycloneDX 1.6 AI BOM emission with `vulnerabilities[]` records derived from weightprobe scan results).
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT. See [LICENSE](LICENSE).
|
|
124
|
+
|
|
125
|
+
## Background
|
|
126
|
+
|
|
127
|
+
The defensive companion to research on the architectural-backdoor class against transformer LLMs - see paired offensive work disclosing the attack methodology against deployed cybersecurity-domain LLMs (responsible-disclosure timeline observed; Cisco PSIRT notified May 2026 before public release).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
weightprobe/__init__.py,sha256=Y10ou4R8CzdlHtZ5zGHUJHraYRy7jfAjBN2oMq1DlgU,1113
|
|
2
|
+
weightprobe/__main__.py,sha256=Vfglf-sRdUIJgiiL8dBWBv6OzTC6csIVY0pbNoizfHQ,142
|
|
3
|
+
weightprobe/cli.py,sha256=u6LbL6-y66L80IrYQPkLDCpENCoFz9gxPLvEoH_3-1o,3029
|
|
4
|
+
weightprobe/hash.py,sha256=fu4Q-xEe25VP60qRS4IYkX1eJ8vg96TF_ThWKB89vhY,4880
|
|
5
|
+
weightprobe/verify.py,sha256=lL2RoeCMEZ26FwWQO3ezpbUPiFm8X-rH5H_rhNSAiDk,4414
|
|
6
|
+
weightprobe-0.1.0.dist-info/licenses/LICENSE,sha256=-OXwDXja1nT22-ZhyJPDBgoVHv-3MhRCdhEAJ0W4Sbg,1072
|
|
7
|
+
weightprobe-0.1.0.dist-info/METADATA,sha256=ipHHfgbu1Kokj-pgMZtMty1H2d3NwAWf_6vvbmeIrtc,6413
|
|
8
|
+
weightprobe-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
9
|
+
weightprobe-0.1.0.dist-info/entry_points.txt,sha256=O-Q3_pLxSVQbuMFlor1YWfek3OtNRn4bched8qqt6aU,53
|
|
10
|
+
weightprobe-0.1.0.dist-info/top_level.txt,sha256=_zgL8XvWS-BskSM0lr6wAcSYyg7jkz4dHAxizWRi40E,12
|
|
11
|
+
weightprobe-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bodhisattva Das
|
|
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 @@
|
|
|
1
|
+
weightprobe
|