appvoid commited on
Commit
ff6ec5b
·
verified ·
1 Parent(s): c2b16ff

Release corrected SmolCUA v1.1 with cached batching and live progress

Browse files

Preserve original v1.0; add audited corrected dataset, pretokenization/cache schema 2, greedy cached batching with OOM backoff and last-position logits, live measured progress, and strict self-scoring. Validated with 38 local tests and tiny-model CPU inference parity.

LOCAL_CHANGES.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Local corrected SmolCUA edition
2
+
3
+ The benchmark suite uses **SmolCUA v1.1 / local-corrected**. This corrected revision was prepared in the benchmark workspace and retains the `local-corrected` edition identifier for reproducibility. Original v1.0 files remain under `runs/v1_seed_20261023`. Use a new output directory when switching editions. The toolkit defaults to corrected v1.1; original v1.0 is available via `--run-subdir runs/v1_seed_20261023`.
4
+
5
+ ## Question repairs
6
+
7
+ 250 of 5,000 prompts were corrected, 50 in each group:
8
+
9
+ - TSV: restore the missing three fields, their order, and delimiter requirements.
10
+ - Safe inset: state the missing horizontal/vertical inset and reference edges.
11
+ - Percentage coordinates: state the missing percentages and top-left origin.
12
+ - Scroll offset: explicitly request viewport coordinates.
13
+ - Markdown table: explicitly require Name then Count column order.
14
+
15
+ Missing values were reconstructed during dataset authoring from the existing authored answer keys. The inference runner never reads keys to construct prompts or choose answers. Options, correct labels, response contracts, per-pass/category counts, and weights remain unchanged. The repaired specifications were checked against the existing choices. This targeted audit is not an exhaustive manual review of all question semantics.
16
+
17
+ `runs/v1_1_seed_20261023/corrections.json` records every ID and before/after prompt. The new manifest records the original and corrected question hashes, label/weight hashes, edition, and correction count. Per-pass files agree with the combined dataset. Corrected scores are not interchangeable with original v1.0 scores. The original weights are retained for continuity; they have not been recalibrated for the clearer wording.
18
+
19
+ Rebuild deterministically from the original files:
20
+
21
+ ```sh
22
+ python3 SmolCUA_v1_0/repair_dataset.py
23
+ ```
24
+
25
+ ## Runner and scorer fixes
26
+
27
+ - Reject partial `--score` requests before loading weights or generating responses.
28
+ - Check all compiled prompts against the context limit before Transformers model allocation; preserve the no-truncation policy.
29
+ - Include context limit and manifest hash in resume metadata, and reject incompatible resumes.
30
+ - Reject unknown/duplicate result IDs, malformed resumed answers, and incomplete inference instead of claiming completion.
31
+ - Reject duplicate JSON object keys under the strict response contract.
32
+ - Detect duplicate dataset IDs, invalid answer labels, nonfinite/nonpositive weights, and scoring-file hash mismatches.
33
+ - Report the actual reliability denominator and identify the edition/hash in scores.
34
+
35
+ Reference-answer scoring reaches 100/100 for weighted score and worst-pass reliability across all 5,000 questions; empty predictions score zero. These are scorer checks, not model results. Geometry repairs are checked by independently computing targets from the repaired prompts. Tests cover resume, context preflight, incomplete inference, and strict parsing.
36
+
37
+ ## Run the local edition
38
+
39
+ From the workspace root:
40
+
41
+ ```sh
42
+ python SmolCUA_v1_0/run_smolcua.py --model YOUR_MODEL \
43
+ --backend transformers --prompt-mode plain \
44
+ --run-dir SmolCUA_v1_0/runs/v1_1_seed_20261023 \
45
+ --max-model-len 4096 --output-dir results/smolcua-corrected --score
46
+ ```
47
+
48
+ `./benchmark` runs this edition automatically on the prepared Void snapshot. Generation budgets are 48 bytes for short contracts, 192 for JSON choice-with-text, and 512 for raw payloads with the Void byte tokenizer. The corrected prompts and budgets fit its 4096-byte context. SmolCUA scores stay outside the Open SLM Intelligence Index.
49
+
50
+ No GPU throughput or full real-model benchmark scores have been validated. The toolkit also provides cached batched inference, last-position logits where supported, CUDA OOM backoff, and measured live progress.
README.md CHANGED
@@ -1,3 +1,120 @@
1
  ---
 
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ pretty_name: SmolCUA — Computer-Use Aptitude
3
  license: apache-2.0
4
+ language:
5
+ - en
6
+ task_categories:
7
+ - text-generation
8
+ tags:
9
+ - benchmark
10
+ - computer-use
11
+ - instruction-following
12
+ - small-language-models
13
+ - reliability
14
+ size_categories:
15
+ - 1K<n<10K
16
+ configs:
17
+ - config_name: default
18
+ data_files:
19
+ - split: test
20
+ path: runs/v1_1_seed_20261023/questions_all_passes.jsonl
21
+ - config_name: original_v1_0
22
+ data_files:
23
+ - split: test
24
+ path: runs/v1_seed_20261023/questions_all_passes.jsonl
25
  ---
26
+
27
+ # SmolCUA — Computer-Use Aptitude
28
+
29
+ SmolCUA evaluates text-based computer-use reasoning: tool selection, next actions,
30
+ strategy switching, instruction following, ambiguity, coding, structured output,
31
+ coordinates, multi-constraint formatting, and state tracking. It is a synthetic
32
+ text benchmark, not live UI automation or a visual computer-use environment.
33
+
34
+ **1,000 questions per pass, five passes, 5,000 total.** Each question contains four
35
+ options and an explicit response contract. Models generate the answer; there is
36
+ no forced-choice logit shortcut, output repair, or answer extraction.
37
+
38
+ ## Current edition
39
+
40
+ The default is **corrected v1.1**, recorded as `edition: local-corrected` in its
41
+ manifest for continuity with the local audit. It repairs 250 incomplete or
42
+ ambiguous prompts across five templates. Original v1.0 data remains available in
43
+ `runs/v1_seed_20261023` and the `original_v1_0` dataset configuration. Options,
44
+ answer labels, and weights are unchanged. The editions have different hashes;
45
+ **do not report corrected scores as original v1.0 scores**.
46
+
47
+ See [LOCAL_CHANGES.md](LOCAL_CHANGES.md) and the per-question
48
+ [corrections](runs/v1_1_seed_20261023/corrections.json). Restored specifications were
49
+ reconstructed during dataset authoring from the original authored answer keys.
50
+ Inference never uses those keys to construct prompts or select answers.
51
+
52
+ ## Run
53
+
54
+ Download this repository's toolkit files, then:
55
+
56
+ ```sh
57
+ pip install -r requirements-transformers.txt
58
+ python run_smolcua.py --model YOUR_ORG/YOUR_MODEL --backend transformers \
59
+ --dataset dotlabs/smolcua --prompt-mode plain --max-model-len 4096 \
60
+ --output-dir results/my-model --score
61
+ ```
62
+
63
+ `plain` is appropriate for base models and provides zero-shot prompts. Use
64
+ `--prompt-mode auto` or `chat` for instruction-tuned models with chat templates.
65
+ There are no few-shot exemplars in either mode. `--dataset-revision COMMIT` pins
66
+ the dataset; `--revision COMMIT` pins model/tokenizer loading.
67
+
68
+ The repository is a public **self-scoring edition**, including files under
69
+ `private/` for evaluation. The directory name does not make them confidential.
70
+ It is not a blind leaderboard. Disclose exposure to answer keys when reporting
71
+ results; do not use test questions/keys for training.
72
+
73
+ ## Pretokenization and inference
74
+
75
+ - All selected prompts are compiled in CPU batches before Transformers model
76
+ weights are loaded. The cache key includes actual prompt contents, dataset
77
+ identity, tokenizer vocabulary/configuration, and prompt formatting.
78
+ - Cache hits reuse exact input IDs. No prompt truncation is allowed.
79
+ - Transformers uses length/budget buckets, greedy cached decoding, a default
80
+ batch size of 32, and CUDA OOM backoff down to one. Supported models compute
81
+ only the last-position logits during generation.
82
+ - Tokenization, model loading, prefill, decode tokens, completed questions,
83
+ elapsed time, throughput, and ETA appear in flushed progress logs. Long calls
84
+ get heartbeat updates; no fabricated completion percentage is shown.
85
+ - EOS counts as a generated token; padding after a completed sequence does not.
86
+ Raw response text is not printed in progress logs.
87
+ - vLLM supports pretokenized inputs and its native generation progress. API
88
+ mode uses concurrent requests and server-side tokenization.
89
+
90
+ ```sh
91
+ # Compile prompts without allocating model weights:
92
+ python run_smolcua.py --model YOUR_MODEL --pretokenize-only --prompt-mode plain
93
+
94
+ # Larger batches; CUDA OOM backoff preserves completed answers:
95
+ python run_smolcua.py --model YOUR_MODEL --backend transformers \
96
+ --batch-size 64 --progress-interval 5 --output-dir results/model --score
97
+ ```
98
+
99
+ Performance depends on model, hardware, padding, and output lengths. Batched
100
+ floating-point inference can differ from single-item inference near logit ties;
101
+ record the batch size and precision. This release does not claim a measured GPU
102
+ speedup. See [RUNNING_AND_PUBLISHING.md](RUNNING_AND_PUBLISHING.md) for settings.
103
+
104
+ ## Scores and outputs
105
+
106
+ - Mean weighted score (0–100), with category-specific weights.
107
+ - Worst-pass exact-answer reliability: `100 * min(correct per pass) / 1000`.
108
+ - Per-pass, category, response-format, and consistency breakdowns.
109
+ - Raw answers, dataset hash/edition, configuration, token-cache statistics,
110
+ actual token counts, generation batching statistics, and throughput.
111
+
112
+ Output files are `predictions.jsonl`, `run_metadata.json`, `performance.json`,
113
+ and `score.json`. `--score` requires all 5,000 responses; partial requests are
114
+ rejected before model loading. The standalone scorer can assess missing answers
115
+ as incorrect. Strict JSON contracts reject duplicate keys.
116
+
117
+ Weights are research-informed and have not been calibrated against a large
118
+ representative model sample. v1.1 retains v1.0 weights despite clearer wording.
119
+ Reference-answer and empty-answer tests validate scorer behavior; they are not
120
+ model performance results.
RUNNING_AND_PUBLISHING.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Running and publishing SmolCUA
2
+
3
+ ## Transformers
4
+
5
+ ```sh
6
+ pip install -r requirements-transformers.txt
7
+ python run_smolcua.py --model YOUR_MODEL --backend transformers \
8
+ --prompt-mode plain --max-model-len 4096 --batch-size 32 \
9
+ --dataset dotlabs/smolcua --output-dir results/model --score
10
+ ```
11
+
12
+ The default dataset is corrected v1.1 (`runs/v1_1_seed_20261023`). To evaluate
13
+ original v1.0, explicitly pass `--run-subdir runs/v1_seed_20261023`. For a local
14
+ copy, use `--run-dir runs/v1_1_seed_20261023`. Keep editions separate.
15
+
16
+ The default short response budget is 48 tokens, JSON choice-with-text uses up to
17
+ 192, and raw payloads use 512. These are model tokens, which are bytes for Void.
18
+ `--max-model-len` covers prompt plus output for decoder-only models. Prompts
19
+ are never truncated. All prompts are checked before Transformers weights load.
20
+
21
+ Batches group equal generation budgets and similar input lengths. Generation
22
+ uses greedy decoding and KV caching; models explicitly supporting
23
+ `logits_to_keep`/`num_logits_to_keep` receive a value of one. CUDA OOM reduces the
24
+ batch size and retries only the unsuccessful batch. Other errors propagate.
25
+ Use `--batch-size 1` for single-item comparisons.
26
+
27
+ ## Progress and performance
28
+
29
+ Progress is written to stderr with flushing, so it works in notebooks, terminals,
30
+ and remote logs. `--progress-interval 5` controls periodic updates; `--quiet`
31
+ suppresses them. Counts measure actual compiled prompts, completed questions,
32
+ and decode tokens. Prefill/model-loading heartbeats show the current stage even
33
+ before the first token arrives. ETA uses completed-item throughput including
34
+ startup cost, and can change as question types and output lengths change.
35
+
36
+ Generation tokens exclude padding after EOS. Batch/padding/OOM statistics are in
37
+ `performance.json`. Progress counts for a resumed run refer to remaining work;
38
+ performance metadata distinguishes previous responses from new ones.
39
+
40
+ ## Token cache
41
+
42
+ ```sh
43
+ python run_smolcua.py --model YOUR_MODEL --pretokenize-only \
44
+ --prompt-mode plain --dataset dotlabs/smolcua
45
+ ```
46
+
47
+ The cache is model-specific and content-addressed at `~/.cache/smolcua/tokens`.
48
+ Use `--token-cache-dir PATH`, `--rebuild-token-cache`, or `--no-token-cache`.
49
+ `--tokenize-batch-size` controls CPU encoding batches (default 512). Cache schema
50
+ 2 invalidates older caches and includes actual prompt content in its identity.
51
+
52
+ ## Resume
53
+
54
+ Rerun the same command with `--resume`. The output directory's configuration,
55
+ context limit, and manifest hash must match. Completed answers are checkpointed
56
+ atomically. Failed/incomplete runs do not claim completion. Changing settings or
57
+ model contents requires a new output directory; prefer immutable model revisions.
58
+
59
+ ## vLLM and API
60
+
61
+ ```sh
62
+ pip install -r requirements-vllm.txt
63
+ python run_smolcua.py --model YOUR_MODEL --backend vllm \
64
+ --batch-size 256 --output-dir results/vllm --score
65
+
66
+ pip install -r requirements-api.txt
67
+ python run_smolcua.py --model SERVER_MODEL --backend api \
68
+ --endpoint http://localhost:8000/v1 --api-concurrency 16 \
69
+ --output-dir results/api --score
70
+ ```
71
+
72
+ vLLM receives compiled token IDs; its native progress reports generation.
73
+ API endpoints receive text and tokenize server-side. API progress can report
74
+ completed requests and returned token usage, not internal server decode steps.
75
+ For API mode, `plain` still uses a chat-completions user message containing the
76
+ plain prompt, so this is not equivalent to a raw completions endpoint.
77
+
78
+ ## Publishing
79
+
80
+ `publish_smolcua.py` accepts only benchmark sources, documentation, approved
81
+ question/manifest files, correction logs, and self-score keys/weights. Build a
82
+ clean staging folder; do not include token caches, model checkpoints, generated
83
+ responses, credentials, `.DS_Store`, or Python bytecode. Unknown files and
84
+ symlinks are rejected.
85
+
86
+ ```sh
87
+ python publish_smolcua.py --repo dotlabs/smolcua --folder /path/to/clean-release
88
+ python publish_smolcua.py --repo dotlabs/smolcua --folder /path/to/clean-release --publish
89
+ ```
90
+
91
+ Existing repository access settings are preserved. `--gated auto` or
92
+ `--gated manual` changes gating only when explicitly requested. A directory
93
+ called `private` does not enforce confidentiality on the Hub; this package is
94
+ intentionally self-scoring. Review the file list before uploading.
inference_runtime.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared batched generation and measured, log-friendly progress (no prompt text)."""
2
+ import gc
3
+ import inspect
4
+ import sys
5
+ import threading
6
+ import time
7
+ from itertools import groupby
8
+
9
+ from token_cache import padded_batch
10
+
11
+
12
+ class Progress:
13
+ def __init__(self, label, total=0, quiet=False, interval=5):
14
+ self.label, self.total, self.quiet = label, total, quiet
15
+ self.interval = interval
16
+ self.done = self.tokens = 0
17
+ self.stage = 'starting'
18
+ self.started = time.monotonic()
19
+ self.last = 0.0
20
+ self.lock = threading.RLock()
21
+ self.stop = threading.Event()
22
+
23
+ def update(self, stage=None, done=None, tokens=None, force=False):
24
+ with self.lock:
25
+ if stage is not None:
26
+ self.stage = stage
27
+ if done is not None:
28
+ self.done = done
29
+ if tokens is not None:
30
+ self.tokens = tokens
31
+ self.render(force)
32
+
33
+ def render(self, force=False):
34
+ now = time.monotonic()
35
+ if self.quiet or (not force and now-self.last < self.interval):
36
+ return
37
+ self.last = now
38
+ elapsed = max(now-self.started, 1e-6)
39
+ rate = self.done/elapsed
40
+ eta = f'{(self.total-self.done)/rate:.0f}s' if rate and self.total else 'pending'
41
+ print(f'{self.label}: {self.stage} | {self.done}/{self.total} complete | '
42
+ f'{self.tokens} generated tokens | {rate:.2f}/s | elapsed {elapsed:.0f}s | ETA {eta}',
43
+ file=sys.stderr, flush=True)
44
+
45
+ def __enter__(self):
46
+ self.update(force=True)
47
+ def heartbeat():
48
+ while not self.stop.wait(self.interval):
49
+ with self.lock:
50
+ self.render()
51
+ self.thread = threading.Thread(target=heartbeat, daemon=True)
52
+ if not self.quiet:
53
+ self.thread.start()
54
+ return self
55
+
56
+ def __exit__(self, kind, value, tb):
57
+ self.stop.set()
58
+ if self.thread.is_alive():
59
+ self.thread.join(timeout=1)
60
+ self.update(stage='failed' if kind else 'finished', force=True)
61
+
62
+
63
+ def eos_ids(model, tokenizer):
64
+ value = getattr(model.generation_config, 'eos_token_id', None)
65
+ if value is None:
66
+ value = tokenizer.eos_token_id
67
+ return set(value if isinstance(value, (list, tuple)) else [] if value is None else [value])
68
+
69
+
70
+ class TokenProgress:
71
+ """Transformers streamer: count actual decode steps without decoding text."""
72
+ def __init__(self, progress, batch_size, eos, base_tokens=0):
73
+ self.progress = progress
74
+ self.active = [True]*batch_size
75
+ self.eos = eos
76
+ self.first = True
77
+ self.count = 0
78
+ self.base = base_tokens
79
+
80
+ def put(self, value):
81
+ if self.first: # Initial prompt (or decoder-start IDs), not generated tokens.
82
+ self.first = False
83
+ return
84
+ values = value.tolist()
85
+ for i, token in enumerate(values):
86
+ if self.active[i]:
87
+ self.count += 1
88
+ if token in self.eos:
89
+ self.active[i] = False
90
+ self.progress.update(stage='decoding', tokens=self.base+self.count)
91
+
92
+ def end(self):
93
+ pass
94
+
95
+
96
+ def trim_after_eos(sequences, eos):
97
+ result = []
98
+ for tokens in sequences:
99
+ end = next((i+1 for i,t in enumerate(tokens) if t in eos), len(tokens))
100
+ result.append(tokens[:end])
101
+ return result
102
+
103
+
104
+ def generate_batches(model, tokenizer, compiled, rows, budget_for, batch_size, emit,
105
+ progress, is_seq2seq=False, keep_special_tokens=False):
106
+ """Length/budget buckets, KV cache, greedy decoding, and CUDA OOM backoff."""
107
+ import torch
108
+ ordered = sorted(rows, key=lambda q: (budget_for(q), len(compiled[q['id']]['input_ids'])))
109
+ eos = eos_ids(model, tokenizer)
110
+ done = tokens_done = 0
111
+ effective_batch = batch_size
112
+ stats = dict(batches=0, oom_retries=0, generated_tokens=0, input_tokens=0, padded_input_tokens=0)
113
+ # Models exposing this documented optimization need only the next-token logits
114
+ # during generation, not a vocabulary projection for every prefill position.
115
+ generation_options = {}
116
+ forward = getattr(model, 'forward', None)
117
+ if forward is not None and not is_seq2seq:
118
+ parameters = inspect.signature(forward).parameters
119
+ for name in ('logits_to_keep', 'num_logits_to_keep'):
120
+ if name in parameters:
121
+ generation_options[name] = 1
122
+ break
123
+ stats['last_token_logits'] = bool(generation_options)
124
+
125
+ def generate(group, budget):
126
+ data = padded_batch([compiled[q['id']] for q in group], tokenizer.pad_token_id, tokenizer.padding_side)
127
+ width = data['input_ids'].shape[1]
128
+ device = model.get_input_embeddings().weight.device
129
+ data = {k:v.to(device) for k,v in data.items()}
130
+ progress.update(stage=f'prefill batch={len(group)} input_width={width}', force=True)
131
+ stream = TokenProgress(progress, len(group), eos, tokens_done)
132
+ # Explicit defaults prevent a checkpoint's sampling/beam config changing the task.
133
+ output = model.generate(**data, max_new_tokens=budget, do_sample=False, num_beams=1,
134
+ num_return_sequences=1, pad_token_id=tokenizer.pad_token_id,
135
+ use_cache=True, streamer=stream, return_dict_in_generate=False,
136
+ output_scores=False, **generation_options)
137
+ prefix = 1 if is_seq2seq else width
138
+ sequences = trim_after_eos(output[:, prefix:].tolist(), eos)
139
+ answers = tokenizer.batch_decode(sequences, skip_special_tokens=not keep_special_tokens,
140
+ clean_up_tokenization_spaces=False)
141
+ if len(answers) != len(group):
142
+ raise RuntimeError('Generation returned an unexpected number of sequences')
143
+ return answers, [len(s) for s in sequences], width
144
+
145
+ with torch.inference_mode():
146
+ for budget, family in groupby(ordered, key=budget_for):
147
+ family = list(family)
148
+ offset = 0
149
+ while offset < len(family):
150
+ group = family[offset:offset+effective_batch]
151
+ try:
152
+ answers, lengths, width = generate(group, budget)
153
+ except torch.cuda.OutOfMemoryError:
154
+ if len(group) == 1:
155
+ raise
156
+ effective_batch = max(1, len(group)//2)
157
+ stats['oom_retries'] += 1
158
+ progress.update(stage=f'CUDA OOM; retry batch={effective_batch}', tokens=tokens_done, force=True)
159
+ else:
160
+ emit([(q['id'], text, length) for q,text,length in zip(group,answers,lengths)])
161
+ done += len(group)
162
+ tokens_done += sum(lengths)
163
+ stats['batches'] += 1
164
+ stats['input_tokens'] += sum(len(compiled[q['id']]['input_ids']) for q in group)
165
+ stats['padded_input_tokens'] += width*len(group)
166
+ progress.update(stage='batch saved', done=done, tokens=tokens_done, force=True)
167
+ offset += len(group)
168
+ continue
169
+ # Release the exception traceback (and its tensors) before GC.
170
+ gc.collect()
171
+ if torch.cuda.is_available():
172
+ torch.cuda.empty_cache()
173
+ stats.update(generated_tokens=tokens_done, final_batch_size=effective_batch)
174
+ return stats
publish_smolcua.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Publish a prepared SmolCUA dataset folder to Hugging Face (opt-in)."""
3
+ from __future__ import annotations
4
+ import argparse
5
+ from pathlib import Path
6
+
7
+
8
+ def files_in(root):
9
+ # Only pre-approved benchmark files are eligible for upload.
10
+ # This prevents accidentally leaking local token caches, model responses,
11
+ # user credentials or debug traces when using the folder as a workdir.
12
+ allowed_root = {'README.md', 'RUNNING_AND_PUBLISHING.md', 'run_smolcua.py',
13
+ 'token_cache.py', 'score_smolcua.py', 'response_formats.py',
14
+ 'publish_smolcua.py', 'inference_runtime.py', 'repair_dataset.py',
15
+ 'LOCAL_CHANGES.md', 'requirements-vllm.txt',
16
+ 'requirements-transformers.txt', 'requirements-api.txt'}
17
+ allowed_run = {'manifest.json', 'questions_all_passes.jsonl', 'corrections.json'} | {
18
+ f'pass_{i:02d}_questions.jsonl' for i in range(1, 6)}
19
+ allowed_private = {'answers_all_passes.jsonl', 'weights_all_passes.jsonl'}
20
+ included = []
21
+ for f in sorted(root.rglob('*')):
22
+ if f.is_symlink():
23
+ raise ValueError(f'Symlinks are not allowed in upload folder: {f}')
24
+ if not f.is_file():
25
+ continue
26
+ parts = f.relative_to(root).parts
27
+ approved = (len(parts) == 1 and parts[0] in allowed_root or
28
+ len(parts) == 3 and parts[0] == 'runs' and parts[1] in ('v1_seed_20261023', 'v1_1_seed_20261023')
29
+ and parts[2] in allowed_run or
30
+ len(parts) == 4 and parts[0] == 'runs' and parts[1] in ('v1_seed_20261023', 'v1_1_seed_20261023') and parts[2] == 'private'
31
+ and parts[3] in allowed_private)
32
+ if approved:
33
+ included.append(str(f.relative_to(root)))
34
+ else:
35
+ raise ValueError(f'Unrecognized file in upload folder: {f}. '
36
+ 'Remove local cache/results before publishing.')
37
+ return included
38
+
39
+
40
+ def main():
41
+ p=argparse.ArgumentParser(description=__doc__)
42
+ p.add_argument('--repo',default='dotlabs/smolcua')
43
+ p.add_argument('--folder',type=Path,required=True,help='Prebuilt hf_selfscore or hf_blind folder')
44
+ p.add_argument('--gated',choices=['auto','manual'],default=None,help='Only change gating if explicitly requested')
45
+ p.add_argument('--publish',action='store_true',help='Actually create and upload; without it only show files')
46
+ args=p.parse_args()
47
+ root=args.folder.resolve()
48
+ if not (root/'README.md').is_file():raise FileNotFoundError('No dataset card: '+str(root/'README.md'))
49
+ if not (root/'runs'/'v1_seed_20261023'/'questions_all_passes.jsonl').is_file():
50
+ raise FileNotFoundError('Full questions file missing')
51
+ print('Dataset:',args.repo,'\nFolder:',root,'\nFiles:')
52
+ for name in files_in(root):print(' '+name)
53
+ if not args.publish:
54
+ print('\nDry run only. Use --publish to perform the actual upload.')
55
+ return
56
+ from huggingface_hub import HfApi
57
+ api=HfApi()
58
+ api.create_repo(repo_id=args.repo,repo_type='dataset',exist_ok=True)
59
+ # Preserve the repository's visibility/access policy unless explicitly changed.
60
+ if args.gated is not None:
61
+ api.update_repo_settings(repo_id=args.repo,repo_type='dataset',gated=args.gated)
62
+ api.upload_folder(repo_id=args.repo,repo_type='dataset',folder_path=str(root),
63
+ commit_message='Release corrected SmolCUA v1.1 with cached batching and live progress')
64
+ print('Uploaded to https://huggingface.co/datasets/'+args.repo)
65
+ print('Verify gated access status in the dataset Settings tab.')
66
+
67
+ if __name__=='__main__':main()
repair_dataset.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build a local corrected edition; preserve the original v1.0 files.
2
+
3
+ Missing specifications are reconstructed from the author-provided keyed payloads.
4
+ This is dataset authoring, never inference-time answer access. Every changed ID
5
+ and its original/replacement question is recorded for review.
6
+ """
7
+ import hashlib
8
+ import json
9
+ import re
10
+ from pathlib import Path
11
+ from decimal import Decimal
12
+
13
+ from response_formats import unwrap_option
14
+
15
+ BASE = Path(__file__).resolve().parent
16
+ SOURCE = BASE / 'runs/v1_seed_20261023'
17
+ DEST = BASE / 'runs/v1_1_seed_20261023'
18
+
19
+
20
+ def load(path):
21
+ return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
22
+
23
+
24
+ def save_rows(path, rows):
25
+ path.write_text(''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in rows))
26
+
27
+
28
+ def repair_question(q, answer):
29
+ text = q['question']
30
+ payload = unwrap_option(q['options'][answer], q['option_presentation'])
31
+ skill = q['subskill']
32
+ if skill == 'tsv_fields':
33
+ fields = payload.split('\t')
34
+ if len(fields) != 3:
35
+ raise ValueError(f'Invalid authored TSV answer: {q["id"]}')
36
+ spec = ('Produce one TSV record with exactly three fields, in this order: '
37
+ + ', '.join(f'`{f}`' for f in fields)
38
+ + '. Separate fields with one literal tab; no header, trailing tab, or extra fields.')
39
+ elif skill == 'safe_inset':
40
+ x1, x2, y1, y2 = map(int, re.search(r'x=(\d+)\.\.(\d+), y=(\d+)\.\.(\d+)', text).groups())
41
+ x, y = map(int, re.fullmatch(r'\((\d+), (\d+)\)', payload).groups())
42
+ if not x1 < x < x2 or not y1 < y < y2:
43
+ raise ValueError(f'Authored inset is outside control: {q["id"]}')
44
+ spec = f'Use a top-left origin. Click exactly {x-x1} pixels right of the left edge and {y-y1} pixels below the top edge. What is the click point?'
45
+ elif skill == 'percentage_to_pixels':
46
+ width, height = map(int, re.search(r'(\d+)×(\d+) pixels', text).groups())
47
+ x, y = map(int, re.fullmatch(r'\((\d+), (\d+)\)', payload).groups())
48
+ px, py = Decimal(x)*100/width, Decimal(y)*100/height
49
+ spec = f'With a top-left origin, the target is at {px.normalize():f}% of the width from the left and {py.normalize():f}% of the height from the top. What is its pixel coordinate?'
50
+ elif skill == 'scroll_offset':
51
+ spec = 'Convert the given page coordinate to viewport coordinates by subtracting the horizontal and vertical scroll offsets respectively.'
52
+ elif skill == 'markdown_table':
53
+ spec = 'The columns must appear in the stated order: Name first, Count second, with the corresponding values in that order.'
54
+ else:
55
+ return text
56
+ # Put the restored specification before the output contract, preserving wrappers.
57
+ marker = '\n\nFor every option below,' if '\n\nFor every option below,' in text else '\nANSWER CONTRACT:'
58
+ if marker not in text:
59
+ raise ValueError(f'Missing answer contract: {q["id"]}')
60
+ return text.replace(marker, '\n\n' + spec + marker, 1)
61
+
62
+
63
+ def main():
64
+ manifest = json.loads((SOURCE/'manifest.json').read_text())
65
+ data = (SOURCE/'questions_all_passes.jsonl').read_bytes()
66
+ if hashlib.sha256(data).hexdigest() != manifest['question_file_sha256']:
67
+ raise ValueError('Original question hash mismatch')
68
+ questions = load(SOURCE/'questions_all_passes.jsonl')
69
+ keys = {r['id']: r for r in load(SOURCE/'private/answers_all_passes.jsonl')}
70
+ changes = []
71
+ for q in questions:
72
+ before = q['question']
73
+ q['question'] = repair_question(q, keys[q['id']]['answer'])
74
+ if before != q['question']:
75
+ changes.append(dict(id=q['id'], subskill=q['subskill'], before=before, after=q['question']))
76
+ (DEST/'private').mkdir(parents=True, exist_ok=True)
77
+ save_rows(DEST/'questions_all_passes.jsonl', questions)
78
+ for p in range(1, manifest['passes']+1):
79
+ save_rows(DEST/f'pass_{p:02d}_questions.jsonl', [q for q in questions if q['pass']==p])
80
+ hashes = {}
81
+ for name in ('answers_all_passes.jsonl', 'weights_all_passes.jsonl'):
82
+ data = (SOURCE/'private'/name).read_bytes()
83
+ (DEST/'private'/name).write_bytes(data)
84
+ hashes[name] = hashlib.sha256(data).hexdigest()
85
+ manifest.update(version='1.1', edition='local-corrected', source_version='1.0',
86
+ source_question_file_sha256=manifest['question_file_sha256'],
87
+ question_file_sha256=hashlib.sha256((DEST/'questions_all_passes.jsonl').read_bytes()).hexdigest(),
88
+ scoring_file_sha256=hashes, corrected_questions=len(changes),
89
+ notes='Local prompt repairs reconstructed from authored answer keys; options, labels and weights unchanged. Not interchangeable with original v1.0 scores.')
90
+ (DEST/'manifest.json').write_text(json.dumps(manifest, indent=2)+'\n')
91
+ (DEST/'corrections.json').write_text(json.dumps(changes, indent=2, ensure_ascii=False)+'\n')
92
+ print(f'Created {DEST}: {len(changes)} corrected questions')
93
+
94
+
95
+ if __name__ == '__main__':
96
+ main()
requirements-api.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ openai>=1.80
2
+ huggingface_hub>=0.32
requirements-transformers.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch>=2.2
2
+ transformers>=4.51
3
+ accelerate>=1.0
4
+ huggingface_hub>=0.32
requirements-vllm.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ vllm>=0.10
2
+ huggingface_hub>=0.32
response_formats.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SmolCUA v1.0 format parsing, preserved from the benchmark's authoritative scorer."""
2
+ from __future__ import annotations
3
+ import ast
4
+ import json
5
+ import re
6
+ import xml.etree.ElementTree as ET
7
+ LETTERS=('A','B','C','D')
8
+
9
+ def _unique_object(pairs):
10
+ result = {}
11
+ for key, value in pairs:
12
+ if key in result:
13
+ raise ValueError('Duplicate JSON key')
14
+ result[key] = value
15
+ return result
16
+
17
+ def unwrap_option(encoded: str, kind: str) -> str:
18
+ if kind=='plain':return encoded
19
+ if kind=='json_envelope':return json.loads(encoded)['candidate']
20
+ if kind=='xml_envelope':return ET.fromstring(encoded).text or ''
21
+ if kind=='markdown_quote':return '\n'.join(line[2:] for line in encoded.split('\n'))
22
+ if kind=='fenced_block':
23
+ assert encoded.startswith('~~~candidate\n') and encoded.endswith('\n~~~')
24
+ return encoded[len('~~~candidate\n'):-len('\n~~~')]
25
+ if kind=='yaml_block':
26
+ assert encoded.startswith('candidate: |\n')
27
+ return '\n'.join(line[2:] for line in encoded[len('candidate: |\n'):].split('\n'))
28
+ if kind=='quoted_string':return json.loads(encoded)
29
+ if kind=='tagged_section':
30
+ assert encoded.startswith('BEGIN CANDIDATE\n') and encoded.endswith('\nEND CANDIDATE')
31
+ return encoded[len('BEGIN CANDIDATE\n'):-len('\nEND CANDIDATE')]
32
+ if kind=='python_string':
33
+ assert encoded.startswith('candidate = ')
34
+ return ast.literal_eval(encoded[len('candidate = '):])
35
+ raise KeyError(kind)
36
+
37
+ def parse_response(text: str,kind: str,opts_unwrapped: dict) -> str|None:
38
+ if not isinstance(text,str):return None
39
+ if kind=='letter':return text if text in LETTERS else None
40
+ if kind=='ordinal':return LETTERS[int(text)-1] if text in ('1','2','3','4') else None
41
+ if kind=='json_choice':
42
+ try:r=json.loads(text, object_pairs_hook=_unique_object)
43
+ except (ValueError,TypeError):return None
44
+ return r['choice'] if isinstance(r,dict) and set(r)=={'choice'} and r['choice'] in LETTERS else None
45
+ if kind=='json_choice_text':
46
+ try:r=json.loads(text, object_pairs_hook=_unique_object)
47
+ except (ValueError,TypeError):return None
48
+ if not isinstance(r,dict) or set(r)!={'choice','text'}:return None
49
+ c=r['choice'];return c if c in LETTERS and r['text']==opts_unwrapped[c] else None
50
+ if kind=='yaml_choice':
51
+ m=re.fullmatch(r'selected: ([A-D])',text);return m.group(1) if m else None
52
+ if kind=='xml_choice':
53
+ m=re.fullmatch(r'<selection>([A-D])</selection>',text);return m.group(1) if m else None
54
+ if kind=='csv_choice':
55
+ m=re.fullmatch(r'selected,([A-D])',text);return m.group(1) if m else None
56
+ if kind=='bracket_choice':
57
+ m=re.fullmatch(r'\[([A-D])\]',text);return m.group(1) if m else None
58
+ if kind=='pipe_choice':
59
+ m=re.fullmatch(r'pick\|([A-D])',text);return m.group(1) if m else None
60
+ if kind=='raw_payload':
61
+ matches=[k for k,v in opts_unwrapped.items() if text==v]
62
+ return matches[0] if len(matches)==1 else None
63
+ raise KeyError(kind)
run_smolcua.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """SmolCUA v1.0 pretokenized text-model evaluation: vLLM, Transformers, or API.
3
+
4
+ Examples:
5
+ python run_smolcua.py --model Qwen/Qwen2.5-1.5B-Instruct --backend vllm --score
6
+ python run_smolcua.py --model dotlabs/void.1 --backend transformers --prompt-mode plain
7
+ python run_smolcua.py --model my-server-model --backend api --endpoint http://localhost:8000/v1
8
+
9
+ No answer extraction, forced choice, or format repair is performed. The model's
10
+ EXACT generated text is saved, so the scorer can test instruction compliance.
11
+ """
12
+ from __future__ import annotations
13
+ import argparse
14
+ from concurrent.futures import ThreadPoolExecutor, as_completed
15
+ import gc
16
+ from itertools import groupby
17
+
18
+ from token_cache import compile_tokens
19
+ from inference_runtime import Progress, generate_batches
20
+ import hashlib
21
+ import importlib.util
22
+ import json
23
+ import os
24
+ from pathlib import Path
25
+ import random
26
+ import sys
27
+ import time
28
+
29
+ DEFAULT_REPO='dotlabs/smolcua'
30
+ DEFAULT_RUN='runs/v1_1_seed_20261023'
31
+
32
+
33
+ def read_jsonl(path):
34
+ with open(path, encoding='utf-8') as f:
35
+ return [json.loads(s) for s in f if s.strip()]
36
+
37
+
38
+ def write_atomic_json(path, value):
39
+ tmp=path.with_name(path.name+'.tmp')
40
+ tmp.write_text(json.dumps(value,indent=2,ensure_ascii=False)+'\n',encoding='utf-8')
41
+ tmp.replace(path)
42
+
43
+
44
+ def write_atomic_jsonl(path, rows):
45
+ tmp=path.with_name(path.name+'.tmp')
46
+ with open(tmp,'w',encoding='utf-8') as f:
47
+ for row in rows:f.write(json.dumps(row,ensure_ascii=False)+'\n')
48
+ tmp.replace(path)
49
+
50
+
51
+ def format_prompt(q):
52
+ # The base question already includes its own ANSWER CONTRACT.
53
+ return q['question']+'\n\n'+'\n'.join(f"{k}. {q['options'][k]}" for k in 'ABCD')
54
+
55
+
56
+ def build_messages(prompt):
57
+ return [{'role':'user','content':prompt}]
58
+
59
+
60
+ def build_plain(prompt):
61
+ return prompt+'\n\nAnswer:\n'
62
+
63
+
64
+ def make_chat_prompt(tokenizer, prompt, mode, template_kwargs):
65
+ if mode=='plain' or (mode=='auto' and not getattr(tokenizer,'chat_template',None)):
66
+ return build_plain(prompt)
67
+ if mode=='chat' and not getattr(tokenizer,'chat_template',None):
68
+ raise ValueError('No chat template in tokenizer; choose --prompt-mode plain')
69
+ return tokenizer.apply_chat_template(build_messages(prompt), tokenize=False,
70
+ add_generation_prompt=True,**template_kwargs)
71
+
72
+
73
+ def token_budget(q, args):
74
+ fmt=q['response_format']
75
+ if fmt=='raw_payload':return args.max_new_tokens
76
+ if fmt=='json_choice_text':return min(args.max_new_tokens,max(192,args.short_max_new_tokens))
77
+ return min(args.max_new_tokens,args.short_max_new_tokens)
78
+
79
+
80
+ def _prepare_all_tokens(pending, tokenizer, args):
81
+ # Compiles the entire selected benchmark before the first GPU request,
82
+ # including rows already scored in a resumed run. Cache hits skip CPU encoding.
83
+ questions = getattr(args, '_all_rows', pending)
84
+ sha256 = getattr(args, '_dataset_sha256', '')
85
+ indexed, info = compile_tokens(questions, tokenizer, args, sha256,
86
+ getattr(args, '_format_prompt', format_prompt),
87
+ prompt_builder=getattr(args, '_prompt_builder', None))
88
+ args._token_cache_info = info
89
+ if not getattr(args, 'quiet', False):
90
+ print(f"Pretokenization: {info['status']} | {info['count']} prompts | "
91
+ f"{info['input_tokens']:,} tokens | {info['elapsed_seconds']:.2f}s | "
92
+ f"cache={info['path']}", flush=True)
93
+ return indexed
94
+
95
+
96
+ def validate_context(rows, compiled, args, context_limit, is_seq2seq=False):
97
+ if not context_limit:
98
+ return
99
+ for q in rows:
100
+ required = len(compiled[q['id']]['input_ids'])
101
+ if not is_seq2seq:
102
+ required += token_budget(q, args)
103
+ if required > context_limit:
104
+ raise ValueError(f'{q["id"]}: input + response needs {required} tokens, '
105
+ f'exceeds model context ({context_limit}); no truncation is allowed')
106
+
107
+
108
+ def run_vllm(pending, args, emit):
109
+ from vllm import LLM, SamplingParams
110
+ kw = dict(model=args.model, trust_remote_code=args.trust_remote_code,
111
+ dtype=args.dtype, tensor_parallel_size=args.tensor_parallel,
112
+ gpu_memory_utilization=args.gpu_memory_utilization,
113
+ enforce_eager=args.enforce_eager,
114
+ enable_prefix_caching=not args.disable_prefix_cache)
115
+ if args.revision:
116
+ kw['revision'] = args.revision
117
+ if getattr(args, 'tokenizer', None):
118
+ kw['tokenizer'] = args.tokenizer
119
+ if getattr(args, 'tokenizer_revision', None):
120
+ kw['tokenizer_revision'] = args.tokenizer_revision
121
+ if args.max_model_len:
122
+ kw['max_model_len'] = args.max_model_len
123
+ if args.quantization:
124
+ kw['quantization'] = args.quantization
125
+ llm = LLM(**kw)
126
+ tokenizer = llm.get_tokenizer()
127
+ if getattr(tokenizer, 'pad_token_id', None) is None and getattr(tokenizer, 'eos_token_id', None) is not None:
128
+ tokenizer.pad_token = tokenizer.eos_token
129
+ compiled = _prepare_all_tokens(pending, tokenizer, args)
130
+ validate_context(getattr(args, '_all_rows', pending), compiled, args, args.max_model_len)
131
+ # Large models benefit from having similar-size prompts in the same chunk.
132
+ # Each question retains its exact max-token budget and original ID.
133
+ ordered = sorted(pending, key=lambda q: (token_budget(q, args), len(compiled[q['id']]['input_ids'])))
134
+ for off in range(0, len(ordered), args.batch_size):
135
+ group = ordered[off:off+args.batch_size]
136
+ # TokensPrompt skips vLLM's text tokenization entirely.
137
+ inputs = [{'prompt_token_ids': compiled[q['id']]['input_ids']} for q in group]
138
+ sampling = [SamplingParams(temperature=0.0, top_p=1.0, n=1,
139
+ max_tokens=token_budget(q, args), seed=args.seed)
140
+ for q in group]
141
+ result = llm.generate(inputs, sampling_params=sampling, use_tqdm=not args.quiet)
142
+ if len(result) != len(group):
143
+ raise RuntimeError('vLLM returned unexpected number of results')
144
+ emit([(q['id'], out.outputs[0].text, len(out.outputs[0].token_ids))
145
+ for q, out in zip(group, result)])
146
+ del llm
147
+
148
+
149
+ def run_transformers(pending, args, emit):
150
+ with Progress(getattr(args, "progress_label", "SmolCUA"), len(pending), args.quiet,
151
+ getattr(args, "progress_interval", 5)) as progress:
152
+ args._progress = progress
153
+ try:
154
+ return _run_transformers(pending, args, emit, progress)
155
+ finally:
156
+ del args._progress
157
+
158
+
159
+ def _run_transformers(pending, args, emit, progress):
160
+ import torch
161
+ from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer, AutoConfig
162
+ progress.update(stage='loading tokenizer/config', force=True)
163
+ model_kw = {'trust_remote_code': args.trust_remote_code}
164
+ if args.revision:
165
+ model_kw['revision'] = args.revision
166
+ tokenizer_kwargs = {'trust_remote_code': args.trust_remote_code}
167
+ if getattr(args, 'tokenizer_revision', None) or args.revision:
168
+ tokenizer_kwargs['revision'] = getattr(args, 'tokenizer_revision', None) or args.revision
169
+ tokenizer = AutoTokenizer.from_pretrained(getattr(args, 'tokenizer', None) or args.model,
170
+ **tokenizer_kwargs)
171
+ config = AutoConfig.from_pretrained(args.model, **model_kw)
172
+ if tokenizer.pad_token_id is None:
173
+ if tokenizer.eos_token_id is None:
174
+ raise ValueError('Tokenizer has neither PAD nor EOS token')
175
+ tokenizer.pad_token = tokenizer.eos_token
176
+ tokenizer.padding_side = 'right' if getattr(config, 'is_encoder_decoder', False) else 'left'
177
+ # Tokenize before model weights are allocated; model.generate never sees text.
178
+ compiled = _prepare_all_tokens(pending, tokenizer, args)
179
+ is_seq2seq = bool(getattr(config, 'is_encoder_decoder', False))
180
+ context_limit = args.max_model_len or getattr(config, 'max_position_embeddings', None)
181
+ validate_context(getattr(args, '_all_rows', pending), compiled, args, context_limit, is_seq2seq)
182
+ dtype_map = {'auto': 'auto', 'float16': torch.float16,
183
+ 'bfloat16': torch.bfloat16, 'float32': torch.float32}
184
+ device = getattr(args, 'device', None) or ('cuda' if torch.cuda.is_available() else (
185
+ 'mps' if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available() else 'cpu'))
186
+ if not device.startswith('cuda') and args.dtype in ('float16', 'bfloat16'):
187
+ print('Warning: requested low precision on non-CUDA device', file=sys.stderr)
188
+ kwargs = dict(model_kw, dtype=dtype_map[args.dtype], low_cpu_mem_usage=True)
189
+ if device.startswith('cuda'):
190
+ kwargs['device_map'] = device
191
+ elif device == 'mps':
192
+ kwargs['device_map'] = 'mps'
193
+ is_seq2seq = bool(getattr(config, 'is_encoder_decoder', False))
194
+ cls = AutoModelForSeq2SeqLM if is_seq2seq else AutoModelForCausalLM
195
+ progress.update(stage='loading model weights', force=True)
196
+ try:
197
+ model = cls.from_pretrained(args.model, **kwargs)
198
+ except (TypeError, ValueError) as exc:
199
+ if 'dtype' not in str(exc):
200
+ raise
201
+ kwargs['torch_dtype'] = kwargs.pop('dtype')
202
+ model = cls.from_pretrained(args.model, **kwargs)
203
+ if device == 'cpu':
204
+ model = model.to('cpu')
205
+ model.eval()
206
+ progress.update(stage='model ready', force=True)
207
+ args._generation_stats = generate_batches(
208
+ model, tokenizer, compiled, pending, lambda q: token_budget(q, args),
209
+ args.batch_size, emit, progress, is_seq2seq=is_seq2seq,
210
+ keep_special_tokens=getattr(args, 'keep_special_tokens', False))
211
+ del model
212
+ gc.collect()
213
+
214
+ def run_api(pending,args,emit):
215
+ # For vLLM servers, TGI-compatible OpenAI endpoints, remote HF deployments, etc.
216
+ from openai import OpenAI
217
+ if not args.endpoint:raise ValueError('--endpoint is required for --backend api')
218
+ api_key=os.getenv(args.api_key_env,'EMPTY')
219
+ client=OpenAI(base_url=args.endpoint,api_key=api_key,max_retries=args.api_retries,
220
+ timeout=args.api_timeout)
221
+ def request(q):
222
+ prompt=format_prompt(q)
223
+ if args.prompt_mode=='plain':
224
+ msg=[{'role':'user','content':build_plain(prompt)}]
225
+ else:msg=build_messages(prompt)
226
+ answer=client.chat.completions.create(model=args.model,messages=msg,
227
+ max_tokens=token_budget(q,args),
228
+ temperature=0,seed=args.seed)
229
+ choice=answer.choices[0]
230
+ content=choice.message.content
231
+ if content is None:content=''
232
+ return (q['id'],content,getattr(answer.usage,'completion_tokens',0) or 0)
233
+ # Bounded concurrent I/O. Never silently swallow failed requests.
234
+ with ThreadPoolExecutor(max_workers=args.api_concurrency) as pool:
235
+ futures={pool.submit(request,q):q['id'] for q in pending}
236
+ done=[]
237
+ for future in as_completed(futures):
238
+ done.append(future.result())
239
+ if len(done)>=args.batch_size:
240
+ emit(done);done=[]
241
+ if done:emit(done)
242
+
243
+
244
+ def parse_passes(value,total):
245
+ if value=='all':return set(range(1,total+1))
246
+ out={int(p) for p in value.split(',')}
247
+ if not out or not out.issubset(set(range(1,total+1))):
248
+ raise ValueError(f'Invalid passes {value}; expected 1..{total}')
249
+ return out
250
+
251
+
252
+ def resolve_run_dir(args):
253
+ if args.run_dir:
254
+ directory=Path(args.run_dir)
255
+ if not (directory/'manifest.json').exists():raise FileNotFoundError(directory/'manifest.json')
256
+ return directory
257
+ from huggingface_hub import snapshot_download
258
+ # Explicit selection only; avoid pulling gigabytes or private generator sources.
259
+ patterns=[f'{args.run_subdir}/manifest.json',f'{args.run_subdir}/questions_all_passes.jsonl']
260
+ if args.score:patterns.extend([f'{args.run_subdir}/private/answers_all_passes.jsonl',
261
+ f'{args.run_subdir}/private/weights_all_passes.jsonl'])
262
+ root=Path(snapshot_download(repo_id=args.dataset,repo_type='dataset',revision=args.dataset_revision,
263
+ allow_patterns=patterns,token=True if os.getenv('HF_TOKEN') else None))
264
+ return root/args.run_subdir
265
+
266
+
267
+ def build_parser():
268
+ ap=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.ArgumentDefaultsHelpFormatter)
269
+ ap.add_argument('--model',required=True,help='Hugging Face model repo ID, local path or deployed API model name')
270
+ ap.add_argument('--backend',choices=['auto','vllm','transformers','api'],default='auto')
271
+ ap.add_argument('--dataset',default=DEFAULT_REPO)
272
+ ap.add_argument('--dataset-revision',default=None)
273
+ ap.add_argument('--run-subdir',default=DEFAULT_RUN)
274
+ ap.add_argument('--run-dir',help='Use an existing local run directory (offline)')
275
+ ap.add_argument('--output-dir',default='results/smolcua_run')
276
+ ap.add_argument('--passes',default='all',help='all or comma-separated pass numbers')
277
+ ap.add_argument('--limit',type=int,default=0,help='Only for quick smoke tests; not a valid published score')
278
+ ap.add_argument('--score',action='store_true',help='Require label and weight files and compute weighted + reliability scores')
279
+ ap.add_argument('--resume',action='store_true',help='Resume only if run metadata matches')
280
+ ap.add_argument('--batch-size',type=int,default=0,help='0 = auto (vLLM 256, Transformers 32, API 32); Transformers backs off on CUDA OOM')
281
+ ap.add_argument('--max-new-tokens',type=int,default=512,help='Upper bound for raw payloads')
282
+ ap.add_argument('--short-max-new-tokens',type=int,default=48,help='Token budget for short response formats')
283
+ ap.add_argument('--dtype',choices=['auto','float16','bfloat16','float32'],default='auto')
284
+ ap.add_argument('--tensor-parallel',type=int,default=1)
285
+ ap.add_argument('--gpu-memory-utilization',type=float,default=0.90)
286
+ ap.add_argument('--max-model-len',type=int,default=0)
287
+ ap.add_argument('--quantization',default=None)
288
+ ap.add_argument('--revision',default=None,help='Pinned model revision for reproducibility')
289
+ ap.add_argument('--trust-remote-code',action='store_true',help='Only for models you trust; executes third-party code')
290
+ ap.add_argument('--tokenizer',default=None,help='Optional HF tokenizer repository (defaults to --model)')
291
+ ap.add_argument('--tokenizer-revision',default=None,help='Optional tokenizer revision (defaults to --revision)')
292
+ ap.add_argument('--token-cache-dir',default='~/.cache/smolcua/tokens',
293
+ help='Persistent, content-addressed CPU token cache (keep local)')
294
+ ap.add_argument('--no-token-cache',action='store_true',help='Pretokenize once in memory without saving')
295
+ ap.add_argument('--rebuild-token-cache',action='store_true',help='Discard any matching on-disk token cache')
296
+ ap.add_argument('--tokenize-batch-size',type=int,default=512,help='CPU tokenization batch size')
297
+ ap.add_argument('--pretokenize-only',action='store_true',
298
+ help='Compile all requested prompts on CPU then exit; no model weights/GPU required')
299
+ ap.add_argument('--prompt-mode',choices=['auto','chat','plain'],default='auto')
300
+ ap.add_argument('--chat-template-kwargs',type=json.loads,default={},help='JSON object, e.g. {"enable_thinking": false}')
301
+ ap.add_argument('--disable-prefix-cache',action='store_true')
302
+ ap.add_argument('--enforce-eager',action='store_true')
303
+ ap.add_argument('--seed',type=int,default=42)
304
+ ap.add_argument('--endpoint',help='OpenAI-compatible /v1 URL for API backend')
305
+ ap.add_argument('--api-key-env',default='OPENAI_API_KEY')
306
+ ap.add_argument('--api-concurrency',type=int,default=16)
307
+ ap.add_argument('--api-retries',type=int,default=3)
308
+ ap.add_argument('--api-timeout',type=int,default=120)
309
+ ap.add_argument('--quiet',action='store_true')
310
+ ap.add_argument('--progress-interval', type=float, default=5, help='Seconds between live progress updates')
311
+ return ap
312
+
313
+
314
+ def main(argv=None):
315
+ ap = build_parser()
316
+ args=ap.parse_args(argv)
317
+ if args.progress_interval <= 0:ap.error('--progress-interval must be positive')
318
+ if args.batch_size<0 or args.max_new_tokens<1 or args.short_max_new_tokens<1 or args.tokenize_batch_size<1:ap.error('batch and token limits must be positive')
319
+ if args.limit < 0 or args.max_model_len < 0 or args.api_concurrency < 1:
320
+ ap.error('limit/context must be nonnegative; API concurrency must be positive')
321
+ if not isinstance(args.chat_template_kwargs,dict):ap.error('--chat-template-kwargs must be a JSON object')
322
+ if args.backend=='auto':
323
+ has_vllm=importlib.util.find_spec('vllm') is not None
324
+ if has_vllm:
325
+ try:
326
+ import torch
327
+ has_vllm=torch.cuda.is_available()
328
+ except ImportError:has_vllm=False
329
+ args.backend='vllm' if has_vllm else 'transformers'
330
+ if args.batch_size==0:args.batch_size={'vllm':256,'transformers':32,'api':32}[args.backend]
331
+ if args.pretokenize_only and not importlib.util.find_spec('transformers'):
332
+ ap.error('For --pretokenize-only install transformers: pip install transformers')
333
+ if not args.pretokenize_only and args.backend=='vllm' and not importlib.util.find_spec('vllm'):
334
+ ap.error('vllm is not installed; use --backend transformers or pip install vllm')
335
+ if not args.pretokenize_only and args.backend=='transformers' and not importlib.util.find_spec('transformers'):
336
+ ap.error('transformers is not installed; pip install torch transformers accelerate')
337
+ if not args.pretokenize_only and args.backend=='api' and not importlib.util.find_spec('openai'):
338
+ ap.error('openai is not installed; pip install openai')
339
+ directory=resolve_run_dir(args)
340
+ manifest=json.loads((directory/'manifest.json').read_text(encoding='utf-8'))
341
+ questions_path=directory/'questions_all_passes.jsonl'
342
+ digest=hashlib.sha256(questions_path.read_bytes()).hexdigest()
343
+ if digest!=manifest['question_file_sha256']:raise ValueError('Dataset questions SHA256 does not match manifest')
344
+ if args.score and not args.pretokenize_only:
345
+ for name in ('answers_all_passes.jsonl','weights_all_passes.jsonl'):
346
+ if not (directory/'private'/name).exists():
347
+ raise FileNotFoundError("Scoring requested, but ground truth is not in this edition. Use the self-score edition or omit --score.")
348
+ rows=read_jsonl(questions_path)
349
+ if len(rows)!=manifest['total_instances']:raise ValueError('Unexpected number of questions')
350
+ selected=parse_passes(args.passes,manifest['passes'])
351
+ rows=[r for r in rows if r['pass'] in selected]
352
+ if args.limit:rows=rows[:args.limit]
353
+ if args.score and not args.pretokenize_only and len(rows) != manifest['total_instances']:
354
+ raise ValueError('--score requires all questions and passes; remove --limit/--passes or omit --score')
355
+ if len({r['id'] for r in rows})!=len(rows):raise ValueError('Duplicate question IDs')
356
+ # In --pretokenize-only mode, precompile every selected question without
357
+ # loading weights. This is useful as a CPU-only preparation step.
358
+ if args.pretokenize_only:
359
+ from transformers import AutoTokenizer
360
+ tok_kw = {'trust_remote_code': args.trust_remote_code}
361
+ revision = args.tokenizer_revision or args.revision
362
+ if revision:
363
+ tok_kw['revision'] = revision
364
+ tok = AutoTokenizer.from_pretrained(args.tokenizer or args.model, **tok_kw)
365
+ if getattr(tok, 'pad_token_id', None) is None and getattr(tok, 'eos_token_id', None) is not None:
366
+ tok.pad_token = tok.eos_token
367
+ _, info = compile_tokens(rows, tok, args, digest, format_prompt)
368
+ print(json.dumps(info, indent=2, ensure_ascii=False))
369
+ return
370
+ out_dir=Path(args.output_dir);out_dir.mkdir(parents=True,exist_ok=True)
371
+ metadata={'model':args.model,'backend':args.backend,'model_revision':args.revision,'tokenizer':args.tokenizer,
372
+ 'tokenizer_revision':args.tokenizer_revision,
373
+ 'dataset_sha256':digest,'passes':sorted(selected),'limit':args.limit,
374
+ 'prompt_mode':args.prompt_mode,'chat_template_kwargs':args.chat_template_kwargs,
375
+ 'dtype':args.dtype,'quantization':args.quantization,'seed':args.seed,
376
+ 'max_new_tokens':args.max_new_tokens,'short_max_new_tokens':args.short_max_new_tokens,
377
+ 'tensor_parallel':args.tensor_parallel,'endpoint':args.endpoint,
378
+ 'max_model_len':args.max_model_len,
379
+ 'manifest_sha256':hashlib.sha256((directory/'manifest.json').read_bytes()).hexdigest(),
380
+ 'pretokenize_schema':1}
381
+ meta_file=out_dir/'run_metadata.json';pred_file=out_dir/'predictions.jsonl'
382
+ if args.resume:
383
+ if not meta_file.exists():raise FileNotFoundError('Cannot resume: run_metadata.json missing')
384
+ if json.loads(meta_file.read_text(encoding='utf-8'))!=metadata:
385
+ raise ValueError('Resume metadata mismatch; choose a new --output-dir')
386
+ previous=read_jsonl(pred_file) if pred_file.exists() else []
387
+ else:
388
+ if meta_file.exists() or pred_file.exists():
389
+ raise FileExistsError('Output directory contains results. Use --resume or a new --output-dir')
390
+ previous=[];write_atomic_json(meta_file,metadata)
391
+ full={r['id']:r for r in previous}
392
+ wanted_ids = {q['id'] for q in rows}
393
+ if len(full)!=len(previous) or any(r['id'] not in wanted_ids for r in previous):
394
+ raise ValueError('Prior predictions contain duplicate or foreign IDs')
395
+ if any(not isinstance(r.get('answer'), str) for r in previous):
396
+ raise ValueError('Prior predictions must contain text answers')
397
+ pending=[r for r in rows if r['id'] not in full]
398
+ args._all_rows=rows
399
+ args._dataset_sha256=digest
400
+ # Shuffle deterministically to prevent running an easier category first; keep IDs for scoring.
401
+ rng=random.Random(args.seed);rng.shuffle(pending)
402
+ generated_tokens=0
403
+ started=time.perf_counter()
404
+ def emit(out):
405
+ nonlocal generated_tokens
406
+ for rid,txt,n in out:
407
+ if rid not in wanted_ids:raise ValueError(f'Unknown inference result {rid}')
408
+ if rid in full:raise ValueError(f'Duplicate inference result {rid}')
409
+ if not isinstance(txt,str):raise TypeError('Model output must be a text string')
410
+ full[rid]={'id':rid,'answer':txt}
411
+ generated_tokens+=n
412
+ # One atomic save per batch; crash-safe resumability.
413
+ write_atomic_jsonl(pred_file,[full[q['id']] for q in rows if q['id'] in full])
414
+ progress = getattr(args, '_progress', None)
415
+ if progress and args.backend != 'transformers':
416
+ progress.update(stage='responses saved', done=len(full)-len(previous), tokens=generated_tokens, force=True)
417
+ if pending:
418
+ if args.backend == 'transformers':
419
+ run_transformers(pending,args,emit)
420
+ else:
421
+ with Progress('SmolCUA', len(pending), args.quiet, args.progress_interval) as progress:
422
+ args._progress = progress
423
+ progress.update(stage='loading vLLM' if args.backend == 'vllm' else 'API requests in flight', force=True)
424
+ try:
425
+ {'vllm':run_vllm,'api':run_api}[args.backend](pending,args,emit)
426
+ finally:
427
+ del args._progress
428
+ if set(full) != wanted_ids:
429
+ raise RuntimeError('Inference ended with missing predictions; partial results retained for --resume')
430
+ elapsed=max(1e-6,time.perf_counter()-started)
431
+ report=dict(metadata,token_cache=getattr(args,'_token_cache_info',None),
432
+ generation=getattr(args,'_generation_stats',None),
433
+ attempted=len(full),expected=len(rows),new_predictions=len(pending),
434
+ elapsed_seconds=round(elapsed,3),questions_per_second=round(len(pending)/elapsed,3),
435
+ generated_tokens=generated_tokens,
436
+ generated_tokens_per_second=round(generated_tokens/elapsed,3),
437
+ speed_note='Only new predictions measured; load/tokenization included; no GPU speed validated here.')
438
+ write_atomic_json(out_dir/'performance.json',report)
439
+ if args.score:
440
+ if len(rows)!=manifest['total_instances'] or len(full)!=manifest['total_instances']:
441
+ raise ValueError('--score requires full benchmark and all passes; partial predictions saved')
442
+ for name in ('answers_all_passes.jsonl','weights_all_passes.jsonl'):
443
+ if not (directory/'private'/name).exists():
444
+ raise FileNotFoundError('Labels are not available. Blind releases need an external evaluator; use self-score release.')
445
+ from score_smolcua import score
446
+ results=score(pred_file,directory)
447
+ write_atomic_json(out_dir/'score.json',results)
448
+ print(f"Weighted: {results['mean_weighted_score_100']:.4f}/100 | "
449
+ f"Reliability: {results['reliability_score_100']:.4f}/100 "
450
+ f"({results['reliability_exact_correct']}/{results['reliability_exact_total']} worst pass)")
451
+ print(f"Completed {len(full)}/{len(rows)}. Saved to {out_dir}. "
452
+ f"New throughput: {report['questions_per_second']:.2f} questions/s")
453
+
454
+ if __name__=='__main__':main()
runs/v1_1_seed_20261023/corrections.json ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/manifest.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "benchmark": "SmolCUA",
3
+ "version": "1.1",
4
+ "seed": 20261023,
5
+ "passes": 5,
6
+ "questions_per_pass": 1000,
7
+ "total_instances": 5000,
8
+ "categories": {
9
+ "tool_use": 100,
10
+ "best_next_action": 100,
11
+ "strategy_switching": 100,
12
+ "instruction_following": 100,
13
+ "ambiguity_understanding": 100,
14
+ "coding": 100,
15
+ "structured_output": 100,
16
+ "coordinate_reasoning": 100,
17
+ "multi_constraint_format": 100,
18
+ "state_tracking": 100
19
+ },
20
+ "category_points": {
21
+ "tool_use": 10.0,
22
+ "best_next_action": 10.0,
23
+ "strategy_switching": 13.0,
24
+ "instruction_following": 8.0,
25
+ "ambiguity_understanding": 12.0,
26
+ "coding": 10.0,
27
+ "structured_output": 7.0,
28
+ "coordinate_reasoning": 8.0,
29
+ "multi_constraint_format": 9.0,
30
+ "state_tracking": 13.0
31
+ },
32
+ "option_styles": [
33
+ "plain",
34
+ "json_envelope",
35
+ "xml_envelope",
36
+ "markdown_quote",
37
+ "fenced_block",
38
+ "yaml_block",
39
+ "quoted_string",
40
+ "tagged_section",
41
+ "python_string"
42
+ ],
43
+ "response_styles": [
44
+ "letter",
45
+ "ordinal",
46
+ "json_choice",
47
+ "json_choice_text",
48
+ "yaml_choice",
49
+ "xml_choice",
50
+ "csv_choice",
51
+ "bracket_choice",
52
+ "pipe_choice",
53
+ "raw_payload"
54
+ ],
55
+ "response_style_frequency_per_category_per_pass": 10,
56
+ "question_file_sha256": "cc73cbf46f695d8e9284bc1f3cf5e73d8497dc29962a2bd6ebdd4497e3e38590",
57
+ "world_sha256": "fd2eeb1324ebb6ebb012edf9b807f1715aa58558d4a165b2a9e13277d742d8f1",
58
+ "overrides_sha256": null,
59
+ "oracle_counts": {
60
+ "preserved_semantics": 1783,
61
+ "authored_semantic_branch": 1217,
62
+ "executed_python": 500,
63
+ "derived_structured_format": 500,
64
+ "derived_geometry": 500,
65
+ "derived_format": 500
66
+ },
67
+ "notes": "Local prompt repairs reconstructed from authored answer keys; options, labels and weights unchanged. Not interchangeable with original v1.0 scores.",
68
+ "edition": "local-corrected",
69
+ "source_version": "1.0",
70
+ "source_question_file_sha256": "ad11f4fb6b280f688b3a40fd04ecf6aa248714b3d035497f31dcbb0e81ef1c1f",
71
+ "scoring_file_sha256": {
72
+ "answers_all_passes.jsonl": "9816fe4cec5ec6aae7b0990727d0d38bba13ed14ff0c2d73fce5ac64a09df8b2",
73
+ "weights_all_passes.jsonl": "3d38027d263c311c5e5e954d05766238f2b835d13eb17acdbc4e6224e0617bf7"
74
+ },
75
+ "corrected_questions": 250
76
+ }
runs/v1_1_seed_20261023/pass_01_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/pass_02_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/pass_03_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/pass_04_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/pass_05_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/private/answers_all_passes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/private/weights_all_passes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_1_seed_20261023/questions_all_passes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/manifest.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "benchmark": "SmolCUA",
3
+ "version": "1.0",
4
+ "seed": 20261023,
5
+ "passes": 5,
6
+ "questions_per_pass": 1000,
7
+ "total_instances": 5000,
8
+ "categories": {
9
+ "tool_use": 100,
10
+ "best_next_action": 100,
11
+ "strategy_switching": 100,
12
+ "instruction_following": 100,
13
+ "ambiguity_understanding": 100,
14
+ "coding": 100,
15
+ "structured_output": 100,
16
+ "coordinate_reasoning": 100,
17
+ "multi_constraint_format": 100,
18
+ "state_tracking": 100
19
+ },
20
+ "category_points": {
21
+ "tool_use": 10.0,
22
+ "best_next_action": 10.0,
23
+ "strategy_switching": 13.0,
24
+ "instruction_following": 8.0,
25
+ "ambiguity_understanding": 12.0,
26
+ "coding": 10.0,
27
+ "structured_output": 7.0,
28
+ "coordinate_reasoning": 8.0,
29
+ "multi_constraint_format": 9.0,
30
+ "state_tracking": 13.0
31
+ },
32
+ "option_styles": [
33
+ "plain",
34
+ "json_envelope",
35
+ "xml_envelope",
36
+ "markdown_quote",
37
+ "fenced_block",
38
+ "yaml_block",
39
+ "quoted_string",
40
+ "tagged_section",
41
+ "python_string"
42
+ ],
43
+ "response_styles": [
44
+ "letter",
45
+ "ordinal",
46
+ "json_choice",
47
+ "json_choice_text",
48
+ "yaml_choice",
49
+ "xml_choice",
50
+ "csv_choice",
51
+ "bracket_choice",
52
+ "pipe_choice",
53
+ "raw_payload"
54
+ ],
55
+ "response_style_frequency_per_category_per_pass": 10,
56
+ "question_file_sha256": "ad11f4fb6b280f688b3a40fd04ecf6aa248714b3d035497f31dcbb0e81ef1c1f",
57
+ "world_sha256": "fd2eeb1324ebb6ebb012edf9b807f1715aa58558d4a165b2a9e13277d742d8f1",
58
+ "overrides_sha256": null,
59
+ "oracle_counts": {
60
+ "preserved_semantics": 1783,
61
+ "authored_semantic_branch": 1217,
62
+ "executed_python": 500,
63
+ "derived_structured_format": 500,
64
+ "derived_geometry": 500,
65
+ "derived_format": 500
66
+ },
67
+ "notes": "Author-curated alternative task branches and bounded answer-preserving transformations. No claim of unrestricted semantic substitution."
68
+ }
runs/v1_seed_20261023/pass_01_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/pass_02_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/pass_03_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/pass_04_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/pass_05_questions.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/private/answers_all_passes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/private/weights_all_passes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
runs/v1_seed_20261023/questions_all_passes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
score_smolcua.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """SmolCUA v1.0 strict response-format scorer with worst-case reliability.
3
+
4
+ Input JSONL: {"id":"P01-CU-01-001","answer":"..."}
5
+ The `answer` field is the string that the model emitted, exactly, using the
6
+ question's required response contract. Incorrect formatting = incorrect item.
7
+ Use all five or more passes; omitted answers are wrong, not excluded.
8
+ """
9
+ from __future__ import annotations
10
+ import argparse, collections, hashlib, json, statistics, math
11
+ from pathlib import Path
12
+ from response_formats import parse_response, unwrap_option
13
+
14
+
15
+ def load(path):
16
+ return [json.loads(line) for line in path.read_text(encoding='utf8').splitlines() if line.strip()]
17
+
18
+
19
+ def indexed(path):
20
+ rows = load(path)
21
+ result = {r['id']: r for r in rows}
22
+ if len(result) != len(rows):
23
+ raise ValueError(f'Duplicate IDs in {path.name}')
24
+ return result
25
+
26
+
27
+ def score(pred_path,run_dir):
28
+ m=json.loads((run_dir/'manifest.json').read_text(encoding='utf8'))
29
+ if m['version'] not in ('1.0', '1.1') or m['passes']<5:raise ValueError('Expected supported SmolCUA run, at least five passes')
30
+ qpath=run_dir/'questions_all_passes.jsonl'
31
+ if hashlib.sha256(qpath.read_bytes()).hexdigest()!=m['question_file_sha256']:
32
+ raise ValueError('Public-question integrity hash mismatch')
33
+ for name, digest in m.get('scoring_file_sha256', {}).items():
34
+ if name not in ('answers_all_passes.jsonl', 'weights_all_passes.jsonl'):
35
+ raise ValueError('Unexpected scoring filename')
36
+ if hashlib.sha256((run_dir/'private'/name).read_bytes()).hexdigest() != digest:
37
+ raise ValueError('Scoring-file integrity hash mismatch')
38
+ questions=indexed(qpath)
39
+ keys=indexed(run_dir/'private'/'answers_all_passes.jsonl')
40
+ weights=indexed(run_dir/'private'/'weights_all_passes.jsonl')
41
+ if set(questions)!=set(keys) or set(keys)!=set(weights) or len(questions)!=m['total_instances']:
42
+ raise ValueError('Question/answer/weight set is inconsistent')
43
+ if any(keys[rid]['answer'] not in ('A', 'B', 'C', 'D') for rid in keys):
44
+ raise ValueError('Invalid answer key')
45
+ if any(not math.isfinite(w['max_points']) or w['max_points'] <= 0 for w in weights.values()):
46
+ raise ValueError('Weights must be finite and positive')
47
+ preds={};parsed={};format_bad=[]
48
+ for i,r in enumerate(load(pred_path),1):
49
+ rid=r.get('id')
50
+ if rid not in questions:raise ValueError(f'Unknown question ID on prediction line {i}: {rid!r}')
51
+ if rid in preds:raise ValueError(f'Duplicate prediction for {rid}')
52
+ if 'answer' not in r:raise ValueError(f'Missing answer field for {rid}')
53
+ preds[rid]=r['answer']
54
+ q=questions[rid]
55
+ raw={k:unwrap_option(v,q['option_presentation']) for k,v in q['options'].items()}
56
+ parsed[rid]=parse_response(r['answer'],q['response_format'],raw)
57
+ if parsed[rid] is None:format_bad.append(rid)
58
+ passes=[];cat_pass=collections.defaultdict(list);style_data=collections.defaultdict(lambda:[0,0,0]);stable=collections.defaultdict(list)
59
+ for rid,q in questions.items():
60
+ sty=q['response_format'];style_data[sty][0]+=1
61
+ if rid in preds:style_data[sty][1]+=1
62
+ if parsed.get(rid)==keys[rid]['answer']:style_data[sty][2]+=1
63
+ stable[q['item_id']].append(parsed.get(rid)==keys[rid]['answer'])
64
+ for p in range(1,m['passes']+1):
65
+ item_ids=[rid for rid,q in questions.items() if q['pass']==p]
66
+ if len(item_ids)!=m['questions_per_pass']:raise ValueError('Unequal pass lengths')
67
+ correct_ids=[rid for rid in item_ids if parsed.get(rid)==keys[rid]['answer']]
68
+ earned=sum(weights[rid]['max_points'] for rid in correct_ids)
69
+ per_cat={}
70
+ for cat,total in m['categories'].items():
71
+ part=[rid for rid in item_ids if questions[rid]['category']==cat]
72
+ if len(part)!=total:raise ValueError(f'Bad number of questions in {cat}')
73
+ good=sum(parsed.get(rid)==keys[rid]['answer'] for rid in part)
74
+ cw=sum(weights[rid]['max_points'] for rid in part if parsed.get(rid)==keys[rid]['answer'])
75
+ entry={'correct':good,'total':len(part),'accuracy_pct':round(good*100/len(part),4),
76
+ 'weighted_points':round(cw,6),'category_budget':m['category_points'][cat]}
77
+ cat_pass[cat].append(entry);per_cat[cat]=entry
78
+ passes.append({'pass':p,'correct':len(correct_ids),'total':len(item_ids),
79
+ 'attempted':sum(rid in preds for rid in item_ids),
80
+ 'unweighted_accuracy_pct':round(len(correct_ids)*100/len(item_ids),4),
81
+ 'weighted_score_100':round(earned,6),'per_category':per_cat})
82
+ weakest=min(s['correct'] for s in passes)
83
+ performance=[s['weighted_score_100'] for s in passes]
84
+ per_cat_reliability={c:{'worst_exact_correct':min(s['correct'] for s in subs),
85
+ 'out_of':m['categories'][c],
86
+ 'worst_accuracy_pct':round(100*min(s['correct'] for s in subs)/m['categories'][c],4)}
87
+ for c,subs in cat_pass.items()}
88
+ consistency=collections.Counter(sum(vals) for vals in stable.values())
89
+ return {'benchmark':f"SmolCUA v{m['version']}",'edition':m.get('edition', 'original'),
90
+ 'dataset_sha256':m['question_file_sha256'],'passes':m['passes'],
91
+ 'mean_weighted_score_100':round(statistics.mean(performance),4),
92
+ 'mean_unweighted_accuracy_pct':round(statistics.mean(s['unweighted_accuracy_pct'] for s in passes),4),
93
+ 'worst_weighted_pass_score_100':round(min(performance),4),
94
+ 'reliability_exact_correct':weakest,'reliability_exact_total':m['questions_per_pass'],
95
+ 'reliability_score_100':round(weakest*100/m['questions_per_pass'],4),
96
+ 'reliability_worst_passes':[s['pass'] for s in passes if s['correct']==weakest],
97
+ 'reliability_definition':'Min exact answer count across all passes; must satisfy required syntax; unweighted; missing answers count as incorrect.',
98
+ 'per_category_reliability':per_cat_reliability,
99
+ 'per_category_mean':{c:{'mean_accuracy_pct':round(statistics.mean(s['accuracy_pct'] for s in subs),4),
100
+ 'mean_weighted_points':round(statistics.mean(s['weighted_points'] for s in subs),4)}
101
+ for c,subs in cat_pass.items()},
102
+ 'per_response_format':{s:{'total':v[0],'attempted':v[1],'correct':v[2],
103
+ 'accuracy_pct':round(v[2]*100/v[0],4)} for s,v in style_data.items()},
104
+ 'invalid_format_submissions':len(format_bad),'invalid_format_question_ids':format_bad[:25],
105
+ 'total_correct':sum(s['correct'] for s in passes),'total_questions':len(questions),
106
+ 'full_coverage_pct':round(len(preds)*100/len(questions),4),
107
+ 'pass_weighted_stddev':round(statistics.pstdev(performance),4),
108
+ 'stable_positions_correct_on_all_passes':consistency[m['passes']],
109
+ 'stable_positions_correct_on_no_passes':consistency[0],
110
+ 'per_pass':passes}
111
+
112
+
113
+ def main():
114
+ ap=argparse.ArgumentParser(description=__doc__)
115
+ ap.add_argument('predictions',type=Path)
116
+ ap.add_argument('--run-dir',type=Path,default=Path(__file__).resolve().parent/'runs'/'v1_seed_20261023')
117
+ ap.add_argument('--output',type=Path)
118
+ a=ap.parse_args()
119
+ result=score(a.predictions,a.run_dir)
120
+ result_json=json.dumps(result,ensure_ascii=False,indent=2)
121
+ if a.output:a.output.write_text(result_json+'\n',encoding='utf8')
122
+ print(result_json)
123
+
124
+ if __name__=='__main__':main()
token_cache.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Content-addressed, model-specific token compilation for SmolCUA.
3
+
4
+ This module is intentionally independent of torch/vLLM. Fast HF tokenizers
5
+ process *all* selected benchmark prompts in CPU batches before inference;
6
+ inference engines only consume token IDs. A content-addressed persistent cache
7
+ skips that CPU work on later runs of the same model and dataset revision.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import statistics
16
+ import time
17
+
18
+ VERSION = 2
19
+
20
+
21
+ def stable_json(value):
22
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
23
+
24
+
25
+ def sha(value):
26
+ return hashlib.sha256(value if isinstance(value, bytes) else str(value).encode('utf-8')).hexdigest()
27
+
28
+
29
+ def tokenizer_fingerprint(tokenizer):
30
+ """Fingerprint the *actual* tokenizer, not only its HF repository name.
31
+
32
+ The backend tokenization graph changes if merges/vocabulary/pre-tokenizer
33
+ change without a revision bump. Slow custom tokenizers use their vocab.
34
+ """
35
+ fp = hashlib.sha256()
36
+ for obj in (type(tokenizer).__module__ + '.' + type(tokenizer).__qualname__,
37
+ getattr(tokenizer, 'init_kwargs', {}),
38
+ getattr(tokenizer, 'special_tokens_map', {}),
39
+ getattr(tokenizer, 'added_tokens_decoder', {}),
40
+ getattr(tokenizer, 'chat_template', None),
41
+ getattr(tokenizer, 'bos_token_id', None),
42
+ getattr(tokenizer, 'eos_token_id', None)):
43
+ fp.update(sha(stable_json(obj)).encode())
44
+ backend = getattr(tokenizer, 'backend_tokenizer', None)
45
+ if backend is not None and hasattr(backend, 'to_str'):
46
+ fp.update(sha(backend.to_str()).encode())
47
+ elif hasattr(tokenizer, 'get_vocab'):
48
+ fp.update(sha(stable_json(tokenizer.get_vocab())).encode())
49
+ return fp.hexdigest()
50
+
51
+
52
+ def compile_key(rows, tokenizer, args, dataset_sha):
53
+ settings = {
54
+ 'cache_version': VERSION,
55
+ 'dataset_sha256': dataset_sha,
56
+ 'selected_ids_sha256': sha(stable_json([r['id'] for r in rows])),
57
+ 'tokenizer_repo': getattr(args, 'tokenizer', None) or args.model,
58
+ 'tokenizer_revision': getattr(args, 'tokenizer_revision', None) or args.revision,
59
+ 'tokenizer_fingerprint': tokenizer_fingerprint(tokenizer),
60
+ 'prompt_mode': args.prompt_mode,
61
+ 'chat_template_kwargs': args.chat_template_kwargs,
62
+ 'prompt_formatter_version': getattr(args, 'prompt_formatter_version', 'smolcua:1'),
63
+ 'prompt_content_sha256': sha(stable_json(rows)),
64
+ }
65
+ return sha(stable_json(settings)), settings
66
+
67
+
68
+ def effective_style(tokenizer, mode):
69
+ has_template = bool(getattr(tokenizer, 'chat_template', None))
70
+ if mode == 'chat' and not has_template:
71
+ raise ValueError('This tokenizer has no chat template: use --prompt-mode plain')
72
+ return ('chat' if has_template else 'plain') if mode == 'auto' else mode
73
+
74
+
75
+ def build_text(row, tokenizer, mode, template_kwargs, format_prompt):
76
+ prompt = format_prompt(row)
77
+ if effective_style(tokenizer, mode) == 'plain':
78
+ return prompt + '\n\nAnswer:\n'
79
+ return tokenizer.apply_chat_template(
80
+ [{'role': 'user', 'content': prompt}], tokenize=False,
81
+ add_generation_prompt=True, **template_kwargs)
82
+
83
+
84
+ def token_stats(items):
85
+ lengths = sorted(len(v['input_ids']) for v in items.values())
86
+ if not lengths:
87
+ return {'count': 0, 'input_tokens': 0, 'max_input_tokens': 0, 'p50_input_tokens': 0, 'p95_input_tokens': 0}
88
+ return {'count': len(lengths), 'input_tokens': sum(lengths),
89
+ 'max_input_tokens': lengths[-1],
90
+ 'p50_input_tokens': int(statistics.median(lengths)),
91
+ 'p95_input_tokens': lengths[min(len(lengths)-1, int((len(lengths)-1)*.95))]}
92
+
93
+
94
+ def compile_tokens(rows, tokenizer, args, dataset_sha, format_prompt, prompt_builder=None):
95
+ """Return (id -> tokenized prompt, performance info).
96
+
97
+ The entire list is compiled *before* the first model.generate call. Reused
98
+ caches preserve exact token sequences and do not repeat tokenizer calls.
99
+ Cache files are local to the evaluating user; never upload token caches or
100
+ real model responses with the public benchmark questions.
101
+ """
102
+ progress = getattr(args, '_progress', None)
103
+ if progress:
104
+ progress.update(stage=f'checking token cache ({len(rows)} prompts)', force=True)
105
+ started = time.perf_counter()
106
+ key, settings = compile_key(rows, tokenizer, args, dataset_sha)
107
+ cache_root = Path(getattr(args, 'token_cache_dir', None) or '~/.cache/smolcua/tokens').expanduser()
108
+ use_disk = not getattr(args, 'no_token_cache', False)
109
+ rebuild = getattr(args, 'rebuild_token_cache', False)
110
+ path = cache_root / (key + '.json') if use_disk else None
111
+ wanted_ids = [r['id'] for r in rows]
112
+
113
+ if path is not None and path.exists() and not rebuild:
114
+ try:
115
+ obj = json.loads(path.read_text(encoding='utf-8'))
116
+ valid = (obj.get('settings') == settings and
117
+ list(obj.get('items', {})) == wanted_ids and
118
+ obj.get('tokens_sha256') == sha(stable_json(obj.get('items', {}))))
119
+ if valid:
120
+ items = obj['items']
121
+ valid = all(isinstance(p.get('input_ids'), list) and p['input_ids'] and
122
+ all(isinstance(t, int) and t >= 0 for t in p['input_ids'])
123
+ for p in items.values())
124
+ if valid:
125
+ if progress:
126
+ progress.update(stage=f'token cache hit: {len(items)}/{len(rows)} prompts', force=True)
127
+ return items, {
128
+ 'status': 'hit', 'path': str(path), 'elapsed_seconds': round(time.perf_counter()-started, 4),
129
+ **token_stats(items)}
130
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
131
+ pass # A stale/partial cache is rebuilt, not silently used.
132
+
133
+ batch_size = int(getattr(args, 'tokenize_batch_size', 512))
134
+ if batch_size <= 0:
135
+ raise ValueError('--tokenize-batch-size must be positive')
136
+ items = {}
137
+ for off in range(0, len(rows), batch_size):
138
+ group = rows[off:off+batch_size]
139
+ prompts = [prompt_builder(q) if prompt_builder else build_text(q, tokenizer, args.prompt_mode, args.chat_template_kwargs, format_prompt)
140
+ for q in group]
141
+ # Batched Rust tokenizer threads when available; no padding and NEVER truncate.
142
+ # Chat templates already inject their own special tokens, so disable
143
+ # add_special_tokens to avoid BOS/EOS duplication.
144
+ enc = tokenizer(prompts, add_special_tokens=False, padding=False,
145
+ truncation=False, return_attention_mask=False)
146
+ ids = enc['input_ids']
147
+ if len(ids) != len(group):
148
+ raise ValueError('Tokenizer returned incorrect number of sequences')
149
+ types = enc.get('token_type_ids') if hasattr(enc, 'get') else None
150
+ for i, (row, sequence) in enumerate(zip(group, ids)):
151
+ seq = [int(t) for t in sequence]
152
+ if not seq or min(seq) < 0:
153
+ raise ValueError(f'Empty/invalid tokenized benchmark prompt: {row["id"]}')
154
+ if row['id'] in items:
155
+ raise ValueError(f'Duplicate row ID: {row["id"]}')
156
+ item = {'input_ids': seq}
157
+ if types is not None:
158
+ t = [int(x) for x in types[i]]
159
+ if len(t) != len(seq):
160
+ raise ValueError('token_type_ids shape mismatch')
161
+ item['token_type_ids'] = t
162
+ items[row['id']] = item
163
+ if progress:
164
+ progress.update(stage=f'pretokenized {len(items)}/{len(rows)} prompts', force=True)
165
+ elif not getattr(args, 'quiet', False):
166
+ print(f'Pretokenized {len(items)}/{len(rows)} prompts', flush=True)
167
+ if path is not None:
168
+ cache_root.mkdir(parents=True, exist_ok=True, mode=0o700)
169
+ tmp = path.with_name(path.name + f'.{os.getpid()}.tmp')
170
+ try:
171
+ with open(tmp, 'w', encoding='utf-8') as f:
172
+ os.chmod(tmp, 0o600)
173
+ json.dump({'settings': settings, 'items': items, 'tokens_sha256': sha(stable_json(items))},
174
+ f, ensure_ascii=False, separators=(',', ':'))
175
+ os.replace(tmp, path)
176
+ finally:
177
+ if tmp.exists():
178
+ tmp.unlink()
179
+ return items, {'status': 'built' if use_disk else 'memory', 'path': str(path) if path else None,
180
+ 'elapsed_seconds': round(time.perf_counter()-started, 4), **token_stats(items)}
181
+
182
+
183
+ def padded_batch(group, pad_token_id, padding_side='left', include_token_types=True):
184
+ """Pad cached token IDs directly into torch tensors without tokenizer calls."""
185
+ import torch
186
+ if not group:
187
+ raise ValueError('Cannot pad an empty group')
188
+ if pad_token_id is None:
189
+ raise ValueError('Tokenizer must have a valid pad token ID for Transformers batching')
190
+ maxlen = max(len(t['input_ids']) for t in group)
191
+ input_ids = torch.full((len(group), maxlen), int(pad_token_id), dtype=torch.long)
192
+ attention_mask = torch.zeros((len(group), maxlen), dtype=torch.long)
193
+ has_types = include_token_types and all('token_type_ids' in t for t in group)
194
+ types = torch.zeros((len(group), maxlen), dtype=torch.long) if has_types else None
195
+ for i, item in enumerate(group):
196
+ toks = item['input_ids']
197
+ start = (maxlen - len(toks)) if padding_side == 'left' else 0
198
+ end = start + len(toks)
199
+ input_ids[i, start:end] = torch.as_tensor(toks, dtype=torch.long)
200
+ attention_mask[i, start:end] = 1
201
+ if has_types:
202
+ types[i, start:end] = torch.as_tensor(item['token_type_ids'], dtype=torch.long)
203
+ out = {'input_ids': input_ids, 'attention_mask': attention_mask}
204
+ if has_types:
205
+ out['token_type_ids'] = types
206
+ return out