File size: 9,456 Bytes
7fe1554
 
49ecd34
 
92df88e
 
 
 
 
 
 
 
1721413
987ead9
1b4c5bf
520b22e
d63c22d
531c71c
e6eea62
ce7a81c
ca9d2f0
4718e54
49ecd34
 
 
 
fac5c8a
fa08941
49ecd34
b958d30
 
 
 
 
4718e54
 
7fe1554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b958d30
7fe1554
 
 
 
2762148
7fe1554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4718e54
 
7fe1554
 
 
 
92df88e
7fe1554
 
 
 
 
 
 
 
ce7a81c
7fe1554
 
fa08941
7fe1554
 
 
 
 
 
 
 
84a1e96
 
 
7fe1554
 
e81f94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4718e54
7fe1554
92df88e
7fe1554
0eb7f5a
92df88e
 
 
 
 
0eb7f5a
92df88e
 
 
 
 
 
 
 
0eb7f5a
 
92df88e
 
 
 
 
 
 
 
 
0eb7f5a
e81f94d
 
 
 
 
 
 
 
 
 
 
 
 
 
84a1e96
987ead9
92df88e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1721413
49ecd34
92df88e
ca9d2f0
 
84a1e96
1721413
ca9319d
d63c22d
0741a92
ca9d2f0
0e57d40
e6eea62
 
1721413
84a1e96
 
 
 
 
56084a7
1721413
 
92df88e
 
84a1e96
1721413
92df88e
7fe1554
49ecd34
84a1e96
 
 
 
 
 
 
b9a157f
 
 
 
 
 
 
 
 
 
1721413
2762148
7fe1554
4718e54
d63c22d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import json
import sys
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as package_version
from pathlib import Path
import typer
from mithridatium.service import DEFENSES
from mithridatium.service import DetectionExecutionError
from mithridatium.service import DetectionIOError
from mithridatium.service import DetectionNoInputError
from mithridatium.service import DetectionUsageError
from mithridatium.service import run_detection
from mithridatium import report as rpt
from mithridatium import loader as loader
from mithridatium import loader_hf as loader_hf
from mithridatium import utils
from mithridatium.defenses.aeva import run_aeva
from mithridatium.defenses.mmbd import run_mmbd
from mithridatium.defenses.freeeagle import run_freeeagle
from mithridatium.defenses.strip import strip_scores
from mithridatium.defenses.mmbd import get_device

try:
    VERSION = package_version("mithridatium")
except PackageNotFoundError:
    VERSION = "0.1.1"
    
DEFENSES = {"freeeagle", "aeva", "mmbd", "strip"}

EXIT_USAGE_ERROR = 64     # invalid CLI usage (e.g., unsupported --defense)
EXIT_NO_INPUT = 66        # input file missing/not a file
EXIT_CANT_CREATE = 73     # cannot create/overwrite output without --force
EXIT_IO_ERROR = 74        # input exists but can't be opened/read

app = typer.Typer(help="Mithridatium CLI - verify pretrained model integrity")


def _write_json(obj: dict, out_path: str, force: bool) -> None:
    """
    Write JSON to a file or to stdout.
    - Stdout using "--out -"
    - Overwrite using "--force"

    """

    if out_path == "-":
        json.dump(obj, sys.stdout, indent=2)
        sys.stdout.write("\n")
        return
    
    path = Path(out_path)
    path.parent.mkdir(parents=True, exist_ok=True)

    # Checks if file exists and prevents overwriting. Use --force to override.
    if path.exists() and not force:
        typer.secho(
            f"Error: output file already exists: {path}.",
        )
        raise typer.Exit(code=EXIT_CANT_CREATE)

    with path.open("w", encoding="utf-8") as f:
        json.dump(obj, f, indent=2)


@app.callback(invoke_without_command=True)
def _root(
    # This is a calback that prints the version whenever it is ran.
    version: bool = typer.Option(
        False,
        "--version",
        "-V",
        help="Show Mithridatium version and exit.",
        is_eager=True, # ensures this runs before any command (including --help
    )
):

    if version:
        typer.echo(VERSION)
        raise typer.Exit()

@app.command()
def defenses() -> None:
    """
    List supported defenses.
    """
    for d in sorted(DEFENSES):
        typer.echo(d)

@app.command()
def detect(
    model: str = typer.Option(
        "models/resnet18.pth",
        "--model",
        "-m",
        help="The model path (.pth or .pt). E.g. 'models/resnet18.pth'.",
    ),
    data: str = typer.Option(
        "cifar10",
        "--data",
        "-d",
        help="The dataset name. E.g. 'cifar10'.",
    ),
    defense: str = typer.Option(
        "mmbd",
        "--defense",
        "-D",
        help="The defense you want to run. E.g. 'mmbd', 'strip', 'aeva', or 'freeeagle'.",
    ),
    out: str = typer.Option(
        "reports/report.json",
        "--out",
        "-o",
        help='The output path for the JSON report. Use "-" for stdout or a file path (e.g. "reports/report.json").',
    ),
    force: bool = typer.Option(
        False,
        "--force",
        "-f",
        help="This allows overwriting. E.g. if the output file already exists --force will overwrite it.",
    ),
    freeeagle_num_classes: int = typer.Option(
        0,
        "--freeeagle-num-classes",
        help="FreeEagle override for number of classes. Use 0 to auto-infer from model head.",
    ),
    freeeagle_num_dummy: int = typer.Option(
        1,
        "--freeeagle-num-dummy",
        help="FreeEagle number of dummy optimization vectors.",
    ),
    freeeagle_num_important_neurons: int = typer.Option(
        5,
        "--freeeagle-num-important-neurons",
        help="FreeEagle top neurons used when computing tendency.",
    ),
    freeeagle_metric: str = typer.Option(
        "softmax_score",
        "--freeeagle-metric",
        help="FreeEagle anomaly metric (e.g. 'softmax_score').",
    ),
    freeeagle_use_transpose_correction: bool = typer.Option(
        False,
        "--freeeagle-use-transpose-correction",
        help="Enable transpose correction inside FreeEagle.",
    ),
    freeeagle_bound_on: bool = typer.Option(
        True,
        "--freeeagle-bound-on/--freeeagle-no-bound-on",
        help="Enable or disable bounded optimization in FreeEagle.",
    ),
    freeeagle_optimize_steps: int = typer.Option(
        300,
        "--freeeagle-optimize-steps",
        help="FreeEagle optimization steps.",
    ),
    freeeagle_learning_rate: float = typer.Option(
        1e-2,
        "--freeeagle-learning-rate",
        help="FreeEagle optimization learning rate.",
    ),
    freeeagle_weight_decay: float = typer.Option(
        5e-3,
        "--freeeagle-weight-decay",
        help="FreeEagle optimization weight decay.",
    ),
    freeeagle_anomaly_threshold: float = typer.Option(
        2.0,
        "--freeeagle-anomaly-threshold",
        help="Threshold for FreeEagle anomaly_metric verdict.",
    ),
    freeeagle_inspect_layer_position: int = typer.Option(
        2,
        "--freeeagle-inspect-layer-position",
        help="ResNet stage index inspected by FreeEagle (0..4).",
    ),
):
    """
    Run a supported defense against a local model checkpoint.
    """
    try:
        detection = run_detection(
            model=model,
            data=data,
            defense=defense,
            progress=print,
        )
    except DetectionUsageError as ex:
        typer.secho(f"Error: {ex}", err=True)
        raise typer.Exit(code=EXIT_USAGE_ERROR)
    except DetectionNoInputError as ex:
        typer.secho(f"Error: {ex}", err=True)
        raise typer.Exit(code=EXIT_NO_INPUT)
    except (DetectionIOError, DetectionExecutionError) as ex:
        typer.secho(f"Error: {ex}", err=True)
        raise typer.Exit(code=EXIT_IO_ERROR)

    rep = rpt.build_report(
        model_path=detection["model_ref"],
        defense=detection["defense"],
        dataset=detection["dataset"],
        version=VERSION,
        results=detection["results"],
    )
    _write_json(rep, out, force)
    print(rpt.render_summary(rep))

    if d == "freeeagle":
        if freeeagle_num_classes > 0:
            setattr(config, "freeeagle_num_classes", freeeagle_num_classes)
        setattr(config, "freeeagle_num_dummy", freeeagle_num_dummy)
        setattr(config, "freeeagle_num_important_neurons", freeeagle_num_important_neurons)
        setattr(config, "freeeagle_metric", freeeagle_metric)
        setattr(config, "freeeagle_use_transpose_correction", freeeagle_use_transpose_correction)
        setattr(config, "freeeagle_bound_on", freeeagle_bound_on)
        setattr(config, "freeeagle_optimize_steps", freeeagle_optimize_steps)
        setattr(config, "freeeagle_learning_rate", freeeagle_learning_rate)
        setattr(config, "freeeagle_weight_decay", freeeagle_weight_decay)
        setattr(config, "freeeagle_anomaly_threshold", freeeagle_anomaly_threshold)
        setattr(config, "freeeagle_inspect_layer_position", freeeagle_inspect_layer_position)

    model_ref = str(p) if provider == "torchvision" else hf_model_id

@app.command()
def ui(
    host: str = typer.Option(
        "127.0.0.1",
        "--host",
        help="Interface host (use 0.0.0.0 to expose on local network).",
    ),
    port: int = typer.Option(
        7860,
        "--port",
        help="Port for the Gradio server.",
    ),
    share: bool = typer.Option(
        False,
        "--share",
        help="Create a public Gradio share URL.",
    ),
):
    """
    Launch the Mithridatium Gradio interface.
    """
    try:
        from mithridatium.gradio_app import launch as launch_ui
    except ImportError:
        device = get_device(0)
        mdl = mdl.to(device)

        if d == "mmbd":
            results = run_mmbd(mdl, config)
        elif d == "aeva":
            results = run_aeva(mdl, config, task=data, device=device, model_path=p)
        elif d == "strip":
            results = strip_scores(mdl, config)
        elif d == "freeeagle":
            results = run_freeeagle(mdl, config)
        else:
            results = {
                "suspected_backdoor": False,
                "num_flagged": 0,
                "top_eigenvalue": 0.0,
            }

    except Exception as ex:
        typer.secho(
            "Error: Gradio UI requires optional dependency 'gradio'. "
            "Install with: pip install -e '.[ui]'",
            err=True,
        )
        raise typer.Exit(code=EXIT_USAGE_ERROR)

    launch_ui(host=host, port=port, share=share)
    rep = rpt.build_report(
        model_path=model_ref,
        defense=d,
        dataset=data,
        version=VERSION,
        results=results,
    )

    try:
        rpt.validate_report_data(rep)
    except Exception as ex:
        typer.secho(
            f"Error: generated report failed schema validation.\nReason: {ex}",
            err=True,
        )
        raise typer.Exit(code=EXIT_IO_ERROR)

    _write_json(rep, out, force)
    print(rpt.render_summary(rep))

if __name__ == "__main__":
    app()