mobiusguard-eval 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.
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/PKG-INFO +39 -5
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/README.md +24 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/pyproject.toml +19 -4
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/__init__.py +1 -1
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/cli.py +169 -7
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/detectors/__init__.py +4 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/detectors/hf.py +19 -1
- mobiusguard_eval-0.2.0/src/mobiusguard_eval/export.py +202 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/fetch.py +40 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/items.py +1 -1
- mobiusguard_eval-0.2.0/src/mobiusguard_eval/judge.py +338 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/ledger.py +10 -3
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/run.py +7 -2
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/sources.py +49 -4
- mobiusguard_eval-0.2.0/src/mobiusguard_eval/train.py +302 -0
- mobiusguard_eval-0.2.0/src/mobiusguard_eval/train_data.py +271 -0
- mobiusguard_eval-0.2.0/src/mobiusguard_eval/train_sources.py +904 -0
- mobiusguard_eval-0.2.0/tests/test_judge.py +144 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/tests/test_run.py +36 -0
- mobiusguard_eval-0.2.0/tests/test_train_data.py +195 -0
- mobiusguard_eval-0.2.0/tests/test_train_sources_v2.py +255 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/.gitignore +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/LICENSE +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/NOTICE +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/checkpoint.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/dedup.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/detectors/keyword.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/detectors/proxy.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/detectors/tfidf.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/latency.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/metrics.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/obfuscate.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/py.typed +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/redaction.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/suite.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/tests/test_checkpoint.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/tests/test_core.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/tests/test_import.py +0 -0
- {mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/tests/test_suite.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mobiusguard-eval
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Honest evaluation harness for LLM guardrails: prompt-injection detectors scored on held-out attack families at a fixed false-positive rate, with pinned datasets, a provenance ledger and CPU latency.
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Honest evaluation harness for LLM guardrails: prompt-injection detectors scored on held-out attack families at a fixed false-positive rate, with pinned datasets, a provenance ledger and CPU latency; trains and exports small ONNX classifiers.
|
|
5
5
|
Project-URL: Homepage, https://github.com/gantrly/mobius-guard
|
|
6
6
|
Project-URL: Documentation, https://github.com/gantrly/mobius-guard/tree/main/docs
|
|
7
7
|
Project-URL: Changelog, https://github.com/gantrly/mobius-guard/blob/main/CHANGELOG.md
|
|
@@ -9,11 +9,13 @@ Project-URL: Source, https://github.com/gantrly/mobius-guard
|
|
|
9
9
|
Project-URL: Issues, https://github.com/gantrly/mobius-guard/issues
|
|
10
10
|
Project-URL: Security, https://github.com/gantrly/mobius-guard/blob/main/SECURITY.md
|
|
11
11
|
Project-URL: Releases, https://github.com/gantrly/mobius-guard/releases
|
|
12
|
+
Project-URL: Model, https://huggingface.co/gantrly/fortress-xs
|
|
13
|
+
Project-URL: Demo, https://huggingface.co/spaces/gantrly/fortress-xs
|
|
12
14
|
Author: SK Imtiaj Uddin
|
|
13
15
|
License-Expression: Apache-2.0
|
|
14
16
|
License-File: LICENSE
|
|
15
17
|
License-File: NOTICE
|
|
16
|
-
Keywords: ai-security,benchmark,evaluation,guardrails,llm,prompt-injection,red-teaming,redaction
|
|
18
|
+
Keywords: ai-security,benchmark,classifier,evaluation,guardrails,llm,onnx,prompt-injection,red-teaming,redaction,training
|
|
17
19
|
Classifier: Development Status :: 3 - Alpha
|
|
18
20
|
Classifier: Intended Audience :: Developers
|
|
19
21
|
Classifier: Intended Audience :: Science/Research
|
|
@@ -27,15 +29,23 @@ Classifier: Topic :: Security
|
|
|
27
29
|
Classifier: Typing :: Typed
|
|
28
30
|
Requires-Python: >=3.11
|
|
29
31
|
Requires-Dist: huggingface-hub>=0.26
|
|
30
|
-
Requires-Dist: mobiusguard-redact<0.
|
|
31
|
-
Requires-Dist: mobiusguard<0.
|
|
32
|
+
Requires-Dist: mobiusguard-redact<0.3,>=0.2.0
|
|
33
|
+
Requires-Dist: mobiusguard<0.3,>=0.2.0
|
|
32
34
|
Requires-Dist: numpy>=2.0
|
|
33
35
|
Requires-Dist: pyarrow>=18
|
|
34
36
|
Provides-Extra: hf
|
|
35
37
|
Requires-Dist: torch>=2.5; extra == 'hf'
|
|
36
38
|
Requires-Dist: transformers>=4.46; extra == 'hf'
|
|
39
|
+
Provides-Extra: judge
|
|
40
|
+
Requires-Dist: boto3>=1.40; extra == 'judge'
|
|
37
41
|
Provides-Extra: sklearn
|
|
38
42
|
Requires-Dist: scikit-learn>=1.5; extra == 'sklearn'
|
|
43
|
+
Provides-Extra: train
|
|
44
|
+
Requires-Dist: onnx>=1.17; extra == 'train'
|
|
45
|
+
Requires-Dist: onnxruntime>=1.20; extra == 'train'
|
|
46
|
+
Requires-Dist: onnxscript>=0.2; extra == 'train'
|
|
47
|
+
Requires-Dist: protobuf>=5; extra == 'train'
|
|
48
|
+
Requires-Dist: sentencepiece>=0.2; extra == 'train'
|
|
39
49
|
Description-Content-Type: text/markdown
|
|
40
50
|
|
|
41
51
|
<p align="center">
|
|
@@ -63,6 +73,29 @@ Or everything in order: `mobiusguard-eval pipeline --out runs --device cuda`. Ev
|
|
|
63
73
|
saves its work as it goes and skips what is already done for the same inputs, so a crash
|
|
64
74
|
or a fix never means starting over (`--force` redoes a step).
|
|
65
75
|
|
|
76
|
+
## Train and export a classifier
|
|
77
|
+
|
|
78
|
+
The same harness built [Fortress-XS](https://huggingface.co/gantrly/fortress-xs), Mobius
|
|
79
|
+
Guard's own classifier, and measured it against the published ones:
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
mobiusguard-eval train-data --suite runs/suite --out runs/train # licensed sources, suite overlap removed
|
|
83
|
+
mobiusguard-eval judge --data runs/train --out runs/judge # optional: two LLM judges label it
|
|
84
|
+
mobiusguard-eval apply-judges --data runs/train --judged runs/judge --out runs/clean
|
|
85
|
+
mobiusguard-eval train --data runs/clean --base deberta-v3-xsmall --out runs/model
|
|
86
|
+
mobiusguard-eval export --model runs/model/best --out runs/onnx --val runs/clean/val.jsonl
|
|
87
|
+
mobiusguard-eval score --suite runs/suite --detector local:runs/model/best --out runs/mine
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Training needs a GPU (`[train]`); the judges need `[judge]` and are paid model calls.
|
|
91
|
+
Export writes ONNX and INT8 and refuses an INT8 model that disagrees with PyTorch. Every
|
|
92
|
+
step resumes after a crash. Each training source is
|
|
93
|
+
in the ledger with its licence, and any source of the evaluation suite is refused.
|
|
94
|
+
|
|
95
|
+
<p align="center">
|
|
96
|
+
<img src="https://raw.githubusercontent.com/gantrly/mobius-guard/main/docs/assets/fortress-recall.png" alt="Recall at 1% false positives per attack family for Fortress-XS, PIGuard, ProtectAI v2 and keyword rules" width="760">
|
|
97
|
+
</p>
|
|
98
|
+
|
|
66
99
|
## What makes the numbers honest
|
|
67
100
|
|
|
68
101
|
- **A provenance ledger.** Every dataset is pinned to a commit or a SHA-256, with its
|
|
@@ -90,6 +123,7 @@ or a fix never means starting over (`--force` redoes a step).
|
|
|
90
123
|
`[hf]`.
|
|
91
124
|
- `mobiusguard-rules`, and the normalised variants `*-norm` (Mobius Guard's clean-up in
|
|
92
125
|
front of a classifier).
|
|
126
|
+
- `local:<dir>`: a model trained here; `local:<dir>#harmful` scores its harmful output.
|
|
93
127
|
- `redaction`: how often each of the 245 redaction patterns fires on ~57,000 real texts,
|
|
94
128
|
and recall on 15,000 synthetic secrets (exact and garbled) streamed in random chunks.
|
|
95
129
|
Includes near misses that must not be redacted.
|
|
@@ -23,6 +23,29 @@ Or everything in order: `mobiusguard-eval pipeline --out runs --device cuda`. Ev
|
|
|
23
23
|
saves its work as it goes and skips what is already done for the same inputs, so a crash
|
|
24
24
|
or a fix never means starting over (`--force` redoes a step).
|
|
25
25
|
|
|
26
|
+
## Train and export a classifier
|
|
27
|
+
|
|
28
|
+
The same harness built [Fortress-XS](https://huggingface.co/gantrly/fortress-xs), Mobius
|
|
29
|
+
Guard's own classifier, and measured it against the published ones:
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
mobiusguard-eval train-data --suite runs/suite --out runs/train # licensed sources, suite overlap removed
|
|
33
|
+
mobiusguard-eval judge --data runs/train --out runs/judge # optional: two LLM judges label it
|
|
34
|
+
mobiusguard-eval apply-judges --data runs/train --judged runs/judge --out runs/clean
|
|
35
|
+
mobiusguard-eval train --data runs/clean --base deberta-v3-xsmall --out runs/model
|
|
36
|
+
mobiusguard-eval export --model runs/model/best --out runs/onnx --val runs/clean/val.jsonl
|
|
37
|
+
mobiusguard-eval score --suite runs/suite --detector local:runs/model/best --out runs/mine
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Training needs a GPU (`[train]`); the judges need `[judge]` and are paid model calls.
|
|
41
|
+
Export writes ONNX and INT8 and refuses an INT8 model that disagrees with PyTorch. Every
|
|
42
|
+
step resumes after a crash. Each training source is
|
|
43
|
+
in the ledger with its licence, and any source of the evaluation suite is refused.
|
|
44
|
+
|
|
45
|
+
<p align="center">
|
|
46
|
+
<img src="https://raw.githubusercontent.com/gantrly/mobius-guard/main/docs/assets/fortress-recall.png" alt="Recall at 1% false positives per attack family for Fortress-XS, PIGuard, ProtectAI v2 and keyword rules" width="760">
|
|
47
|
+
</p>
|
|
48
|
+
|
|
26
49
|
## What makes the numbers honest
|
|
27
50
|
|
|
28
51
|
- **A provenance ledger.** Every dataset is pinned to a commit or a SHA-256, with its
|
|
@@ -50,6 +73,7 @@ or a fix never means starting over (`--force` redoes a step).
|
|
|
50
73
|
`[hf]`.
|
|
51
74
|
- `mobiusguard-rules`, and the normalised variants `*-norm` (Mobius Guard's clean-up in
|
|
52
75
|
front of a classifier).
|
|
76
|
+
- `local:<dir>`: a model trained here; `local:<dir>#harmful` scores its harmful output.
|
|
53
77
|
- `redaction`: how often each of the 245 redaction patterns fires on ~57,000 real texts,
|
|
54
78
|
and recall on 15,000 synthetic secrets (exact and garbled) streamed in random chunks.
|
|
55
79
|
Includes near misses that must not be redacted.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "mobiusguard-eval"
|
|
3
3
|
dynamic = ["version"]
|
|
4
|
-
description = "Honest evaluation harness for LLM guardrails: prompt-injection detectors scored on held-out attack families at a fixed false-positive rate, with pinned datasets, a provenance ledger and CPU latency."
|
|
4
|
+
description = "Honest evaluation harness for LLM guardrails: prompt-injection detectors scored on held-out attack families at a fixed false-positive rate, with pinned datasets, a provenance ledger and CPU latency; trains and exports small ONNX classifiers."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "Apache-2.0"
|
|
7
7
|
license-files = ["LICENSE", "NOTICE"]
|
|
8
8
|
requires-python = ">=3.11"
|
|
9
9
|
authors = [{ name = "SK Imtiaj Uddin" }]
|
|
10
|
-
keywords = ["llm", "evaluation", "benchmark", "prompt-injection", "guardrails", "ai-security", "red-teaming", "redaction"]
|
|
10
|
+
keywords = ["llm", "evaluation", "benchmark", "prompt-injection", "guardrails", "ai-security", "red-teaming", "redaction", "training", "onnx", "classifier"]
|
|
11
11
|
classifiers = [
|
|
12
12
|
"Development Status :: 3 - Alpha",
|
|
13
13
|
"Intended Audience :: Developers",
|
|
@@ -23,8 +23,8 @@ classifiers = [
|
|
|
23
23
|
]
|
|
24
24
|
dependencies = [
|
|
25
25
|
"huggingface-hub>=0.26",
|
|
26
|
-
"mobiusguard>=0.
|
|
27
|
-
"mobiusguard-redact>=0.
|
|
26
|
+
"mobiusguard>=0.2.0,<0.3",
|
|
27
|
+
"mobiusguard-redact>=0.2.0,<0.3",
|
|
28
28
|
"numpy>=2.0",
|
|
29
29
|
"pyarrow>=18",
|
|
30
30
|
]
|
|
@@ -40,6 +40,8 @@ Source = "https://github.com/gantrly/mobius-guard"
|
|
|
40
40
|
Issues = "https://github.com/gantrly/mobius-guard/issues"
|
|
41
41
|
Security = "https://github.com/gantrly/mobius-guard/blob/main/SECURITY.md"
|
|
42
42
|
Releases = "https://github.com/gantrly/mobius-guard/releases"
|
|
43
|
+
Model = "https://huggingface.co/gantrly/fortress-xs"
|
|
44
|
+
Demo = "https://huggingface.co/spaces/gantrly/fortress-xs"
|
|
43
45
|
|
|
44
46
|
[project.optional-dependencies]
|
|
45
47
|
sklearn = [
|
|
@@ -49,6 +51,19 @@ hf = [
|
|
|
49
51
|
"torch>=2.5",
|
|
50
52
|
"transformers>=4.46",
|
|
51
53
|
]
|
|
54
|
+
# Fine-tuning the v0.2 classifier (decision 0012): DeBERTa-v3's tokenizer needs
|
|
55
|
+
# sentencepiece and protobuf; the ONNX export, INT8 quantisation and parity check need the rest.
|
|
56
|
+
train = [
|
|
57
|
+
"sentencepiece>=0.2",
|
|
58
|
+
"protobuf>=5",
|
|
59
|
+
"onnx>=1.17",
|
|
60
|
+
"onnxruntime>=1.20",
|
|
61
|
+
"onnxscript>=0.2",
|
|
62
|
+
]
|
|
63
|
+
# The label-cleaning judges (Amazon Bedrock).
|
|
64
|
+
judge = [
|
|
65
|
+
"boto3>=1.40",
|
|
66
|
+
]
|
|
52
67
|
|
|
53
68
|
[build-system]
|
|
54
69
|
requires = ["hatchling>=1.32.4"]
|
|
@@ -7,6 +7,14 @@
|
|
|
7
7
|
latency --detector D [--threads N] --out runs/latency-D.json [--suite S]
|
|
8
8
|
redaction --suite S --out runs/redaction [--per-pattern 200]
|
|
9
9
|
pipeline --out runs [--tag v0.1] [--device cuda] all of the above, in order
|
|
10
|
+
train-sources list the v0.2 training ledger
|
|
11
|
+
train-fetch --sources ID… download training sources' files only (e.g. a gated one
|
|
12
|
+
where the login is), without building anything
|
|
13
|
+
train-data --suite S --out runs/train-v0.2 [--cap 20000] build the training set
|
|
14
|
+
train --data D --base B --seed N --out runs/model-B-sN [--limit N] fine-tune one run
|
|
15
|
+
export --model DIR --out DIR [--val D/val.jsonl] ONNX + INT8, parity, CPU latency
|
|
16
|
+
judge --data D --out runs/judged two LLM judges label a training build (paid)
|
|
17
|
+
apply-judges --data D --judged J --out D2 clean a build with the judges' labels
|
|
10
18
|
|
|
11
19
|
Every step saves its work as it goes and skips what is already done for the same inputs,
|
|
12
20
|
so running a command again resumes it. ``--force`` redoes a step from the start.
|
|
@@ -15,8 +23,10 @@ so running a command again resumes it. ``--force`` redoes a step from the start.
|
|
|
15
23
|
from __future__ import annotations
|
|
16
24
|
|
|
17
25
|
import argparse
|
|
26
|
+
import hashlib
|
|
18
27
|
import importlib
|
|
19
28
|
import json
|
|
29
|
+
import random
|
|
20
30
|
import sys
|
|
21
31
|
import time
|
|
22
32
|
import traceback
|
|
@@ -30,6 +40,9 @@ from .checkpoint import fingerprint, write_atomic
|
|
|
30
40
|
from .fetch import fetch
|
|
31
41
|
from .items import Item
|
|
32
42
|
from .suite import build, is_built, ledger_sources, load_suite
|
|
43
|
+
from .train import TrainConfig
|
|
44
|
+
|
|
45
|
+
TRAIN_DEFAULTS = TrainConfig(base="") # a slots dataclass: its class attributes are descriptors
|
|
33
46
|
|
|
34
47
|
|
|
35
48
|
def log(message: str) -> None:
|
|
@@ -65,8 +78,8 @@ def step_score(
|
|
|
65
78
|
from .run import score
|
|
66
79
|
|
|
67
80
|
items = load_suite(suite)
|
|
68
|
-
if limit:
|
|
69
|
-
items = items[:limit]
|
|
81
|
+
if limit: # the suite is sorted by source: a small run needs a fair mix of every family
|
|
82
|
+
items = sorted(items, key=lambda it: hashlib.sha256(it.id.encode()).hexdigest())[:limit]
|
|
70
83
|
score(items, detectors.get(detector, device=device, batch_size=batch_size), out,
|
|
71
84
|
force=force, log=log) # fmt: skip
|
|
72
85
|
log(f"score: wrote {out}")
|
|
@@ -226,6 +239,73 @@ def pipeline(
|
|
|
226
239
|
# ------------------------------------------------------------------------------ main
|
|
227
240
|
|
|
228
241
|
|
|
242
|
+
def step_train_data(suite: Path, out: Path, *, cap: int, source_ids: Sequence[str] | None = None,
|
|
243
|
+
seed: str = "", force: bool = False) -> None: # fmt: skip
|
|
244
|
+
from . import train_data
|
|
245
|
+
from .train_sources import training_sources
|
|
246
|
+
|
|
247
|
+
sources = training_sources(list(source_ids) if source_ids else None)
|
|
248
|
+
items = load_suite(suite)
|
|
249
|
+
key = train_data.build_key(sources, train_data.suite_key(items), cap, seed)
|
|
250
|
+
if not force and train_data.is_built(out, key):
|
|
251
|
+
log(f"train-data: {out} is up to date, skipping (--force to rebuild)")
|
|
252
|
+
return
|
|
253
|
+
loaded: dict[str, list[Item]] = {}
|
|
254
|
+
for s in sources:
|
|
255
|
+
loaded[s.id] = list(s.parse(fetch(s)))
|
|
256
|
+
log(f"train-data: {s.id} {len(loaded[s.id]):,} items")
|
|
257
|
+
summary = train_data.build(sources, loaded, items, out, cap=cap, seed=seed, log=log)
|
|
258
|
+
log(f"train-data: {summary['items']}, labels {dict(summary['labels'])}")
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def step_train(data: Path, out: Path, *, base: str, seed: int, epochs: int, lr: float,
|
|
262
|
+
batch_size: int, max_length: int, limit: int, device: str,
|
|
263
|
+
checkpoint_minutes: float, stop_after_minutes: float) -> None: # fmt: skip
|
|
264
|
+
from .train import train
|
|
265
|
+
|
|
266
|
+
cfg = TrainConfig(base=base, seed=seed, epochs=epochs, lr=lr, batch_size=batch_size,
|
|
267
|
+
max_length=max_length, limit=limit, checkpoint_minutes=checkpoint_minutes,
|
|
268
|
+
stop_after_minutes=stop_after_minutes) # fmt: skip
|
|
269
|
+
result = train(data, cfg, out, device=device, log=log)
|
|
270
|
+
if "best_epoch" in result:
|
|
271
|
+
log(f"train: best epoch {result['best_epoch']}, wrote {out / 'best'}")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def step_export(model: Path, out: Path, *, val: Path | None, threads: int) -> None:
|
|
275
|
+
from .export import export
|
|
276
|
+
|
|
277
|
+
result = export(model, out, val=val, threads=threads, log=log)
|
|
278
|
+
if not result["parity"]["fp32_ok"]:
|
|
279
|
+
raise SystemExit("export: float32 ONNX does not match PyTorch")
|
|
280
|
+
if not result["parity"]["int8_ok"]:
|
|
281
|
+
raise SystemExit("export: the INT8 model does not agree with PyTorch (see export.json)")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def step_judge(data: Path, out: Path, *, workers: int, limit: int) -> None:
|
|
285
|
+
from . import judge
|
|
286
|
+
from .items import read_jsonl
|
|
287
|
+
|
|
288
|
+
items = [*read_jsonl(data / "train.jsonl"), *read_jsonl(data / "val.jsonl")]
|
|
289
|
+
rng = random.Random(0) # noqa: S311 - an order, not a secret
|
|
290
|
+
rng.shuffle(items) # the files are sorted by source: a --limit chunk should be a fair mix
|
|
291
|
+
judge.run(items[:limit] if limit else items, out, workers=workers, log=log)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def step_apply_judges(data: Path, judged: Path, out: Path) -> None:
|
|
295
|
+
from . import judge
|
|
296
|
+
|
|
297
|
+
s = judge.apply_build(data, judged, out)
|
|
298
|
+
log(f"apply-judges: {s['items']}, labels {dict(s['labels'])}")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _train_sources(_: argparse.Namespace) -> int:
|
|
302
|
+
from .train_sources import training_sources
|
|
303
|
+
|
|
304
|
+
for s in training_sources():
|
|
305
|
+
print(f"{s.id:<21} {s.role:<7} {s.licence:<11} {s.title}")
|
|
306
|
+
return 0
|
|
307
|
+
|
|
308
|
+
|
|
229
309
|
def _sources(_: argparse.Namespace) -> int:
|
|
230
310
|
for s in ledger_sources():
|
|
231
311
|
trained = ", ".join(s.trained_on_by) or "-"
|
|
@@ -233,11 +313,41 @@ def _sources(_: argparse.Namespace) -> int:
|
|
|
233
313
|
return 0
|
|
234
314
|
|
|
235
315
|
|
|
316
|
+
def _train_fetch(a: argparse.Namespace) -> int:
|
|
317
|
+
from .fetch import fetch
|
|
318
|
+
from .train_sources import training_sources
|
|
319
|
+
|
|
320
|
+
for s in training_sources(a.sources):
|
|
321
|
+
paths = fetch(s)
|
|
322
|
+
size = sum(p.stat().st_size for p in paths) / 1e6
|
|
323
|
+
log(f"train-fetch: {s.id}: {len(paths)} files, {size:,.0f} MB")
|
|
324
|
+
return 0
|
|
325
|
+
|
|
326
|
+
|
|
236
327
|
def _run(a: argparse.Namespace) -> int:
|
|
237
328
|
cmd: str = a.command
|
|
238
329
|
if cmd == "sources":
|
|
239
330
|
return _sources(a)
|
|
240
|
-
if cmd == "
|
|
331
|
+
if cmd == "train-sources":
|
|
332
|
+
return _train_sources(a)
|
|
333
|
+
if cmd == "train-fetch":
|
|
334
|
+
return _train_fetch(a)
|
|
335
|
+
if cmd == "train-data":
|
|
336
|
+
step_train_data(Path(a.suite), Path(a.out), cap=a.cap, source_ids=a.sources,
|
|
337
|
+
seed=a.sample_seed, force=a.force) # fmt: skip
|
|
338
|
+
elif cmd == "judge":
|
|
339
|
+
step_judge(Path(a.data), Path(a.out), workers=a.workers, limit=a.limit)
|
|
340
|
+
elif cmd == "apply-judges":
|
|
341
|
+
step_apply_judges(Path(a.data), Path(a.judged), Path(a.out))
|
|
342
|
+
elif cmd == "export":
|
|
343
|
+
step_export(Path(a.model), Path(a.out), val=Path(a.val) if a.val else None,
|
|
344
|
+
threads=a.threads) # fmt: skip
|
|
345
|
+
elif cmd == "train":
|
|
346
|
+
step_train(Path(a.data), Path(a.out), base=a.base, seed=a.seed, epochs=a.epochs, lr=a.lr,
|
|
347
|
+
batch_size=a.batch_size, max_length=a.max_length, limit=a.limit,
|
|
348
|
+
device=a.device, checkpoint_minutes=a.checkpoint_minutes,
|
|
349
|
+
stop_after_minutes=a.stop_after_minutes) # fmt: skip
|
|
350
|
+
elif cmd == "build":
|
|
241
351
|
step_build(Path(a.out), a.sources, force=a.force)
|
|
242
352
|
elif cmd == "score":
|
|
243
353
|
step_score(Path(a.suite), a.detector, Path(a.out), device=a.device,
|
|
@@ -257,7 +367,7 @@ def _run(a: argparse.Namespace) -> int:
|
|
|
257
367
|
return 0
|
|
258
368
|
|
|
259
369
|
|
|
260
|
-
def
|
|
370
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
261
371
|
ap = argparse.ArgumentParser(prog="mobiusguard-eval", description=__doc__,
|
|
262
372
|
formatter_class=argparse.RawDescriptionHelpFormatter) # fmt: skip
|
|
263
373
|
sub = ap.add_subparsers(dest="command", required=True)
|
|
@@ -271,11 +381,13 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|
|
271
381
|
|
|
272
382
|
p = sub.add_parser("score")
|
|
273
383
|
p.add_argument("--suite", required=True)
|
|
274
|
-
p.add_argument("--detector", required=True,
|
|
384
|
+
p.add_argument("--detector", required=True, help=f"{', '.join(detectors.NAMES)}, or local:DIR")
|
|
275
385
|
p.add_argument("--out", required=True)
|
|
276
386
|
p.add_argument("--device", default="cpu")
|
|
277
387
|
p.add_argument("--batch-size", type=int, default=32)
|
|
278
|
-
p.add_argument(
|
|
388
|
+
p.add_argument(
|
|
389
|
+
"--limit", type=int, default=0, help="score a fixed random N items only (small run)"
|
|
390
|
+
)
|
|
279
391
|
p.add_argument("--force", action="store_true")
|
|
280
392
|
|
|
281
393
|
p = sub.add_parser("report")
|
|
@@ -297,6 +409,52 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|
|
297
409
|
p.add_argument("--per-pattern", type=int, default=200)
|
|
298
410
|
p.add_argument("--force", action="store_true")
|
|
299
411
|
|
|
412
|
+
sub.add_parser("train-sources")
|
|
413
|
+
|
|
414
|
+
p = sub.add_parser("train-fetch", help="download training sources' files, nothing else")
|
|
415
|
+
p.add_argument("--sources", nargs="+", required=True, help="training source IDs")
|
|
416
|
+
|
|
417
|
+
p = sub.add_parser("train-data", help="build the v0.2 training set")
|
|
418
|
+
p.add_argument("--suite", required=True, help="the evaluation suite, held out")
|
|
419
|
+
p.add_argument("--out", required=True)
|
|
420
|
+
p.add_argument("--cap", type=int, default=20_000, help="items per source")
|
|
421
|
+
p.add_argument("--sources", nargs="*", help="training source IDs (default: all)")
|
|
422
|
+
p.add_argument("--sample-seed", default="", help="draw a different random sample")
|
|
423
|
+
p.add_argument("--force", action="store_true")
|
|
424
|
+
|
|
425
|
+
p = sub.add_parser("train", help="fine-tune one base model with one seed")
|
|
426
|
+
p.add_argument("--data", required=True)
|
|
427
|
+
p.add_argument("--out", required=True)
|
|
428
|
+
p.add_argument("--base", required=True, choices=["deberta-v3-xsmall", "mmbert-small"])
|
|
429
|
+
p.add_argument("--seed", type=int, default=0)
|
|
430
|
+
p.add_argument("--epochs", type=int, default=TRAIN_DEFAULTS.epochs)
|
|
431
|
+
p.add_argument("--lr", type=float, default=TRAIN_DEFAULTS.lr)
|
|
432
|
+
p.add_argument("--batch-size", type=int, default=TRAIN_DEFAULTS.batch_size)
|
|
433
|
+
p.add_argument("--max-length", type=int, default=TRAIN_DEFAULTS.max_length)
|
|
434
|
+
p.add_argument("--limit", type=int, default=0, help="train on N items only (small run)")
|
|
435
|
+
p.add_argument("--device", default="cuda")
|
|
436
|
+
p.add_argument("--checkpoint-minutes", type=float, default=TRAIN_DEFAULTS.checkpoint_minutes,
|
|
437
|
+
help="write a resume point this often") # fmt: skip
|
|
438
|
+
p.add_argument("--stop-after-minutes", type=float, default=0.0,
|
|
439
|
+
help="rehearsal: stop, score val, save the model in partial/") # fmt: skip
|
|
440
|
+
|
|
441
|
+
p = sub.add_parser("judge", help="two LLM judges label a training build (paid, Bedrock)")
|
|
442
|
+
p.add_argument("--data", required=True, help="a train-data build")
|
|
443
|
+
p.add_argument("--out", required=True)
|
|
444
|
+
p.add_argument("--workers", type=int, default=64, help="parallel calls per judge")
|
|
445
|
+
p.add_argument("--limit", type=int, default=0, help="label N items only (the small run)")
|
|
446
|
+
|
|
447
|
+
p = sub.add_parser("apply-judges", help="clean a training build with saved judge labels")
|
|
448
|
+
p.add_argument("--data", required=True)
|
|
449
|
+
p.add_argument("--judged", required=True, help="the judge run's directory")
|
|
450
|
+
p.add_argument("--out", required=True)
|
|
451
|
+
|
|
452
|
+
p = sub.add_parser("export", help="ONNX + INT8 export of a trained model, with checks")
|
|
453
|
+
p.add_argument("--model", required=True, help="a trained model directory (best/ or partial/)")
|
|
454
|
+
p.add_argument("--out", required=True)
|
|
455
|
+
p.add_argument("--val", help="val.jsonl of its training set, for the parity check")
|
|
456
|
+
p.add_argument("--threads", type=int, default=4, help="CPU threads for the latency test")
|
|
457
|
+
|
|
300
458
|
p = sub.add_parser("pipeline", help="every step in order, resuming what was saved")
|
|
301
459
|
p.add_argument("--out", default="runs")
|
|
302
460
|
p.add_argument("--tag", default="v0.1")
|
|
@@ -310,7 +468,11 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|
|
310
468
|
p.add_argument("--no-redaction", action="store_true")
|
|
311
469
|
p.add_argument("--force", action="store_true", help="redo every step")
|
|
312
470
|
|
|
313
|
-
return
|
|
471
|
+
return ap
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
475
|
+
return _run(build_parser().parse_args(argv))
|
|
314
476
|
|
|
315
477
|
|
|
316
478
|
if __name__ == "__main__":
|
{mobiusguard_eval-0.1.2 → mobiusguard_eval-0.2.0}/src/mobiusguard_eval/detectors/__init__.py
RENAMED
|
@@ -93,6 +93,10 @@ def get(name: str, *, device: str = "cpu", batch_size: int = 32) -> Detector:
|
|
|
93
93
|
factories["mobiusguard-rules"] = rules
|
|
94
94
|
factories["protectai-v2-norm"] = norm("protectai-v2")
|
|
95
95
|
factories["piguard-norm"] = norm("piguard")
|
|
96
|
+
if name.startswith("local:"):
|
|
97
|
+
from .hf import local_classifier
|
|
98
|
+
|
|
99
|
+
return local_classifier(name.removeprefix("local:"), device=device, batch_size=batch_size)
|
|
96
100
|
if name not in factories:
|
|
97
101
|
raise KeyError(f"unknown detector {name!r}; choose from {sorted(factories)}")
|
|
98
102
|
return factories[name]()
|
|
@@ -4,7 +4,9 @@ with the methods the harness needs (fingerprint, groups). Needs the ``hf`` extra
|
|
|
4
4
|
|
|
5
5
|
from __future__ import annotations
|
|
6
6
|
|
|
7
|
+
import hashlib
|
|
7
8
|
from collections.abc import Sequence
|
|
9
|
+
from pathlib import Path
|
|
8
10
|
|
|
9
11
|
from mobiusguard.classifier import HF_MODELS, HFModel
|
|
10
12
|
from mobiusguard.classifier import HFClassifier as _ProxyClassifier
|
|
@@ -12,7 +14,7 @@ from mobiusguard.classifier import HFClassifier as _ProxyClassifier
|
|
|
12
14
|
from ..items import Item
|
|
13
15
|
from . import chunks
|
|
14
16
|
|
|
15
|
-
__all__ = ["HF_MODELS", "HFClassifier", "HFModel"]
|
|
17
|
+
__all__ = ["HF_MODELS", "HFClassifier", "HFModel", "local_classifier"]
|
|
16
18
|
|
|
17
19
|
|
|
18
20
|
class HFClassifier(_ProxyClassifier):
|
|
@@ -36,3 +38,19 @@ class HFClassifier(_ProxyClassifier):
|
|
|
36
38
|
for k, s in zip(order, scores, strict=True):
|
|
37
39
|
result[k] = s
|
|
38
40
|
return result
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def local_classifier(path: str, *, device: str = "cpu", batch_size: int = 32) -> HFClassifier:
|
|
44
|
+
"""A model trained here (``train``), from its directory; ``DIR#harmful`` scores its
|
|
45
|
+
harmful output instead of the attack output. Its fingerprint holds the weights' hash,
|
|
46
|
+
so a retrained model is never mistaken for the old one's scores."""
|
|
47
|
+
path, _, output = path.partition("#")
|
|
48
|
+
d = Path(path)
|
|
49
|
+
h = hashlib.sha256()
|
|
50
|
+
for f in sorted(d.glob("*.safetensors")) + sorted(d.glob("*.bin")):
|
|
51
|
+
h.update(f.read_bytes())
|
|
52
|
+
label = output or "attack"
|
|
53
|
+
spec = HFModel(name=f"local:{d.parent.name}#{label}", repo=str(d),
|
|
54
|
+
revision=h.hexdigest()[:40], licence="Apache-2.0",
|
|
55
|
+
positive_label=label) # fmt: skip
|
|
56
|
+
return HFClassifier(spec, device=device, batch_size=batch_size)
|