Metadata-Version: 2.4
Name: sdm-learn
Version: 0.1.2
Summary: Self-documenting models: the document is the model.
Author: Yulu Gan
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/sunrainyg/sdm
Project-URL: Repository, https://github.com/sunrainyg/sdm
Keywords: machine-learning,llm,interpretability,self-documenting,supervised-learning
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24
Provides-Extra: image
Requires-Dist: numpy>=1.21; extra == "image"
Requires-Dist: Pillow>=9; extra == "image"
Requires-Dist: cairosvg>=2.5; extra == "image"
Provides-Extra: audio
Requires-Dist: numpy>=1.21; extra == "audio"
Requires-Dist: Pillow>=9; extra == "audio"
Provides-Extra: pods
Requires-Dist: Pillow>=9; extra == "pods"
Requires-Dist: pyarrow>=12; extra == "pods"
Provides-Extra: science
Requires-Dist: numpy>=1.21; extra == "science"
Requires-Dist: Pillow>=9; extra == "science"
Requires-Dist: h5py>=3; extra == "science"
Provides-Extra: all
Requires-Dist: numpy>=1.21; extra == "all"
Requires-Dist: Pillow>=9; extra == "all"
Requires-Dist: cairosvg>=2.5; extra == "all"
Requires-Dist: pyarrow>=12; extra == "all"
Requires-Dist: h5py>=3; extra == "all"
Dynamic: license-file

# sdm-learn: Self-Documenting Models

**The document *is* the model.**

[![PyPI](https://img.shields.io/pypi/v/sdm-learn.svg)](https://pypi.org/project/sdm-learn/)
[![Python](https://img.shields.io/pypi/pyversions/sdm-learn.svg)](https://pypi.org/project/sdm-learn/)
[![checks](https://github.com/sunrainyg/sdm/actions/workflows/test.yml/badge.svg)](https://github.com/sunrainyg/sdm/actions/workflows/test.yml)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)

`sdm` trains a classifier that has no weights. An LLM writes a document that
says how to tell the classes apart, the same LLM reads that document to
classify new inputs, and a gate keeps a revision only when it does not lower
accuracy on protected training rows. What you train is a readable file. What
you read is what runs.

```bash
pip install sdm-learn
sdm run --dataset cifar10                      # a markdown rulebook, plus the zero-shot control
sdm run --dataset pods --format html           # the same learner writing an HTML page
sdm run --dataset data/mine --algo base        # your own JSONL rows, control only
```

---

## Contents

1. [How it works](#how-it-works)
2. [Installation](#installation)
3. [Configuring the LLM](#configuring-the-llm)
4. [Quickstart](#quickstart)
5. [Concepts](#concepts)
6. [Command-line reference](#command-line-reference)
7. [Python API reference](#python-api-reference)
8. [Skill formats](#skill-formats)
9. [Datasets](#datasets)
10. [What a run writes](#what-a-run-writes)
11. [Environment variables](#environment-variables)
12. [Results](#results)
13. [Development](#development)
14. [FAQ](FAQ.md) · [Changelog](CHANGELOG.md) · [License](#license)

---

## How it works

One training run is a loop over **epochs**. Each epoch:

1. **Predict.** The reader classifies a batch of feedback rows from the
   current document. Labels are hidden.
2. **Reveal and revise.** The labels are revealed together with the
   predictions, and the writer proposes one bounded revision of the document.
3. **Gate.** The current document and the candidate each classify the
   *protected* rows, which the writer never sees. The candidate is kept only
   if its protected accuracy is at least the current document's.

The protected rows and their labels never appear in any prompt to the writer,
so the writer cannot fit the gate. Every model request is archived, so a
finished run can be audited.

Two algorithms ship:

| `algo` | What it does |
|---|---|
| `sdm` | The loop above: an LLM writes the document, the gate selects revisions. |
| `base` | The zero-training control: the same reader and prompts, no document, no training requests. |

The document can be written in several **formats** (markdown rules, plain
text, an HTML page with inline SVG, a wordless SVG picture, a synthesized
audio clip), switched with one parameter. Every format goes through the same
loop, the same gate, and the same evaluation.

## Installation

Python 3.9 or newer.

```bash
pip install sdm-learn                 # text formats only; depends on httpx alone
pip install 'sdm-learn[image]'        # + Pillow, numpy, cairosvg: image rows and the image format
pip install 'sdm-learn[audio]'        # + Pillow, numpy: the audio format
pip install 'sdm-learn[pods]'         # + Pillow, pyarrow: the PODS and DF2 datasets
pip install 'sdm-learn[science]'      # + Pillow, numpy, h5py: the four science datasets
pip install 'sdm-learn[all]'          # everything above
```

The import name is `sdm`; the distribution is `sdm-learn` because `sdm` on
PyPI was taken by an unrelated package.

From a checkout, `./setup.sh` creates a virtual environment and installs the
package in editable mode with every extra. By default it does so inside a
[Docker Sandbox](https://docs.docker.com/ai/sandboxes/); `./setup.sh
--no-sandbox` installs directly into `.venv`.

## Configuring the LLM

Every request goes through one OpenAI-compatible Chat Completions endpoint.
Put the provider, model, and key in `settings.json` in the working directory
(the file is gitignored):

```bash
cp settings.example.json settings.json
```

```json
{
  "provider": "openai",
  "model": "gpt-5.6",
  "api_key": "your-api-key"
}
```

`provider` selects the endpoint; `model` is passed through verbatim, so use a
current model name from the provider's own documentation. Image datasets and
the `image` and `audio` formats need a model that accepts image input.

<details>
<summary><strong>Supported providers</strong></summary>

| `provider` | Key variable (optional) | Docs |
|---|---|---|
| `openai` | `OPENAI_API_KEY` | [docs](https://platform.openai.com/docs/api-reference/chat) |
| `google` (alias `gemini`) | `GEMINI_API_KEY` | [docs](https://ai.google.dev/gemini-api/docs/openai) |
| `anthropic` (alias `claude`) | `ANTHROPIC_API_KEY` | [docs](https://platform.claude.com/docs/en/api/openai-sdk) |
| `kimi` (alias `moonshot`) | `MOONSHOT_API_KEY` | [docs](https://platform.kimi.ai/docs/api/quickstart) |
| `xai` | `XAI_API_KEY` | [docs](https://docs.x.ai/docs/guides/chat) |
| `deepseek` | `DEEPSEEK_API_KEY` | [docs](https://api-docs.deepseek.com/) |
| `qwen` | `DASHSCOPE_API_KEY` | [docs](https://www.alibabacloud.com/help/en/model-studio/qwen-api-via-openai-chat-completions) |
| `mistral` | `MISTRAL_API_KEY` | [docs](https://docs.mistral.ai/api/endpoint/chat) |
| `groq` | `GROQ_API_KEY` | [docs](https://console.groq.com/docs/openai) |
| `huggingface` | `HF_TOKEN` | [docs](https://huggingface.co/docs/inference-providers/en/index) |
| `novita` | `NOVITA_API_KEY` | [docs](https://novita.ai/docs/guides/llm-api) |
| `openrouter` | `OPENROUTER_API_KEY` | [docs](https://openrouter.ai/docs/quickstart) |
| `hyperbolic` | `HYPERBOLIC_API_KEY` | [docs](https://www.hyperbolic.ai/docs/inference/text-apis) |
| `cerebras` | `CEREBRAS_API_KEY` | [docs](https://inference-docs.cerebras.ai/resources/openai) |
| `mercury` (alias `inception`) | `INCEPTION_API_KEY` | [docs](https://docs.inceptionlabs.ai/get-started/get-started) |
| `ollama` (local) | none | [docs](https://docs.ollama.com/api/openai-compatibility) |
| `vllm` (local) | none | [docs](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) |
| `custom` | none | any OpenAI-compatible gateway; set `gateway_url` |

</details>

The key is looked up in this order: `SDM_API_KEY`, the provider's key
variable, `api_key` in `settings.json`, then the file `~/.sdm_key`.

**Company gateway.** For an OpenAI-compatible gateway of your own:

```json
{
  "provider": "custom",
  "gateway_url": "https://llm.company.example/v1/chat/completions",
  "model": "your-company-model",
  "api_key": "your-gateway-token"
}
```

Leave `api_key` empty if the gateway needs no bearer token.

**Reasoning effort.** `"effort": "low"` (the default) is sent as
`reasoning_effort` only when `SDM_EFFORT_FIELD=reasoning_effort`; many
endpoints reject unknown fields, so nothing is sent by default. See
[Environment variables](#environment-variables) for temperature, token
ceilings, extra payload fields, and a separate writer model.

## Quickstart

### Python

```python
import sdm

data = sdm.dataset(
    train=[{"text": "wire me $500 today", "label": "spam"},
           {"text": "claim your free reward", "label": "spam"},
           {"text": "lunch at one?", "label": "ham"},
           {"text": "please review my pull request", "label": "ham"}],
    test=[{"text": "urgent cash prize", "label": "spam"},
          {"text": "standup moved to ten", "label": "ham"}],
    classes=("spam", "ham"),
    description="Each input is one email body.",
)

skill = sdm.train(data, algo="sdm", format="markdown",
                  batch_size=2, holdout_per_class=1, epochs=1,
                  run_dir="runs/email")
print(skill.text)                       # the learned document
report = sdm.evaluate(skill, data)      # score it on data.test
print(report.accuracy, report.rows[0])
```

`sdm.run_experiment(data, run_dir=...)` does the same and also runs the
`base` control, caches both, and writes `results.json`.

### Command line

```bash
sdm ui                                                 # the same, from a web page
sdm run --dataset cifar10                              # rulebook + zero-shot control
sdm run --dataset pods --format html --style "decision tree, tables, illustrations"
sdm run --dataset camelyon17 --algo base               # control only
sdm run --dataset data/mine --description "Each input is one support ticket."
```

Results land in `runs/<dataset>-<algo>-<format>/`. Rerunning the same command
resumes an interrupted run and returns a finished one from cache.

## Concepts

**Dataset.** Labeled rows. Every row has a `label` and either `text` (prose
or serialized features) or `image` (a file path, a PIL image, or an RGB
array). `classes` is the label vocabulary; `description` is the one sentence
the model gets about what an input is, so it is worth writing carefully.

**Document, writer, reader.** The document is the hypothesis. The *writer* is
the model call that proposes a revision from revealed labels; the *reader* is
the model call that classifies inputs given the document. They are the same
model unless `SDM_WRITER_MODEL` says otherwise.

**Format.** How the document is written down and revised: numbered rules
under an edit grammar, or a whole document (text, HTML, SVG, audio score)
revised by SEARCH/REPLACE patches or full replacement. Formats are sections of
`format.md`; see [Skill formats](#skill-formats).

**Epoch.** One pass over a slice of the feedback rows: predict them, reveal
their labels, propose one revision, gate it. `epochs` sets how many slices;
a slice is at least one batch.

**Protected rows and the gate.** `holdout_per_class` rows of every class (or
every row whose `split` field equals `holdout_split`) are set aside before
training. Only the gate ever sees them, and only the reader sees them, never
the writer. A candidate is accepted when its protected accuracy is at least
the current document's; a regression is rejected. `gate_scoring="separate"`
classifies the protected rows once per document in separate requests, so the
text of one document can never leak into the other's answers;
`"paired"` scores both in one request with the letters shuffled.

**Style.** Free text handed to the writer with every revision request,
naming the kinds of content the document should use
(`"decision tree, tables, illustrations"`). The format's grammar and limits
still decide what is legal.

## Command-line reference

```
sdm --version
sdm init [--force]          write an editable format.md into the working directory
sdm formats                 list the formats the active format.md defines
sdm run --dataset NAME|DIR [options]
sdm ui [--port 8765] [--host 127.0.0.1] [--no-browser]
sdm showcase OUT.html [GROUP/]LABEL[|RULE]=RUN_DIR ...
```

### `sdm ui`

A local web app with four views. **Runs** lists everything under `runs/`
(dataset, document format, gate rule, result, status), filterable, with
checkboxes to compare. **New run** is a form over `sdm run`: dataset
(built-in or your own directory), algorithm, format, style, provider, model
and API key, and every gate setting; each run is a subprocess whose key
travels in its environment and is never written to disk. **Run detail** shows
the live log, the verdict per epoch, the results, and the document epoch by
epoch. **Compare** draws the selected runs as the showcase does: the metric
per format, document growth, per-class scores, and the documents side by
side, grouped by dataset. It binds to localhost and has no authentication,
so do not expose it further.

### `sdm run`

| Option | Default | Meaning |
|---|---|---|
| `--dataset` | required | `cifar10`, `pods`, `df2`, `camelyon17`, `gravityspy`, `galaxy10`, `bloodmnist`, `eclipsing`, or a directory holding `train.jsonl` and `test.jsonl` |
| `--algo` | `sdm` | `sdm` learns a document under the gate; `base` is the zero-training control |
| `--format` | per dataset | a section of `format.md`: `markdown`, `rulebook-html`, `text`, `html`, `image`, `audio`, or your own |
| `--style` | none | what the document should contain, in words |
| `--description` | none | custom dataset only: what one input is |
| `--train`, `--test` | per dataset | training rows, test rows (PODS and DF2: test photos per object) |
| `--image-size` | per dataset | pixels per side for image rows |
| `--batch-size` | `10` | inputs per prediction request |
| `--epochs` | per dataset | revisions per pass |
| `--passes` | per dataset | passes over the training rows (the writer sees every row once per pass) |
| `--max-rules` | format default | rule cap, or one per pass (`100,200`) |
| `--no-gate`, `--gate` | per dataset | protect nothing and keep every valid revision, or force the held-out gate |
| `--holdout-per-class` | per dataset | protected rows per class |
| `--gate-scoring` | per dataset | `paired` or `separate` |
| `--max-semantic-edits` | per dataset | ADD/REVISE/DELETE operations one candidate may make (`markdown`) |
| `--no-proposal-history` | off | hide earlier candidates' edits and verdicts from the writer |
| `--no-baseline` | off | skip the `base` control (it is run and cached by default for `--algo sdm`) |
| `--seed` | `0` | shuffles the holdout draw and the feedback order |
| `--data-dir` | per dataset | where the dataset lives |
| `--run-dir` | `runs/<dataset>-<algo>-<format>` | where artifacts go |

Each built-in dataset carries the settings its protocol uses (see
[Datasets](#datasets)); a flag overrides only that setting. PODS and DF2 also
score the original paper's one-vs-all PR-AUC after top-1 accuracy.

## Python API reference

Everything public is available as `sdm.<name>`.

### Data

```python
sdm.dataset(train, test=(), *, classes=(), name="custom", title="",
            description="", representation="text", image_size=224) -> Dataset
sdm.from_jsonl(train, test=None, *, limit=None, test_limit=None, **options) -> Dataset
```

`sdm.dataset` wraps in-memory rows. `sdm.from_jsonl` reads one JSON object
per line; relative `image` paths resolve from the file's own directory.
`classes` is inferred from the labels when omitted. `representation` is
`"text"` (rows are serialized into the prompt) or `"image"` (rows are
attached as images at `image_size` pixels per side). `Dataset` fields:
`train`, `test`, `classes`, `name`, `title`, `description`,
`representation`, `image_size`.

```python
sdm.datasets.cifar10(train=100, test=100, *, root="data/cifar", download=True)
sdm.datasets.pods(classes="test", test_per_class=10, *, root="data/pods",
                  image_size=512, anonymize=True, seed=0, category=None)
sdm.datasets.df2(classes="train", test_per_class=10, *, root="data/personal/df2/df2",
                 image_size=512, seed=0, val_per_class=0, anonymize=True)
sdm.datasets.camelyon17(train=100, test=500, *, root="data/wilds/camelyon17",
                        image_size=288, seed=0, train_folder="train", val=0, val_folder="val")
sdm.science.gravityspy(...), sdm.science.galaxy10(...), sdm.science.bloodmnist(...), sdm.science.eclipsing(...)
```

### Training and evaluation

```python
sdm.train(data, *, algo="sdm", format=None, format_file=None, style=None,
          batch_size=10, epochs=4, holdout_per_class=None, holdout_split=None,
          gate_scoring="paired", proposal_history=False, proposal_examples=None,
          max_semantic_edits=None, max_support_edits=None,
          max_words=None, max_rules=None, max_chars=None,
          passes=1, gate=True,
          seed=0, order_seed=20260818, thin_classes_feedback_only=False,
          run_dir=None, resume=True, evaluate_after=False) -> Skill
```

| Parameter | Meaning |
|---|---|
| `algo` | `"sdm"` or `"base"` |
| `format`, `format_file` | a section name in `format.md`, and which `format.md` to read (default: `./format.md`, else the packaged one) |
| `style` | free-text content guide for the writer |
| `batch_size` | inputs per prediction request, in training and in the gate |
| `epochs` | gated revisions; clipped to the number of feedback batches |
| `holdout_per_class` | protected rows per class; default is a tenth of the training rows split across classes, at least one |
| `holdout_split` | protect the rows whose `split` field has this value instead |
| `gate_scoring` | `"paired"` or `"separate"` |
| `proposal_history` | show the writer every earlier candidate's edits and verdict |
| `proposal_examples` | cap the feedback rows shown to the writer per epoch, failures first |
| `max_semantic_edits`, `max_support_edits` | per-candidate edit budget for the `markdown` format |
| `max_words`, `max_rules`, `max_chars` | override the format's size knobs; `max_rules` may be a list with one cap per pass |
| `passes` | repeat the feedback schedule; every training row is shown once per pass |
| `gate` | `False` protects nothing and keeps every valid candidate |
| `seed`, `order_seed` | holdout draw and feedback order; gate row order |
| `thin_classes_feedback_only` | let a class with too few rows to hold out stay feedback-only instead of raising |
| `run_dir`, `resume` | where to write artifacts, and whether to continue a run found there |
| `evaluate_after` | score `data.test` before returning |

```python
sdm.evaluate(skill, data, *, batch_size=10, run_dir=None) -> Report
sdm.load(path) -> Skill              # a run directory or a state.json
sdm.run_experiment(data, *, run_dir, algo="sdm", format=None, batch_size=10,
                   eval_batch_size=None, holdout_per_class=None, epochs=4,
                   resume=True, run_baseline=True, metadata=None, **train_options) -> dict
sdm.evaluate_prauc(skill, data, *, run_dir=None, batch_size=10, top_k=5, tag="prauc") -> dict
```

`Report` has `correct`, `total`, `accuracy`, `requests`, and `rows` (one dict
per test row: `index`, `true`, `pred`, `correct`, `rules_used`, `evidence`).
`run_experiment` returns `{"config", "learned", "baseline", "delta"}` and
refuses to reuse cached results when the rows or settings changed.
`evaluate_prauc` returns `mean_prauc`, `top1_from_scores`, and `per_class`.

### `Skill`

| Member | Meaning |
|---|---|
| `skill.text` | the rendered document |
| `skill.format` | the format name (`None` for `base`) |
| `skill.rules` | the rule list for the `markdown` format |
| `skill.state` | the full state: config, rules or document source, training log, candidates, request audit |
| `skill.save(path)` | a file path writes the document; a directory writes the whole run |
| `Skill.load(path)` | the inverse |

### Format helpers

```python
sdm.formats(path=None) -> dict[str, SkillFormat]
sdm.get_format(name=None, path=None) -> SkillFormat
sdm.format_file(path=None) -> Path          # which format.md a run reads
sdm.write_format_file(target=None, *, force=False) -> Path   # what `sdm init` does
```

## Skill formats

A format is a section of `format.md`. The packaged file ships five; `sdm
init` copies it into the working directory so you can edit or add sections,
and `sdm formats` lists what the active file defines.

| Format | Mechanism | What the writer writes | What the reader sees | Text allowed |
|---|---|---|---|---|
| `markdown` | `edits` | one bounded diff of numbered rules (`ADD`, `REVISE`, `SUPPORT`, `DELETE`, `SKETCH`, `NOOP`) | the rulebook, with per-rule use and hit counters | yes |
| `rulebook-html` | `edits` | the same diff; `SKETCH \| class \| <svg>` adds one schematic per class | the rulebook as an HTML page with a section per class | yes |
| `text` | `document` | one plain-text document | the text | yes |
| `html` | `document` | one static page; inline SVG encouraged | the page source | yes |
| `image` | `document` | one standalone SVG | the rasterized picture | **none**: `<text>`, `<tspan>`, `<textPath>`, `<foreignObject>` are refused |
| `audio` | `signal` | a synthesis score (`TONE hz seconds`, `REST seconds`) | a mel spectrogram and a segment analysis; the score itself is withheld | n/a |

`document` formats are revised by a `<patch>` of SEARCH/REPLACE hunks against
the current source, by a complete replacement, or kept with `NOOP`; every
result must pass the format's validator (size caps, no scripts or external
references, balanced tags, the text ban for `image`) or the candidate is
rejected as invalid.

### Adding a format

A new text-based format is a new section, no Python:

```markdown
## checklist

mechanism: document
validator: text
block: skill_checklist
max_words: 3000
max_chars: 15000

One numbered checklist the reader walks top to bottom. Each line names one
observable cue and the class it points to.
```

| Knob | Mechanisms | Meaning |
|---|---|---|
| `mechanism` | all | `edits`, `document`, or `signal` |
| `validator` | `document` | `text`, `html`, or `svg` |
| `render` | `document` | `svg` to show the reader a rasterized picture instead of the source |
| `block` | `document` | the tag the writer wraps a replacement in |
| `signal` | `signal` | the codec: `audio` |
| `max_words`, `max_chars`, `max_rules` | as applicable | size caps |

A ```` ```seed ```` fenced block inside a section supplies the empty document
a run starts from. The prose after the knobs is shown to the writer as the
format's instructions.

## Datasets

### Built-in

| `--dataset` | Task | Protocol defaults | Data |
|---|---|---|---|
| `cifar10` | 10 classes, 100 training images, 100 test images | 1 protected image per class, 5 epochs | downloaded on first use to `data/cifar/` |
| `pods` | 70 personal objects, 3 training photos each, up to 10 test photos per object; scored by top-1 and the paper's one-vs-all PR-AUC | 1 protected photo per object, 7 epochs, separate gate scoring, proposal history, 60 edits per candidate | `pods_info.json`, `train`, and `test_dense` download on first use; fetch the three full test shards as in [`reproduce/pods`](reproduce/pods/README.md) |
| `df2` | 139 shirts from DeepFashion2 under the same protocol | as `pods` | unpack the PODS paper's zip under `data/personal/df2/` |
| `camelyon17` | tumor vs normal lymph-node patches, tested on a hospital not seen in training | 10 protected patches per class, 4 epochs, separate gate scoring | prepared WILDS subset under `data/wilds/camelyon17/{train,test}/` as `<id>.jpg` + `<id>.cls` |
| `gravityspy` | 10 LIGO glitch morphologies from four-window spectrograms, 300 training images | science protocol | downloaded on first use (3.3 GB); see [`reproduce/ai4science`](reproduce/ai4science/README.md) |
| `galaxy10` | 10 Galaxy Zoo morphology classes from DECaLS cutouts, 100 training images | science protocol | downloaded on first use (2.7 GB) |
| `bloodmnist` | 8 peripheral blood cell types, 300 training images | science protocol | downloaded on first use (1.5 GB) |
| `eclipsing` | contact / semidetached / detached binaries from Fourier coefficients (text), 60 training rows | science protocol | catalog and photometry fetched on first use |

The four science loaders live in `sdm.science` and need the `science` extra.
Their protocol is the one the checked-in rulebooks in
[`reproduce/ai4science`](reproduce/ai4science/README.md) were learned under:
the `rulebook-html` format with one sketch per class, 10 revisions per pass
over two passes under a 100- then a 200-rule cap, and no held-out gate
(`--gate` turns it back on).

### Your own

A directory with `train.jsonl` and `test.jsonl`:

```jsonl
{"text": "wire me $500 today", "label": "spam"}
{"image": "photos/0001.jpg", "label": "mug-1"}
```

```bash
sdm run --dataset data/mine --description "Each input is one email body."
```

Rows need a `label` and `text` or `image`; the representation is inferred
from the first row; image paths resolve relative to the JSONL file; classes
are the labels seen. The same rows work in Python through `sdm.from_jsonl` or
`sdm.dataset`, and `runs/my_experiment.py` is a template whose `load_data()`
is the only part to edit.

## What a run writes

```
runs/<name>/
  state.json             the truth: config, document or rules, training log, candidates, request audit
  skill.md | skill.txt | skill.html | skill.svg (+ skill.png) | skill.score.txt (+ skill.wav, skill.mp3, skill.spectrogram.png)
  candidates.json        one entry per epoch: edits, gate scores, decision and reason
  candidate_skills/      the document each epoch proposed, accepted or not
  raw/train/ raw/candidates/ raw/gate/   every model reply, verbatim
  results.json           test accuracy (and the control's) with per-row predictions
  baseline.json          the cached control
  prauc.json             PODS and DF2: per-object PR-AUC
```

`state.json` is what `sdm.load` reopens and what a resumed run continues
from. `results.json` records a fingerprint of the rows, so a changed dataset
in the same `run_dir` is refused rather than mixed. `reproduce/audit.py`
checks a run directory for split leakage from these files alone.

## Environment variables

Every variable overrides `settings.json`; none is required.

| Variable | Meaning |
|---|---|
| `SDM_SETTINGS_FILE` | path of the settings file (default `./settings.json`) |
| `SDM_PROVIDER`, `SDM_MODEL`, `SDM_GATEWAY_URL`, `SDM_API_KEY`, `SDM_API_KEY_FILE` | the connection |
| `SDM_EFFORT` | reasoning effort value (default `low`) |
| `SDM_EFFORT_FIELD` | `reasoning_effort` to send it, `off` (default) to send nothing |
| `SDM_MAX_TOKENS_FIELD` | `max_tokens` (default) or `max_completion_tokens` |
| `SDM_MAX_COMPLETION_TOKENS` | ceiling on completion tokens (`0` = none) |
| `SDM_TEMPERATURE` | sampling temperature for the reader (unset = endpoint default) |
| `SDM_EXTRA_PAYLOAD` | JSON merged into every reader request body, e.g. `{"chat_template_kwargs": {"enable_thinking": false}}` |
| `SDM_WRITER_MODEL`, `SDM_WRITER_EFFORT` | a different model or effort for the writer |
| `SDM_WRITER_GATEWAY_URL`, `SDM_WRITER_API_KEY` | a different endpoint for the writer |
| `SDM_FORMAT_FILE` | which `format.md` to read |
| `SDM_RENDER_MEDIA` | `0` disables rasterizing and synthesis (the offline tests set this) |

## Results

PODS (Sundaram et al., ICLR 2025): 70 personal objects, 3 training photos
each, one-vs-all PR-AUC over 700 test photos, labels anonymized to `mug-3`
so nothing can be guessed from a name. One reader, one gate, several formats;
single runs, about ±2 points between repeats.

| Format | PR-AUC | top-1 |
|---|---|---|
| zero-shot (`--algo base`) | 5.7 | 6.4% |
| DINOv2 pretrained (the paper's baseline, reproduced) | 30.3 | 58.1% |
| `text` | **96.0** | 93.6% |
| `html --style "decision tree, tables, illustrations"` | **95.6** | 92.9% |
| `markdown` | **95.4** | 91.4% |
| `html` | 91.3 | 85.9% |
| `image` (no words) | 64.5 | 59.4% |
| `audio` | 6.1 | 7.0% |

Commands, data preparation, and the remaining differences from the paper are
in [`reproduce/`](reproduce/README.md). [`reproduce/ai4science`](reproduce/ai4science/README.md)
holds four science tasks (LIGO glitches, galaxy morphology, blood cells,
eclipsing binaries) with their learned HTML rulebooks and designed views.
`sdm showcase` renders a set of runs as one interactive page; the Compare
tab of `sdm ui` shows the same view for any finished runs.

## Development

```bash
git clone https://github.com/sunrainyg/sdm && cd sdm
./setup.sh --no-sandbox                 # .venv with every extra, editable install
.venv/bin/python tests/test_sdm.py      # offline: the gateway is the one seam the tests stub
.venv/bin/python -m pyflakes src/sdm/*.py tests/*.py reproduce/*.py
```

The layout is four components with imports pointing one way:

```
src/sdm/gateway.py     the wire to an LLM; settings, retries, SetupNeeded
src/sdm/data.py        Dataset, representations, row rendering
src/sdm/formats.py     how the hypothesis is written down, validated, revised
src/sdm/signals.py     the audio codec, imported only on demand
src/sdm/learn.py       the gate, the control, train / evaluate, run artifacts
src/sdm/experiment.py  run_experiment: caching, the control, results.json
src/sdm/prauc.py       the PODS paper's metric
src/sdm/datasets.py    CIFAR-10, PODS, DF2, Camelyon17
src/sdm/science.py     Gravity Spy, Galaxy10, BloodMNIST, eclipsing binaries
src/sdm/benchmarks.py  the `sdm run` registry and command
```

Releases: bump `sdm.__version__`, tag `vX.Y.Z`, push the tag. The publish
workflow checks that the tag matches the version, runs the tests, builds, and
uploads to PyPI through trusted publishing.

## License

Apache-2.0
