exsl 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
exsl/__init__.py ADDED
@@ -0,0 +1,87 @@
1
+ """ExSL: the document *is* the model.
2
+
3
+ There are no weights and no classifier head. A document holds the learned
4
+ hypothesis, an LLM reads it to classify inputs, and then rewrites it from the
5
+ revealed labels. What you train is readable, and what you read is what runs.
6
+
7
+ Four components plug into one interface, one file each, and the imports only
8
+ point downward:
9
+
10
+ gateway.py the wire to an LLM, and SetupNeeded
11
+ data.py the dataset, the input representation, row rendering
12
+ formats.py how the hypothesis is written down and revised
13
+ signals.py the audio codec, imported only on demand
14
+ learn.py run artifacts, the gate, the baseline, train / evaluate
15
+
16
+ ``import exsl`` is the only entry point: everything public is re-exported here,
17
+ so callers never see the split.
18
+
19
+ The gate algorithm runs this loop per epoch::
20
+
21
+ predict the feedback batches from the current document (labels hidden)
22
+ reveal the labels and ask for one bounded revision
23
+ score the current and revised documents head to head on protected rows
24
+ keep the revision only if it wins
25
+
26
+ ``state.json`` is the truth; the skill file is rendered from it.
27
+
28
+ import exsl
29
+
30
+ data = exsl.dataset(
31
+ train=[{"text": "wire me $500 today", "label": "spam"},
32
+ {"text": "lunch at one?", "label": "ham"}],
33
+ classes=("spam", "ham"),
34
+ description="Each input is one email body.",
35
+ )
36
+ skill = exsl.train(data, algo="exsl")
37
+ print(skill)
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+
43
+ def _legacy_environment():
44
+ """Before the rename to ExSL every setting was an SDM_* variable; an old SDM_X still sets EXSL_X when that is unset."""
45
+ import os
46
+ for name in [n for n in os.environ if n.startswith("SDM_")]:
47
+ os.environ.setdefault("EXSL_" + name[4:], os.environ[name])
48
+
49
+
50
+ _legacy_environment()
51
+
52
+ from . import datasets, science
53
+ from .data import (REPRESENTATIONS, Dataset, Report, content, dataset,
54
+ describe, from_jsonl, labeled)
55
+ from .formats import (DEFAULT_FORMAT_MD, PACKAGED_FORMAT_FILE, apply_edits, clean_condition, codecs,
56
+ credit, format_file, formats, get_format, load_formats,
57
+ new_state, parse_edits, parse_predictions, render,
58
+ validate_html, validate_svg, validate_text,
59
+ write_format_file)
60
+ from .gateway import SetupNeeded
61
+ from .learn import (ALGOS, GATE_SCORING, Skill, epoch_points, decide,
62
+ evaluate, load, parse_paired, proposal_history_text,
63
+ split_holdout, stratified_holdout, train)
64
+ from .experiment import run_experiment
65
+ from .prauc import average_precision, evaluate_prauc
66
+
67
+ __version__ = "0.3.0"
68
+
69
+ __all__ = [
70
+ # the API
71
+ "Dataset", "Report", "Skill", "SetupNeeded",
72
+ "dataset", "datasets", "science", "from_jsonl", "load", "train", "evaluate",
73
+ "run_experiment", "evaluate_prauc", "average_precision",
74
+ # the four components
75
+ "REPRESENTATIONS", "describe",
76
+ "formats", "get_format", "load_formats", "DEFAULT_FORMAT_MD",
77
+ "format_file", "write_format_file", "PACKAGED_FORMAT_FILE",
78
+ "ALGOS", "GATE_SCORING", "codecs",
79
+ # the pieces the README and the checks reach for
80
+ "render", "new_state", "parse_edits", "apply_edits", "clean_condition",
81
+ "parse_predictions", "parse_paired", "credit",
82
+ "validate_text", "validate_html", "validate_svg",
83
+ "stratified_holdout", "split_holdout", "epoch_points", "decide",
84
+ "proposal_history_text",
85
+ "content", "labeled",
86
+ "__version__",
87
+ ]
exsl/__main__.py ADDED
@@ -0,0 +1,140 @@
1
+ """``python -m exsl``, and the ``exsl`` console script.
2
+
3
+ Small on purpose. The library is the product; this exists so a pip-installed
4
+ user can get an editable ``format.md``, confirm the install works without an
5
+ API key, run the shipped benchmarks, and open the local web UI.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import sys
12
+
13
+ from . import __version__, format_file, formats, write_format_file
14
+ from .gateway import SetupNeeded
15
+
16
+
17
+ def main(argv=None) -> int:
18
+ parser = argparse.ArgumentParser(
19
+ prog="exsl", description="ExSL: the externalized supervised learner.")
20
+ parser.add_argument("--version", action="version",
21
+ version=f"exsl {__version__}")
22
+ commands = parser.add_subparsers(dest="command", required=True)
23
+
24
+ initialize = commands.add_parser(
25
+ "init", help="set up this directory: a settings.json template and an editable format.md")
26
+ initialize.add_argument("--force", action="store_true",
27
+ help="overwrite an existing format.md")
28
+
29
+ commands.add_parser(
30
+ "formats", help="list the skill formats format.md defines")
31
+
32
+ from . import benchmarks
33
+ benchmarks.add_arguments(commands.add_parser(
34
+ "run", help="run a shipped benchmark: --dataset, --algo, --format"))
35
+
36
+ importer = commands.add_parser(
37
+ "import", help="fetch a public dataset, or convert your own file, into a run-ready directory")
38
+ importer.add_argument("name", help="gpqa, mmlu, arc, boolq, sst2, agnews, or file")
39
+ importer.add_argument("--out", help="directory to write (default data/<name>)")
40
+ importer.add_argument("--train", type=int, help="training rows (default 100)")
41
+ importer.add_argument("--test", type=int, help="test rows (default 100)")
42
+ importer.add_argument("--seed", type=int, default=0)
43
+ importer.add_argument("--from", dest="source", help="file: a .jsonl/.json/.csv/.tsv table")
44
+ importer.add_argument("--test-from", dest="test_source", help="file: a separate test table")
45
+ importer.add_argument("--text", help="file: the text column")
46
+ importer.add_argument("--image", help="file: a column of image paths instead of text")
47
+ importer.add_argument("--label", help="file: the label column")
48
+ importer.add_argument("--choices", help="file: option columns for multiple choice, comma-separated")
49
+ importer.add_argument("--description", help="file: what one input is")
50
+
51
+ showcase = commands.add_parser(
52
+ "showcase", help="write one HTML page comparing finished runs")
53
+ showcase.add_argument("out", help="the HTML file to write")
54
+ showcase.add_argument("runs", nargs="+", metavar="[GROUP/]LABEL[|RULE]=RUN_DIR",
55
+ help="a finished run directory and how to label it")
56
+
57
+ ui = commands.add_parser(
58
+ "ui", help="open a local web page that configures and launches runs")
59
+ ui.add_argument("--host", default="127.0.0.1")
60
+ ui.add_argument("--port", type=int, default=8765)
61
+ ui.add_argument("--no-browser", action="store_false", dest="browser",
62
+ help="do not open the page in a browser")
63
+ ui.add_argument("--datasets", default=None,
64
+ help="which datasets' runs to show: a comma list, or all (default: pods, df2, gravityspy, bloodmnist, galaxy10, sr/squarewave; sr = all six families)")
65
+
66
+ home = commands.add_parser(
67
+ "home", help="write a static copy of the exsl ui page (the learned documents) for a web site")
68
+ home.add_argument("--out", required=True, help="directory to write (index.html and data/)")
69
+ home.add_argument("--datasets", default=None,
70
+ help="which datasets to include: a comma list, or all (default: the ui's default)")
71
+ home.add_argument("--scale", type=int, default=1, help="device pixels per CSS pixel for page renders")
72
+
73
+ options = parser.parse_args(argv)
74
+ try:
75
+ if options.command == "run":
76
+ return benchmarks.run(options)
77
+ if options.command == "import":
78
+ from . import imports
79
+ if options.name == "file":
80
+ if not (options.source and options.label and (options.text or options.image) and options.out):
81
+ parser.error("import file needs --from, --label, --text or --image, and --out")
82
+ summary = imports.import_file(
83
+ options.source, text=options.text, label=options.label, image=options.image,
84
+ out=options.out, description=options.description or "",
85
+ choices=options.choices.split(",") if options.choices else None,
86
+ train=options.train, test=options.test, test_file=options.test_source,
87
+ seed=options.seed)
88
+ else:
89
+ summary = imports.import_recipe(options.name, out=options.out,
90
+ train=options.train or 100, test=options.test or 100,
91
+ seed=options.seed)
92
+ print(f"wrote {summary['out']}: {summary['train']} train, {summary['test']} test, "
93
+ f"classes {', '.join(summary['classes'])}")
94
+ if summary.get("description_defaulted"):
95
+ print(f"no --description given: edit {summary['out']}/description.txt to say what one "
96
+ "input is and what the labels mean; it is all the model is told")
97
+ print(f"next: exsl run --dataset {summary['out']} (or pick it in exsl ui)")
98
+ return 0
99
+ if options.command == "showcase":
100
+ from .showcase import main as build_showcase
101
+ return build_showcase([options.out] + options.runs)
102
+ if options.command == "ui":
103
+ from .ui import serve
104
+ return serve(options.host, options.port, options.browser, options.datasets)
105
+ if options.command == "home":
106
+ from pathlib import Path
107
+ from . import ui
108
+ if options.datasets:
109
+ ui.VISIBLE = None if options.datasets.strip() == "all" else {d.strip() for d in options.datasets.split(",") if d.strip()}
110
+ summary = ui.home(Path(options.out), options.scale)
111
+ print(f"home: {summary['runs']} runs of {len(summary['datasets'])} datasets, "
112
+ f"{summary['documents']} documents -> {summary['out']}/index.html")
113
+ return 0
114
+
115
+ if options.command == "init":
116
+ from pathlib import Path
117
+ from .gateway import SETTINGS_TEMPLATE
118
+ settings = Path.cwd() / "settings.json"
119
+ if settings.exists():
120
+ print(f"kept {settings}")
121
+ else:
122
+ settings.write_text(SETTINGS_TEMPLATE)
123
+ print(f"wrote {settings} <- fill in provider, model, api_key")
124
+ path = write_format_file(force=options.force)
125
+ print(f"wrote {path} <- the skill formats; edit or add sections")
126
+ print("Next: `exsl run --dataset cifar10` or `exsl ui`.")
127
+ return 0
128
+
129
+ active = format_file()
130
+ print(f"reading {active}")
131
+ for name, skill_format in sorted(formats().items()):
132
+ print(f" {name:10s} mechanism: {skill_format.mechanism}")
133
+ return 0
134
+ except SetupNeeded as error:
135
+ print(f"exsl: {error}", file=sys.stderr)
136
+ return 1
137
+
138
+
139
+ if __name__ == "__main__":
140
+ raise SystemExit(main())
exsl/benchmarks.py ADDED
@@ -0,0 +1,339 @@
1
+ """The shipped benchmarks, and the one command that runs them.
2
+
3
+ exsl run --dataset pods --algo exsl --format html
4
+ exsl run --dataset data/mine # train.jsonl and test.jsonl inside
5
+
6
+ Each benchmark is a loader plus the gate settings its protocol calls for. The
7
+ command line only overrides those defaults; the lifecycle (zero-training
8
+ control, gated training, evaluation, resume, result files) is the shared
9
+ :func:`exsl.run_experiment`. PODS and DF2 add the original paper's one-vs-all
10
+ PR-AUC after top-1 accuracy. A directory of JSONL rows is a benchmark too,
11
+ with the generic defaults.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+ from . import datasets, science, sequences
22
+ from .data import from_jsonl, exact_answer_grader
23
+ from .experiment import run_experiment
24
+ from .gateway import check_ready
25
+ from .learn import ALGO_ALIASES, ALGOS, GATE_SCORING, load
26
+ from .prauc import evaluate_prauc
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Benchmark:
31
+ """One dataset and the training settings its protocol uses."""
32
+
33
+ load: object
34
+ protocol: str
35
+ settings: dict = field(default_factory=dict)
36
+ train: int | None = None
37
+ test: int | None = None
38
+ image_size: int | None = None
39
+ prauc: bool = False
40
+ format: str = "markdown"
41
+
42
+
43
+ PERSONAL = {"holdout_per_class": 1, "epochs": 7, "gate_scoring": "separate",
44
+ "proposal_history": True, "max_semantic_edits": 60}
45
+ # The protocol the checked-in science rulebooks were learned under
46
+ # (reproduce/ai4science): an HTML rulebook with one sketch per class, two
47
+ # passes over the training rows under a 100- then a 200-rule cap, and no
48
+ # held-out gate, so every valid revision is kept.
49
+ SCIENCE = {"epochs": 10, "passes": 2, "max_rules": [100, 200], "gate": False,
50
+ "max_semantic_edits": 12}
51
+
52
+ # SR under the reproduction's protocol: 30 training sequences in batches of
53
+ # ten, one revision per batch, no held-out gate, an HTML rulebook with a
54
+ # sketch. The zero-shot control is the reproduction's no-document baseline.
55
+ SR = {"epochs": 3, "gate": False, "max_rules": 100, "max_semantic_edits": 12}
56
+
57
+ BENCHMARKS = {
58
+ "cifar10": Benchmark(
59
+ load=lambda o: datasets.cifar10(o.train, o.test, root=o.data_dir or "data/cifar"),
60
+ protocol="direct RGB images, 10 classes",
61
+ settings={"holdout_per_class": 1, "epochs": 5,
62
+ "max_semantic_edits": 100, "max_support_edits": 100},
63
+ train=100, test=100),
64
+ "pods": Benchmark(
65
+ load=lambda o: datasets.pods("test", o.test, image_size=o.image_size,
66
+ root=o.data_dir or "data/pods"),
67
+ protocol="PODS paper class split: 70 test objects, 3 training photos "
68
+ "each, test photos per object from the full test split",
69
+ settings=PERSONAL, test=10, image_size=512, prauc=True),
70
+ "df2": Benchmark(
71
+ load=lambda o: datasets.df2("train", o.test, image_size=o.image_size,
72
+ val_per_class=0,
73
+ root=o.data_dir or "data/personal/df2/df2"),
74
+ protocol="PODS paper protocol on DF2: 139 test shirts, 3 training "
75
+ "photos each, test photos per shirt",
76
+ settings=PERSONAL, test=10, image_size=512, prauc=True),
77
+ **{f"sr-{family}": Benchmark(
78
+ load=(lambda family: lambda o: sequences.sequence(family, o.train, o.test))(family),
79
+ protocol=f"SR {family}: 20 observed values, predict the next 10; 30 training and 100 "
80
+ "test sequences; scored per value at a 0.1 tolerance",
81
+ settings=SR, format="rulebook-html", train=30, test=100)
82
+ for family in sequences.FAMILIES},
83
+ "camelyon17": Benchmark(
84
+ load=lambda o: datasets.camelyon17(
85
+ o.train, o.test, image_size=o.image_size, seed=o.seed,
86
+ root=o.data_dir or "data/wilds/camelyon17"),
87
+ protocol="WILDS in-distribution training patches, official "
88
+ "out-of-distribution test patches",
89
+ settings={"holdout_per_class": 10, "epochs": 4,
90
+ "gate_scoring": "separate"},
91
+ train=100, test=500, image_size=288),
92
+ # The four science benchmarks of reproduce/ai4science. Their reported
93
+ # numbers were produced with the SLMD-dev learner (see that README); here
94
+ # they run under the generic gate settings.
95
+ "gravityspy": Benchmark(
96
+ load=lambda o: science.gravityspy(
97
+ o.train, o.test, image_size=o.image_size, seed=o.seed,
98
+ root=o.data_dir or "data/gravityspy"),
99
+ protocol="Gravity Spy v1.0 official train / test samples, the ten "
100
+ "largest glitch classes, four-window spectrograms with a Hz "
101
+ "ruler and time axis",
102
+ settings=SCIENCE, format="rulebook-html", train=300, test=400, image_size=412),
103
+ "galaxy10": Benchmark(
104
+ load=lambda o: science.galaxy10(
105
+ o.train, o.test, image_size=o.image_size, seed=o.seed,
106
+ root=o.data_dir or "data/galaxy10"),
107
+ protocol="Galaxy10 DECaLS colour cutouts, ten Galaxy Zoo morphology "
108
+ "classes, class-balanced seeded draw (no official split)",
109
+ settings=SCIENCE, format="rulebook-html", train=100, test=100, image_size=224),
110
+ "bloodmnist": Benchmark(
111
+ load=lambda o: science.bloodmnist(
112
+ o.train, o.test, image_size=o.image_size, seed=o.seed,
113
+ root=o.data_dir or "data/bloodmnist"),
114
+ protocol="BloodMNIST 224 px official train / test split, eight "
115
+ "peripheral blood cell types",
116
+ settings=SCIENCE, format="rulebook-html", train=300, test=160, image_size=224),
117
+ "eclipsing": Benchmark(
118
+ load=lambda o: science.eclipsing(
119
+ o.train, o.test, seed=o.seed, root=o.data_dir or "data/ogle3"),
120
+ protocol="OGLE-III LMC eclipsing binaries as order-4 Fourier "
121
+ "coefficients of the folded I-band light curve; contact / "
122
+ "semidetached / detached",
123
+ settings=SCIENCE, format="rulebook-html", train=60, test=150),
124
+ }
125
+
126
+
127
+ def _grader_of(path: Path, spec) -> object:
128
+ """The grader a graded directory's ``meta.json`` names.
129
+
130
+ ``"exact"`` (or nothing) is the exact-answer grader. ``"grader.py:grade"``
131
+ loads that function from a file beside the JSONL rows; it takes
132
+ ``(row, response)`` and returns a score in [0, 1] or ``(score, feedback)``,
133
+ which is how a task scored by a program (IFBench's constraint checker, a
134
+ unit-test runner) plugs in.
135
+ """
136
+ if not spec or spec == "exact":
137
+ return exact_answer_grader
138
+ file_name, _, function = str(spec).partition(":")
139
+ import importlib.util
140
+ location = path / file_name
141
+ if not location.is_file():
142
+ raise FileNotFoundError(f"{location} named by meta.json is missing")
143
+ module_spec = importlib.util.spec_from_file_location(f"exsl_grader_{path.name}", location)
144
+ module = importlib.util.module_from_spec(module_spec)
145
+ module_spec.loader.exec_module(module)
146
+ return getattr(module, function or "grade")
147
+
148
+
149
+ def custom(path: Path) -> Benchmark:
150
+ """A directory holding ``train.jsonl`` and ``test.jsonl`` as a benchmark.
151
+
152
+ Rows need a ``label`` and ``text`` or ``image`` (paths relative to the
153
+ file); classes are the labels seen. ``description.txt`` beside them, or
154
+ ``--description``, tells the model what one input is. A ``meta.json``
155
+ with ``{"task": "generation"}`` makes it a graded free-response task: the
156
+ reader writes an answer and ``label`` is the exact answer expected
157
+ (``exsl import gsm8k`` writes one); ``"grader": "grader.py:grade"`` in
158
+ that file scores with your own function instead.
159
+ """
160
+ train, test = path / "train.jsonl", path / "test.jsonl"
161
+ for file in (train, test):
162
+ if not file.is_file():
163
+ raise FileNotFoundError(
164
+ f"{file} is missing; a custom --dataset is a directory with "
165
+ "train.jsonl and test.jsonl")
166
+ with open(train) as handle:
167
+ first = json.loads(next(handle))
168
+ representation = "image" if "image" in first else "text"
169
+
170
+ described = path / "description.txt"
171
+ meta_file = path / "meta.json"
172
+ meta = json.loads(meta_file.read_text()) if meta_file.is_file() else {}
173
+ graded = ({"grader": _grader_of(path, meta.get("grader")), "classes": ("response",)}
174
+ if meta.get("task") == "generation" else {})
175
+
176
+ def load(options):
177
+ return from_jsonl(train, test, limit=options.train,
178
+ test_limit=options.test, name=path.name,
179
+ representation=representation,
180
+ description=options.description
181
+ or (described.read_text().strip() if described.is_file() else ""),
182
+ **graded,
183
+ **({"image_size": options.image_size}
184
+ if options.image_size else {}))
185
+
186
+ return Benchmark(load=load, protocol=f"JSONL rows under {path}",
187
+ settings={"epochs": 4})
188
+
189
+
190
+ def add_arguments(parser: argparse.ArgumentParser) -> None:
191
+ parser.add_argument("--dataset", required=True,
192
+ help=f"one of {', '.join(sorted(BENCHMARKS))}, or a "
193
+ "directory with train.jsonl and test.jsonl")
194
+ parser.add_argument("--description",
195
+ help="custom dataset: what one input is")
196
+ parser.add_argument("--algo", choices=tuple(ALGOS) + tuple(ALGO_ALIASES), default="exsl",
197
+ help="exsl: learn a document under the gate; "
198
+ "base: the zero-training control")
199
+ parser.add_argument("--format", default=None,
200
+ help="a section of format.md: markdown, rulebook-html, text, "
201
+ "html, image, audio, or your own (default: the "
202
+ "dataset's)")
203
+ parser.add_argument("--style",
204
+ help="what the document should contain, in words, "
205
+ "e.g. \"decision tree, tables, illustrations\"")
206
+ parser.add_argument("--train", type=int, help="training rows")
207
+ parser.add_argument("--test", type=int,
208
+ help="test rows (PODS, DF2: per object)")
209
+ parser.add_argument("--image-size", type=int, help="pixels per side")
210
+ parser.add_argument("--batch-size", type=int, default=10)
211
+ parser.add_argument("--epochs", type=int, help="revisions per pass")
212
+ parser.add_argument("--passes", type=int, help="passes over the training rows")
213
+ parser.add_argument("--max-rules", help="rule cap, or one per pass: 100,200")
214
+ parser.add_argument("--labels-only", action="store_true",
215
+ help="control: the writer sees each epoch's rows with labels but "
216
+ "no reader predictions (chunked document distillation)")
217
+ parser.add_argument("--no-gate", action="store_true",
218
+ help="protect nothing; keep every valid revision")
219
+ parser.add_argument("--gate", action="store_true",
220
+ help="use the held-out gate even where the dataset's protocol turns it off")
221
+ parser.add_argument("--holdout-per-class", type=int,
222
+ help="rows per class the gate protects")
223
+ parser.add_argument("--gate-scoring", choices=GATE_SCORING)
224
+ parser.add_argument("--max-semantic-edits", type=int,
225
+ help="rule edits one candidate may make")
226
+ parser.add_argument("--no-proposal-history", action="store_true",
227
+ help="hide earlier candidates' verdicts from the writer")
228
+ parser.add_argument("--proposal-examples", type=int,
229
+ help="most rows the writer is shown per revision, failures "
230
+ "first (an endpoint that allows 50 images per request "
231
+ "wants 50)")
232
+ parser.add_argument("--no-baseline", action="store_true",
233
+ help="skip the zero-training control")
234
+ parser.add_argument("--init-from", default=None, metavar="RUN",
235
+ help="warm start: begin from this run's document (the "
236
+ "federated round: a site revises the shared document)")
237
+ parser.add_argument("--classes", default=None,
238
+ help="train on a subset of the labels: comma-separated "
239
+ "names, or a file with one label per line (the "
240
+ "federated setting: each site sees its own classes)")
241
+ parser.add_argument("--seed", type=int, default=0)
242
+ parser.add_argument("--data-dir", help="where the dataset lives")
243
+ parser.add_argument("--run-dir",
244
+ help="default: runs/<dataset>-<algo>-<format>")
245
+
246
+
247
+ def settings_for(benchmark: Benchmark, options) -> dict:
248
+ """The benchmark's defaults, with explicit command-line values winning."""
249
+ settings = dict(benchmark.settings)
250
+ for key in ("epochs", "passes", "holdout_per_class", "gate_scoring",
251
+ "max_semantic_edits", "proposal_examples"):
252
+ value = getattr(options, key, None)
253
+ if value is not None:
254
+ settings[key] = value
255
+ if getattr(options, "max_rules", None):
256
+ caps = [int(part) for part in str(options.max_rules).split(",")]
257
+ settings["max_rules"] = caps[0] if len(caps) == 1 else caps
258
+ if getattr(options, "no_gate", False):
259
+ settings["gate"] = False
260
+ if getattr(options, "labels_only", False):
261
+ settings["feedback_predictions"] = False
262
+ if getattr(options, "gate", False):
263
+ settings.pop("gate", None)
264
+ if options.no_proposal_history:
265
+ settings.pop("proposal_history", None)
266
+ if options.style:
267
+ settings["style"] = options.style
268
+ return settings
269
+
270
+
271
+ def restrict_classes(data, spec: str) -> list[str]:
272
+ """Keep only the rows (train and test) whose label is in ``spec``: a
273
+ comma-separated list or a file with one label per line. ``data.classes``
274
+ shrinks to the kept labels in their original order. Returns the kept
275
+ labels. The document learned this way knows nothing of the other labels;
276
+ ``evaluate.py --all-classes`` scores it against the full label list."""
277
+ path = Path(spec)
278
+ wanted = ([line.strip() for line in path.read_text().splitlines() if line.strip()]
279
+ if path.is_file() else [part.strip() for part in spec.split(",") if part.strip()])
280
+ known = {str(c) for c in data.classes}
281
+ missing = [w for w in wanted if w not in known]
282
+ if missing:
283
+ raise SystemExit(f"--classes: unknown labels {missing[:5]}; the dataset has "
284
+ f"{', '.join(list(known)[:8])}...")
285
+ keep = set(wanted)
286
+ data.train = [r for r in data.train if str(r["label"]) in keep]
287
+ data.test = [r for r in data.test if str(r["label"]) in keep]
288
+ data.classes = tuple(c for c in data.classes if str(c) in keep)
289
+ return [str(c) for c in data.classes]
290
+
291
+
292
+ def run(options) -> int:
293
+ if options.dataset in BENCHMARKS:
294
+ benchmark = BENCHMARKS[options.dataset]
295
+ elif Path(options.dataset).is_dir():
296
+ benchmark = custom(Path(options.dataset))
297
+ else:
298
+ raise SystemExit(f"exsl run: unknown dataset {options.dataset!r}; choose "
299
+ f"{', '.join(sorted(BENCHMARKS))} or a directory with "
300
+ "train.jsonl and test.jsonl")
301
+ name = Path(options.dataset).name
302
+ if options.format is None:
303
+ options.format = benchmark.format
304
+ check_ready()
305
+ for key in ("train", "test", "image_size"):
306
+ if getattr(options, key) is None:
307
+ setattr(options, key, getattr(benchmark, key))
308
+ data = benchmark.load(options)
309
+ subset = None
310
+ if getattr(options, "classes", None):
311
+ subset = restrict_classes(data, options.classes)
312
+ options.algo = ALGO_ALIASES.get(options.algo, options.algo) # "sdm", the name before ExSL
313
+ run_dir = options.run_dir or f"runs/{name}-{options.algo}-{options.format}"
314
+ settings = settings_for(benchmark, options)
315
+ if getattr(options, "init_from", None):
316
+ import json as _json
317
+ seed_cfg = _json.loads((Path(options.init_from) / "state.json").read_text())["config"]
318
+ known = [str(c) for c in seed_cfg.get("classes", [])]
319
+ known += [str(c) for c in data.classes if str(c) not in set(known)]
320
+ settings["init_from"] = options.init_from
321
+ settings["known_classes"] = known
322
+ print(f"{name}: {len(data.classes)} classes, {len(data.train)} "
323
+ f"training rows, {len(data.test)} test rows; {benchmark.protocol}")
324
+ print(f"algo={options.algo}; format={options.format}", flush=True)
325
+ run_experiment(
326
+ data, run_dir=run_dir, algo=options.algo, format=options.format,
327
+ batch_size=options.batch_size,
328
+ run_baseline=options.algo == "exsl" and not options.no_baseline,
329
+ metadata={"protocol": benchmark.protocol, "seed": options.seed,
330
+ **({"classes_subset": subset} if subset else {})},
331
+ seed=options.seed, **settings)
332
+ if benchmark.prauc:
333
+ skill = load(run_dir)
334
+ result = evaluate_prauc(skill, data, run_dir=run_dir, tag="prauc")
335
+ print(f"PR-AUC {100 * result['mean_prauc']:.1f}, top-1 from the same "
336
+ f"scores {100 * result['top1_from_scores']:.1f}% "
337
+ f"({result['unparsed_inputs']} unparsed inputs); saved to "
338
+ f"{run_dir}/prauc.json")
339
+ return 0