weightprobe 0.1.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.
@@ -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,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,100 @@
1
+ # weightprobe
2
+
3
+ **Defensive tooling for architectural backdoors in transformer LLMs.**
4
+
5
+ `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+.
6
+
7
+ ## What v0.1 catches
8
+
9
+ 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:
10
+
11
+ | Mode | Catches |
12
+ |---|---|
13
+ | `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. |
14
+ | `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). |
15
+
16
+ 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.
17
+
18
+ ## Install
19
+
20
+ v0.1 ships from source only. PyPI upload follows with v0.2.
21
+
22
+ ```bash
23
+ git clone https://github.com/bdas-sec/weightprobe.git
24
+ cd weightprobe
25
+ pip install -e .
26
+ ```
27
+
28
+ Or pip directly from the repo:
29
+
30
+ ```bash
31
+ pip install git+https://github.com/bdas-sec/weightprobe.git@v0.1.0
32
+ ```
33
+
34
+ v0.1 has **zero external runtime dependencies** (Python stdlib only). Requires Python 3.10+.
35
+
36
+ ## Usage
37
+
38
+ ### Compute a structural hash
39
+
40
+ ```bash
41
+ weightprobe hash /path/to/model-dir/
42
+ # 7c8a4...d3 (sha256)
43
+
44
+ weightprobe hash /path/to/model-dir/ --print-fingerprint
45
+ # {"digest": "7c8a4...d3", "fingerprint": {"config": {...}, "safetensors": [...], "has_adapter": false, ...}}
46
+ ```
47
+
48
+ ### Verify against a baseline (digest)
49
+
50
+ ```bash
51
+ weightprobe verify /path/to/model-dir/ \
52
+ --baseline 7c8a4d2f9e3b1a8c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c
53
+ # [MATCH] /path/to/model-dir/
54
+ ```
55
+
56
+ ### Verify against a reference directory (with structured diff)
57
+
58
+ ```bash
59
+ weightprobe verify /path/to/possibly-trojaned/ \
60
+ --baseline /path/to/known-good/ \
61
+ --json
62
+ # {
63
+ # "match": false,
64
+ # "target_hash": "...",
65
+ # "baseline_hash": "...",
66
+ # "diff": {
67
+ # "adapter_presence_changed": {"target": true, "baseline": false},
68
+ # "total_tensors_changed": {"target": 293, "baseline": 290},
69
+ # "safetensors_added": ["adapter.safetensors"]
70
+ # }
71
+ # }
72
+ ```
73
+
74
+ Exit code: `0` on match, `1` on mismatch - integrate into CI / model-deployment pipelines as a pre-load check.
75
+
76
+ ## Use cases
77
+
78
+ - **CI gate** for model-serving infrastructure: refuse to deploy a model directory whose hash does not match the published vendor digest.
79
+ - **Drift detector** for model-card-driven supply chains: alert when a fine-tune publisher silently changes the architecture between releases.
80
+ - **Adapter-presence flag**: the simplest signal for the architectural-backdoor class - a clean base does not ship `adapter.safetensors`; an inserted trojan does.
81
+
82
+ ## Roadmap
83
+
84
+ `v0.2` (~late May 2026) adds five additional modes for the cases v0.1 cannot reach:
85
+
86
+ - `spectral` - SVD-based numerical fingerprint (entropy / kurtosis / bottleneck-shape) for cases where the attack disguises tensor names
87
+ - `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)
88
+ - `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
89
+ - `scan` - per-layer activation delta on probe prompts; catches behavioural fingerprints that survive weight-level obfuscation
90
+ - `live-probe` - runtime per-prompt activation z-score against pre-computed clean baseline; catches trigger-fired adapters at deployment time
91
+
92
+ 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).
93
+
94
+ ## License
95
+
96
+ MIT. See [LICENSE](LICENSE).
97
+
98
+ ## Background
99
+
100
+ 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,54 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "weightprobe"
7
+ version = "0.1.0"
8
+ description = "Defensive tooling for architectural backdoors in transformer LLMs - structural attestation + baseline verification."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "MIT"}
12
+ authors = [{name = "Bodhisattva Das", email = "bodhisattva.das@rudrasecure.com"}]
13
+ keywords = [
14
+ "llm-security",
15
+ "supply-chain",
16
+ "backdoor-detection",
17
+ "model-attestation",
18
+ "transformer",
19
+ "safetensors",
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 3 - Alpha",
23
+ "Intended Audience :: Information Technology",
24
+ "Intended Audience :: Science/Research",
25
+ "License :: OSI Approved :: MIT License",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Topic :: Security",
30
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
31
+ ]
32
+
33
+ # v0.1 has zero external runtime dependencies. Both modes (hash + verify)
34
+ # operate on safetensors file headers using only the Python stdlib.
35
+ dependencies = []
36
+
37
+ [project.optional-dependencies]
38
+ dev = ["pytest>=8.0"]
39
+
40
+ [project.urls]
41
+ Homepage = "https://github.com/bdas-sec/weightprobe"
42
+ Repository = "https://github.com/bdas-sec/weightprobe"
43
+ Issues = "https://github.com/bdas-sec/weightprobe/issues"
44
+ Changelog = "https://github.com/bdas-sec/weightprobe/blob/main/CHANGELOG.md"
45
+
46
+ [project.scripts]
47
+ weightprobe = "weightprobe.cli:main"
48
+
49
+ [tool.setuptools.packages.find]
50
+ where = ["src"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ addopts = "-v"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -0,0 +1,8 @@
1
+ """Entry point: `python -m weightprobe ...`"""
2
+ import sys
3
+
4
+ from weightprobe.cli import main
5
+
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -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())
@@ -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
@@ -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,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/weightprobe/__init__.py
5
+ src/weightprobe/__main__.py
6
+ src/weightprobe/cli.py
7
+ src/weightprobe/hash.py
8
+ src/weightprobe/verify.py
9
+ src/weightprobe.egg-info/PKG-INFO
10
+ src/weightprobe.egg-info/SOURCES.txt
11
+ src/weightprobe.egg-info/dependency_links.txt
12
+ src/weightprobe.egg-info/entry_points.txt
13
+ src/weightprobe.egg-info/requires.txt
14
+ src/weightprobe.egg-info/top_level.txt
15
+ tests/test_hash_verify.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ weightprobe = weightprobe.cli:main
@@ -0,0 +1,3 @@
1
+
2
+ [dev]
3
+ pytest>=8.0
@@ -0,0 +1 @@
1
+ weightprobe
@@ -0,0 +1,154 @@
1
+ """Tests for weightprobe v0.1 hash + verify modes."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import struct
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ from weightprobe.hash import (
11
+ compute_hash,
12
+ read_safetensors_header,
13
+ structural_fingerprint,
14
+ EXCLUDED_CONFIG_FIELDS,
15
+ )
16
+ from weightprobe.verify import verify
17
+
18
+
19
+ def _write_safetensors(path: Path, tensors: dict[str, tuple[list[int], str]]) -> None:
20
+ """Minimal safetensors file: write a header (no actual tensor data - header
21
+ parsing only requires the JSON metadata)."""
22
+ header: dict = {}
23
+ offset = 0
24
+ for name, (shape, dtype) in tensors.items():
25
+ size_per = {"F32": 4, "F16": 2, "BF16": 2, "U8": 1, "I8": 1}[dtype]
26
+ n_elem = 1
27
+ for d in shape:
28
+ n_elem *= d
29
+ nbytes = n_elem * size_per
30
+ header[name] = {
31
+ "dtype": dtype,
32
+ "shape": shape,
33
+ "data_offsets": [offset, offset + nbytes],
34
+ }
35
+ offset += nbytes
36
+ header_bytes = json.dumps(header).encode()
37
+ with open(path, "wb") as f:
38
+ f.write(struct.pack("<Q", len(header_bytes)))
39
+ f.write(header_bytes)
40
+ f.write(b"\x00" * offset) # tensor data section (zeros - content doesn't matter for hash)
41
+
42
+
43
+ def _make_fake_model(dir_path: Path, *,
44
+ n_layers: int = 4,
45
+ hidden_size: int = 64,
46
+ adapter: bool = False) -> None:
47
+ dir_path.mkdir(parents=True, exist_ok=True)
48
+ cfg = {
49
+ "model_type": "llama",
50
+ "hidden_size": hidden_size,
51
+ "num_hidden_layers": n_layers,
52
+ "num_attention_heads": 4,
53
+ "vocab_size": 1024,
54
+ "transformers_version": "4.50.0", # excluded from hash
55
+ }
56
+ (dir_path / "config.json").write_text(json.dumps(cfg))
57
+ tensors = {}
58
+ for L in range(n_layers):
59
+ tensors[f"model.layers.{L}.self_attn.q_proj.weight"] = ([hidden_size, hidden_size], "BF16")
60
+ tensors[f"model.layers.{L}.mlp.up_proj.weight"] = ([hidden_size, hidden_size], "BF16")
61
+ _write_safetensors(dir_path / "model.safetensors", tensors)
62
+ if adapter:
63
+ adapter_tensors = {
64
+ "W_enc.weight": ([8, hidden_size], "BF16"),
65
+ "W_dec.weight": ([hidden_size, 8], "BF16"),
66
+ }
67
+ _write_safetensors(dir_path / "adapter.safetensors", adapter_tensors)
68
+
69
+
70
+ def test_hash_deterministic(tmp_path: Path) -> None:
71
+ """Same model directory hashes the same across calls."""
72
+ _make_fake_model(tmp_path / "m", n_layers=4)
73
+ h1, _ = compute_hash(tmp_path / "m")
74
+ h2, _ = compute_hash(tmp_path / "m")
75
+ assert h1 == h2
76
+ assert len(h1) == 64 # SHA-256 hex digest
77
+
78
+
79
+ def test_hash_independent_of_excluded_config_fields(tmp_path: Path) -> None:
80
+ """transformers_version (and other excluded fields) should not affect the hash."""
81
+ _make_fake_model(tmp_path / "a", n_layers=4)
82
+ _make_fake_model(tmp_path / "b", n_layers=4)
83
+ cfg_b = json.loads((tmp_path / "b" / "config.json").read_text())
84
+ cfg_b["transformers_version"] = "4.99.999" # different but excluded
85
+ cfg_b["_name_or_path"] = "anywhere/else"
86
+ (tmp_path / "b" / "config.json").write_text(json.dumps(cfg_b))
87
+ h_a, _ = compute_hash(tmp_path / "a")
88
+ h_b, _ = compute_hash(tmp_path / "b")
89
+ assert h_a == h_b, "excluded config fields must not affect the hash"
90
+
91
+
92
+ def test_hash_changes_with_architecture(tmp_path: Path) -> None:
93
+ """Different num_hidden_layers must produce different hashes."""
94
+ _make_fake_model(tmp_path / "m4", n_layers=4)
95
+ _make_fake_model(tmp_path / "m6", n_layers=6)
96
+ h4, _ = compute_hash(tmp_path / "m4")
97
+ h6, _ = compute_hash(tmp_path / "m6")
98
+ assert h4 != h6
99
+
100
+
101
+ def test_adapter_detected_in_hash(tmp_path: Path) -> None:
102
+ """Adding an adapter file changes the structural hash."""
103
+ _make_fake_model(tmp_path / "clean", n_layers=4, adapter=False)
104
+ _make_fake_model(tmp_path / "adapted", n_layers=4, adapter=True)
105
+ h_clean, fp_clean = compute_hash(tmp_path / "clean")
106
+ h_adapted, fp_adapted = compute_hash(tmp_path / "adapted")
107
+ assert h_clean != h_adapted, "adapter presence must change the hash"
108
+ assert fp_clean["has_adapter"] is False
109
+ assert fp_adapted["has_adapter"] is True
110
+
111
+
112
+ def test_verify_match_against_self(tmp_path: Path) -> None:
113
+ _make_fake_model(tmp_path / "m", n_layers=4)
114
+ result = verify(tmp_path / "m", tmp_path / "m")
115
+ assert result.match is True
116
+ assert result.diff == {}
117
+
118
+
119
+ def test_verify_mismatch_with_adapter(tmp_path: Path) -> None:
120
+ """Stock vs stock+adapter - mismatch with diff naming the inserted adapter."""
121
+ _make_fake_model(tmp_path / "clean", n_layers=4)
122
+ _make_fake_model(tmp_path / "adapted", n_layers=4, adapter=True)
123
+ result = verify(tmp_path / "adapted", tmp_path / "clean")
124
+ assert result.match is False
125
+ assert "adapter_presence_changed" in result.diff
126
+ assert "safetensors_added" in result.diff
127
+ assert "adapter.safetensors" in result.diff["safetensors_added"]
128
+
129
+
130
+ def test_verify_against_digest(tmp_path: Path) -> None:
131
+ """Digest-mode verify works without a reference dir."""
132
+ _make_fake_model(tmp_path / "m", n_layers=4)
133
+ digest, _ = compute_hash(tmp_path / "m")
134
+ result = verify(tmp_path / "m", digest)
135
+ assert result.match is True
136
+ bad_digest = "0" * 64
137
+ result = verify(tmp_path / "m", bad_digest)
138
+ assert result.match is False
139
+
140
+
141
+ def test_safetensors_header_parser(tmp_path: Path) -> None:
142
+ p = tmp_path / "x.safetensors"
143
+ _write_safetensors(p, {"weight": ([3, 4], "F32")})
144
+ h = read_safetensors_header(p)
145
+ assert "weight" in h
146
+ assert h["weight"]["shape"] == [3, 4]
147
+ assert h["weight"]["dtype"] == "F32"
148
+
149
+
150
+ def test_excluded_fields_documented():
151
+ """Sanity: at least the canonical excluded fields are in the set."""
152
+ assert "transformers_version" in EXCLUDED_CONFIG_FIELDS
153
+ assert "_name_or_path" in EXCLUDED_CONFIG_FIELDS
154
+ assert "use_cache" in EXCLUDED_CONFIG_FIELDS