smolscript / README.md
appvoid's picture
Use newline-only headers and semantic browser grading (0.5.0)
fa26615 verified
|
Raw History Blame Contribute Delete
19.6 kB
metadata
pretty_name: SmolScript
license: mit
language:
  - en
tags:
  - code
  - code-generation
  - evaluation
  - multilingual
configs:
  - config_name: default
    default: true
    data_files:
      - split: test
        path: data/smolscript.parquet
  - config_name: full2000
    data_files:
      - split: test
        path: archive/v0.1.0/smolscript.parquet
  - config_name: previous1000
    data_files:
      - split: test
        path: archive/v0.2.0/smolscript.parquet

SmolScript

An original execution-based benchmark of basic programming for 25M–350M parameter language models. Evaluator 0.5.0, 350 default examples (fixed dataset edition 0.3.0), nine languages, MIT license.

Release status: execution-unverified candidate. All 350 default records have been generated and statically validated. No complete reference execution run or model baseline is claimed. The authoring environment has no Docker/Podman daemon; all 350 default reference solutions and their negative controls still require execution in the supplied sandbox image. See validation_report.json for the machine-readable audit. Do not treat this candidate as a validated leaderboard release until python validate.py succeeds.

Composition

Language Easy Medium Moderate Total
Python 26 13 5 44
JavaScript 27 13 4 44
HTML 21 11 3 35
CSS 21 10 4 35
C++ 24 12 4 40
C 23 12 4 39
Lua 21 11 3 35
C# 24 11 4 39
Rust 23 12 4 39
Total 210 105 35 350

Programming tasks cover arithmetic and conditions, ASCII string transformations, filtered collection reductions, frequency tables, and short combinations of basic operations. JavaScript includes 4 browser DOM/event tasks in the default subset. HTML tasks check elements, attributes, text, and nesting. CSS tasks check computed properties, selector scope, unaffected distractors, flex row/column geometry, and responsive breakpoints. No generated solution uses external packages.

Tasks are original compositions from an explicit operation grammar, not scraped HumanEval/MBPP/MultiPL-E questions. Variants change operations and observable behavior, not just names or numbers. Shared tasks across programming languages are intentional translations for comparative coverage. Within each language, deterministic behavioral probe fingerprints reject equivalent programming tasks. Web tasks have unique structural specs. Trigram similarity flags are reported; the seven retained pairs differ in count versus sum and have distinct behavior. This is a finite behavioral/structural audit, not a mathematical proof of semantic uniqueness. Difficulty labels are design judgments; empirical calibration on small models remains future work.

Install and build the offline sandbox

Requires Python 3.11+, Docker or Podman on Linux (or Docker Desktop's Linux VM), approximately 2 GB memory per concurrent container, and disk space for Chromium and compilers. GPU is optional for generation. All runtime downloads occur during image construction.

python -m venv .venv
. .venv/bin/activate
pip install -e '.[inference]'
docker build -f sandbox/Dockerfile -t smolscript-runtime:0.1.0 .
python validate.py

The image supplies CPython, Node.js, GCC/G++ (C11/C++17), Lua 5.4, Mono C#, Rust (edition 2021), and Playwright Chromium. Candidate functions use basic C# features supported by Mono. The base Playwright image and Python browser dependencies are pinned. OS compiler packages are resolved at build time; preserve/export the built image for exact runtime reproduction. Every evaluation records the immutable local image ID and available registry digests. Rebuilding later may produce a different image.

Containers run as UID 1000 with network disabled, a read-only root, no Linux capabilities, no privilege escalation, 2 GB memory/swap ceiling, one CPU, 512 processes, bounded temporary filesystems, CPU/wall timeouts, and bounded output. Compilation has a separate 30-second limit; each program test has a three-second CPU limit plus a one-second wall allowance. Browser operations have three-second timeouts and a container supervisor limit. Candidates have access only to their code, fixture, and input values; expected answers remain in the host scorer. No host home, Docker socket, credentials, or full dataset is mounted. There is no host-execution fallback. Containers are the required isolation boundary; use a dedicated worker for adversarial submissions.

The sandbox uses the documented Docker resource and isolation options and the Playwright Python container image. Evaluation requires no network after model/tokenizer weights and the image have been cached. To enforce offline Hugging Face loading, set HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1.

Validate

python validate.py                 # Full reference + negative-control execution
python validate.py --static-only   # Counts, uniqueness, oracle cases, hashes, Parquet
python -m unittest discover -s tests -v
python generators/build.py         # Deterministically regenerate all artifacts

validate.py checks every reference against every hidden test and rejects a deliberately wrong solution for every task. For programming tasks it also checks a plausible near-miss mutation where the hidden inputs distinguish it (missing transformation stage, mapping, or filter). Failure stops validation with the task ID. Missing sandbox/runtime exits 2 and records unverified coverage. Static-only success never marks execution as passed. The reference ASTs for all 44 Python tasks are also parsed by the local unit suite.

Evaluate a model

python evaluate.py --model HuggingFaceTB/SmolLM2-135M --output results.json
python evaluate.py --model HuggingFaceTB/SmolLM2-135M --output results.json --resume
python evaluate.py --model HuggingFaceTB/SmolLM2-135M --language python rust --difficulty easy --output subset.json

One fixed completion prompt (smolscript-base-completion-v3), one generation, seed 0, greedy decoding, no beam search, and versioned task budgets from 96 to 256 tokens. Starting batch size is 64, with automatic CUDA OOM backoff. Prompts are grouped by token budget and length; KV caching and supported last-token logits optimizations are enabled. Progress is reported between batches, avoiding per-token GPU-to-CPU synchronization. The same completion template is used for base and instruction models; no model-specific chat template is applied. The model revision resolves to an immutable commit and is retained on resume. Use --revision SHA for an explicit pin. Prompts contain task comments, the input domain, supplied standard-library imports, web fixtures/base styles where needed, and a function/markup prefix. Models continue the supplied source directly. References, public examples, hidden tests, and expected answers are never sent to the model.

Existing files require --resume. Settings, dataset/runner hashes, image ID and selected IDs must match. Completed task results are checkpointed atomically; a generated response is saved before execution, so an execution interruption can reuse it. Partial runs never receive a full score. Use one process per output path (a file lock enforces this). Context overflow is an explicit failure; input prompts are never silently truncated.

For externally generated code, create JSONL records {"id":"...","code":"..."} and use:

python evaluate.py --predictions predictions.jsonl --output results.json

Externally supplied predictions use complete source code (raw code or a single fenced code block). Model inference stores raw continuations and deterministically assembles the supplied prefix before scoring. Multiple or unfinished fences are rejected. Function tasks receive fixed stdin/stdout wrappers. Compiled languages compile once per task, then run a fresh process per test. HTML is parsed with html5lib and checked in Chromium with document scripts disabled. CSS syntax is reported with tinycss2 and behavior is tested against a fixed fixture at the specified widths. Browser tests assert DOM/computed styles and geometry, without image similarity.

Metrics

All metrics are on 0–100. A task passes only when every hidden assertion passes. With one generation, per-language accuracy is Pass@1. SmolScript Score and overall Pass@1 are the macro-average of the nine language accuracies. Syntax Success is likewise macro-averaged across languages and measures parse/compile success, separately from behavior. micro_accuracy is an explicitly secondary count-weighted diagnostic. No score is chance-adjusted.

Filters produce filtered_macro_score over selected languages rather than the official nine-language smolscript_score. Per-test outputs and pass/fail results are retained. Build failures count as syntax failures; runtime failures count as behavioral failures. Sandbox infrastructure errors stop the run instead of assigning a score.

examples/result-format.json illustrates output structure using explicitly synthetic numbers; it is not a model result.

Files and Hugging Face

data/smolscript.jsonl and data/smolscript.parquet contain the public test examples. To keep one consistent Parquet schema across modalities, tests and metadata are JSON strings in Parquet; JSONL uses native JSON values. Decode them with json.loads after loading through Hugging Face Datasets. Public reference_solution is null; full references are in references/solutions.jsonl. Hidden tests live in private_tests/hidden.jsonl, outside the public dataset split. These evaluation-only files are published for independent auditing; they are not access-controlled secrets. Never include them in model context. Offline evaluation requires downloading the complete repository, including these files.

from datasets import load_dataset
import json
rows = load_dataset('dotlabs/smolscript', split='test')
metadata = json.loads(rows[0]['metadata'])

The generator, runners and audit reports are included in this repository. Record the Hugging Face repository commit, manifest checksums, generation settings, dependency versions and image ID with any reported result.

Fast default (0.3.0)

The default split and both local/Modal evaluators now use the same fixed 350 IDs, selected from the prior 1,000-task edition by deterministic SHA256 ranking within language, difficulty, family and category strata. The selection manifest lists every ID and its hash. IDs, instructions, references and tests are preserved for selected tasks. The original 2,000-task edition is archived under archive/v0.1.0; Hugging Face users can request config full2000. The prior 1,000-task edition is also preserved as config previous1000 under archive/v0.2.0. Current evaluation commands use the 350-task edition.

The language budgets (before a 32-token moderate-task allowance, capped at 256) are Python 128, JavaScript 192, HTML 160, CSS 96, C++ 224, C 256, Lua 160, C# 256, Rust 256. They depend only on language/difficulty, never reference solutions. --max-new-tokens N overrides these budgets for a separately recorded experiment; --batch-size N overrides the default 64. A response that hits its cap is scored as generated; incorrect or incomplete code still fails the normal execution tests. Generation statistics include token-limit completions, OOM retries, final batch size, elapsed generation time and measured token throughput.

Example: python evaluate.py --model HuggingFaceTB/SmolLM2-135M --batch-size 64 --output results-v030.json. Generated batches are checkpointed before execution, and resume skips their inference. Numerical batching differences can change greedy outputs for near-tied logits. This release reduces the task count from 1,000 to 350 and retains the fast decoding budgets introduced in 0.2.0. Its scores must not be merged with earlier editions. Template IDs are smolscript-0.5.0 and cognirank2-v5; use a new output path. No GPU throughput speedup is claimed without a measured run.

Browser timeout handling

The phase-watchdog-v1 evaluator supervises the browser worker in a separate process group. Chromium launch has a 20-second limit; trusted setup/cleanup phases have a 45-second watchdog. Generated browser code and its assertions have a per-scenario wall limit of max(6, 3*timeout_seconds) (nine seconds for current tasks), in addition to three-second Playwright operation timeouts. This also bounds page.evaluate, script injection, and stuck page teardown, which do not all obey Playwright's default timeout.

A candidate-phase timeout preserves successful syntax parsing and completed observations, fails the unfinished assertions, and lets later tasks continue. Setup failures remain infrastructure errors and do not receive an invented score. The supervisor kills the worker process group during cleanup. Docker/Modal outer deadlines provide additional containment; an outer infrastructure timeout remains a failed evaluation. Modal evaluators run without credentials, and worker environments are explicitly filtered.

Rebuild the Docker image after updating these files. The Modal launcher automatically submits the updated supervisor and worker image. Full browser runtime validation remains unverified in the local authoring environment; watchdog regression tests use trusted synthetic worker fixtures.

CSS fixture setup correction

CSS styles are inserted synchronously with a DOM style element; the evaluator does not use Playwright 1.56 add_style_tag, whose inline-style path waits for a load callback. This avoids waiting for that callback on the HTML/CSS pages with scripting disabled. Trusted fixture and baseline errors remain infrastructure failures, separate from candidate execution. Timeout diagnostics now name the precise phase, operation, scenario and language and include bounded worker stderr.

The Modal path first checks runtime availability and a trusted CSS computed-style/distractor probe, before model generation. Worker processes use explicit subprocess UID/GID settings and private writable HOME/XDG/TMP directories; no Python pre-exec callback is used in the threaded launcher. These changes preserve the fixed 350-example dataset and scoring definition. End-to-end Modal browser verification is still required; local tests cover the injection protocol, diagnostic fields, preflight failure and watchdog behavior.

Base-model completion protocol (0.5.0)

The same completion template is used for every model, including instruction models. There is no chat wrapper, conversational instruction block, worked solution, reference implementation, test input, expected answer, or answer-dependent repair. Example prompt ending:

# Starting with n, double it, then take the last decimal digit of its absolute value. Return the result.
# Integer n from -120 to 120.
def solve(n):

The prompt ends immediately after the header newline, with no trailing spaces or tabs. The model supplies its own body indentation. Python headers omit type annotations. JavaScript, C, C++, C#, Rust and Lua receive their function/method openings (including the C# class), and applicable supplied imports. HTML receives a task comment followed by <; CSS receives its fixture/context and task as a CSS comment. examples/base-prompts.json contains an example for each language. completion.py is the authoritative prompt and assembly implementation.

The supplied prefix is attached to the generated continuation. Answer-independent lexical scope extraction keeps the first completed function/class body and discards trailing prose. Python uses indentation tokens; braced languages count delimiters while ignoring ordinary strings/comments (and supported regex/raw/verbatim strings); Lua counts block keywords. These are constrained completion delimiters, not general language parsers. Syntax and behavior are still checked inside the sandbox. Missing delimiters, malformed indentation, expressions, and return values are never repaired, and no closing suffix is invented. Complete entry-point definitions emitted from scratch, including a single fenced code block, are accepted as deterministic formatting alternatives.

Raw continuations and assembled evaluated_code are saved separately. The standalone --predictions path continues to accept complete code and bypasses the completion prefix. All 350 supplied reference bodies roundtrip through assembly (Python body AST equality, other languages source equality); this is a static assembly check, not complete runtime validation. Full isolated reference execution and a new KLM benchmark run remain outstanding.

Use a new output path for smolscript-0.5.0 / cognirank2-v5. Dataset edition/selection 0.3.0 remains fixed; only the evaluation prompt/assembly protocol changes. Old scores are not comparable and must be rerun for leaderboard comparisons. Token budgets, deterministic greedy decoding, batch size 64, eight isolated Modal scoring workers, tests and weights remain the same.

Behavioral equivalence (0.5.0)

Correctness is determined by the executable tests, never by source similarity. Newline-only function openings now leave indentation generation to the model. Fenced body completions preserve indentation, and valid Python source with module-level helper functions is retained.

HTML checks accept semantic equivalents: case-insensitive enumerated attribute values (method="POST"/"post", dir="RTL"/"rtl"), equivalent hidden/boolean states, numeric attribute representations, and class-token ordering. Required elements, nesting, targets and content still matter. URL, ID, name and ordinary text values are not indiscriminately lowercased. Attribute lookup errors and missing required attributes still fail.

For ordinary HTML text, collapsible ASCII whitespace is normalized; preformatted text retains significant whitespace, and pre-line preserves line breaks. Extra inline spans with the same text can satisfy the same text check. JavaScript string outputs and programming string tasks retain exact observable content. CSS compares computed styles, so equivalent selectors, shorthands and color notations can pass when they produce all required styles and leave distractors unchanged.

HTML/CSS syntax reporting is now independent of behavioral testing: the native browser may recover from a parsing issue and still satisfy every assertion. Such a task can pass behavior while Syntax Success reports false. Full HTML documents and fragments are parsed in the appropriate mode. JavaScript syntax failures still prevent execution. No model source is rewritten to repair errors.

The optional hidden_test_pass_rate diagnostic averages test-pass fractions per task and then macro-averages across languages. It shows partial functional success. The official SmolScript Score remains all-tests-required Pass@1, macro-averaged across nine languages; this diagnostic does not affect CogniRank weights. It does not award credit for comments describing a solution that was not implemented.

These scoring/format changes require a new output path (smolscript-0.5.0, cognirank2-v5). All 350 tasks, reference implementations and hidden test files remain byte-identical. The local equivalence controls use observation fixtures and a mocked browser; full real-browser reference validation remains outstanding.