Buckets:
| """Build notebooks/fit_eval.ipynb from the cell texts below, then pack the code bundle into it. | |
| Run this only when the notebook structure changes. For code changes, run | |
| python -m src.colab_sync pack notebooks/fit_eval.ipynb | |
| """ | |
| from pathlib import Path | |
| import nbformat | |
| from src import colab_sync | |
| NOTEBOOK = Path("notebooks/fit_eval.ipynb") | |
| CELLS = [ | |
| ("title", "markdown", """# Eastern Arabic digits evaluation of Qwen/Qwen3.5-4B | |
| This notebook rebuilds every table and figure of the evaluation from the saved model outputs. | |
| Run it on a Colab GPU runtime (Runtime, Change runtime type, T4 GPU), then Runtime, Run all. | |
| It takes about 15 minutes, most of it for downloading the model. | |
| The project code (`src/`, `config.yaml`, `prompts/`, `data/`) and the saved outputs come in one file, | |
| `fit_bundle.tar.gz`, next to this notebook. Upload it to the Colab Files pane before you run the notebook, | |
| or let the bootstrap cell download it from the public bucket. The cell checks the file's SHA-256 hash | |
| and unpacks it to `/content/fit`. | |
| The main run (3,000 prompts) and the probe were run on a Colab T4 from a terminal with the runner | |
| `fit_colab.py`, which carries the same code. A browser session could not stay connected for the | |
| 50 minutes of the main run. The runner logs are in `logs/`. | |
| With `RUN_MODEL = True` the notebook loads the model and generates 30 of the saved prompts again, | |
| one for each task and twin type, and checks that the new outputs equal the saved ones. | |
| With `RERUN = True` it generates all 3,000 outputs and the probe again, which takes about 75 minutes on a T4."""), | |
| ("settings", "code", """RUNTIME = "auto" # "auto", "colab" or "local" | |
| RUN_MODEL = True # load the model and regenerate a sample of the saved outputs. Needs a GPU | |
| RERUN = False # regenerate all 3,000 outputs and the probe. Needs a GPU and about 75 minutes | |
| N_CHECK = 30 # prompts regenerated for the check | |
| import os | |
| if RUNTIME == "auto": | |
| RUNTIME = "colab" if os.environ.get("COLAB_RELEASE_TAG") else "local" | |
| print("runtime:", RUNTIME, "| RUN_MODEL:", RUN_MODEL, "| RERUN:", RERUN)"""), | |
| ("bootstrap", "code", "# filled by src/colab_sync.py pack"), | |
| ("install", "code", """import subprocess | |
| import sys | |
| import yaml | |
| if RUNTIME == "colab": | |
| pins = yaml.safe_load(open("config.yaml"))["runtimes"]["colab"]["pip"] | |
| subprocess.run([sys.executable, "-m", "pip", "install", "-q", *pins], check=True) | |
| print("installed:", " ".join(pins)) | |
| else: | |
| print("local runtime, using the project venv")"""), | |
| ("setup", "code", """from src import runtime | |
| RT = runtime.setup(RUNTIME) | |
| CFG = RT["config"] | |
| REPO, REV = CFG["model"]["repo_id"], CFG["model"]["revision"] | |
| print("model:", REPO, "| snapshot:", REV, "| dtype:", RT["dtype"]) | |
| print("GPU:", runtime.gpu_summary()) | |
| if RUN_MODEL or RERUN: | |
| runtime.require_gpu()"""), | |
| ("helpers", "code", """import csv | |
| import json | |
| from pathlib import Path | |
| from IPython.display import Image, display | |
| import pandas as pd | |
| pd.set_option("display.max_rows", 200) | |
| pd.set_option("display.width", 200) | |
| def table(path, **filters): | |
| df = pd.read_csv(path) | |
| for column, value in filters.items(): | |
| df = df[df[column] == value] | |
| display(df.reset_index(drop=True)) | |
| def jsonl(path): | |
| with open(path, encoding="utf-8") as f: | |
| return [json.loads(line) for line in f if line.strip()]"""), | |
| ("env-md", "markdown", """## Environment | |
| The same description is written to `env.txt` by `src/env_info.py`. The main run's server is in `logs/env_full.txt`."""), | |
| ("env", "code", """from src import env_info | |
| print(env_info.describe())"""), | |
| ("data-md", "markdown", """## Evaluation set | |
| `data/eval_set.jsonl` holds 5 tasks with 100 base items each. Every base item has 6 twins: | |
| 3 numeral systems times 2 prompt languages. Twins share the same values."""), | |
| ("data", "code", """from src import run_eval | |
| ITEMS = run_eval.load_items() | |
| counts = pd.crosstab([pd.Series([i["task"] for i in ITEMS], name="task")], | |
| [pd.Series([i["numeral_system"] for i in ITEMS], name="system"), | |
| pd.Series([i["prompt_lang"] for i in ITEMS], name="prompt")]) | |
| display(counts) | |
| for i in ITEMS: | |
| if i["base_id"] == "compute-002": | |
| print(f"--- {i['item_id']} gold: {i['gold_string']}") | |
| print(i["prompt"])"""), | |
| ("tokens-md", "markdown", """## Tokenization | |
| Tokens per digit and the token pieces of example numbers (`src/tokenizer_survey.py`, `src/probe.py`). | |
| Each Eastern Arabic or Persian digit is two byte tokens. The first byte is the same for all ten digits of a system."""), | |
| ("tokens", "code", """from src import tokenizer_survey, probe | |
| PROBE_ROWS = jsonl("data/probe_set.jsonl") | |
| if RUN_MODEL: | |
| tokenizer_survey.main("results/mechanism/tokens_per_digit.csv", {REPO: REV}) | |
| table("results/mechanism/tokens_per_digit.csv") | |
| for e in json.load(open("results/mechanism/tokenization_examples.json", encoding="utf-8")): | |
| print(f"{e['value']:>12} {e['numeral_system']:<15} {e['text']:<22} {e['n_tokens']:>3} tokens")"""), | |
| ("check-md", "markdown", """## Model and reproducibility check | |
| Greedy decoding in bf16, the model's chat template with thinking turned off, one prompt at a time, | |
| at most 128 new tokens (`config.yaml`). The check regenerates one prompt for each pair of task and twin type | |
| and compares the output with the saved one."""), | |
| ("check", "code", """import time | |
| import torch | |
| from src import model as model_io | |
| from src.colab_job import batch_check_items | |
| SAVED = {r["item_id"]: r for r in jsonl("outputs/raw/full.jsonl")} | |
| if RUN_MODEL: | |
| torch.manual_seed(CFG["seeds"]["torch"]) | |
| MODEL, TOKENIZER = model_io.load(REPO, REV, RT["dtype"]) | |
| settings = run_eval.settings_for(CFG, RT) | |
| rows, start = [], time.perf_counter() | |
| for item in batch_check_items(ITEMS, N_CHECK): | |
| prompt = model_io.render(TOKENIZER, item["prompt"], item["system_prompt"]) | |
| text, n_new, hit = run_eval.generate_batch(MODEL, TOKENIZER, [prompt], settings["max_new_tokens"])[0] | |
| saved = SAVED[item["item_id"]]["raw_output"] | |
| rows.append({"item_id": item["item_id"], "same_as_saved": text == saved, "new_output": text.strip()[:60], | |
| "saved_output": saved.strip()[:60]}) | |
| seconds = time.perf_counter() - start | |
| check = pd.DataFrame(rows) | |
| display(check) | |
| print(f"{check['same_as_saved'].sum()} of {len(check)} regenerated outputs equal the saved outputs, " | |
| f"{len(check) / seconds:.2f} prompts per second, peak GPU memory {torch.cuda.max_memory_allocated() / 1e9:.2f} GB") | |
| else: | |
| print("RUN_MODEL is False, the model is not loaded")"""), | |
| ("rerun-md", "markdown", """## Full rerun (only with RERUN = True) | |
| Removes the saved outputs that the bundle carries and runs the main evaluation and the probe again | |
| with the same code as the terminal runner (`src/colab_job.py`)."""), | |
| ("rerun", "code", """from src import colab_job | |
| if RERUN: | |
| if RUN_MODEL: | |
| del MODEL | |
| torch.cuda.empty_cache() | |
| Path(colab_job.FULL_OUTPUTS).unlink() | |
| Path(colab_job.PROBE_RESULTS).unlink() | |
| colab_job.full(RT) | |
| colab_job.probe_phase(RT) | |
| else: | |
| print("RERUN is False, the saved outputs are used")"""), | |
| ("score-md", "markdown", """## Scoring | |
| Rule-based scoring (`src/score.py`). The parser reads digits in all three systems in the same way. | |
| Below are the replies that held no number with a value."""), | |
| ("score", "code", """from src import score | |
| score.main("outputs/raw/full.jsonl", "outputs/scored/full.jsonl") | |
| SCORED = jsonl("outputs/scored/full.jsonl") | |
| fails = [{"item_id": s["item_id"], "raw_output": SAVED[s["item_id"]]["raw_output"].strip()} | |
| for s in SCORED if s["error_type"] == "parse_failure"] | |
| display(pd.DataFrame(fails))"""), | |
| ("tables-md", "markdown", """## Results tables | |
| All tables are written to `results/full/` by `src/report.py`. Accuracy per cell has Wilson 95% intervals. | |
| The 20 paired comparisons use exact McNemar tests with Holm correction and paired bootstrap intervals | |
| (10,000 resamples). A gap needs a Holm-adjusted p-value below 0.05 and an interval that excludes zero."""), | |
| ("tables", "code", """from src import report | |
| report.full("outputs/scored/full.jsonl", "results/full") | |
| print("Accuracy per cell") | |
| table("results/full/accuracy_by_cell.csv") | |
| print("The 20 pre-registered paired comparisons") | |
| table("results/full/paired_tests.csv") | |
| print("Twin consistency") | |
| table("results/full/twin_consistency.csv")"""), | |
| ("tables2", "code", """print("Value correct and number-only replies (copy, convert), format match (compute, statement QA)") | |
| table("results/full/secondary_by_cell.csv") | |
| print("Accuracy by question type") | |
| table("results/full/accuracy_by_factor.csv", factor="subtype") | |
| print("Accuracy by integer length") | |
| table("results/full/accuracy_by_factor.csv", factor="length")"""), | |
| ("tables3", "code", """print("Error types per numeral system, all tasks and both prompt languages") | |
| table("results/full/error_types_by_system.csv") | |
| print("Relative error of wrong but parsed answers") | |
| table("results/full/relative_errors.csv") | |
| print("Exploratory: easy compare pairs, by whether the first digits point to the wrong option") | |
| table("results/full/compare_first_digit.csv") | |
| print("Exploratory: Eastern Arabic against Persian, and English against Arabic prompts") | |
| table("results/full/exploratory_tests.csv")"""), | |
| ("figures-md", "markdown", """## Figures | |
| Drawn by `src/figures.py` from the CSV files."""), | |
| ("figures", "code", """from src import figures | |
| figures.main("results/full", "figures", "results/probe_r2.csv") | |
| for name in ["accuracy_by_task", "paired_differences", "accuracy_by_length", "format_match", "error_types"]: | |
| display(Image(f"figures/{name}.png"))"""), | |
| ("probe-md", "markdown", """## Linear probe | |
| Ridge regression per layer on the hidden state at the last token of each number, for 2,000 values | |
| in each numeral system, inside an English and an Arabic carrier sentence (`src/probe.py`). | |
| The reading rules were fixed in PLAN.md before the probe was run."""), | |
| ("probe", "code", """probe.write_reading("results/probe_r2.csv", "results/mechanism/probe_reading.csv") | |
| table("results/mechanism/probe_reading.csv") | |
| display(Image("figures/probe_r2.png"))"""), | |
| ] | |
| def build(): | |
| nb = nbformat.v4.new_notebook() | |
| for cell_id, kind, text in CELLS: | |
| cell = nbformat.v4.new_markdown_cell(text) if kind == "markdown" else nbformat.v4.new_code_cell(text) | |
| cell["id"] = cell_id | |
| nb.cells.append(cell) | |
| nb.metadata["kernelspec"] = {"name": "python3", "display_name": "Python 3", "language": "python"} | |
| nb.metadata["accelerator"] = "GPU" | |
| nb.metadata["colab"] = {"gpuType": "T4"} | |
| NOTEBOOK.parent.mkdir(exist_ok=True) | |
| nbformat.write(nb, NOTEBOOK) | |
| colab_sync.pack(NOTEBOOK) | |
| if __name__ == "__main__": | |
| build() | |
Xet Storage Details
- Size:
- 10.9 kB
- Xet hash:
- c4d0d21f54c5de590035ceb5c700be38d9be40c85da40e5cab134b8eb83b6046
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.