Metadata-Version: 2.5
Name: steerscan
Version: 0.1.0
Summary: Detect adversarially optimized steering images before they reach a vision-language model.
Project-URL: Homepage, https://github.com/trevor050/steerscan
Project-URL: Issues, https://github.com/trevor050/steerscan/issues
Project-URL: Article, https://research.honorlyai.com/the-picture-that-switches-off-the-tutor/
Author: Trevor Rosato
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: adversarial examples,detection,security,steganalysis,vision-language models
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.23
Requires-Dist: pillow>=9.1
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Requires-Dist: scikit-learn>=1.2; extra == 'dev'
Provides-Extra: fit
Requires-Dist: scikit-learn>=1.2; extra == 'fit'
Provides-Extra: probe
Requires-Dist: torch>=2.1; extra == 'probe'
Requires-Dist: transformers>=4.45; extra == 'probe'
Description-Content-Type: text/markdown

# steerscan

Detect adversarially optimized "steering" images before they reach a vision-language model.

A steering image is an input image optimized by gradient descent so that a vision-language model
ignores its instructions. In the study this package comes from, one such image made a tutor model
give out final answers it had been told to withhold. steerscan scores an image for this kind of
optimization before the model sees it. It never changes the image you pass to the model.

It has two tiers:

- **`steerscan.pixel` (tier B)** is the main detector. It works from the image bytes alone, on CPU,
  in about 35 ms for a 448 px image. The only dependencies are numpy and Pillow. It works with any
  model, including hosted APIs.
- **`steerscan.probe` (tier A)** is a linear probe on hidden states that an open-weight model already
  computes during prefill. It is for deployers who serve the model themselves. torch and
  transformers are optional extras.

steerscan accompanies the research article [The picture that switches off the
tutor](https://research.honorlyai.com/the-picture-that-switches-off-the-tutor/) on image-space attacks against
tutor-prompted VLMs. It
adapts published detection methods (see [Prior work](#prior-work)). We found no maintained
open-source detector for this threat that we could fork.

> **Status: research release (0.1.0).** The thresholds were calibrated on public datasets, not on
> real user uploads. Recalibrate on your own traffic and run in shadow or review mode before
> blocking anything. A score is not evidence of misconduct.

## Install

```bash
pip install "git+https://github.com/trevor050/steerscan"            # pixel detector: numpy + Pillow
pip install "steerscan[probe] @ git+https://github.com/trevor050/steerscan"  # + torch, transformers
pip install "steerscan[fit] @ git+https://github.com/trevor050/steerscan"    # + scikit-learn
```

Python 3.10 or newer.

## Quick start

```python
import steerscan

result = steerscan.scan("upload.png", fpr=0.001)  # path, bytes, or a PIL image
result.score  # float, higher is more attack-like
result.threshold  # threshold for the chosen false-positive rate
result.flagged  # score > threshold

steerscan.score(image_bytes)  # just the score
steerscan.scan(pil_image, variants=True).variant_scores
# {'raw': 27.26, 'jpeg95': 11.75, 'jpeg85': 12.02}
```

The input is never modified. The detector scores a private copy, which it resizes to 448x448 to
match the data the shipped model was fitted on. Pass the original image to your model as usual.

### Command line

```console
$ steerscan scan tests/assets/
FLAG   score    27.11  threshold   3.27  tests/assets/A3_seed0.png
FLAG   score    25.97  threshold   3.27  tests/assets/A5_A3_seed0.png
FLAG   score    27.26  threshold   3.27  tests/assets/Q38_A3_onpol_seed0.png
ok     score     1.64  threshold   3.27  tests/assets/worksheet.png
4 file(s), 3 flagged at FPR 0.001, 0 error(s)
$ echo $?
1
```

`steerscan scan` accepts files and directories. It exits with 0 when nothing is flagged, 1 when
anything is flagged and 2 on errors, so you can use it as a CI gate. Options:

- `--fpr 0.01` uses the 1% operating point.
- `--json` prints machine-readable output.
- `--variants` also reports the scores of JPEG re-encodes.
- `--weights model.json` loads a recalibrated model.

`steerscan info` prints the model's provenance and thresholds.

## What it detects, and what it does not

**Detects:** images whose pixels were optimized by gradient descent against a VLM. These images
carry dense, high-frequency structure that does not occur in photographs, scans, handwriting or
figures. The detector looks for it in high-pass residuals, chroma noise, the FFT band energy
profile and JPEG recompression error. Unconstrained ("free") attack images were caught every time
in our evaluation, including after JPEG re-encoding. That held for an attack on a different,
larger model that was never used in fitting, and for an attack optimized to evade the activation
probe.

**Partly misses:** budgeted perturbations, which are small (L-infinity 8 to 32 out of 255), applied
to a real cover image and trained to survive JPEG and resizing. The pixel detector flags about half
of them in raw form at 0.1% false positives and almost none after JPEG re-encoding (table below).
In the study these images were also the weaker attacks: on the small model they added little over
the clean cover photo, and on the larger model the budgeted attack failed outright. Even so, this
gap is real.

**Does not detect:**

- Typographic injection: instructions written visibly in the image. These are natural images. Use
  an OCR-based scanner for them (see [Related tools](#related-tools)).
- The effect of ordinary images. In the study, ordinary photos and worksheets already weakened the
  small model's system-prompt rule. That is model behavior, not an attack, and no input detector
  can flag it.
- Attacks built by an adversary who optimizes against the pixel detector itself. This was not
  tested. The activation probe failed under exactly that test, so assume the pixel detector can
  also be evaded by an attacker who targets it.
- Steganographic payloads and other hidden-data channels. These are a different threat.

## Measured performance

### Protocol

- **Benign corpus:** 8,409 images from MathVista (3,994), IAM handwriting lines (2,915) and
  COCO (1,500). Cover images used for budgeted attacks were excluded. 30% of the files were also
  included as JPEG-95 and JPEG-85 re-encodes, so that the detector cannot key on "was
  JPEG-compressed".
- **Size control:** the attack images are all 448x448. To keep the detector from learning image
  size, every benign image was resized to 448x448 before feature extraction (the shipped model).
  The study's first, native-size fit is reported for comparison.
- **Split:** benign images were split by source file into thirds (train, calibration and test) with
  `numpy.random.RandomState(0)`. The classifier is fitted on benign-train plus attacks. The
  threshold is the `1 - FPR` quantile of benign-calibration scores. False-positive rates are
  measured on benign-test.
- **Attacks:** 16 images from the study, all targeting Qwen/Qwen3.5-4B with a generic tutor
  prompt. 8 are free (unconstrained pixels). 8 are budgeted (L-infinity 8, 16 or 32 out of 255 on
  a worksheet photo or a MathVista cover, trained through JPEG and resampling). Each attack is
  scored raw and as JPEG-95 and JPEG-85 re-encodes.
- **Leave-one-attack-out (LOAO):** for each attack image, the classifier is refitted without that
  image, and the held-out image's three variants are scored.

### Pixel detector (tier B), leave-one-attack-out

TPR is the fraction of attack images flagged.

| | target FPR | benign-test FPR | TPR raw: all / free / budgeted | TPR JPEG-95: all / free / budgeted | TPR JPEG-85: all / free / budgeted |
|---|---|---|---|---|---|
| shipped (size-controlled, 16 attacks) | 0.1% | 0.02% (max 0.13%) | 0.75 / 1.00 / 0.50 | 0.56 / 1.00 / 0.12 | 0.50 / 1.00 / 0.00 |
| shipped (size-controlled, 16 attacks) | 1% | 1.19% (max 1.34%) | 0.88 / 1.00 / 0.75 | 0.75 / 1.00 / 0.50 | 0.75 / 1.00 / 0.50 |
| native-size fit (15 attacks) | 0.1% | 0.10% (max 0.20%) | 0.73 / 1.00 / 0.43 | 0.53 / 1.00 / 0.00 | 0.53 / 1.00 / 0.00 |
| native-size fit (15 attacks) | 1% | 0.95% (max 1.05%) | 0.93 / 1.00 / 0.86 | 0.67 / 1.00 / 0.29 | 0.67 / 1.00 / 0.29 |

The "benign-test FPR" column is the mean over the 16 (or 15) LOAO fits; "max" is the largest
single fit. The final shipped model, fitted on all 16 attacks, has thresholds of 3.27 (0.1%) and
1.04 (1%). It flags 0 of 4,465 benign-test rows at 0.1% and 1.21% at 1%.

### Images never used in fitting

Scores from the shipped model; the 0.1% threshold is 3.27 and the 1% threshold is 1.04.

| image | raw | JPEG-95 | JPEG-85 |
|---|---|---|---|
| free attack on Qwen3.8-27B, a different and larger model (`Q38_A3_onpol_seed0`) | **27.26** | **11.75** | **12.02** |
| budgeted attack on Qwen3.8-27B (the attack itself failed) | **6.18** | 2.35 | 1.65 |
| free attack optimized to evade the activation probe (`A5_A3_seed0`) | **25.97** | **12.83** | **12.78** |
| budgeted attack optimized to evade the activation probe | **5.76** | 2.50 | 1.62 |
| clean worksheet photo (`worksheet.png`) | 1.64 | -0.70 | -1.15 |

Bold means flagged at 0.1%. The clean worksheet is a false positive at the 1% operating point.

### Activation probe (tier A), Qwen/Qwen3.5-4B

The probe reads the last prompt token at layers 8, 12, 16, 20, 24 and 28. Features pass through a
StandardScaler, then PCA to 128 dimensions, then logistic regression; the three steps are composed
into a single linear map. The same split and size control were used, with 3,000 benign images (one
prompt each) and 8 prompts per attack variant.

| target FPR | benign-test FPR | TPR raw: all / free / budgeted | TPR JPEG-95 | TPR JPEG-85 |
|---|---|---|---|---|
| 0.1% | 0.09% | 0.75 / 0.84 / 0.66 | 0.73 | 0.70 |
| 1% | 1.34% | 0.92 / 1.00 / 0.84 | 0.94 | 0.93 |

**The probe alone is not a defense against an adaptive attacker.** An attack optimized against it
(A5) went undetected on 0 of 24 held-out prompts, while it still broke the tutor's rule as often
as the non-adaptive attack. The pixel detector still caught that image: in the study it scored
26.4 against a threshold of 3.2 (native-size fit), and it scores 25.97 against 3.27 under the
shipped model. Use the probe as a second signal next to the pixel detector, not on its own.

### Baseline: CrossGuard

[CrossGuard](https://github.com/crossguard-ai/crossguard-py) (commit `4613715`) includes a
bytes-only, non-mutating anomaly score (`crossguard/detect.py`). The score is a noisy-OR of three
fixed sub-scores: a median-filter residual, an LSB chi-square test and high-pass energy. Nothing in
it is trained. We scored the same benign calibration and test rows, rebuilt from the original
images, and the same attack variants. CrossGuard got the same treatment as steerscan: thresholds
at quantiles of benign-calibration scores. For CrossGuard we used its raw ensemble score, because
the public API rounds to 4 decimals.

| detector | target FPR | benign-test FPR | TPR free (raw / JPEG-95 / JPEG-85) | TPR budgeted (raw / JPEG-95 / JPEG-85) |
|---|---|---|---|---|
| steerscan (LOAO) | 0.1% | 0.02% | 1.00 / 1.00 / 1.00 | **0.50** / **0.12** / 0.00 |
| CrossGuard | 0.1% | 0.02% | 1.00 / 1.00 / 1.00 | 0.00 / 0.00 / 0.00 |
| steerscan (LOAO) | 1% | 1.19% | 1.00 / 1.00 / 1.00 | **0.75** / **0.50** / **0.50** |
| CrossGuard | 1% | 0.96% | 1.00 / 1.00 / 1.00 | 0.00 / 0.00 / 0.00 |
| CrossGuard, default threshold 0.5 | n/a | 1.32% | 1.00 / 1.00 / 1.00 | 0.00 / 0.00 / 0.00 |

On the held-out images, both detectors flag the free Qwen3.8-27B attack and the probe-evading free
attack in every variant at 0.1%. On the two held-out budgeted attacks, steerscan flags the raw
image at 0.1% and every variant at 1%. CrossGuard flags none of them at either target.

Both detectors catch every free attack, and CrossGuard does so without any training. It scores
these images at 0.99 or higher, mostly through its median-residual pass. steerscan's advantage is entirely on
budgeted perturbations, where CrossGuard's scores (0.02 to 0.14) are indistinguishable from clean
images (benign median 0.035, 99th percentile 0.62). One caveat favors steerscan: even under LOAO it
was trained on other attacks from this study, including images made with the same recipe as the
held-out one, while CrossGuard has seen none of them. The rebuilt benign rows were spot-checked
against the study's archived features on every 50th file. The largest relative deviation was
8e-2, and in the files we inspected such deviations were on features whose value is near zero.
Reproduce with
`benchmarks/crossguard_baseline.py`. The full output is in
`benchmarks/results/crossguard_vs_steerscan.json`.

### Latency

`PixelDetector.score(bytes)` end to end (decode, resize to 448x448, features, logit). Single
thread on an Apple M1 (8 GB RAM), Python 3.12, numpy 2.5, Pillow 13. 50 timed runs after warm-up.
The uploads are the clean worksheet rescaled to each size.

| upload | file size | decode p50 (ms) | `score()` p50 (ms) | `score()` p95 (ms) | `scan(variants=True)` p50 (ms) |
|---|---|---|---|---|---|
| 448 px PNG | 325 KiB | 3.5 | 39.3 | 41.9 | 110.6 |
| 448 px JPEG | 45 KiB | 0.6 | 33.3 | 33.7 | 103.6 |
| 1024 px PNG | 1118 KiB | 15.7 | 62.0 | 64.8 | 133.9 |
| 1024 px JPEG | 149 KiB | 2.3 | 47.4 | 48.3 | 118.5 |
| 2048 px PNG | 2882 KiB | 59.5 | 129.8 | 162.0 | 206.6 |
| 2048 px JPEG | 417 KiB | 8.5 | 80.6 | 81.5 | 155.1 |

Peak resident memory for the whole benchmark process was 116 MB. Reproduce with
`python scripts/benchmark.py`. The probe adds one dot product of length 15,360 to a prefill you
already run.

## Limits

- **Calibrated on public data, not on your users.** The benign corpus is MathVista, IAM and COCO.
  Real uploads differ: phone photos of paper, screenshots, scans, heavy compression and unusual
  devices. Your false-positive rate will differ from the numbers above. Recalibrate before relying
  on any threshold (next section).
- **Small attack set.** 16 attack images from one study, mostly against one model. Leave-one-out is
  per image, not per attack recipe, and images from the same recipe resemble each other. TPR on a
  new attack recipe can be lower.
- **Budgeted, JPEG-robust perturbations are partly missed**, as shown above.
- **The tail is coarsely measured.** 0.1% of about 4,500 benign-test rows is about 4 images, and
  rows from JPEG variants of the same file are correlated. Treat the 0.1% numbers as provisional.
- **No adaptive test against the pixel detector.** An attacker who knows the features can
  probably evade them. The activation probe was evaded completely under that test.
- **Size dependence.** The shipped model resizes every input to 448x448 because the attacks in the
  study were that size. Attacks optimized at other resolutions are untested.
- **Shadow mode first.** Log scores and review flagged items. Do not block uploads or take action
  against users until you have measured false positives on your own traffic.
- **A score is not evidence of misconduct.** Clean images can score high, and a flagged image may
  not have been made, or knowingly sent, by the person who uploaded it.

## Recalibrate on your own traffic

The model weights stay fixed. Recalibration only moves the thresholds, setting them to quantiles
of the scores of your own clean images.

```console
$ steerscan recalibrate ./clean_uploads/ -o steerscan-local.json --source "2026-12 uploads, reviewed"
$ steerscan scan --weights steerscan-local.json new_upload.jpg
```

```python
from steerscan import PixelDetector, recalibrate

det = recalibrate(list_of_clean_images, fprs=(0.001, 0.01), source="December uploads")
det.save("steerscan-local.json")
det = PixelDetector.from_file("steerscan-local.json")
```

Use images that are representative of normal traffic and that you have reviewed as clean. Do not
reuse them for anything else. A threshold at false-positive rate `f` needs well over `1 / f`
images: aim for 10,000 or more at 0.1%. steerscan warns below `10 / f`. If you have attack examples
of your own, refit the classifier with `steerscan.fit.fit_pixel`.

## Activation probe (open-weight deployments)

The probe reads hidden states from the prefill you already run to generate the reply, so it adds
no extra forward pass.

```python
from steerscan.probe import LinearProbe, LastTokenRecorder, last_token_features

probe = LinearProbe.qwen35_4b()  # reference weights; refit for your prompt and traffic

# Option 1: hidden states from the prefill forward (left padding, so the last token is -1)
out = model(**inputs, output_hidden_states=True)
result = probe.scan(last_token_features(out.hidden_states, probe.layers))

# Option 2: forward hooks during generate(); only the prefill pass is recorded
with LastTokenRecorder(model, probe.layers) as rec:
    reply = model.generate(**inputs, max_new_tokens=512)
result = probe.scan(rec.features())
```

`hidden_states[l + 1]` is the output of decoder layer `l`. With right padding, pass
`token_index=attention_mask.sum(1) - 1`.

The shipped probe was fitted on Qwen/Qwen3.5-4B in bf16 with a generic math-tutor system prompt.
Its scores depend on the model, the layers, the prompt template and the traffic, so fit your own:

```python
from steerscan.fit import fit_probe

model_json = fit_probe(X_train, y_train, X_benign_calibration, layers=[8, 12, 16, 20, 24, 28], model="your/model")
probe = LinearProbe(model_json)
```

`fit_probe` fits a scaler, PCA and logistic regression, composes them into one linear map, and sets
thresholds from held-out benign features.

## Reproducing the numbers

The pixel-tier feature archive, the benign-corpus manifest (with a script that rebuilds the corpus
from the public datasets), the problems, student messages and tutor prompts are in [`eval/`](eval/).
The native-size and activation-probe archives are not included.

```bash
pip install -e ".[fit]"
python scripts/fit_pixel.py eval/tierb_sq.npz --out src/steerscan/weights/pixel_v1.json   # shipped model + LOAO
python scripts/fit_pixel.py tierb.npz --native --eval-only                           # native-size fit
python scripts/fit_probe_study.py tiera_sq.npz probe_w.npy probe_meta.json --loao    # tier A
python benchmarks/crossguard_baseline.py --help                                      # baseline comparison
python scripts/benchmark.py                                                          # latency
```

The feature extractor matches the study's scipy-based extractor to within float32 rounding. A
test checks it against the study's own feature rows.

## Prior work

steerscan adapts published methods.

- **Spatial rich models**: J. Fridrich and J. Kodovský, "Rich Models for Steganalysis of Digital
  Images", IEEE TIFS 2012. The high-pass residual kernels and residual statistics come from this
  line of steganalysis.
- **SpectralDefense**: P. Harder et al., "SpectralDefense: Detecting Adversarial Attacks on CNNs
  in the Fourier Domain", IJCNN 2021. The source of the FFT magnitude features.
- **Feature Squeezing**: W. Xu, D. Evans and Y. Qi, "Feature Squeezing: Detecting Adversarial
  Examples in Deep Neural Networks", NDSS 2018. steerscan's JPEG recompression error borrows the
  idea of comparing an input with a squeezed copy.
- **Learning to Detect (LoD)**: arXiv:2508.09201. Layerwise linear readouts on the final input
  token for detecting multimodal attacks.
- **JRS-Rem**: arXiv:2603.17372. Directions in last-token activations that separate jailbreak
  images from benign ones.

The activation probe follows the last two in reading the last prompt token at several layers. It
replaces their detectors with a single regularized linear map.

## Related tools

- [CrossGuard](https://github.com/crossguard-ai/crossguard-py) (MIT): bytes-only, non-mutating anomaly score for steganographic and adversarial images; the baseline above.
- [VIPI](https://github.com/EnXan/VIPI) (Apache-2.0): OCR-based scanner for readable instructions injected into images. Complementary to steerscan, which does not cover typographic text.
- [IBM Adversarial Robustness Toolbox](https://github.com/Trusted-AI/adversarial-robustness-toolbox) (MIT): attacks, defenses and detectors, mostly oriented to image classifiers.
- [Sealwatch](https://github.com/uibk-uncover/sealwatch) (MPL-2.0) and [Aletheia](https://github.com/daniellerch/aletheia) (MIT): steganalysis toolkits with rich-model features, the family the residual features come from.
- NEARSIDE ([arXiv:2410.22888](https://arxiv.org/abs/2410.22888)), [LoD](https://github.com/ShuangLiangX/Learning-to-Detect) and [RCS](https://github.com/sarendis56/Jailbreak_Detection_RCS): research activation-space detectors for VLM attacks, related to the probe tier.

## Citation

See [`CITATION.cff`](CITATION.cff).

## License

Apache-2.0. See [`LICENSE`](LICENSE).
