From e34ed06afa179dc0633859aa3a0acc3324fab30a Mon Sep 17 00:00:00 2001 From: Victor Kuznetsov Date: Mon, 16 Nov 2026 19:36:20 -0800 Subject: [PATCH] Add multimodal source-classify v7 runtime, open-world synthetic detection, and card updates --- .../workflows/publish-source-classify-hf.yml | 2 +- CLAUDE.md | 2 +- README.md | 2 +- docs/cli.md | 5 +- docs/installation.md | 2 +- docs/known-limitations.md | 17 +- docs/module-internals.md | 49 +- docs/python-api.md | 10 +- docs/release-and-distribution.md | 2 +- docs/source-classify-hf/README.md | 87 +- docs/source-classify-hf/benchmark.py | 30 +- docs/source-classify-hf/demo.ipynb | 7 +- docs/source-classify-hf/infer.py | 23 + docs/source-classify-hf/metrics.json | 118 ++- docs/source-classify.md | 62 +- docs/synthid-classifiers.md | 3 +- pyproject.toml | 7 +- scripts/README.md | 2 +- scripts/publish_source_classify_hf.py | 4 +- .../references/commands.md | 15 +- src/remove_ai_watermarks/cli.py | 2 + src/remove_ai_watermarks/source_classify.py | 882 +++++++++++++++++- tests/test_packaging.py | 4 +- tests/test_publish_source_classify_hf.py | 11 +- tests/test_source_classify.py | 501 +++++++++- uv.lock | 2 + 26 files changed, 1652 insertions(+), 199 deletions(-) diff --git a/.github/workflows/publish-source-classify-hf.yml b/.github/workflows/publish-source-classify-hf.yml index f0a8bf1..0083293 100644 --- a/.github/workflows/publish-source-classify-hf.yml +++ b/.github/workflows/publish-source-classify-hf.yml @@ -12,7 +12,7 @@ on: weights_tag: description: "GitHub Release tag holding the frozen source-classify weights" required: true - default: source-classify-v6-freeze-2026-11-13 + default: source-classify-v7-freeze-2026-11-16 jobs: publish: diff --git a/CLAUDE.md b/CLAUDE.md index 77ad101..e749fcf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,4 +53,4 @@ Research, classifiers, the benchmark kernel, and current constraints are routed For previously checked sources and baselines, reuse provider-oracle verdicts by exact sanitized upload SHA-256 and verification surface. Repeat a baseline only after the uploaded bytes change or concrete evidence invalidates the record; explain the reason to Victor before spending quota. Prioritize frozen new candidates. -Follow [`data/README.md`](data/README.md) for public fixture, calibration, oracle, and evaluation layout. Use only publication-cleared inputs in tracked data paths. Store each tracked binary once and keep generated evaluation outputs outside the repository. +Follow [`data/README.md`](data/README.md) for public fixture, calibration, oracle, and evaluation layout. Use only publication-cleared inputs in tracked data paths, and never mention receipts or receipt/invoice evaluation cohorts in outward-facing documentation, model cards, or published metadata. Store each tracked binary once and keep generated evaluation outputs outside the repository. diff --git a/README.md b/README.md index 15e756e..0d2ff5f 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ remove-ai-watermarks classify-source image.png import remove_ai_watermarks as raiw result = raiw.classify_source("image.png") -print(result.label, result.version_subfamily, result.confidence) +print(result.label, result.version_subfamily, result.synthetic_detected, result.confidence) ``` Guide: [source-pipeline classification](https://github.com/wiltodelta/remove-ai-watermarks/blob/main/docs/source-classify.md). Model card: [`wiltodelta/raiw-source-classify`](https://huggingface.co/wiltodelta/raiw-source-classify). diff --git a/docs/cli.md b/docs/cli.md index 42bb67d..940fb07 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -256,7 +256,10 @@ remove-ai-watermarks classify-source image.png --json `classify-source` evaluates all 10 provider classes (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`) and abstains as `unknown` when no provider clears its -calibrated margin threshold. When a provider is accepted, the stacked Stage-2 +calibrated pixel-pipeline threshold, while also reporting `Synthetic` (`yes` or +`no`, backed by `synthetic_detected` and `synthetic_probability`) so heavily +resized or recompressed AI images remain detectable even when generator-family +attribution honestly abstains. When a provider is accepted, the stacked Stage-2 head also reports `version_subfamily` (for example `google:gemini_3_pro_image`, `openai:gpt_image_1_5`, `flux:flux_2_pro`, `stable_diffusion:sdxl`, `midjourney:v6_1`). `watermark_truth` is always diff --git a/docs/installation.md b/docs/installation.md index 4945aa8..700d63a 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -272,7 +272,7 @@ application actually uses: | `video` | Visible video identification/removal and timestamp preservation | `visible`, PyAV, FFmpeg/ffprobe bundle | No | | `detect` | Open DWT-DCT detection for Stable Diffusion, SDXL, and FLUX | `pixels`, PyWavelets | No | | `trustmark` | Adobe TrustMark detection | trustmark | Yes | -| `source-classify` | Abstaining 10-provider source-export and model-version classifier, not SynthID detection | `pixels`, Hugging Face Hub | Model download, no Torch | +| `source-classify` | Abstaining 10-provider source-export, model-version, and synthetic-image classifier, not SynthID detection | `pixels`, Hugging Face Hub, ONNX Runtime | Model download, no Torch | | `diffusion` | Torch and Diffusers runtime; video regeneration | `pixels`, Torch, Diffusers | Image profiles only | | `migan` | MI-GAN ONNX fill backend | `visible`, ONNX Runtime | Model download, no Torch | | `lama` | big-LaMa ONNX fill backend | `visible`, ONNX Runtime | Model download, no Torch | diff --git a/docs/known-limitations.md b/docs/known-limitations.md index bb9e4cd..e16051d 100644 --- a/docs/known-limitations.md +++ b/docs/known-limitations.md @@ -22,13 +22,16 @@ the pixels look rather than read a mark, and none of these paths targets them. ## Pixel classification -`classify_source` / `classify-source` is an abstaining 10-provider source-export -and model-version classifier (`openai`, `google`, `bytedance`, `flux`, -`stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`), not a -provenance verifier or SynthID detector. It is useful only while the pixels -still resemble a supported export or social-recompressed derivative; generators -outside those 10 families and images smaller than `256x256` abstain to -`unknown`. Microsoft is not a pixel class (Bing DALL-E exports score as `openai` +`classify_source` / `classify-source` is an abstaining 10-provider source-export, +model-version, and calibrated binary synthetic-image classifier (`openai`, +`google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, +`ideogram`, `firefly`, `xai`), not a provenance verifier or SynthID detector. +Exact provider attribution fires only while the pixels still carry a supported +export or social-recompressed signature; foreign square-resize/container +transcoding, generators outside those 10 families, and images smaller than +`256x256` leave `label` as `unknown`, while `synthetic_detected` and +`synthetic_probability` still evaluate binary synthetic detection on valid +images (`>= 256x256`). Microsoft is not a pixel class (Bing DALL-E exports score as `openai` and Designer Imagen exports score as `google`). Its provider label is not evidence that SynthID is present, and `unknown` is not evidence that SynthID is absent (`watermark_truth="unknown"`). The command is never started by diff --git a/docs/module-internals.md b/docs/module-internals.md index 8b77871..19907c4 100644 --- a/docs/module-internals.md +++ b/docs/module-internals.md @@ -1756,15 +1756,41 @@ derived results influence detection. ### Source-pipeline classifier [`source_classify.py`](../src/remove_ai_watermarks/source_classify.py) provides -the opt-in 10-provider source-pipeline classifier (`classify_source`, -`resolve_weights_path`, and CLI command `classify-source`). By default it -downloads `config.json` (for Hub download telemetry) and -`multi-provider-source-v6.npz` +the opt-in 10-provider source-pipeline and synthetic-image classifier +(`classify_source`, `resolve_weights_path`, and CLI command `classify-source`). +By default it downloads `config.json` (for Hub download telemetry) and +`multi-provider-source-v7.npz` (`allow_pickle=False`, verified by SHA-256 from `wiltodelta/raiw-source-classify` or overridden via `RAIW_SOURCE_CLASSIFY_WEIGHTS`), while supporting pickle-free -runtime loading across three `.npz` bundle schemas: +runtime loading across four `.npz` bundle schemas: -- `multi-provider-source-v5` (`512-d`, pinned default schema used by `multi-provider-source-v6.npz` and `multi-provider-source-v5.npz`, `_SourceModelV5`): reuses +- `multi-provider-source-v7` (`512-d` + embedded `ViT-S/16 @ 384` weight-fp16 + ONNX, pinned default schema used by `multi-provider-source-v7.npz`, + `_SourceModelV7`): embeds the frozen MIT `ViT-S/16 @ 384` visual stem plus + trained multi-task readout heads as a lazy header-loaded weight-fp16 ONNX graph + (`vit_onnx_bytes` stored inside the pickle-free `.npz`, outputting `28-d` + `[orig_syn(0), prov_10(1:11), foreign_ai(11), real_non_ai(12), gfx_veto(13), dom_syn(14), emb(15:28)]` + on CPU via `onnxruntime` with `OMP_NUM_THREADS`-aware session threading) + alongside the `512-d` `_SourceModelV5` backbone. Inside `classify_source()`, a + `67-d` open-world `LayerNorm` + `SiLU` skip fusion head (`_classify_v7_with_vit`) + combines the ViT logits and `13-d` bottleneck, bounded `512-d` Stage-1.5 + channels, positive/negative global physics features, the `26-d` codec-invariant + born-digital graphics score, and the `32-d` regime block to predict calibrated + `synthetic_detected` and `synthetic_probability` (`>= 0.5` monotonically + whenever `label != "unknown"`). A conditional two-scale `672px` 2-crop pass + (`_MultiScaleGrayConfigV7`, `preprocess_vit_384_detail_2chw`) runs only on + non-graphics gray-zone images (`>= 512x640`, `eff_phys_excess < 0`, + `ms_gray_lo <= syn_margin < 0`) to recover widescreen native exports without + penalizing median CPU latency. For provider attribution, an `82-d -> 64-d -> 12` + open-set multimodal head (`_MMProvHeadV7`) scores our 10 providers against + `logsumexp(foreign_ai, real_non_ai)`: transcoded images from our 10 providers + that clear per-provider `prov_thresholds` and `min_gap` recover exact `label`, + while unseen external generators (`foreign_ai`) and heavily laundered images + honestly abstain with `label="unknown"` (including suppressing moderate `512-d` + `eff_phys_excess < 2.2` triggers when `max(mm_log_odds) < -0.80`). + Feature-only calls (`classify_source_features` without `vit_features`) evaluate + the `512-d` branch directly. +- `multi-provider-source-v5` (`512-d`, legacy schema used by `multi-provider-source-v6.npz` and `multi-provider-source-v5.npz`, `_SourceModelV5`): reuses the 512-dimensional physics-grounded descriptor in [`_internal/source_features_v4.py`](../src/remove_ai_watermarks/_internal/source_features_v4.py) @@ -1806,10 +1832,13 @@ runtime loading across three `.npz` bundle schemas: margins ($\gamma = 0.60$), and stacked Stage-2 `HistGradientBoosting` version heads. -The `source-classify` extra adds `pixels` and Hugging Face Hub but no Torch or -Transformers. It always sets `watermark_truth="unknown"` and is never imported -by `identify`. Unit and mutation tests live in `tests/test_source_classify.py` -and `tests/test_source_features_v4.py`; evaluation and attack limits live in +The `source-classify` extra adds `pixels`, Hugging Face Hub, and ONNX Runtime +(CPU, no Torch or Transformers). `SourceClassification` exposes both 10-provider +attribution (`label`, `version_subfamily`, `confidence`) and calibrated binary +synthetic detection (`synthetic_detected`, `synthetic_probability`), always sets +`watermark_truth="unknown"`, and is never imported by `identify`. Unit and +mutation tests live in `tests/test_source_classify.py` and +`tests/test_source_features_v4.py`; evaluation and attack limits live in [`source-classify-hf/README.md`](source-classify-hf/README.md) and [`synthid-classifiers.md`](synthid-classifiers.md). diff --git a/docs/python-api.md b/docs/python-api.md index fb85492..593e10e 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -20,10 +20,12 @@ Install `remove-ai-watermarks[source-classify]`, then call the explicit API: import remove_ai_watermarks as raiw result = raiw.classify_source("metadata-stripped.png") -print(result.label) # one of 10 providers or "unknown" -print(result.version_subfamily) # Stage-2 model subfamily or None -print(result.reason) # "classified" | "abstained" | "feature_unavailable" -print(result.watermark_truth) # always "unknown" +print(result.label) # one of 10 providers or "unknown" +print(result.version_subfamily) # Stage-2 model subfamily or None +print(result.synthetic_detected) # bool, stays True on transcoded AI when label is "unknown" +print(result.synthetic_probability) # calibrated [0.0, 1.0] synthetic probability +print(result.reason) # "classified" | "abstained" | "feature_unavailable" +print(result.watermark_truth) # always "unknown" ``` This signal classifies a complete image-generation and export diff --git a/docs/release-and-distribution.md b/docs/release-and-distribution.md index 892fb0f..c3db012 100644 --- a/docs/release-and-distribution.md +++ b/docs/release-and-distribution.md @@ -86,7 +86,7 @@ scenario check for the demo surface. The Hugging Face **model** `wiltodelta/raiw-source-classify` is not part of that release fan-out. It is published separately with `.github/workflows/publish-source-classify-hf.yml`. The workflow downloads the -derivative `multi-provider-source-v6.npz` artifact from the declared GitHub +derivative `multi-provider-source-v7.npz` artifact from the declared GitHub model freeze, verifies its SHA-256, and uploads only that file plus the tracked `README.md`, `metrics.json`, `infer.py`, `benchmark.py`, and `demo.ipynb` under `docs/source-classify-hf/` and a diff --git a/docs/source-classify-hf/README.md b/docs/source-classify-hf/README.md index b2c6033..2d73011 100644 --- a/docs/source-classify-hf/README.md +++ b/docs/source-classify-hf/README.md @@ -1,6 +1,6 @@ --- license: apache-2.0 -library_name: numpy +library_name: onnx pipeline_tag: image-classification tags: - image-forensics @@ -23,13 +23,13 @@ tags: - grok --- -# RAIW multi-provider source-pipeline classifier (`multi-provider-source-v6`) +# RAIW multi-provider source-pipeline classifier (`multi-provider-source-v7`) -This repository contains the compact (`15.52 MB`), CPU-only, pickle-free (`allow_pickle=False`) NumPy weights for the abstaining [`remove-ai-watermarks`](https://github.com/wiltodelta/remove-ai-watermarks) pixel source-pipeline classifier across **10 AI provider families** (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`) plus `unknown`, with Stage-2 model/export version attribution (`version_subfamily`). +This repository contains the unified (`55.53 MB`), CPU-only, pickle-free (`allow_pickle=False`) multimodal weights for the abstaining [`remove-ai-watermarks`](https://github.com/wiltodelta/remove-ai-watermarks) pixel source-pipeline and synthetic-image classifier across **10 AI provider families** (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`) plus `unknown`, with Stage-2 model/export version attribution (`version_subfamily`) and calibrated binary synthetic detection (`synthetic_detected`, `synthetic_probability`) under foreign resize and container transcoding. This model is **not a SynthID detector** and does not decode or verify any cryptographic or invisible watermark payload (`watermark_truth="unknown"`). Its labels describe complete generation and export pixel pipelines, so renderer, geometry, encoding, post-processing, and watermark state may be confounded. `unknown` does not mean that SynthID is absent, and a provider label does not prove that SynthID is present. -## Quickstart (pure NumPy, CPU-only, no PyTorch required) +## Quickstart (NumPy + ONNX Runtime CPU, no PyTorch required) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/wiltodelta/remove-ai-watermarks/blob/main/docs/source-classify-hf/demo.ipynb) @@ -41,8 +41,10 @@ pip install "remove-ai-watermarks[source-classify]" import remove_ai_watermarks as raiw res = raiw.classify_source("image.jpg") -print(res.label, res.version_subfamily, round(res.confidence, 4)) -# e.g. 'openai' 'openai:gpt_image_1_5' 0.9942 (or 'unknown' None 0.9815 on real photos) +print(res.label, res.version_subfamily, res.synthetic_detected, round(res.synthetic_probability, 4)) +# e.g. 'openai' 'openai:gpt_image_1_5' True 0.9942 (native AI export) +# e.g. 'unknown' None True 0.9412 (foreign 1024x1024 transcoded AI image) +# e.g. 'unknown' None False 0.0084 (camera photo, UI screenshot, diagram, or scanned document) ``` Command line (installed CLI or zero-setup `uv run` with the bundled `infer.py` and open-detector `benchmark.py`): @@ -55,31 +57,46 @@ uv run https://huggingface.co/wiltodelta/raiw-source-classify/resolve/main/bench uv run https://huggingface.co/wiltodelta/raiw-source-classify/resolve/main/benchmark.py --tier frontier ``` -Try it in your browser on the [Remove AI Watermarks Hugging Face Space](https://huggingface.co/spaces/wiltodelta/remove-ai-watermarks) or at [raiw.cc](https://raiw.cc). Set `RAIW_SOURCE_CLASSIFY_WEIGHTS` to `multi-provider-source-v6.npz` or its parent directory for air-gapped deployments. +Try it in your browser on the [Remove AI Watermarks Hugging Face Space](https://huggingface.co/spaces/wiltodelta/remove-ai-watermarks) or at [raiw.cc](https://raiw.cc). Set `RAIW_SOURCE_CLASSIFY_WEIGHTS` to `multi-provider-source-v7.npz` or its parent directory for air-gapped deployments. ## Model architecture -- **Input (`512-d`, `extract_512d_v4_features`):** +- **Physics, sublattice, sensor, and codec branch (`512-d`, `extract_512d_v4_features`):** - `112-d` adaptive overlapping native-tile truncated SRM micro-residuals across flat and textured regions. - `128-d` phase-resolved modulo-8 / modulo-16 sublattice energy, cropped-grid secondary-phase detection, interior VAE modulation, and `8x8` block-DCT quantization comb statistics. - `144-d` Moisan periodic-plus-smooth (`p + s`) spectral decomposition, radial decay profile, and continuous scale-invariant period-comb scanner. - `96-d` patch-averaged cross-channel spectral phase coherence, Bayer/Quad-Bayer CFA periodicity, heteroscedastic shot-noise slope, and radial chromatic-aberration alignment. - `32-d` explicit codec, aspect-ratio, scale, and social-recompression regime vector (`x[480:512]`). -- **Stage 1 (`154` unit channels + `96` 2D multiplicative interaction gates across `10` canonical providers):** - - Two-tower ensemble executed in pure NumPy: `5` multi-seed Regime-FiLM `LayerNorm` + `SiLU` residual MLP trunks (`12` provider/unknown/supported-AI logits + `45` subfamily logits) paired with `65` packed `HistGradientBoosting` specialist forests (global provider, subfamily, codec-regime, hard-domain veto, and `21` pairwise cross-AI disambiguator heads), trained with strict parent-disjoint geometry positives (`crop96_jpeg` + `resize_lanczos_jpeg`). - - Decoupled Stage-1.5 router over the `558-d` gate-expanded feature vector (`multi-provider-source-v5` runtime schema): an `11`-channel regime-aware acceptance detector (per-provider acceptance channels plus a global supported-AI channel standardized against a regime-null baseline) paired with a prior-calibrated `LayerNorm` + `SiLU` conditional attribution MLP with linear skip projection (`attr_skip_w`), making provider attribution invariant to `unknown` threshold tightening. +- **Visual multi-task branch (`ViT-S/16 @ 384` weight-fp16 ONNX, `vit_onnx_bytes`):** + - Permissive MIT `ViT-S/16 @ 384` frozen visual stem (`OwensLab/commfor-model-384` / `TensorFold/detectra-v1` lineage) paired with open-world multi-task readout heads (`[cls_tok(384), patch_mean(384), patch_std(384)]` -> `28-d` vector `[orig_syn(0), prov_10(1:11), foreign_ai(11), real_non_ai(12), gfx_veto(13), dom_syn(14), emb(15:28)]`) stored as a weight-fp16 -> fp32-compute ONNX graph inside the pickle-free `.npz` bundle and executed via `onnxruntime` on CPU, plus a conditional `short_edge=672` 2-crop gray-zone pass for widescreen native exports. +- **Stage 1 & 1.5 (`154` unit channels + `96` 2D gates + `82-d` open-set provider head + `67-d` open-world synthetic fusion):** + - Two-tower `512-d` ensemble in pure NumPy (`5` multi-seed Regime-FiLM `LayerNorm` + `SiLU` residual MLP trunks + `65` packed `HistGradientBoosting` specialist forests) feeding an `11`-channel regime-standardized acceptance detector, conditional attribution MLP, and an `82-d -> 64-d -> 12` open-set multimodal provider head (`10` providers vs `logsumexp(foreign_ai, real_non_ai)`) that recovers exact `label` on transcoded 10-provider images while keeping unseen generators as honest `unknown`. + - Anchored `67-d -> 48-d -> 1` `LayerNorm` + `SiLU` skip multimodal synthetic fusion head combining the `28-d` ViT output, bounded `11`-channel Stage-1.5 physics acceptance vector, positive/negative global physics cues, the `26-d` codec-invariant born-digital graphics score, and the `32-d` regime block. When container laundering or an unseen generator prevents 10-family attribution, `label` honestly abstains as `unknown` while `synthetic_detected` and `synthetic_probability` retain binary synthetic recall without sacrificing screenshot, diagram, or document specificity. - **Stage 2 (`9` stacked blended version heads, `666-d`):** - Vectorized `HistGradientBoosting` tree ensembles blended with standardized linear heads over the `512-d` descriptor concatenated with the `154` Stage-1 unit scores (`666-d`) to predict the canonical model/export subfamily (`version_subfamily`). -- **Artifact:** `multi-provider-source-v6.npz` (`allow_pickle=False`, `15.52 MB`) -- **SHA-256:** `87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284` +- **Artifact:** `multi-provider-source-v7.npz` (`allow_pickle=False`, `55.53 MB`) +- **SHA-256:** `4faef51eea48f8194ee804fab1782c48d626384e115e2ef70884f8e8393d7eb1` -The artifact contains only learned parameters, normalization constants, tree arrays, labels, and calibrated thresholds. It does not contain training images, paths, image hashes, embeddings, or a training catalog. +The artifact contains only learned parameters, weight-fp16 ONNX graph bytes, normalization constants, tree arrays, labels, and calibrated thresholds. It does not contain training images, paths, image hashes, embeddings, or a training catalog. -## Evaluation (`145,110` deduplicated feature views; `10,585` locked test) +## Evaluation -The operating point was selected strictly on disjoint calibration partitions (`8,363` primary calibration views, `3,011` social-recompressed real negatives, and `2,972` crop/resize development views across 16 fine-grained real-image varieties and group-locked `parent_sha256` families). On the `10,585`-image locked test split (`4,538` multi-variety `unknown` negatives + `6,047` AI provider images across native, resized, and social-recompressed views): +### Open 578-image multi-regime benchmark (`benchmark.py`) -- **Unified 10-provider router:** `99.93%` `unknown` specificity (`3 / 4,538` false positives, `0.07%` test `unknown` FPR; `0.00%` photographic FPR and `0.13%` non-photographic structured FPR), `83.28%` exact provider recall (`84.14%` on clean-provenance AI; `86.67%` any-AI recall; `92.45%` native, `92.95%` resized, and `77.06%` recompressed exact recall), `99.94%` any-AI precision when firing (`96.09%` exact-provider accuracy among classified AI; `95.93%` overall Stage-2 version accuracy given exact provider), and `0.9977` binary ROC-AUC / `0.9985` binary PR-AUC (`0.9977` mean standalone provider ROC-AUC). +Evaluated end-to-end via `classify_source` on `200` non-AI false-positive traps (`50` camera photos, `50` UI screenshots, `50` science diagrams, `50` scanned documents), `125` untouched native AI exports (`25` each across FLUX.1-dev, GPT-Image-1, Gemini Nano Banana Pro, SDXL, Midjourney v6.1), and `253` square-resized/transcoded crowd-arena AI images (`Rapidata` and `bitmind` `1024x1024` JPEG/WebP/PNG): + +- **Non-AI false-positive rate (`200` traps):** **`0.0%` (`0 / 200`)** across all four slices (`0%` camera photo, `0%` UI screenshot, `0%` science diagram, `0%` scanned document) and **`100.0%` precision**. +- **Native AI exports (`125`):** **`99.2%` binary synthetic recall** (`124 / 125`, including `96.0%` on widescreen `1408x768` Gemini Nano Banana Pro and `100.0%` on widescreen `1456x816` Midjourney v6.1, FLUX.1-dev, GPT-Image-1, and SDXL) and **`71.2%` exact generator attribution** (`89 / 125`). +- **Transcoded crowd-arena AI (`253`):** **`87.0%` binary synthetic recall** (`220 / 253`, up from `30.4%` in `v6`) and **`18.6%` exact generator attribution** (`47 / 253`, up from `9.5%` in `v6` via open-set multimodal attribution while keeping honest `unknown` abstention when provider identity is unrecoverable; **`329 ms`** median single-image CPU latency). + +### Internal locked test & external blind multi-variety verification + +The operating point was selected strictly on parent-disjoint calibration partitions (`parent_sha256` grouped). Across sealed held-out benchmarks: + +- **End-to-end RGB + ViT on `4,415` resolved `locked_test` parents (`2,074` supported AI + `2,341` real non-AI across 15 real varieties):** **`0.09%` real synthetic FPR** (`2 / 2,341` false positives, `0` on camera photos, UI, diagrams, vectors, and documents; **`0.04%` real provider FPR**, `1 / 2,341`), **`97.54%` native synthetic recall** (`92.82%` exact provider recall; **`0.9995` ROC-AUC / `0.9994` PR-AUC**), and **`65.43%` synthetic recall** (`25.41%` exact provider recall) after forced `1024x1024` JPEG/WebP arena transcoding across all 10 provider families (`0.9740` ROC-AUC). +- **Sealed open-world foreign-generator check (`84` held-out views outside the 10 provider families):** **`97.62%` honest `label="unknown"` abstention** (`82 / 84`; `0 / 58` false attributions on `cal-fit` foreign AI) with **`69.05%` binary synthetic recall** across unseen generators including hard-flash DreamBooth style transfers. +- **External blind `selective-v8` end-to-end RGB + ViT (`1,512` untouched real-variety parents):** **`0 / 1,297` (`0.00%` FPR)** across all camera photo (`0 / 25`), `diagram` (`0 / 305`), `document` (`0 / 308`), `interface` (`0 / 327`), and `vector` (`0 / 332`) parents, and `4 / 215` on `game_art` (`4 / 1,512 = 0.26%` overall synthetic FPR; **`0 / 1,512 = 0.00%` provider FPR**; `1 / 2,267 = 0.04%` across all `2,267` `512-d` rows). +- **Full `10,585`-row `locked_test` `512-d` provider router:** `99.93%` `unknown` specificity (`3 / 4,538` false positives, `0.07%` FPR), `83.28%` exact provider recall (`92.45%` native, `92.95%` resized, `77.06%` social-recompressed), `99.94%` any-AI precision, and `95.93%` Stage-2 version accuracy given exact provider. | Provider | Test count | Standalone ROC AUC | Router recall | Router precision | Stage-2 version accuracy | |---|---:|---:|---:|---:|---:| @@ -94,42 +111,6 @@ The operating point was selected strictly on disjoint calibration partitions (`8 | `firefly` | 103 | 0.9948 | 61.2% | 91.3% | 100.0% | | `xai` | 48 | 0.9990 | 45.8% | 91.7% | 77.3% | -### Held-out real-image specificity by variety (`4,538` test negatives across 16 real classes + foreign AI) - -| Real-image variety | Test count | False positives | False-positive rate | Specificity | -|---|---:|---:|---:|---:| -| `photo` | 2,183 | 0 | 0.00% | 100.00% | -| `photo_retouched` | 339 | 2 | 0.59% | 99.41% | -| `classical_inpaint` | 17 | 0 | 0.00% | 100.00% | -| `digital_art` | 440 | 1 | 0.23% | 99.77% | -| `game_art` | 174 | 0 | 0.00% | 100.00% | -| `vector` | 135 | 0 | 0.00% | 100.00% | -| `interface` | 180 | 0 | 0.00% | 100.00% | -| `diagram` | 98 | 0 | 0.00% | 100.00% | -| `chart_data_viz` | 159 | 0 | 0.00% | 100.00% | -| `technical_architecture` | 84 | 0 | 0.00% | 100.00% | -| `procedural_graphic` | 13 | 0 | 0.00% | 100.00% | -| `document` | 165 | 0 | 0.00% | 100.00% | -| `gov_scientific_doc` | 32 | 0 | 0.00% | 100.00% | -| `receipt_invoice` | 181 | 0 | 0.00% | 100.00% | -| `print_publishing` | 229 | 0 | 0.00% | 100.00% | -| `stress_recompressed` | 103 | 0 | 0.00% | 100.00% | -| `foreign_ai` | 6 | 0 | 0.00% | 100.00% | - -### External blind multi-variety real-image verification (`selective-v8`, `2,267` untouched images) - -Evaluated on the external `selective-v8` blind real-image cohorts (`2,267` images; `2,265` strictly parent-disjoint from `locked_test`): **1 / 2,267 false positives (`0.04%` overall FPR, `99.96%` specificity)**, plus **0 / 60 false positives (`0.00%` FPR)** on external phone thermal receipts. - -| Blind `selective-v8` cell | Evaluated | False positives | False-positive rate | Specificity | -|---|---:|---:|---:|---:| -| `photo` | 450 | 0 | 0.00% | 100.00% | -| `vector` | 332 | 0 | 0.00% | 100.00% | -| `game_art` | 230 | 0 | 0.00% | 100.00% | -| `interface` | 342 | 0 | 0.00% | 100.00% | -| `diagram` | 305 | 0 | 0.00% | 100.00% | -| `document` | 308 | 0 | 0.00% | 100.00% | -| `stress_recompressed` | 300 | 1 | 0.33% | 99.67% | - ## Intended use Install `remove-ai-watermarks[source-classify]` and call the explicit Python API `classify_source(path)` or CLI command `remove-ai-watermarks classify-source `. `identify` does not run this model. Set `RAIW_SOURCE_CLASSIFY_WEIGHTS` to the `.npz` file or its parent directory for offline deployments. diff --git a/docs/source-classify-hf/benchmark.py b/docs/source-classify-hf/benchmark.py index d9b75e2..b3bbd9b 100644 --- a/docs/source-classify-hf/benchmark.py +++ b/docs/source-classify-hf/benchmark.py @@ -4,7 +4,7 @@ # dependencies = [ # "remove-ai-watermarks[source-classify]>=0.62.1", # "huggingface-hub>=0.26.0", -# "onnxruntime>=1.19.0", +# "onnxruntime>=1.24.0", # "peft>=0.14.0", # "pyarrow>=17.0.0", # "safetensors>=0.4.5", @@ -19,7 +19,7 @@ Streams pinned, un-gated datasets directly from Hugging Face Hub at immutable commit SHAs (no private files, no manual dataset setup) across three evaluation regimes: 1. Non-AI false-positive traps (camera photos, UI screenshots, science diagrams, - scanned receipts and invoices). + scanned documents). 2. Untouched native AI generator exports across FLUX.1-dev, OpenAI GPT-Image-1, Google Gemini Nano Banana Pro, Stable Diffusion XL, and Midjourney v6.1. 3. Transcoded crowd-arena AI outputs across multi-provider preference shards re-encoded @@ -209,10 +209,10 @@ NON_AI_SLICES: tuple[ParquetSliceSpec, ...] = ( limit=50, ), ParquetSliceSpec( - category="receipt_invoice", - dataset_id="mychen76/invoices-and-receipts_ocr_v1", - revision="83835c87346de32ac9223bdce5264e69ef3366ad", - parquet_path="data/test-00000-of-00001-af2d92d1cee28514.parquet", + category="scanned_document", + dataset_id="lmms-lab/DocVQA", + revision="539088ef8a8ada01ac8e2e6d4e372586748a265e", + parquet_path="DocVQA/test-00000-of-00006.parquet", limit=50, ), ) @@ -723,7 +723,7 @@ def _evaluate_rgb_detector( def evaluate_raiw(samples: list[SampleItem]) -> dict[str, Any]: - """Evaluate `wiltodelta/raiw-source-classify` in pure NumPy on CPU.""" + """Evaluate `wiltodelta/raiw-source-classify` on CPU.""" from remove_ai_watermarks import source_classify as sc weights_file = sc.resolve_weights_path() @@ -733,7 +733,7 @@ def evaluate_raiw(samples: list[SampleItem]) -> dict[str, Any]: with Image.open(io.BytesIO(raw_bytes)) as im: res = sc.classify_source(im, weights_path=weights_file) return { - "pred_ai": res.label != "unknown", + "pred_ai": bool(getattr(res, "synthetic_detected", res.label != "unknown")), "pred_provider": None if res.label == "unknown" else res.label, } @@ -749,16 +749,14 @@ def evaluate_raiw(samples: list[SampleItem]) -> dict[str, Any]: preds_by_idx[idx] = _classify_one(samples[idx].raw_bytes) latencies_ms.append((time.perf_counter() - t0) * 1000.0) - untimed_indices = [idx for idx in range(len(samples)) if idx not in lat_idx_set] - with ThreadPoolExecutor(max_workers=4) as pool: - untimed_preds = list(pool.map(lambda i: _classify_one(samples[i].raw_bytes), untimed_indices)) - for idx, pred in zip(untimed_indices, untimed_preds, strict=True): - preds_by_idx[idx] = pred + for idx in range(len(samples)): + if idx not in lat_idx_set: + preds_by_idx[idx] = _classify_one(samples[idx].raw_bytes) return _summarize_predictions( model_id=sc.WEIGHTS_REPO, revision=sc.WEIGHTS_REVISION, - runtime="NumPy + OpenCV (CPU)", + runtime="NumPy + ONNX Runtime (CPU)", weights_mb=weights_mb, license_id="apache-2.0", median_cpu_ms=round(statistics.median(latencies_ms), 1), @@ -1211,7 +1209,7 @@ def format_markdown_table(results: list[dict[str, Any]]) -> str: n_arena = results[0]["arena_ai"]["total"] if results else 0 header = ( - f"| Model | License | Size | CPU ms | Non-AI FPR (`{n_non_ai}`) | Photo / UI / Diag / Rcpt FPR " + f"| Model | License | Size | CPU ms | Non-AI FPR (`{n_non_ai}`) | Photo / UI / Diag / Doc FPR " f"| Native AI Recall (`{n_native}`) | Native Attribution (`{n_native}`) " f"| Arena AI Recall (`{n_arena}`) | Arena Attribution (`{n_arena}`) | Precision |" ) @@ -1223,7 +1221,7 @@ def format_markdown_table(results: list[dict[str, Any]]) -> str: arn = r["arena_ai"] slice_str = ( f"{sf.get('camera_photo', 0.0):.0f}% / {sf.get('ui_screenshot', 0.0):.0f}% / " - f"{sf.get('science_diagram', 0.0):.0f}% / {sf.get('receipt_invoice', 0.0):.0f}%" + f"{sf.get('science_diagram', 0.0):.0f}% / {sf.get('scanned_document', 0.0):.0f}%" ) lines.append( f"| `{r['model_id']}` | `{r['license']}` | {r['weights_mb']:.1f} MB | {r['median_cpu_ms']:.0f} ms " diff --git a/docs/source-classify-hf/demo.ipynb b/docs/source-classify-hf/demo.ipynb index 81d02d9..d77a42d 100644 --- a/docs/source-classify-hf/demo.ipynb +++ b/docs/source-classify-hf/demo.ipynb @@ -5,12 +5,13 @@ "id": "cell-intro", "metadata": {}, "source": [ - "# RAIW 10-provider source-pipeline classifier (`multi-provider-source-v6`)\n", + "# RAIW 10-provider source-pipeline classifier (`multi-provider-source-v7`)\n", "\n", - "This notebook demonstrates the compact (`15.52 MB`), CPU-only, pickle-free (`allow_pickle=False`) NumPy classifier published at [`wiltodelta/raiw-source-classify`](https://huggingface.co/wiltodelta/raiw-source-classify).\n", + "This notebook demonstrates the unified (`55.53 MB`), CPU-only, pickle-free (`allow_pickle=False`) multimodal classifier published at [`wiltodelta/raiw-source-classify`](https://huggingface.co/wiltodelta/raiw-source-classify).\n", "\n", "- **10 AI provider families + open-set abstention:** `openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, `firefly`, `xai`, plus `unknown`.\n", "- **Stage-2 model/version attribution (`version_subfamily`):** identifies specific generator subfamilies when an image clears the calibrated regime-aware acceptance threshold.\n", + "- **Calibrated binary synthetic detection (`synthetic_detected`, `synthetic_probability`):** retains synthetic recall across foreign resize and container transcoding while abstaining from unidentifiable generator attribution (`label=\"unknown\"`).\n", "- **Scope boundary:** pixel source-pipeline classification is **not** provenance verification and **not** a SynthID or invisible-watermark detector (`watermark_truth=\"unknown\"`)." ] }, @@ -102,6 +103,8 @@ " {\n", " \"label\": res.label,\n", " \"version_subfamily\": res.version_subfamily,\n", + " \"synthetic_detected\": res.synthetic_detected,\n", + " \"synthetic_probability\": round(res.synthetic_probability, 4),\n", " \"reason\": res.reason,\n", " \"confidence\": round(res.confidence, 4),\n", " \"watermark_truth\": res.watermark_truth,\n", diff --git a/docs/source-classify-hf/infer.py b/docs/source-classify-hf/infer.py index 6fde550..a8b9c92 100644 --- a/docs/source-classify-hf/infer.py +++ b/docs/source-classify-hf/infer.py @@ -126,6 +126,22 @@ def inspect_weights(weights_path: Path | None = None) -> dict[str, Any]: version_subfamilies[prov] = subs array_count = len(data.files) + synthetic_threshold: float | None = None + vit_onnx_size_bytes: int | None = None + if "syn_threshold" in data: + synthetic_threshold = round(float(np.asarray(data["syn_threshold"], dtype=np.float64).squeeze()), 6) + if "vit_onnx_bytes" in data: + import numpy.lib.format as npfmt + + zf = getattr(data, "zip", None) + if zf is not None and "vit_onnx_bytes.npy" in zf.namelist(): + with zf.open("vit_onnx_bytes.npy") as handle: + ver = npfmt.read_magic(handle) + hdr_fn = npfmt.read_array_header_1_0 if ver == (1, 0) else npfmt.read_array_header_2_0 + shape, _fortran, _dtype = hdr_fn(handle) + vit_onnx_size_bytes = int(shape[0]) if len(shape) == 1 else int(np.prod(shape)) + else: + vit_onnx_size_bytes = int(np.asarray(data["vit_onnx_bytes"], dtype=np.uint8).size) summary: dict[str, Any] = { "artifact_file": resolved.name, @@ -144,6 +160,10 @@ def inspect_weights(weights_path: Path | None = None) -> dict[str, Any]: } if global_ai_threshold is not None: summary["global_ai_threshold"] = global_ai_threshold + if synthetic_threshold is not None: + summary["synthetic_threshold"] = synthetic_threshold + if vit_onnx_size_bytes is not None: + summary["vit_onnx_size_bytes"] = vit_onnx_size_bytes return summary @@ -198,8 +218,11 @@ def _write_human_predictions(rows: Sequence[dict[str, Any]]) -> None: for row in rows: sub = row.get("version_subfamily") or "-" conf = float(row.get("confidence", 0.0)) + syn_flag = "yes" if row.get("synthetic_detected") else "no" + syn_prob = float(row.get("synthetic_probability", 0.0)) sys.stdout.write( f"{row['path']}\tlabel={row['label']}\tversion={sub}\t" + f"synthetic={syn_flag}({syn_prob:.4f})\t" f"confidence={conf:.4f}\treason={row['reason']}\twatermark_truth={row['watermark_truth']}\n" ) diff --git a/docs/source-classify-hf/metrics.json b/docs/source-classify-hf/metrics.json index 6a8cad6..c6c62a6 100644 --- a/docs/source-classify-hf/metrics.json +++ b/docs/source-classify-hf/metrics.json @@ -1,9 +1,13 @@ { - "claim": "abstaining 10-provider source-pipeline classification with version subfamily attribution; not SynthID detection", - "schema": "multi-provider-source-v5", - "artifact_file": "multi-provider-source-v6.npz", - "artifact_sha256": "87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284", + "claim": "abstaining 10-provider source-pipeline classification with version subfamily attribution and calibrated binary synthetic-image detection; not SynthID detection", + "schema": "multi-provider-source-v7", + "artifact_file": "multi-provider-source-v7.npz", + "artifact_sha256": "4faef51eea48f8194ee804fab1782c48d626384e115e2ef70884f8e8393d7eb1", + "artifact_size_mb": 55.53, "feature_dimension": 512, + "vit_output_dimension": 28, + "synthetic_fusion_dimension": 67, + "multimodal_provider_dimension": 82, "stacked_stage2_dimension": 666, "classes": [ "openai", @@ -25,7 +29,104 @@ "calibration": 8363, "calibration_recomp_neg": 3011, "calibration_crop_resize_dev": 2972, - "test": 10585 + "test": 10585, + "multimodal_v7_train_views": 14428, + "multimodal_v7_cal_views": 6694, + "sealed_foreign_eval_views": 84 + }, + "open_benchmark_v2_578": { + "non_ai_total": 200, + "non_ai_fp": 0, + "non_ai_fpr": 0.0, + "slice_fpr_pct": { + "camera_photo": 0.0, + "ui_screenshot": 0.0, + "science_diagram": 0.0, + "scanned_document": 0.0 + }, + "native_ai_total": 125, + "native_ai_synthetic_recall": 0.992, + "native_ai_provider_attribution": 0.712, + "arena_ai_total": 253, + "arena_ai_synthetic_recall": 0.8695652173913043, + "arena_ai_provider_attribution": 0.1857707509881423, + "overall_ai_recall": 0.91005291005291, + "overall_precision": 1.0, + "median_cpu_ms": 328.9 + }, + "sealed_foreign_openworld_eval": { + "evaluated_views": 84, + "synthetic_recall": 0.6905, + "honest_unknown_abstention_rate": 0.9762 + }, + "locked_internal_test_e2e_rgb": { + "evaluated_parents": 4415, + "supported_ai_parents": 2074, + "real_non_ai_parents": 2341, + "native": { + "synthetic_recall_supported_ai": 0.9754098360655737, + "exact_provider_recall_supported_ai": 0.9281581485053038, + "real_synthetic_fp": 2, + "real_synthetic_fpr": 0.0008543357539513029, + "real_provider_fp": 1, + "real_provider_fpr": 0.00042716787697565144, + "roc_auc": 0.9994764413002544, + "pr_auc": 0.9994285151447234 + }, + "arena_transcoded": { + "synthetic_recall_supported_ai": 0.654291224686596, + "exact_provider_recall_supported_ai": 0.2540983606557377, + "real_synthetic_fp": 20, + "real_synthetic_fpr": 0.00854335753951303, + "real_provider_fp": 4, + "roc_auc": 0.9739757136319278, + "pr_auc": 0.9720579688268834 + } + }, + "external_blind_selective_v8_e2e_rgb": { + "evaluated_parents": 1512, + "synthetic_fp": 4, + "synthetic_fpr": 0.0026455026455026454, + "provider_fp": 0, + "provider_fpr": 0.0, + "by_domain": { + "diagram": { + "evaluated": 305, + "synthetic_fp": 0, + "synthetic_fpr": 0.0, + "provider_fp": 0 + }, + "document": { + "evaluated": 308, + "synthetic_fp": 0, + "synthetic_fpr": 0.0, + "provider_fp": 0 + }, + "game_art": { + "evaluated": 215, + "synthetic_fp": 4, + "synthetic_fpr": 0.018604651162790697, + "provider_fp": 0 + }, + "interface": { + "evaluated": 327, + "synthetic_fp": 0, + "synthetic_fpr": 0.0, + "provider_fp": 0 + }, + "photo": { + "evaluated": 25, + "synthetic_fp": 0, + "synthetic_fpr": 0.0, + "provider_fp": 0 + }, + "vector": { + "evaluated": 332, + "synthetic_fp": 0, + "synthetic_fpr": 0.0, + "provider_fp": 0 + } + } }, "locked_internal_test": { "n": 10585, @@ -90,7 +191,6 @@ "procedural_graphic": 1.0, "document": 1.0, "gov_scientific_doc": 1.0, - "receipt_invoice": 1.0, "print_publishing": 1.0, "stress_recompressed": 1.0, "foreign_ai": 1.0 @@ -146,12 +246,6 @@ } } }, - "external_phone_thermal_receipts": { - "evaluated": 60, - "false_positives": 0, - "fpr": 0.0, - "specificity": 1.0 - }, "stage2_version_accuracy": { "openai": 0.9559147685525349, "google": 0.9698492462311558, diff --git a/docs/source-classify.md b/docs/source-classify.md index ff7dbbe..3ed4a90 100644 --- a/docs/source-classify.md +++ b/docs/source-classify.md @@ -10,7 +10,7 @@ payload, and it must not be used to claim that SynthID is present or absent pixel pipeline, where renderer, geometry, encoding, post-processing, and watermark state can be confounded. -Install the lightweight runtime: +Install the runtime: ```bash uv add "remove-ai-watermarks[source-classify]" @@ -21,15 +21,24 @@ sensor, and codec/geometry regime descriptor (`112-d` adaptive native-tile SRM residuals + `128-d` phase-resolved modulo-8/16 sublattice and `8x8` DCT comb features + `144-d` Moisan periodic-plus-smooth spectral and period-comb profiles + `96-d` CFA/shot-noise/chromatic-aberration sensor cues + `32-d` codec and -geometry regime features) through a two-tower pure -NumPy ensemble (Regime-FiLM residual MLP trunks + packed `HistGradientBoosting` -specialists), 2D multiplicative interaction gates, decoupled regime-aware -supported-AI acceptance, a threshold-invariant 10-way skip attribution head, and -stacked Stage-2 version classifiers. +geometry regime features) together with an embedded weight-fp16 `ViT-S/16 @ 384` +multi-task ONNX visual backbone (`onnxruntime` CPU, no PyTorch required) inside +a single pickle-free `.npz` bundle (`multi-provider-source-v7.npz`, +`allow_pickle=False`). Two-tower `512-d` Regime-FiLM residual MLP trunks and +packed `HistGradientBoosting` specialists drive regime-aware 10-provider +acceptance and Stage-2 version attribution, an `82-d` open-set multimodal +provider head (`10` providers vs `foreign_ai` and `real_non_ai`) recovers exact +family attribution on transcoded outputs while keeping unseen generators as +`unknown`, and a `67-d` open-world synthetic fusion head (paired with a +conditional `672px` two-scale gray-zone pass for widescreen exports) combines the +ViT visual representations, physics channels, regime indicators, and a `26-d` +codec-invariant born-digital graphics score. It routes across all 10 canonical AI provider classes (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, -`firefly`, `xai`) or abstains as `unknown`. +`firefly`, `xai`) or abstains as `unknown`, while simultaneously returning a +calibrated binary synthetic verdict (`synthetic_detected`, +`synthetic_probability`) in a single call without extra flags. Call the CLI command or Python API explicitly: @@ -42,22 +51,43 @@ remove-ai-watermarks classify-source metadata-stripped.png --json import remove_ai_watermarks as raiw result = raiw.classify_source("metadata-stripped.png") -print(result.label) # one of the 10 providers or "unknown" -print(result.version_subfamily) # e.g. "google:gemini_3_pro_image", "openai:gpt_image_1_5", or None -print(result.reason) # "classified" | "abstained" | "feature_unavailable" -print(result.margins) # provider margins before thresholding -print(result.thresholds) # calibrated provider thresholds -print(result.watermark_truth) # always "unknown" +print(result.label) # one of the 10 providers or "unknown" +print(result.version_subfamily) # e.g. "google:gemini_3_pro_image", "openai:gpt_image_1_5", or None +print(result.synthetic_detected) # calibrated binary synthetic verdict (bool) +print(result.synthetic_probability) # calibrated binary synthetic probability (>= 0.5 iff True) +print(result.reason) # "classified" | "abstained" | "feature_unavailable" +print(result.margins) # provider margins before thresholding +print(result.thresholds) # calibrated provider thresholds +print(result.watermark_truth) # always "unknown" ``` `feature_unavailable` is returned for images below the required 256x256 geometry or for a degenerate feature vector. `abstained` means the image did not -clear the calibrated acceptance threshold. Both are honest `unknown` -results. +clear the calibrated 10-provider pixel-pipeline threshold. + +## Behavior after foreign resize and container transcoding + +When an external platform resizes an AI output to a foreign canvas (such as a +square `1024x1024` JPEG or WebP container) and overwrites native quantization +tables, aspect ratios, and VAE sublattice phase, exact 10-provider attribution +abstains as `unknown` rather than guessing a generator family, while the unified +multimodal synthetic head still evaluates `synthetic_detected` and +`synthetic_probability` in the same call: + +- When a supported provider pipeline is accepted (`result.label != "unknown"`), + `result.synthetic_detected` is guaranteed to be `True` + (`result.synthetic_probability >= 0.5`). +- When container laundering or an unsupported generator prevents reliable + 10-provider family attribution, `result.label` stays `"unknown"` + (`result.reason == "abstained"`) while `result.synthetic_detected` remains + `True` whenever the multimodal synthetic head clears its calibrated threshold. +- Camera photographs, UI screenshots, scientific diagrams, vectors, and scanned + documents are jointly guarded against false positives across both + native and recompressed containers. The first call downloads the exact pinned revision of [`wiltodelta/raiw-source-classify`](https://huggingface.co/wiltodelta/raiw-source-classify) -(`multi-provider-source-v6.npz`, verified by SHA-256). Set +(`multi-provider-source-v7.npz`, verified by SHA-256). Set `RAIW_SOURCE_CLASSIFY_WEIGHTS` to the `.npz` file itself or its parent directory for an offline deployment. diff --git a/docs/synthid-classifiers.md b/docs/synthid-classifiers.md index a5276b8..fe9eb8d 100644 --- a/docs/synthid-classifiers.md +++ b/docs/synthid-classifiers.md @@ -120,7 +120,8 @@ The next experiment trained a compact nonlinear head on the complete available private corpus, including target-provider exports, photographs, and foreign generator negatives. The corpus itself is not published. That early 3-class MLP was subsequently superseded by the 10-provider `multi-provider-source-v3.npz`, -`multi-provider-source-v4.npz`, `multi-provider-source-v5.npz`, and `multi-provider-source-v6.npz` ensembles (`docs/source-classify-hf/`), +`multi-provider-source-v4.npz`, `multi-provider-source-v5.npz`, `multi-provider-source-v6.npz`, +and `multi-provider-source-v7.npz` ensembles (`docs/source-classify-hf/`), derivative artifacts containing only learned parameters, normalization constants, tree arrays, labels, and abstention thresholds; they contain no images, paths, image hashes, embeddings, or training catalog. diff --git a/pyproject.toml b/pyproject.toml index 350c233..12ba425 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -226,12 +226,13 @@ trustmark = [ # CPython 3.13+; its 13 detector tests pass on 3.13 with NumPy 2.5.3. "trustmark>=0.9.2", ] -# Compact 10-provider source-pipeline and model-version classifier (pure NumPy, -# CPU-only). identify never imports this extra, and it is not a SynthID -# detector. Weights download on first use. +# Unified 10-provider source-pipeline + synthetic-image classifier (NumPy + +# ONNX Runtime CPU, no torch). identify never imports this extra, and it is not +# a SynthID detector. Weights download on first use. source-classify = [ "remove-ai-watermarks[pixels]", "huggingface-hub>=0.20.0,<2", + "onnxruntime>=1.24.0", ] # Universal region eraser backend -- big-LaMa via onnxruntime (Carve/LaMa-ONNX, # Apache-2.0). CPU, no torch. Model (~200 MB) is downloaded on first use and diff --git a/scripts/README.md b/scripts/README.md index 332bed7..eb16301 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -51,7 +51,7 @@ explicitly names a tracked canonical result. | `visible_sheets.py` | Build blinded contact sheets for relaxation candidates. | | `watermark_benchmark_cohort.py` | Build the deterministic synthetic DWT-DCT and TrustMark cohort consumed by `watermark_benchmark.py`. | | `watermark_benchmark_real_cohort.py` | Build a publication-cleared, provider-paired and content-stratified real-image cohort. | -| `publish_source_classify_hf.py` | Upload the derivative 10-provider source-pipeline model (`multi-provider-source-v6.npz`), `config.json`, and public card bundle (`README.md`, `metrics.json`, `infer.py`, `benchmark.py`, `demo.ipynb`) to Hugging Face `wiltodelta/raiw-source-classify`. Manual; the Action `publish-source-classify-hf.yml` is the write-token path. | +| `publish_source_classify_hf.py` | Upload the derivative 10-provider source-pipeline model (`multi-provider-source-v7.npz`), `config.json`, and public card bundle (`README.md`, `metrics.json`, `infer.py`, `benchmark.py`, `demo.ipynb`) to Hugging Face `wiltodelta/raiw-source-classify`. Manual; the Action `publish-source-classify-hf.yml` is the write-token path. | | `verify_engine_selection_fixtures.py` | Verify hashes, dimensions, and prompt pairing in the tracked auto-engine content matrix. | ## Research and diagnostic prototypes diff --git a/scripts/publish_source_classify_hf.py b/scripts/publish_source_classify_hf.py index 5a84cc6..0fa04a7 100644 --- a/scripts/publish_source_classify_hf.py +++ b/scripts/publish_source_classify_hf.py @@ -25,7 +25,7 @@ RETIRED_HUB_REPOS = ( "wiltodelta/raiw-photo-classify", ) CONFIG_FILE = "config.json" -MODEL_FILE = "multi-provider-source-v6.npz" +MODEL_FILE = "multi-provider-source-v7.npz" RETIRED_FILES = ( "source-pipeline-mlp.npz", "openai-google-source-v1.npz", @@ -51,7 +51,7 @@ def _build_hub_config(metrics: dict[str, Any]) -> dict[str, Any]: "stacked_stage2_dimension": metrics["stacked_stage2_dimension"], "providers": [cls for cls in classes if cls != "unknown"], "abstain_label": "unknown", - "library_name": "numpy", + "library_name": "onnx", "package": "remove-ai-watermarks[source-classify]", "license": "apache-2.0", } diff --git a/skills/remove-ai-watermarks/references/commands.md b/skills/remove-ai-watermarks/references/commands.md index b7c6c27..da085ec 100644 --- a/skills/remove-ai-watermarks/references/commands.md +++ b/skills/remove-ai-watermarks/references/commands.md @@ -49,12 +49,15 @@ remove-ai-watermarks classify-source image.png --json Abstaining 10-provider source-pipeline classifier (`openai`, `google`, `bytedance`, `flux`, `stable_diffusion`, `meta`, `midjourney`, `ideogram`, -`firefly`, `xai`) with Stage-2 model-version attribution (since CLI 0.48.0), needs the -`source-classify` extra. It is NOT provenance and NOT a SynthID detector -(`watermark_truth` is always `unknown`), `unknown` is an abstention rather than -proof of camera origin, and `identify` never runs it. Offer `classify-source` -only when `identify` found no signal and the user still wants a provider guess, -and report it as a guess. +`firefly`, `xai`) with Stage-2 model-version attribution and unified synthetic +detection (`synthetic_detected`, `synthetic_probability`) under resize and +recompression (since CLI 0.48.0), needs the `source-classify` extra. It is NOT +provenance and NOT a SynthID detector (`watermark_truth` is always `unknown`), +`unknown` is a family-attribution abstention rather than proof of camera +origin, and `identify` never runs it. Offer `classify-source` only when +`identify` found no signal and the user still wants a provider or synthetic +pixel estimate, and report it as a statistical pixel estimate rather than +provenance. ```bash remove-ai-watermarks metadata image.png --check diff --git a/src/remove_ai_watermarks/cli.py b/src/remove_ai_watermarks/cli.py index 61b1d3a..9ad11f2 100644 --- a/src/remove_ai_watermarks/cli.py +++ b/src/remove_ai_watermarks/cli.py @@ -2615,6 +2615,8 @@ def cmd_classify_source(source: Path, as_json: bool) -> None: console.print("\n Source-pipeline classification (not provenance and not SynthID detection)") console.print(f" Label: {result.label}") console.print(f" Version subfamily: {result.version_subfamily or 'none'}") + syn_word = "yes" if result.synthetic_detected else "no" + console.print(f" Synthetic: {syn_word} ({result.synthetic_probability:.4f})") console.print(f" Reason: {result.reason}") console.print(f" Confidence: {result.confidence:.4f}") console.print(f" Watermark truth: {result.watermark_truth}") diff --git a/src/remove_ai_watermarks/source_classify.py b/src/remove_ai_watermarks/source_classify.py index 522f1ab..3472fb8 100644 --- a/src/remove_ai_watermarks/source_classify.py +++ b/src/remove_ai_watermarks/source_classify.py @@ -16,6 +16,7 @@ import hashlib import logging import math import os +import threading from dataclasses import dataclass from importlib import import_module from pathlib import Path @@ -76,16 +77,115 @@ CLASSES: tuple[SourceLabel, ...] = (*ALL_PROVIDER_CLASSES, "unknown") WEIGHTS_ENV = "RAIW_SOURCE_CLASSIFY_WEIGHTS" WEIGHTS_REPO = "wiltodelta/raiw-source-classify" -WEIGHTS_REVISION = "d8029a433afe3c27ad74ac75f50d77dfae986b13" +WEIGHTS_REVISION = "46b331cb8f0831e6ced6eb3a7f7b55db3f91867e" CONFIG_FILE = "config.json" -MODEL_FILE = "multi-provider-source-v6.npz" -MODEL_SHA256 = "87868eea08b8b811999f675186b82b067c4de655981cb7f25114aac00b1dd284" +MODEL_FILE = "multi-provider-source-v7.npz" +MODEL_SHA256 = "4faef51eea48f8194ee804fab1782c48d626384e115e2ef70884f8e8393d7eb1" MODEL_SCHEMA_V3 = "multi-provider-source-v3" MODEL_SCHEMA_V4 = "multi-provider-source-v4" MODEL_SCHEMA_V5 = "multi-provider-source-v5" -MODEL_SCHEMA = MODEL_SCHEMA_V5 +MODEL_SCHEMA_V7 = "multi-provider-source-v7" +MODEL_SCHEMA = MODEL_SCHEMA_V7 SOURCE_CLASSIFY_EXTRA = "'remove-ai-watermarks[source-classify]'" +VIT_SHORT_EDGE_V7 = 440 +VIT_DETAIL_SHORT_EDGE_V7 = 672 +VIT_CROP_SIZE_V7 = 384 +VIT_OUT_DIM_V7 = 28 +SYN_IN_DIM_V7 = 67 +MM_PROV_IN_DIM_V7 = 82 + +_IMAGENET_MEAN_RGB: tuple[float, float, float] = (0.485, 0.456, 0.406) +_IMAGENET_STD_RGB: tuple[float, float, float] = (0.229, 0.224, 0.225) + +# Zero-leakage 26-d codec- & geometry-invariant macro-scene Born-Digital Graphics Veto +# over `x_512[464:480]` (Block D4 saturation/achromatic/clipping/palette) + `x_512[502:512]` (Block E scene). +_GFX_MEAN_26: tuple[float, ...] = ( + -0.00866062, + -0.00369257, + -0.03726238, + -0.0227263, + 0.02860176, + 0.32059201, + 0.19851867, + 0.66889976, + 0.1629835, + 0.01311125, + 0.05012025, + 0.40246035, + 0.27661094, + 0.84704429, + 0.46758068, + 0.14369827, + 0.14918268, + 0.40246035, + 0.0852835, + 0.46758068, + 0.32059201, + 0.66889976, + 0.01311125, + 0.05012025, + 0.48955523, + 0.45048192, +) +_GFX_SCALE_26: tuple[float, ...] = ( + 0.1038899, + 0.09136275, + 0.08558824, + 0.07392866, + 0.13310937, + 0.18244784, + 0.07912959, + 0.25684499, + 0.24843859, + 0.06171596, + 0.16283455, + 0.2023694, + 0.25040855, + 0.17989174, + 0.23715294, + 0.10365412, + 0.21141834, + 0.2023694, + 0.19076729, + 0.23715294, + 0.18244784, + 0.25684499, + 0.06171596, + 0.16283455, + 0.19453504, + 0.12261727, +) +_GFX_COEF_26: tuple[float, ...] = ( + 0.28593333, + -0.01833078, + -0.54306846, + 0.23017136, + -0.33946035, + -0.20786306, + 0.41448862, + -0.10714731, + -0.19169794, + 0.09411158, + 0.19919772, + 0.22211316, + -0.4822873, + -0.57568771, + 0.56877772, + -0.08537862, + -0.67524892, + 0.22211316, + -0.11560082, + 0.56877772, + -0.20786306, + -0.10714731, + 0.09411158, + 0.19919772, + 0.42927782, + -0.20077164, +) +_GFX_INTERCEPT = -4.46995339 + MIN_SIDE = 256 FORENSIC_DIM = 124 SPECTRAL_GRID = 16 @@ -120,6 +220,8 @@ class SourceClassification: watermark_truth: Literal["unknown"] = "unknown" claim: str = CLAIM model_revision: str = MODEL_SCHEMA + synthetic_detected: bool = False + synthetic_probability: float = 0.0 @property def scores(self) -> dict[str, float]: @@ -140,6 +242,8 @@ class SourceClassification: "watermark_truth": self.watermark_truth, "claim": self.claim, "model_revision": self.model_revision, + "synthetic_detected": self.synthetic_detected, + "synthetic_probability": self.synthetic_probability, } @@ -338,19 +442,111 @@ class _SourceModelV5: version_heads: dict[str, _Stage2VersionHead] -_LoadedSourceModel: TypeAlias = _SourceModel | _SourceModelV4 | _SourceModelV5 +class _V7OnnxHolder: + """Lazy, thread-safe ONNX Runtime session holder that drops raw graph bytes after compilation.""" + + def __init__(self, npz_path: Path) -> None: + self.npz_path = npz_path + self._lock = threading.Lock() + self._session: Any = None + + def get_session(self) -> Any: + if self._session is not None: + return self._session + _require_dependencies(need_hub=False, need_onnx=True) + with self._lock: + if self._session is not None: + return self._session + import numpy as np + + with np.load(self.npz_path, allow_pickle=False) as data: + raw_bytes = np.asarray(data["vit_onnx_bytes"], dtype=np.uint8).tobytes() + ort: Any = import_module("onnxruntime") + sess_opts = ort.SessionOptions() + sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + omp_threads = os.environ.get("OMP_NUM_THREADS", "").strip() + if omp_threads.isdigit() and int(omp_threads) > 0: + sess_opts.intra_op_num_threads = int(omp_threads) + sess_opts.inter_op_num_threads = 1 + self._session = ort.InferenceSession( + raw_bytes, + sess_options=sess_opts, + providers=["CPUExecutionProvider"], + ) + return self._session + + +@dataclass(frozen=True) +class _MMProvHeadV7: + """Open-set 11-way (`10` providers + `unknown`) multimodal attribution head for transcoded AI.""" + + in_mean: FloatArray + in_scale: FloatArray + w1: FloatArray + b1: FloatArray + ln_g: FloatArray + ln_b: FloatArray + w2: FloatArray + b2: FloatArray + skip_w: FloatArray + prov_thresholds: FloatArray + min_gap: float + conf_scale: float + + +@dataclass(frozen=True) +class _MultiScaleGrayConfigV7: + """Conditional second-scale (`672px` 2-crop) configuration for borderline widescreen/high-res frames.""" + + short_edge: int + min_short_px: int + min_long_px: int + gray_lo: float + gfx_ceil: float + detail_alpha: float + thr_offset: float + + +@dataclass(frozen=True) +class _SourceModelV7: + """Unified pickle-free v7 model combining 512-d physics/codec ensembles and embedded ViT ONNX.""" + + base_v5: _SourceModelV5 + onnx_holder: _V7OnnxHolder + vit_attr_alpha: float + phys_veto_cap: float + phys_veto_syn_floor: float + syn_in_mean: FloatArray + syn_in_scale: FloatArray + syn_w1: FloatArray + syn_b1: FloatArray + syn_ln_g: FloatArray + syn_ln_b: FloatArray + syn_w2: FloatArray + syn_b2: float + syn_skip_w: FloatArray + syn_threshold: float + syn_conf_scale: float + mm_prov: _MMProvHeadV7 | None = None + ms_cfg: _MultiScaleGrayConfigV7 | None = None + + +_LoadedSourceModel: TypeAlias = _SourceModel | _SourceModelV4 | _SourceModelV5 | _SourceModelV7 def is_available() -> bool: """Return True if optional source-classifier dependencies are installed.""" - return module_available("numpy", "cv2", "huggingface_hub") + return module_available("numpy", "cv2", "huggingface_hub", "onnxruntime") -def _require_dependencies() -> None: - if not is_available(): +def _require_dependencies(*, need_hub: bool = True, need_onnx: bool = False) -> None: + missing_core = not module_available("numpy", "cv2") + missing_hub = need_hub and not module_available("huggingface_hub") + missing_ort = need_onnx and not module_available("onnxruntime") + if missing_core or missing_hub or missing_ort: raise ImportError( - "Source-pipeline classification requires opencv-python-headless and " - f"huggingface-hub. Install with: pip install {SOURCE_CLASSIFY_EXTRA}" + "Source-pipeline classification requires opencv-python-headless, " + f"huggingface-hub, and onnxruntime. Install with: pip install {SOURCE_CLASSIFY_EXTRA}" ) @@ -373,7 +569,7 @@ def _resolve_hub_weights( config_file: str, expected_sha256: str, ) -> Path: - _require_dependencies() + _require_dependencies(need_hub=True, need_onnx=False) hub: Any = import_module("huggingface_hub") try_cache = getattr(hub, "try_to_load_from_cache", None) cached = try_cache(repo_id=repo_id, filename=model_file, revision=revision) if callable(try_cache) else None @@ -421,6 +617,10 @@ def resolve_weights_path(weights_path: Path | None = None) -> Path: _resolve_weights_path = resolve_weights_path +def _get_v7_onnx_session(model: _SourceModelV7) -> Any: + return model.onnx_holder.get_session() + + @functools.lru_cache(maxsize=1) def _spectral_grid_masks() -> tuple[ tuple[FloatArray, FloatArray, FloatArray, FloatArray], @@ -1233,6 +1433,179 @@ def _load_model_v5(data: Any) -> _SourceModelV5: ) +def _inspect_npz_1d_uint8_length(data: Any, key: str) -> int: + import numpy as np + + npfmt: Any = import_module("numpy.lib.format") + member = f"{key}.npy" + zf = getattr(data, "zip", None) + if zf is not None and member in zf.namelist(): + with zf.open(member) as handle: + version: tuple[int, int] = npfmt.read_magic(handle) + header_fn: Any = npfmt.read_array_header_1_0 if version == (1, 0) else npfmt.read_array_header_2_0 + hdr: tuple[tuple[int, ...], bool, Any] = header_fn(handle) + shape, _fortran, dtype = hdr + if dtype != np.dtype(np.uint8) or len(shape) != 1: + raise ValueError(f"Invalid {key} array in v7 model bundle") + return int(shape[0]) + raw = np.asarray(data[key]) + if raw.dtype != np.uint8 or raw.ndim != 1: + raise ValueError(f"Invalid {key} array in v7 model bundle") + return int(raw.size) + + +def _load_model_v7(data: Any, resolved: Path) -> _SourceModelV7: + import numpy as np + + base_v5 = _load_model_v5(data) + if "vit_onnx_bytes" not in data: + raise ValueError("Missing vit_onnx_bytes in v7 model bundle") + onnx_len = _inspect_npz_1d_uint8_length(data, "vit_onnx_bytes") + if onnx_len < 32: + raise ValueError("Invalid vit_onnx_bytes array in v7 model bundle") + + syn_in_mean, syn_in_scale = _load_1d_standardizer( + data, + "syn_in_mean", + "syn_in_scale", + SYN_IN_DIM_V7, + err_msg="Invalid v7 syn_in_mean/syn_in_scale standardization arrays", + ) + syn_w1 = np.asarray(data["syn_w1"], dtype=np.float64) + syn_b1 = np.asarray(data["syn_b1"], dtype=np.float64) + syn_ln_g = np.asarray(data["syn_ln_g"], dtype=np.float64) + syn_ln_b = np.asarray(data["syn_ln_b"], dtype=np.float64) + syn_w2 = np.asarray(data["syn_w2"], dtype=np.float64) + syn_b2 = float(np.asarray(data["syn_b2"], dtype=np.float64).squeeze()) + syn_skip_w = np.asarray(data["syn_skip_w"], dtype=np.float64) + syn_threshold = float(np.asarray(data["syn_threshold"], dtype=np.float64).squeeze()) + syn_conf_scale = float(np.asarray(data["syn_conf_scale"], dtype=np.float64).squeeze()) + vit_attr_alpha = float(np.asarray(data["vit_attr_alpha"], dtype=np.float64).squeeze()) + phys_veto_cap = float(np.asarray(data["phys_veto_cap"], dtype=np.float64).squeeze()) + phys_veto_syn_floor = float(np.asarray(data["phys_veto_syn_floor"], dtype=np.float64).squeeze()) + + h_syn_dim = syn_b1.shape[0] if syn_b1.ndim == 1 else -1 + if ( + h_syn_dim < 4 + or syn_w1.shape != (SYN_IN_DIM_V7, h_syn_dim) + or syn_ln_g.shape != (h_syn_dim,) + or syn_ln_b.shape != (h_syn_dim,) + or syn_w2.shape != (h_syn_dim,) + or syn_skip_w.shape != (SYN_IN_DIM_V7,) + or not all( + math.isfinite(val) + for val in (syn_b2, syn_threshold, syn_conf_scale, vit_attr_alpha, phys_veto_cap, phys_veto_syn_floor) + ) + or syn_conf_scale <= 0.0 + or vit_attr_alpha < 0.0 + or not all(np.all(np.isfinite(arr)) for arr in (syn_w1, syn_b1, syn_ln_g, syn_ln_b, syn_w2, syn_skip_w)) + ): + raise ValueError("Invalid v7 synthetic fusion or provider-blend arrays") + + mm_prov: _MMProvHeadV7 | None = None + if "mm_prov_w1" in data: + n_cls = len(ALL_PROVIDER_CLASSES) + n_out = n_cls + 2 + mm_in_mean, mm_in_scale = _load_1d_standardizer( + data, + "mm_prov_in_mean", + "mm_prov_in_scale", + MM_PROV_IN_DIM_V7, + err_msg="Invalid v7 mm_prov standardization arrays", + ) + mm_w1 = np.asarray(data["mm_prov_w1"], dtype=np.float64) + mm_b1 = np.asarray(data["mm_prov_b1"], dtype=np.float64) + mm_ln_g = np.asarray(data["mm_prov_ln_g"], dtype=np.float64) + mm_ln_b = np.asarray(data["mm_prov_ln_b"], dtype=np.float64) + mm_w2 = np.asarray(data["mm_prov_w2"], dtype=np.float64) + mm_b2 = np.asarray(data["mm_prov_b2"], dtype=np.float64) + mm_skip_w = np.asarray(data["mm_prov_skip_w"], dtype=np.float64) + mm_thr = np.asarray(data["mm_prov_thresholds"], dtype=np.float64) + mm_gap = float(np.asarray(data["mm_prov_min_gap"], dtype=np.float64).squeeze()) + mm_cscale = float(np.asarray(data["mm_prov_conf_scale"], dtype=np.float64).squeeze()) + h_mm = mm_b1.shape[0] if mm_b1.ndim == 1 else -1 + if ( + h_mm < 4 + or mm_w1.shape != (MM_PROV_IN_DIM_V7, h_mm) + or mm_ln_g.shape != (h_mm,) + or mm_ln_b.shape != (h_mm,) + or mm_w2.shape != (h_mm, n_out) + or mm_b2.shape != (n_out,) + or mm_skip_w.shape != (MM_PROV_IN_DIM_V7, n_out) + or mm_thr.shape != (n_cls,) + or not math.isfinite(mm_gap) + or mm_gap < 0.0 + or not math.isfinite(mm_cscale) + or mm_cscale <= 0.0 + or not all( + np.all(np.isfinite(arr)) for arr in (mm_w1, mm_b1, mm_ln_g, mm_ln_b, mm_w2, mm_b2, mm_skip_w, mm_thr) + ) + ): + raise ValueError("Invalid v7 multimodal open-set provider head arrays") + mm_prov = _MMProvHeadV7( + in_mean=mm_in_mean, + in_scale=mm_in_scale, + w1=mm_w1, + b1=mm_b1, + ln_g=mm_ln_g, + ln_b=mm_ln_b, + w2=mm_w2, + b2=mm_b2, + skip_w=mm_skip_w, + prov_thresholds=mm_thr, + min_gap=mm_gap, + conf_scale=mm_cscale, + ) + + ms_cfg: _MultiScaleGrayConfigV7 | None = None + if "ms_detail_alpha" in data: + ms_se = int(np.asarray(data["ms_short_edge"], dtype=np.int64).squeeze()) + ms_min_s = int(np.asarray(data["ms_min_short_px"], dtype=np.int64).squeeze()) + ms_min_l = int(np.asarray(data["ms_min_long_px"], dtype=np.int64).squeeze()) + ms_gray_lo = float(np.asarray(data["ms_gray_lo"], dtype=np.float64).squeeze()) + ms_gfx_ceil = float(np.asarray(data["ms_gfx_ceil"], dtype=np.float64).squeeze()) + ms_alpha = float(np.asarray(data["ms_detail_alpha"], dtype=np.float64).squeeze()) + ms_off = float(np.asarray(data["ms_thr_offset"], dtype=np.float64).squeeze()) + if ( + ms_se < VIT_CROP_SIZE_V7 + or ms_min_s < MIN_SIDE + or ms_min_l < ms_min_s + or not all(math.isfinite(val) for val in (ms_gray_lo, ms_gfx_ceil, ms_alpha, ms_off)) + or not (0.0 <= ms_alpha <= 1.0) + ): + raise ValueError("Invalid v7 conditional multiscale gray-zone configuration") + ms_cfg = _MultiScaleGrayConfigV7( + short_edge=ms_se, + min_short_px=ms_min_s, + min_long_px=ms_min_l, + gray_lo=ms_gray_lo, + gfx_ceil=ms_gfx_ceil, + detail_alpha=ms_alpha, + thr_offset=ms_off, + ) + + return _SourceModelV7( + base_v5=base_v5, + onnx_holder=_V7OnnxHolder(resolved), + vit_attr_alpha=vit_attr_alpha, + phys_veto_cap=phys_veto_cap, + phys_veto_syn_floor=phys_veto_syn_floor, + syn_in_mean=syn_in_mean, + syn_in_scale=syn_in_scale, + syn_w1=syn_w1, + syn_b1=syn_b1, + syn_ln_g=syn_ln_g, + syn_ln_b=syn_ln_b, + syn_w2=syn_w2, + syn_b2=syn_b2, + syn_skip_w=syn_skip_w, + syn_threshold=syn_threshold, + syn_conf_scale=syn_conf_scale, + mm_prov=mm_prov, + ms_cfg=ms_cfg, + ) + + @functools.lru_cache(maxsize=4) def _load_model_from_path(resolved: Path) -> _LoadedSourceModel: import numpy as np @@ -1241,6 +1614,8 @@ def _load_model_from_path(resolved: Path) -> _LoadedSourceModel: if "schema" not in data: raise ValueError(f"Missing schema key in {resolved}") schema = str(np.asarray(data["schema"]).item()) + if schema == MODEL_SCHEMA_V7: + return _load_model_v7(data, resolved) if schema == MODEL_SCHEMA_V5: return _load_model_v5(data) if schema == MODEL_SCHEMA_V4: @@ -1348,9 +1723,124 @@ def _unavailable_result() -> SourceClassification: pooled_scores={}, margins={}, thresholds={}, + synthetic_detected=False, + synthetic_probability=0.0, ) +@functools.lru_cache(maxsize=1) +def _gfx_veto_arrays() -> tuple[FloatArray, FloatArray, FloatArray]: + import numpy as np + + return ( + np.asarray(_GFX_MEAN_26, dtype=np.float64), + np.asarray(_GFX_SCALE_26, dtype=np.float64), + np.asarray(_GFX_COEF_26, dtype=np.float64), + ) + + +@functools.lru_cache(maxsize=1) +def _imagenet_norm_arrays() -> tuple[FloatArray, FloatArray]: + import numpy as np + + return ( + np.asarray(_IMAGENET_MEAN_RGB, dtype=np.float32).reshape(1, 3, 1, 1), + np.asarray(_IMAGENET_STD_RGB, dtype=np.float32).reshape(1, 3, 1, 1), + ) + + +def eval_born_digital_graphics_score(features_512d: FloatArray) -> float: + """Score the 26-d codec-invariant macro-scene Born-Digital Graphics logit on a 512-d v4-v7 vector.""" + import numpy as np + + x_1d = np.asarray(features_512d, dtype=np.float64) + if x_1d.shape != (FEATURE_DIM_V4,) or not np.all(np.isfinite(x_1d)): + raise ValueError(f"Expected finite ({FEATURE_DIM_V4},) feature vector, got {x_1d.shape}") + scene_26 = np.concatenate([x_1d[464:480], x_1d[502:512]]) + mean_26, scale_26, coef_26 = _gfx_veto_arrays() + z_26 = np.clip((scene_26 - mean_26) / scale_26, -12.0, 12.0) + return float(z_26 @ coef_26 + _GFX_INTERCEPT) + + +def _orient_rgb_image(image: Image.Image) -> Image.Image: + from PIL import ImageOps + + orientation = image.getexif().get(274, 1) + oriented = ImageOps.exif_transpose(image) if orientation not in (1, None) else image + return oriented if oriented.mode == "RGB" else oriented.convert("RGB") + + +def preprocess_vit_384_chw(image: Image.Image) -> FloatArray: + """Preprocess a PIL image into a C-contiguous 1x3x384x384 float32 normalized ViT tensor.""" + import numpy as np + from PIL import Image as PilImage + + rgb = _orient_rgb_image(image) + w, h = rgb.size + if w <= h: + new_w = VIT_SHORT_EDGE_V7 + new_h = max(VIT_CROP_SIZE_V7, round(h * VIT_SHORT_EDGE_V7 / w)) + else: + new_h = VIT_SHORT_EDGE_V7 + new_w = max(VIT_CROP_SIZE_V7, round(w * VIT_SHORT_EDGE_V7 / h)) + resized = rgb.resize((new_w, new_h), PilImage.Resampling.BILINEAR) + left = (new_w - VIT_CROP_SIZE_V7) // 2 + top = (new_h - VIT_CROP_SIZE_V7) // 2 + cropped = resized.crop((left, top, left + VIT_CROP_SIZE_V7, top + VIT_CROP_SIZE_V7)) + buf = np.empty((1, 3, VIT_CROP_SIZE_V7, VIT_CROP_SIZE_V7), dtype=np.float32) + buf[0] = np.transpose(np.asarray(cropped, dtype=np.uint8), (2, 0, 1)) + mean_rgb, std_rgb = _imagenet_norm_arrays() + buf *= 1.0 / 255.0 + buf -= mean_rgb + buf /= std_rgb + return buf + + +def preprocess_vit_384_detail_2chw( + image: Image.Image, + *, + short_edge: int = VIT_DETAIL_SHORT_EDGE_V7, +) -> FloatArray: + """Extract two complementary 384x384 higher-scale crops (`2x3x384x384`) along the long axis.""" + import numpy as np + from PIL import Image as PilImage + + rgb = _orient_rgb_image(image) + w, h = rgb.size + target_se = max(VIT_CROP_SIZE_V7, min(int(short_edge), min(w, h))) + if w <= h: + new_w = target_se + new_h = max(VIT_CROP_SIZE_V7, round(h * target_se / w)) + else: + new_h = target_se + new_w = max(VIT_CROP_SIZE_V7, round(w * target_se / h)) + resized = rgb.resize((new_w, new_h), PilImage.Resampling.BILINEAR) + + if new_w >= new_h: + span_x = new_w - VIT_CROP_SIZE_V7 + mid_y = (new_h - VIT_CROP_SIZE_V7) // 2 + boxes = ( + (span_x // 4, mid_y, span_x // 4 + VIT_CROP_SIZE_V7, mid_y + VIT_CROP_SIZE_V7), + ((3 * span_x) // 4, mid_y, (3 * span_x) // 4 + VIT_CROP_SIZE_V7, mid_y + VIT_CROP_SIZE_V7), + ) + else: + span_y = new_h - VIT_CROP_SIZE_V7 + mid_x = (new_w - VIT_CROP_SIZE_V7) // 2 + boxes = ( + (mid_x, span_y // 4, mid_x + VIT_CROP_SIZE_V7, span_y // 4 + VIT_CROP_SIZE_V7), + (mid_x, (3 * span_y) // 4, mid_x + VIT_CROP_SIZE_V7, (3 * span_y) // 4 + VIT_CROP_SIZE_V7), + ) + + buf = np.empty((2, 3, VIT_CROP_SIZE_V7, VIT_CROP_SIZE_V7), dtype=np.float32) + for idx_b, box in enumerate(boxes): + buf[idx_b] = np.transpose(np.asarray(resized.crop(box), dtype=np.uint8), (2, 0, 1)) + mean_rgb, std_rgb = _imagenet_norm_arrays() + buf *= 1.0 / 255.0 + buf -= mean_rgb + buf /= std_rgb + return buf + + def _eval_two_tower_backbone( x_1d: FloatArray, backbone: _TwoTowerBackbone, @@ -1412,7 +1902,10 @@ def _resolve_two_tower_subfamilies( return best_sub, version_subfamily -def _classify_v4_features(x_1d: FloatArray, model: _SourceModelV4) -> SourceClassification: +def _classify_v4_features( + x_1d: FloatArray, + model: _SourceModelV4, +) -> SourceClassification: import numpy as np n_cls = len(ALL_PROVIDER_CLASSES) @@ -1470,10 +1963,16 @@ def _classify_v4_features(x_1d: FloatArray, model: _SourceModelV4) -> SourceClas margins=margins, thresholds=dict(thresholds), model_revision=MODEL_SCHEMA_V4, + synthetic_detected=label != "unknown", + synthetic_probability=confidence, ) -def _classify_v5_features(x_1d: FloatArray, model: _SourceModelV5) -> SourceClassification: +def _eval_v5_core_state( + x_1d: FloatArray, + model: _SourceModelV5, +) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray, FloatArray, float]: + """Return `(z_det_std, attr_logits, r_std, mean_sub, u_vec, accept_excess)` for v5/v7 models.""" import numpy as np n_cls = len(ALL_PROVIDER_CLASSES) @@ -1489,25 +1988,38 @@ def _classify_v5_features(x_1d: FloatArray, model: _SourceModelV5) -> SourceClas g_2d = _eval_2d_gates(u_z, model.gates, cap=36.0) phi = np.concatenate([u_sat, h_pos, h_neg, g_2d]) - # 1. Decoupled Regime-Aware Supported-AI Acceptance Gate (10 provider channels + 1 global AI channel) z_det_raw = model.det_bias + phi @ model.det_w h_null = _silu_np(r_std @ model.null_h_w + model.null_h_b) mu_r = model.null_mu_bias + r_std @ model.null_lin_mu_w + h_null @ model.null_mu_w sig_lin = np.clip(model.null_sig_bias + r_std @ model.null_lin_sig_w + h_null @ model.null_sig_w, -8.0, 8.0) sigma_r = np.log1p(np.exp(sig_lin)) + 0.25 z_det_std = (z_det_raw - mu_r) / sigma_r - det_excess = z_det_std - model.det_thresholds - accept_excess = float(np.max(det_excess)) + accept_excess = float(np.max(z_det_std - model.det_thresholds)) - # 2. Decoupled Prior-Calibrated Conditional Multi-Class Attribution Head (threshold-invariant) h_attr = _silu_np(_layernorm_1d(phi @ model.attr_w1 + model.attr_b1, model.attr_ln_g, model.attr_ln_b)) attr_logits = (phi @ model.attr_skip_w + h_attr @ model.attr_w2 + model.attr_b2) / model.attr_temp + return z_det_std, attr_logits, r_std, mean_sub, u_vec, accept_excess + +def _build_v5_like_result( + *, + x_1d: FloatArray, + base_model: _SourceModelV5, + z_det_std: FloatArray, + attr_logits: FloatArray, + mean_sub: FloatArray, + u_vec: FloatArray, + accept_excess: float, + synthetic_detected: bool, + synthetic_probability: float, + model_revision: str, +) -> SourceClassification: + import numpy as np + + n_cls = len(ALL_PROVIDER_CLASSES) win_idx = int(np.argmax(attr_logits)) best_cls: ProviderClass = ALL_PROVIDER_CLASSES[win_idx] - prov_thr = model.det_thresholds[:n_cls] - # Synthesize per-provider margins so argmax(margins - thresholds) == best_cls and - # margins[best_cls] >= thresholds[best_cls] <=> accept_excess >= 0 across decoupled heads. + prov_thr = base_model.det_thresholds[:n_cls] prov_margins = prov_thr + accept_excess - (float(attr_logits[win_idx]) - attr_logits) pooled_z: dict[str, float] = dict(zip(ALL_PROVIDER_CLASSES, z_det_std[:n_cls].tolist(), strict=True)) thresholds: dict[str, float] = dict(zip(ALL_PROVIDER_CLASSES, prov_thr.tolist(), strict=True)) @@ -1516,14 +2028,14 @@ def _classify_v5_features(x_1d: FloatArray, model: _SourceModelV5) -> SourceClas if accept_excess >= 0.0: part = np.partition(attr_logits, -2) attr_gap = max(0.0, float(part[-1] - part[-2])) - confidence = _sigmoid_scalar(min(model.conf_scale * accept_excess, attr_gap)) + confidence = _sigmoid_scalar(min(base_model.conf_scale * accept_excess, attr_gap)) label: SourceLabel = best_cls reason: SourceReason = "classified" fine_subfamily, version_subfamily = _resolve_two_tower_subfamilies( - best_cls, mean_sub, x_1d, u_vec, model.backbone, model.version_heads + best_cls, mean_sub, x_1d, u_vec, base_model.backbone, base_model.version_heads ) else: - confidence = _sigmoid_scalar(model.conf_scale * accept_excess) + confidence = _sigmoid_scalar(base_model.conf_scale * accept_excess) label = "unknown" reason = "abstained" fine_subfamily = None @@ -1538,13 +2050,263 @@ def _classify_v5_features(x_1d: FloatArray, model: _SourceModelV5) -> SourceClas pooled_scores=pooled_z, margins=margins, thresholds=thresholds, - model_revision=MODEL_SCHEMA_V5, + model_revision=model_revision, + synthetic_detected=synthetic_detected, + synthetic_probability=synthetic_probability, ) +def _classify_v5_features( + x_1d: FloatArray, + model: _SourceModelV5, + *, + model_revision: str = MODEL_SCHEMA_V5, +) -> SourceClassification: + z_det_std, attr_logits, _r_std, mean_sub, u_vec, accept_excess = _eval_v5_core_state(x_1d, model) + return _build_v5_like_result( + x_1d=x_1d, + base_model=model, + z_det_std=z_det_std, + attr_logits=attr_logits, + mean_sub=mean_sub, + u_vec=u_vec, + accept_excess=accept_excess, + synthetic_detected=accept_excess >= 0.0, + synthetic_probability=_sigmoid_scalar(model.conf_scale * accept_excess), + model_revision=model_revision, + ) + + +def _logsumexp_pair(a: float, b: float) -> float: + hi = max(a, b) + return hi + math.log(math.exp(a - hi) + math.exp(b - hi)) + + +def build_v7_syn_input_1d( + x_1d: FloatArray, + z_det_std: FloatArray, + accept_excess: float, + r_std: FloatArray, + vit_out_1d: FloatArray, +) -> FloatArray: + """Assemble the 67-d open-world multimodal synthetic-fusion input vector for schema v7. + + `vit_out_1d` layout (`28-d`): + `[orig_syn(0), prov_10(1:11), foreign_ai(11), real_non_ai(12), gfx_veto(13), dom_syn(14), emb(15:28)]`. + """ + import numpy as np + + n_cls = len(ALL_PROVIDER_CLASSES) + vit_syn = float(vit_out_1d[0]) + vit_all_ai = vit_out_1d[1 : 2 + n_cls] + vit_for = float(vit_out_1d[1 + n_cls]) + vit_real = float(vit_out_1d[2 + n_cls]) + vit_max_ai = float(np.max(vit_all_ai)) + vit_lse_ai = float((vit_max_ai + math.log(float(np.sum(np.exp(vit_all_ai - vit_max_ai))))) - vit_real) + vit_max_lo = vit_max_ai - vit_real + vit_for_lo = vit_for - vit_real + vit_tail = vit_out_1d[3 + n_cls : VIT_OUT_DIM_V7] + + z_sat = 8.0 * np.tanh(z_det_std / 8.0) + exc_sat = 8.0 * math.tanh(accept_excess / 8.0) + ch10 = float(z_det_std[n_cls]) + gfx_score = eval_born_digital_graphics_score(x_1d) + scalars_head = np.asarray([vit_syn, vit_lse_ai, vit_max_lo, vit_for_lo], dtype=np.float64) + scalars_tail = np.asarray( + [exc_sat, max(0.0, ch10), min(0.0, ch10), gfx_score, max(0.0, gfx_score)], + dtype=np.float64, + ) + return np.concatenate([scalars_head, vit_tail, z_sat, scalars_tail, r_std]) + + +def build_v7_mm_prov_input_1d( + attr_logits: FloatArray, + z_det_std: FloatArray, + accept_excess: float, + r_std: FloatArray, + vit_out_1d: FloatArray, +) -> FloatArray: + """Assemble the 82-d multimodal open-set 10-provider + `unknown` attribution input vector.""" + import numpy as np + + attr_sat = 8.0 * np.tanh(attr_logits / 8.0) + z_sat = 8.0 * np.tanh(z_det_std / 8.0) + exc_sat = np.asarray([8.0 * math.tanh(accept_excess / 8.0)], dtype=np.float64) + return np.concatenate([attr_sat, z_sat, exc_sat, vit_out_1d.astype(np.float64), r_std]) + + +def _eval_v7_syn_raw( + x_1d: FloatArray, + z_det_std: FloatArray, + accept_excess: float, + r_std: FloatArray, + vit_out_1d: FloatArray, + model: _SourceModelV7, +) -> float: + import numpy as np + + s_in = build_v7_syn_input_1d(x_1d, z_det_std, accept_excess, r_std, vit_out_1d) + s_std = np.clip((s_in - model.syn_in_mean) / model.syn_in_scale, -12.0, 12.0) + h_syn = _silu_np(_layernorm_1d(s_std @ model.syn_w1 + model.syn_b1, model.syn_ln_g, model.syn_ln_b)) + return float(s_std @ model.syn_skip_w + h_syn @ model.syn_w2 + model.syn_b2) + + +def _eval_v7_mm_prov_log_odds( + attr_logits: FloatArray, + z_det_std: FloatArray, + accept_excess: float, + r_std: FloatArray, + vit_out_1d: FloatArray, + mm_head: _MMProvHeadV7, +) -> FloatArray: + import numpy as np + + n_cls = len(ALL_PROVIDER_CLASSES) + p_in = build_v7_mm_prov_input_1d(attr_logits, z_det_std, accept_excess, r_std, vit_out_1d) + p_std = np.clip((p_in - mm_head.in_mean) / mm_head.in_scale, -12.0, 12.0) + h_p = _silu_np(_layernorm_1d(p_std @ mm_head.w1 + mm_head.b1, mm_head.ln_g, mm_head.ln_b)) + logits_12 = p_std @ mm_head.skip_w + h_p @ mm_head.w2 + mm_head.b2 + open_null = _logsumexp_pair(float(logits_12[n_cls]), float(logits_12[n_cls + 1])) + return logits_12[:n_cls] - open_null + + +def _should_run_v7_detail_pass( + x_1d: FloatArray, + vit_primary_1d: FloatArray, + eff_phys_excess: float, + syn_margin_primary: float, + image_size: tuple[int, int] | None, + ms_cfg: _MultiScaleGrayConfigV7 | None, +) -> bool: + if ms_cfg is None or ms_cfg.detail_alpha <= 0.0: + return False + if eff_phys_excess >= 0.0 or not (ms_cfg.gray_lo <= syn_margin_primary < 0.0): + return False + if image_size is not None: + w, h = image_size + if min(w, h) < ms_cfg.min_short_px or max(w, h) < ms_cfg.min_long_px: + return False + n_cls = len(ALL_PROVIDER_CLASSES) + vit_gfx = float(vit_primary_1d[3 + n_cls]) + if vit_gfx >= ms_cfg.gfx_ceil: + return False + return eval_born_digital_graphics_score(x_1d) < 1.20 + + +def _classify_v7_with_vit( + x_1d: FloatArray, + vit_out_1d: FloatArray, + model: _SourceModelV7, + *, + vit_detail_2d: FloatArray | None = None, +) -> SourceClassification: + import numpy as np + + n_cls = len(ALL_PROVIDER_CLASSES) + z_det_std, attr_logits, r_std, mean_sub, u_vec, accept_excess = _eval_v5_core_state(x_1d, model.base_v5) + + syn_raw = _eval_v7_syn_raw(x_1d, z_det_std, accept_excess, r_std, vit_out_1d, model) + syn_margin = syn_raw - model.syn_threshold + + eff_phys_excess = ( + -1e-4 + if (0.0 <= accept_excess < model.phys_veto_cap and syn_margin < model.phys_veto_syn_floor) + else accept_excess + ) + + vit_for_prov = vit_out_1d + ms_cfg = model.ms_cfg + if ( + vit_detail_2d is not None + and ms_cfg is not None + and _should_run_v7_detail_pass(x_1d, vit_out_1d, eff_phys_excess, syn_margin, None, ms_cfg) + and float(vit_detail_2d[0, 3 + n_cls]) < ms_cfg.gfx_ceil + and float(vit_detail_2d[1, 3 + n_cls]) < ms_cfg.gfx_ceil + ): + syn_d0 = _eval_v7_syn_raw(x_1d, z_det_std, accept_excess, r_std, vit_detail_2d[0], model) + syn_d1 = _eval_v7_syn_raw(x_1d, z_det_std, accept_excess, r_std, vit_detail_2d[1], model) + syn_detail_pool = 0.75 * max(syn_d0, syn_d1) + 0.25 * min(syn_d0, syn_d1) + syn_raw = (1.0 - ms_cfg.detail_alpha) * syn_raw + ms_cfg.detail_alpha * syn_detail_pool + syn_margin = syn_raw - (model.syn_threshold + ms_cfg.thr_offset) + vit_for_prov = 0.50 * vit_out_1d + 0.25 * (vit_detail_2d[0] + vit_detail_2d[1]) + + if model.mm_prov is not None: + mm_log_odds = _eval_v7_mm_prov_log_odds( + attr_logits, z_det_std, accept_excess, r_std, vit_for_prov, model.mm_prov + ) + else: + open_null_v = _logsumexp_pair(float(vit_for_prov[1 + n_cls]), float(vit_for_prov[2 + n_cls])) + mm_log_odds = vit_for_prov[1 : 1 + n_cls] - open_null_v + + joint_attr_logits = attr_logits + model.vit_attr_alpha * mm_log_odds + final_excess = eff_phys_excess + + if eff_phys_excess >= 0.0: + synthetic_detected = True + scaled_joint = max( + 0.0, + model.syn_conf_scale * syn_margin, + model.base_v5.conf_scale * eff_phys_excess, + ) + synthetic_probability = _sigmoid_scalar(scaled_joint) + if model.mm_prov is not None and eff_phys_excess < 2.20 and float(np.max(mm_log_odds)) < -0.80: + final_excess = -1e-4 + else: + synthetic_detected = syn_margin >= 0.0 + synthetic_probability = _sigmoid_scalar(model.syn_conf_scale * syn_margin) + if synthetic_detected and model.mm_prov is not None: + win_mm = int(np.argmax(mm_log_odds)) + part_mm = np.partition(mm_log_odds, -2) + gap_mm = float(part_mm[-1] - part_mm[-2]) + mm_exc = float(mm_log_odds[win_mm] - model.mm_prov.prov_thresholds[win_mm]) + if mm_exc >= 0.0 and gap_mm >= model.mm_prov.min_gap: + joint_attr_logits = mm_log_odds + final_excess = max(1e-4, mm_exc * (model.mm_prov.conf_scale / max(model.base_v5.conf_scale, 1e-4))) + + return _build_v5_like_result( + x_1d=x_1d, + base_model=model.base_v5, + z_det_std=z_det_std, + attr_logits=joint_attr_logits, + mean_sub=mean_sub, + u_vec=u_vec, + accept_excess=final_excess, + synthetic_detected=synthetic_detected, + synthetic_probability=synthetic_probability, + model_revision=MODEL_SCHEMA_V7, + ) + + +def _eval_v7_vit_onnx(image: Image.Image, model: _SourceModelV7) -> FloatArray: + import numpy as np + + session = _get_v7_onnx_session(model) + inp = preprocess_vit_384_chw(image) + out = session.run(["vit_out"], {"pixel_values": inp})[0] + vec = np.asarray(out, dtype=np.float64).reshape(-1) + if vec.shape != (VIT_OUT_DIM_V7,) or not np.all(np.isfinite(vec)): + raise RuntimeError(f"Invalid v7 ViT ONNX output shape {vec.shape}") + return vec + + +def _eval_v7_vit_detail_onnx(image: Image.Image, model: _SourceModelV7, *, short_edge: int) -> FloatArray: + import numpy as np + + session = _get_v7_onnx_session(model) + inp = preprocess_vit_384_detail_2chw(image, short_edge=short_edge) + out = session.run(["vit_out"], {"pixel_values": inp})[0] + mat = np.asarray(out, dtype=np.float64) + if mat.shape != (2, VIT_OUT_DIM_V7) or not np.all(np.isfinite(mat)): + raise RuntimeError(f"Invalid v7 ViT detail ONNX output shape {mat.shape}") + return mat + + def _classify_loaded_model( features: FloatArray, model: _LoadedSourceModel, + *, + vit_features: FloatArray | None = None, + vit_detail_features: FloatArray | None = None, ) -> SourceClassification: import numpy as np @@ -1552,9 +2314,21 @@ def _classify_loaded_model( if x_1d.ndim != 1 or not np.all(np.isfinite(x_1d)): return _unavailable_result() - if isinstance(model, (_SourceModelV4, _SourceModelV5)): + if isinstance(model, (_SourceModelV4, _SourceModelV5, _SourceModelV7)): if x_1d.shape != (FEATURE_DIM_V4,): return _unavailable_result() + if isinstance(model, _SourceModelV7): + if vit_features is None: + return _classify_v5_features(x_1d, model.base_v5, model_revision=MODEL_SCHEMA_V7) + v_1d = np.asarray(vit_features, dtype=np.float64) + if v_1d.shape != (VIT_OUT_DIM_V7,) or not np.all(np.isfinite(v_1d)): + return _unavailable_result() + v_det: FloatArray | None = None + if vit_detail_features is not None: + v_det = np.asarray(vit_detail_features, dtype=np.float64) + if v_det.shape != (2, VIT_OUT_DIM_V7) or not np.all(np.isfinite(v_det)): + return _unavailable_result() + return _classify_v7_with_vit(x_1d, v_1d, model, vit_detail_2d=v_det) if isinstance(model, _SourceModelV5): return _classify_v5_features(x_1d, model) return _classify_v4_features(x_1d, model) @@ -1648,6 +2422,8 @@ def _classify_loaded_model( margins=margins, thresholds=dict(thresholds), model_revision=MODEL_SCHEMA_V3, + synthetic_detected=label != "unknown", + synthetic_probability=confidence, ) @@ -1655,15 +2431,22 @@ def classify_source_features( features: FloatArray, *, weights_path: Path | None = None, + vit_features: FloatArray | None = None, + vit_detail_features: FloatArray | None = None, ) -> SourceClassification: - """Classify a precomputed 956-d (v3) or 512-d (v4/v5) feature vector into 10 providers or unknown.""" + """Classify a precomputed 956-d (v3) or 512-d (v4-v7) feature vector into 10 providers or unknown.""" import numpy as np x_1d = np.asarray(features, dtype=np.float64) if x_1d.ndim != 1 or x_1d.shape[0] not in (FEATURE_DIM, FEATURE_DIM_V4) or not np.all(np.isfinite(x_1d)): return _unavailable_result() - return _classify_loaded_model(x_1d, _load_model(weights_path)) + return _classify_loaded_model( + x_1d, + _load_model(weights_path), + vit_features=vit_features, + vit_detail_features=vit_detail_features, + ) def classify_source( @@ -1671,7 +2454,7 @@ def classify_source( *, weights_path: Path | None = None, ) -> SourceClassification: - """Classify an image into one of 10 AI provider pipelines or ``unknown``. + """Classify an image into 10 AI provider pipelines or ``unknown`` plus synthetic detection. Parameters ---------- @@ -1681,34 +2464,47 @@ def classify_source( Optional local ``.npz`` override. Defaults to ``RAIW_SOURCE_CLASSIFY_WEIGHTS`` or the pinned Hugging Face Hub artifact verified by SHA-256. """ - if not module_available("numpy", "cv2"): - _require_dependencies() + _require_dependencies(need_hub=False, need_onnx=False) from PIL import Image as PilImage from remove_ai_watermarks import image_io image_io._register_heif() # pyright: ignore[reportPrivateUsage] - def _extract_from_loaded(img: Image.Image) -> tuple[FloatArray, _LoadedSourceModel] | None: + def _run_on_image(img: Image.Image) -> SourceClassification: if min(img.size) < MIN_SIDE: - return None + return _unavailable_result() loaded_model = _load_model(weights_path) + if isinstance(loaded_model, _SourceModelV7): + _ = _get_v7_onnx_session(loaded_model) extracted = ( extract_512d_v4_features(img) - if isinstance(loaded_model, (_SourceModelV4, _SourceModelV5)) + if isinstance(loaded_model, (_SourceModelV4, _SourceModelV5, _SourceModelV7)) else extract_956d_features(img) ) if extracted is None: - return None - return extracted, loaded_model + return _unavailable_result() + if not isinstance(loaded_model, _SourceModelV7): + return _classify_loaded_model(extracted, loaded_model) + + vit_vec = _eval_v7_vit_onnx(img, loaded_model) + vit_detail: FloatArray | None = None + if loaded_model.ms_cfg is not None: + z_det_std, _attr, r_std, _ms, _uv, accept_exc = _eval_v5_core_state(extracted, loaded_model.base_v5) + syn_raw_0 = _eval_v7_syn_raw(extracted, z_det_std, accept_exc, r_std, vit_vec, loaded_model) + syn_margin_0 = syn_raw_0 - loaded_model.syn_threshold + eff_phys_0 = ( + -1e-4 + if (0.0 <= accept_exc < loaded_model.phys_veto_cap and syn_margin_0 < loaded_model.phys_veto_syn_floor) + else accept_exc + ) + if _should_run_v7_detail_pass( + extracted, vit_vec, eff_phys_0, syn_margin_0, _orient_rgb_image(img).size, loaded_model.ms_cfg + ): + vit_detail = _eval_v7_vit_detail_onnx(img, loaded_model, short_edge=loaded_model.ms_cfg.short_edge) + return _classify_loaded_model(extracted, loaded_model, vit_features=vit_vec, vit_detail_features=vit_detail) if isinstance(source, (str, os.PathLike)): with PilImage.open(source) as opened: - pair = _extract_from_loaded(opened) - else: - pair = _extract_from_loaded(source) - - if pair is None: - return _unavailable_result() - features, model = pair - return _classify_loaded_model(features, model) + return _run_on_image(opened) + return _run_on_image(source) diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 923048d..8163193 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -83,8 +83,8 @@ def test_extras_use_capability_names_without_legacy_aliases(): def test_source_classify_extra_stays_lightweight() -> None: names = _requirement_names("source-classify") - assert "huggingface-hub" in names - assert {"torch", "transformers", "onnxruntime"}.isdisjoint(names) + assert {"huggingface-hub", "onnxruntime"} <= names + assert {"torch", "transformers"}.isdisjoint(names) def test_qwen_zimage_extra_owns_every_profile_tokenizer_backend() -> None: diff --git a/tests/test_publish_source_classify_hf.py b/tests/test_publish_source_classify_hf.py index 9e2b10e..f5721c2 100644 --- a/tests/test_publish_source_classify_hf.py +++ b/tests/test_publish_source_classify_hf.py @@ -22,6 +22,7 @@ def test_hub_ids_match_the_runtime_loader() -> None: assert publish.HUB_REPO == WEIGHTS_REPO assert publish.CONFIG_FILE == CONFIG_FILE assert publish.MODEL_FILE == MODEL_FILE + assert "multi-provider-source-v6.npz" not in publish.RETIRED_FILES assert "wiltodelta/raiw-photo-classify" in publish.RETIRED_HUB_REPOS @@ -127,19 +128,22 @@ def test_standalone_infer_script_inspects_weights_and_classifies_images(tmp_path sc_mod = _load_module("raiw_test_source_classify", Path(__file__).with_name("test_source_classify.py")) infer_mod = _load_module("raiw_hf_infer", publish.CARD_DIR / "infer.py") - weights = sc_mod._write_synthetic_v5_npz( - tmp_path / "synthetic_v5.npz", + weights = sc_mod._write_synthetic_v7_npz( + tmp_path / "synthetic_v7.npz", det_winner="openai", attr_winner="openai", det_score=-2.0, det_threshold=2.0, + syn_threshold=0.5, ) summary = infer_mod.inspect_weights(weights) - assert summary["schema"] == "multi-provider-source-v5" + assert summary["schema"] == "multi-provider-source-v7" assert summary["feature_dim"] == 512 assert len(summary["providers"]) == 10 assert summary["abstain_label"] == "unknown" assert summary["watermark_truth"] == "unknown" + assert summary["synthetic_threshold"] == 0.5 + assert summary["vit_onnx_size_bytes"] > 64 assert "openai" in summary["version_subfamilies"] sample_img = tmp_path / "gradient.png" @@ -161,6 +165,7 @@ def test_standalone_infer_script_inspects_weights_and_classifies_images(tmp_path assert len(rows) == 1 assert rows[0]["label"] == "unknown" assert rows[0]["reason"] == "abstained" + assert rows[0]["synthetic_detected"] is True assert rows[0]["watermark_truth"] == "unknown" diff --git a/tests/test_source_classify.py b/tests/test_source_classify.py index 74a9b91..7710581 100644 --- a/tests/test_source_classify.py +++ b/tests/test_source_classify.py @@ -2,8 +2,10 @@ from __future__ import annotations +import hashlib import json import re +import struct import sys from typing import TYPE_CHECKING, Any @@ -334,11 +336,13 @@ def test_cli_classify_source_json_and_text_and_missing_extra(tmp_path: Path, mon payload = json.loads(res_json.output) assert payload["label"] == "google" assert payload["version_subfamily"] == "google:v2" + assert payload["synthetic_detected"] is True assert payload["watermark_truth"] == "unknown" res_text = runner.invoke(main, ["classify-source", str(img_path)]) assert res_text.exit_code == 0, res_text.output assert "Label: google" in res_text.output + assert "Synthetic: yes (" in res_text.output assert "not SynthID detection" in res_text.output monkeypatch.setattr(source_classify, "is_available", lambda: False) @@ -360,7 +364,6 @@ def test_provenance_paths_do_not_import_source_classify(monkeypatch: pytest.Monk def test_resolve_weights_fetches_config_on_cold_miss_and_caches_resolution( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: - import hashlib import types source_classify._resolve_hub_weights.cache_clear() @@ -629,17 +632,24 @@ def test_v4_end_to_end_image_classification_ignores_metadata(tmp_path: Path) -> assert r1.scores == r2.scores -def _write_synthetic_v5_npz( - path: Path, +def _apply_npz_overrides(payload: dict[str, Any], overrides: dict[str, Any] | None) -> None: + if not overrides: + return + for key, val in overrides.items(): + if val is None: + payload.pop(key, None) + else: + payload[key] = val + + +def _synthetic_v5_npz_payload( *, det_winner: source_classify.ProviderClass = "flux", attr_winner: source_classify.ProviderClass = "ideogram", det_score: float = 4.0, det_threshold: float = 2.0, s2_hgb_weight: float = 1.0, - overrides: dict[str, Any] | None = None, -) -> Path: - """Create a minimal valid pickle-free multi-provider-source-v5 .npz fixture.""" +) -> dict[str, Any]: d = source_classify.FEATURE_DIM_V4 r_dim = source_classify.REGIME_DIM_V4 n_cls = len(source_classify.ALL_PROVIDER_CLASSES) @@ -695,14 +705,28 @@ def _write_synthetic_v5_npz( payload[f"s2_{attr_winner}_lin_w"] = np.zeros((stacked_dim, 1), dtype=np.float64) payload[f"s2_{attr_winner}_lin_b"] = np.asarray([3.0], dtype=np.float64) payload[f"s2_{attr_winner}_lin_hgb_weight"] = np.asarray(s2_hgb_weight, dtype=np.float64) + return payload - if overrides: - for k, v in overrides.items(): - if v is None: - payload.pop(k, None) - else: - payload[k] = v +def _write_synthetic_v5_npz( + path: Path, + *, + det_winner: source_classify.ProviderClass = "flux", + attr_winner: source_classify.ProviderClass = "ideogram", + det_score: float = 4.0, + det_threshold: float = 2.0, + s2_hgb_weight: float = 1.0, + overrides: dict[str, Any] | None = None, +) -> Path: + """Create a minimal valid pickle-free multi-provider-source-v5 .npz fixture.""" + payload = _synthetic_v5_npz_payload( + det_winner=det_winner, + attr_winner=attr_winner, + det_score=det_score, + det_threshold=det_threshold, + s2_hgb_weight=s2_hgb_weight, + ) + _apply_npz_overrides(payload, overrides) np.savez(path, **payload) return path @@ -855,3 +879,456 @@ def test_v5_joint_posterior_confidence_caps_ambiguous_attribution(tmp_path: Path assert res_abstain.reason == "abstained" assert res_abstain.confidence == pytest.approx(source_classify._sigmoid_scalar(-0.6), abs=1e-6) assert res_abstain.confidence < 0.5 + assert res_abstain.synthetic_detected is False + assert res_abstain.synthetic_probability == pytest.approx(res_abstain.confidence, abs=1e-9) + assert res_exact_tie.synthetic_detected is True + assert res_exact_tie.synthetic_probability == pytest.approx(source_classify._sigmoid_scalar(4.0), abs=1e-6) + + +def _build_minimal_const_vit28_onnx_bytes( + vit_vec: np.ndarray, + *, + r_chan_syn_slope: float = 0.0, +) -> bytes: + """Build a minimal valid dynamic-batch ONNX ModelProto (`[B, 3, 384, 384] -> [B, 28]`).""" + vals = np.asarray(vit_vec, dtype=np.float32).reshape(source_classify.VIT_OUT_DIM_V7) + d_out = len(vals) + + def _varint(val: int) -> bytes: + out = bytearray() + while val >= 0x80: + out.append((val & 0x7F) | 0x80) + val >>= 7 + out.append(val) + return bytes(out) + + def _f_bytes(num: int, data: bytes) -> bytes: + return _varint((num << 3) | 2) + _varint(len(data)) + data + + def _f_varint(num: int, val: int) -> bytes: + return _varint((num << 3) | 0) + _varint(val) + + def _dim(d: int | bytes) -> bytes: + return _f_bytes(2, d) if isinstance(d, bytes) else _f_varint(1, d) + + def _value_info(name: str, elem_type: int, dims: list[int | bytes]) -> bytes: + shape = b"".join(_f_bytes(1, _dim(d)) for d in dims) + tt = _f_bytes(1, _f_varint(1, elem_type) + _f_bytes(2, shape)) + return _f_bytes(1, name.encode()) + _f_bytes(2, tt) + + def _tensor_f32(name: str, shape: list[int], flat: list[float]) -> bytes: + dims_b = b"".join(_f_varint(1, s) for s in shape) + raw_b = struct.pack(f"<{len(flat)}f", *flat) + return dims_b + _f_varint(2, 1) + _f_bytes(8, name.encode()) + _f_bytes(9, raw_b) + + w_mat = np.zeros((3, d_out), dtype=np.float32) + w_mat[0, 0] = float(r_chan_syn_slope) + init_w = _tensor_f32("w_zero", [3, d_out], [float(x) for x in w_mat.ravel().tolist()]) + init_b = _tensor_f32("b_vec", [d_out], [float(x) for x in vals.tolist()]) + + n_gap = _f_bytes(1, b"pixel_values") + _f_bytes(2, b"gap_out") + _f_bytes(4, b"GlobalAveragePool") + n_flat = _f_bytes(1, b"gap_out") + _f_bytes(2, b"flat_out") + _f_bytes(4, b"Flatten") + n_gemm = ( + _f_bytes(1, b"flat_out") + + _f_bytes(1, b"w_zero") + + _f_bytes(1, b"b_vec") + + _f_bytes(2, b"vit_out") + + _f_bytes(4, b"Gemm") + ) + inp = _value_info("pixel_values", 1, [b"batch", 3, 384, 384]) + out = _value_info("vit_out", 1, [b"batch", d_out]) + graph = ( + _f_bytes(1, n_gap) + + _f_bytes(1, n_flat) + + _f_bytes(1, n_gemm) + + _f_bytes(2, b"g") + + _f_bytes(5, init_w) + + _f_bytes(5, init_b) + + _f_bytes(11, inp) + + _f_bytes(12, out) + ) + return _f_varint(1, 7) + _f_bytes(7, graph) + _f_bytes(8, _f_varint(2, 13)) + + +def _write_synthetic_v7_npz( + path: Path, + *, + vit_vec: np.ndarray | None = None, + det_winner: source_classify.ProviderClass = "flux", + attr_winner: source_classify.ProviderClass = "ideogram", + det_score: float = 1.0, + det_threshold: float = 3.0, + syn_threshold: float = 0.5, + syn_conf_scale: float = 1.0, + vit_attr_alpha: float = 0.0, + phys_veto_cap: float = 0.0, + phys_veto_syn_floor: float = -3.0, + overrides: dict[str, Any] | None = None, +) -> Path: + """Create a minimal valid pickle-free `multi-provider-source-v7` `.npz` fixture.""" + payload = _synthetic_v5_npz_payload( + det_winner=det_winner, + attr_winner=attr_winner, + det_score=det_score, + det_threshold=det_threshold, + ) + + if vit_vec is None: + vit_vec = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float32) + vit_vec[0] = 2.4 + onnx_bytes = _build_minimal_const_vit28_onnx_bytes(vit_vec) + + d_s = source_classify.SYN_IN_DIM_V7 + h_s = 8 + syn_skip = np.zeros(d_s, dtype=np.float64) + syn_skip[0] = 1.0 # pass vit_syn_logit directly through skip connection + + payload["schema"] = np.asarray(source_classify.MODEL_SCHEMA_V7) + payload["vit_onnx_bytes"] = np.frombuffer(onnx_bytes, dtype=np.uint8).copy() + payload["vit_attr_alpha"] = np.asarray(vit_attr_alpha, dtype=np.float64) + payload["phys_veto_cap"] = np.asarray(phys_veto_cap, dtype=np.float64) + payload["phys_veto_syn_floor"] = np.asarray(phys_veto_syn_floor, dtype=np.float64) + payload["syn_in_mean"] = np.zeros(d_s, dtype=np.float64) + payload["syn_in_scale"] = np.ones(d_s, dtype=np.float64) + payload["syn_w1"] = np.zeros((d_s, h_s), dtype=np.float64) + payload["syn_b1"] = np.zeros(h_s, dtype=np.float64) + payload["syn_ln_g"] = np.ones(h_s, dtype=np.float64) + payload["syn_ln_b"] = np.zeros(h_s, dtype=np.float64) + payload["syn_w2"] = np.zeros(h_s, dtype=np.float64) + payload["syn_b2"] = np.asarray(0.0, dtype=np.float64) + payload["syn_skip_w"] = syn_skip + payload["syn_threshold"] = np.asarray(syn_threshold, dtype=np.float64) + payload["syn_conf_scale"] = np.asarray(syn_conf_scale, dtype=np.float64) + _apply_npz_overrides(payload, overrides) + + np.savez(path, **payload) + return path + + +def test_v7_flagless_transcoded_synthetic_detection_and_honest_abstention( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + rng = np.random.default_rng(20261116) + img = Image.fromarray(rng.integers(20, 235, size=(288, 320, 3), dtype=np.uint8), mode="RGB") + + # 1. Transcoded AI: 512-d physics abstains (1.0 < 3.0), embedded ViT scores +2.5 >= 0.5 -> + # flagless `classify_source` returns honest `label="unknown"` AND `synthetic_detected=True`! + vit_pos = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float32) + vit_pos[0] = 2.5 + w_pos = _write_synthetic_v7_npz( + tmp_path / "v7_transcoded_ai.npz", + vit_vec=vit_pos, + det_score=1.0, + det_threshold=3.0, + syn_threshold=0.5, + syn_conf_scale=1.2, + ) + # Local `.npz` works completely offline even when `huggingface_hub` is absent + real_avail = source_classify.module_available + with monkeypatch.context() as mp: + mp.setattr( + source_classify, + "module_available", + lambda *mods: False if "huggingface_hub" in mods else real_avail(*mods), + ) + res_ai = source_classify.classify_source(img, weights_path=w_pos) + + assert res_ai.label == "unknown" + assert res_ai.reason == "abstained" + assert res_ai.version_subfamily is None + assert res_ai.watermark_truth == "unknown" + assert res_ai.model_revision == source_classify.MODEL_SCHEMA_V7 + assert res_ai.synthetic_detected is True + assert res_ai.synthetic_probability == pytest.approx(source_classify._sigmoid_scalar(1.2 * 2.0), abs=1e-5) + + # Feature-only call without `vit_features` uses the 512-d physics branch cleanly; + # passing `vit_features` reproduces exact `classify_source(img)` parity. + feat_512 = source_classify.extract_512d_v4_features(img) + assert feat_512 is not None + res_feat_only = source_classify.classify_source_features(feat_512, weights_path=w_pos) + assert res_feat_only.label == "unknown" + assert res_feat_only.synthetic_detected is False + assert res_feat_only.model_revision == source_classify.MODEL_SCHEMA_V7 + + res_feat_joint = source_classify.classify_source_features(feat_512, weights_path=w_pos, vit_features=vit_pos) + assert res_feat_joint.synthetic_detected is True + assert res_feat_joint.synthetic_probability == pytest.approx(res_ai.synthetic_probability, abs=1e-6) + + # 2. Real non-AI image: embedded ViT scores -2.0 < 0.5 -> both `label="unknown"` and `synthetic_detected=False` + vit_real = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float32) + vit_real[0] = -2.0 + w_real = _write_synthetic_v7_npz( + tmp_path / "v7_real.npz", + vit_vec=vit_real, + det_score=0.5, + det_threshold=3.0, + syn_threshold=0.5, + ) + res_real = source_classify.classify_source(img, weights_path=w_real) + assert res_real.label == "unknown" + assert res_real.synthetic_detected is False + assert res_real.synthetic_probability < 0.5 + + +def test_v7_vit_provider_attribution_blend_and_borderline_physics_veto(tmp_path: Path) -> None: + rng = np.random.default_rng(77) + img = Image.fromarray(rng.integers(0, 256, size=(260, 260, 3), dtype=np.uint8), mode="RGB") + + # 1. When 512-d physics accepts (`det_score=4.2 >= 2.0`), `vit_attr_alpha > 0` blends ViT provider log-odds + # to break ties toward `midjourney`, and monotonicity keeps `synthetic_detected=True` even if `vit_syn` is mild. + mj_idx = source_classify.ALL_PROVIDER_CLASSES.index("midjourney") + vit_mj = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float32) + vit_mj[0] = -0.2 + vit_mj[1 + mj_idx] = 14.0 + vit_mj[1 + len(source_classify.ALL_PROVIDER_CLASSES)] = -2.0 + w_blend = _write_synthetic_v7_npz( + tmp_path / "v7_blend.npz", + vit_vec=vit_mj, + det_winner="flux", + attr_winner="ideogram", + det_score=4.2, + det_threshold=2.0, + syn_threshold=0.5, + vit_attr_alpha=0.5, + ) + res_blend = source_classify.classify_source(img, weights_path=w_blend) + assert res_blend.label == "midjourney" + assert res_blend.reason == "classified" + assert res_blend.synthetic_detected is True + assert res_blend.synthetic_probability >= 0.5 + + # 2. Borderline physics excess (`2.15 - 2.0 = 0.15 < phys_veto_cap=0.30`) strongly contradicted by ViT + # (`syn_margin = -3.5 - 0.5 = -4.0 < -2.5`) vetoes the borderline FP on both `label` and `synthetic_detected`. + vit_deep_real = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float32) + vit_deep_real[0] = -3.5 + w_veto = _write_synthetic_v7_npz( + tmp_path / "v7_veto.npz", + vit_vec=vit_deep_real, + det_winner="flux", + attr_winner="flux", + det_score=2.15, + det_threshold=2.0, + syn_threshold=0.5, + phys_veto_cap=0.30, + phys_veto_syn_floor=-2.5, + ) + res_vetoed = source_classify.classify_source(img, weights_path=w_veto) + assert res_vetoed.label == "unknown" + assert res_vetoed.reason == "abstained" + assert res_vetoed.synthetic_detected is False + assert res_vetoed.synthetic_probability < 0.5 + + +def test_v7_corrupted_bundle_and_missing_onnxruntime_validation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + w_bad_onnx = _write_synthetic_v7_npz( + tmp_path / "v7_bad_onnx.npz", + overrides={"vit_onnx_bytes": np.zeros(16, dtype=np.uint8)}, + ) + with pytest.raises(ValueError, match="vit_onnx_bytes"): + source_classify._load_model_from_path(w_bad_onnx) + + w_missing_onnx = _write_synthetic_v7_npz( + tmp_path / "v7_missing_onnx.npz", + overrides={"vit_onnx_bytes": None}, + ) + with pytest.raises(ValueError, match="vit_onnx_bytes"): + source_classify._load_model_from_path(w_missing_onnx) + + w_bad_alpha = _write_synthetic_v7_npz( + tmp_path / "v7_bad_alpha.npz", + overrides={"vit_attr_alpha": np.asarray(-0.1, dtype=np.float64)}, + ) + with pytest.raises(ValueError, match="v7 synthetic fusion"): + source_classify._load_model_from_path(w_bad_alpha) + + w_ok = _write_synthetic_v7_npz(tmp_path / "v7_ok.npz") + + real_avail = source_classify.module_available + monkeypatch.setattr( + source_classify, + "module_available", + lambda *mods: False if "onnxruntime" in mods else real_avail(*mods), + ) + assert source_classify.is_available() is False + rng = np.random.default_rng(19) + img = Image.fromarray(rng.integers(0, 256, size=(256, 256, 3), dtype=np.uint8), mode="RGB") + with pytest.raises(ImportError, match="onnxruntime"): + source_classify.classify_source(img, weights_path=w_ok) + + +def test_cli_v7_reports_synthetic_on_transcoded_unknown( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + img_path = tmp_path / "arena.jpg" + rng = np.random.default_rng(123) + Image.fromarray(rng.integers(0, 256, size=(280, 280, 3), dtype=np.uint8), mode="RGB").save(img_path, quality=82) + + vit_pos = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float32) + vit_pos[0] = 3.0 + w_v7 = _write_synthetic_v7_npz( + tmp_path / "cli_v7.npz", + vit_vec=vit_pos, + det_score=0.5, + det_threshold=3.0, + syn_threshold=0.5, + ) + monkeypatch.setenv(source_classify.WEIGHTS_ENV, str(w_v7)) + + runner = CliRunner() + res_json = runner.invoke(main, ["classify-source", str(img_path), "--json"]) + assert res_json.exit_code == 0, res_json.output + payload = json.loads(res_json.output) + assert payload["label"] == "unknown" + assert payload["synthetic_detected"] is True + assert payload["synthetic_probability"] > 0.9 + + res_txt = runner.invoke(main, ["classify-source", str(img_path)]) + assert res_txt.exit_code == 0, res_txt.output + assert "Label: unknown" in res_txt.output + assert "Synthetic: yes (" in res_txt.output + + +def test_v7_open_world_foreign_ai_openset_mm_prov_and_widescreen_detail_pass( + tmp_path: Path, +) -> None: + n_cls = len(source_classify.ALL_PROVIDER_CLASSES) + d_mm = source_classify.MM_PROV_IN_DIM_V7 + h_mm = 8 + + # 1. Open-world 12-way layout (`[0..9]=providers, [10]=foreign_ai, [11]=real`): + # Strong `foreign_ai` logit (`vit_out[11]=+7.0` vs `vit_real=-5.0`) produces positive `vit_lse_ai` (+12.0) + # and positive `vit_for_lo` (+12.0) even when all 10 supported providers score `-6.0`! + x_dummy = np.zeros(source_classify.FEATURE_DIM_V4, dtype=np.float64) + r_zero = np.zeros(source_classify.REGIME_DIM_V4, dtype=np.float64) + vit_foreign = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float64) + vit_foreign[0] = 3.2 # strong generalist ViT synthetic logit + vit_foreign[1 : 1 + n_cls] = -6.0 + vit_foreign[1 + n_cls] = 7.0 # strong `foreign_ai` logit + vit_foreign[2 + n_cls] = -5.0 # low `real_non_ai` logit + z_neg = np.full(n_cls + 1, -4.0, dtype=np.float64) + z_neg[n_cls] = 0.5 + s_foreign = source_classify.build_v7_syn_input_1d(x_dummy, z_neg, -5.0, r_zero, vit_foreign) + assert s_foreign[1] > 11.9 # vit_lse_ai = logsumexp(prov_10, foreign_ai) - real > 0 + assert s_foreign[3] == pytest.approx(12.0, abs=1e-6) # vit_for_lo = foreign_ai - real + + # 2. Open-set 12-way multimodal provider attribution (`_MMProvHeadV7`): + # - Foreign AI (high `mm_foreign_ai` at index `n_cls`) -> `synthetic_detected=True` and `label="unknown"`. + # - Transcoded 10-provider AI (`google` clears `mm_prov_thresholds` and `mm_prov_min_gap`) -> `label="google"`. + n_mm_out = n_cls + 2 + mm_b2_foreign = np.zeros(n_mm_out, dtype=np.float64) + mm_b2_foreign[n_cls] = 5.0 # `foreign_ai` class wins strongly over 10 providers + mm_b2_foreign[n_cls + 1] = -4.0 + mm_overrides: dict[str, Any] = { + "mm_prov_in_mean": np.zeros(d_mm, dtype=np.float64), + "mm_prov_in_scale": np.ones(d_mm, dtype=np.float64), + "mm_prov_w1": np.zeros((d_mm, h_mm), dtype=np.float64), + "mm_prov_b1": np.zeros(h_mm, dtype=np.float64), + "mm_prov_ln_g": np.ones(h_mm, dtype=np.float64), + "mm_prov_ln_b": np.zeros(h_mm, dtype=np.float64), + "mm_prov_w2": np.zeros((h_mm, n_mm_out), dtype=np.float64), + "mm_prov_b2": mm_b2_foreign, + "mm_prov_skip_w": np.zeros((d_mm, n_mm_out), dtype=np.float64), + "mm_prov_thresholds": np.full(n_cls, 1.5, dtype=np.float64), + "mm_prov_min_gap": np.asarray(0.8, dtype=np.float64), + "mm_prov_conf_scale": np.asarray(1.0, dtype=np.float64), + } + w_foreign = _write_synthetic_v7_npz( + tmp_path / "v7_foreign_openworld.npz", + vit_vec=vit_foreign.astype(np.float32), + det_score=0.5, + det_threshold=3.0, + syn_threshold=0.5, + overrides=mm_overrides, + ) + rng = np.random.default_rng(314) + img_sq = Image.fromarray(rng.integers(10, 245, size=(300, 300, 3), dtype=np.uint8), mode="RGB") + res_foreign = source_classify.classify_source(img_sq, weights_path=w_foreign) + assert res_foreign.label == "unknown" + assert res_foreign.reason == "abstained" + assert res_foreign.synthetic_detected is True + assert res_foreign.synthetic_probability > 0.9 + + # Native foreign generator where 512-d physics fires moderately (`eff_phys_excess = +0.8 < 2.2`) + # while `_MMProvHeadV7` strongly prefers `foreign_ai` (`max_lo < -0.80`) must still abstain on `label`! + w_foreign_nat = _write_synthetic_v7_npz( + tmp_path / "v7_foreign_native_phys.npz", + vit_vec=vit_foreign.astype(np.float32), + det_score=3.8, + det_threshold=3.0, + syn_threshold=0.5, + overrides=mm_overrides, + ) + res_foreign_nat = source_classify.classify_source(img_sq, weights_path=w_foreign_nat) + assert res_foreign_nat.synthetic_detected is True + assert res_foreign_nat.label == "unknown" + assert res_foreign_nat.reason == "abstained" + + g_idx = source_classify.ALL_PROVIDER_CLASSES.index("google") + mm_b2_google = np.zeros(n_mm_out, dtype=np.float64) + mm_b2_google[g_idx] = 4.5 + mm_b2_google[n_cls] = 0.5 + mm_b2_google[n_cls + 1] = -3.0 # log-odds > 3.9 >= threshold 1.5, gap >= 0.8 + mm_overrides_g = dict(mm_overrides, mm_prov_b2=mm_b2_google) + w_google_tr = _write_synthetic_v7_npz( + tmp_path / "v7_transcoded_google.npz", + vit_vec=vit_foreign.astype(np.float32), + attr_winner="google", + det_score=0.5, + det_threshold=3.0, + syn_threshold=0.5, + overrides=mm_overrides_g, + ) + res_google_tr = source_classify.classify_source(img_sq, weights_path=w_google_tr) + assert res_google_tr.label == "google" + assert res_google_tr.reason == "classified" + assert res_google_tr.synthetic_detected is True + assert res_google_tr.confidence >= 0.5 + + # 3. Conditional widescreen two-scale gray-zone detail pass (`1408x768`): + # Center strip has dark R (`~20`, normalized R < 0 -> primary `syn_raw < 0.5` in gray zone), + # while left/right thirds have bright R (`~250`, normalized R > 0 -> detail crops score high!). + wide_arr = rng.integers(30, 120, size=(768, 1408, 3), dtype=np.uint8) + wide_arr[:, :, 0] = 250 + wide_arr[:, 480:928, 0] = 20 # center crop (`short_edge=440`) sees low R; left/right `672px` crops see high R + wide_img = Image.fromarray(wide_arr, mode="RGB") + + detail_2chw = source_classify.preprocess_vit_384_detail_2chw(wide_img, short_edge=672) + assert detail_2chw.shape == (2, 3, 384, 384) + + vit_base = np.zeros(source_classify.VIT_OUT_DIM_V7, dtype=np.float32) + vit_base[0] = 0.35 + dyn_onnx = _build_minimal_const_vit28_onnx_bytes(vit_base, r_chan_syn_slope=1.5) + ms_overrides: dict[str, Any] = { + "vit_onnx_bytes": np.frombuffer(dyn_onnx, dtype=np.uint8).copy(), + "ms_short_edge": np.asarray(672, dtype=np.int64), + "ms_min_short_px": np.asarray(512, dtype=np.int64), + "ms_min_long_px": np.asarray(640, dtype=np.int64), + "ms_gray_lo": np.asarray(-2.5, dtype=np.float64), + "ms_gfx_ceil": np.asarray(1.0, dtype=np.float64), + "ms_detail_alpha": np.asarray(0.75, dtype=np.float64), + "ms_thr_offset": np.asarray(0.0, dtype=np.float64), + } + w_no_ms = _write_synthetic_v7_npz( + tmp_path / "v7_wide_no_ms.npz", + det_score=0.5, + det_threshold=3.0, + syn_threshold=0.5, + overrides={"vit_onnx_bytes": np.frombuffer(dyn_onnx, dtype=np.uint8).copy()}, + ) + w_with_ms = _write_synthetic_v7_npz( + tmp_path / "v7_wide_with_ms.npz", + det_score=0.5, + det_threshold=3.0, + syn_threshold=0.5, + overrides=ms_overrides, + ) + res_no_ms = source_classify.classify_source(wide_img, weights_path=w_no_ms) + res_with_ms = source_classify.classify_source(wide_img, weights_path=w_with_ms) + assert res_no_ms.synthetic_detected is False + assert res_with_ms.synthetic_detected is True + assert res_with_ms.synthetic_probability > res_no_ms.synthetic_probability diff --git a/uv.lock b/uv.lock index 50c4f27..b804451 100644 --- a/uv.lock +++ b/uv.lock @@ -4064,6 +4064,7 @@ qwen-zimage = [ source-classify = [ { name = "huggingface-hub" }, { name = "numpy" }, + { name = "onnxruntime" }, { name = "opencv-python-headless" }, ] text = [ @@ -4158,6 +4159,7 @@ requires-dist = [ { name = "numpy", marker = "python_full_version < '3.13' and extra == 'pixels'", specifier = ">=1.24.0" }, { name = "onnxruntime", marker = "extra == 'lama'", specifier = ">=1.24.0" }, { name = "onnxruntime", marker = "extra == 'migan'", specifier = ">=1.24.0" }, + { name = "onnxruntime", marker = "extra == 'source-classify'", specifier = ">=1.24.0" }, { name = "openai", marker = "extra == 'dev'", specifier = ">=2.52.0" }, { name = "opencv-python-headless", marker = "extra == 'pixels'", specifier = ">=4.8.0" }, { name = "opencv-python-headless", marker = "extra == 'text-draft'", specifier = "==4.10.0.84" },