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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "6ac12115",
|
| 6 |
+
"metadata": {
|
| 7 |
+
"tags": [
|
| 8 |
+
"papermill-error-cell-tag"
|
| 9 |
+
]
|
| 10 |
+
},
|
| 11 |
+
"source": [
|
| 12 |
+
"<span style=\"color:red; font-family:Helvetica Neue, Helvetica, Arial, sans-serif; font-size:2em;\">An Exception was encountered at '<a href=\"#papermill-error-cell\">In [9]</a>'.</span>"
|
| 13 |
+
]
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "markdown",
|
| 17 |
+
"id": "c7161cf4",
|
| 18 |
+
"metadata": {
|
| 19 |
+
"papermill": {
|
| 20 |
+
"duration": 0.002279,
|
| 21 |
+
"end_time": "2026-10-22T19:07:44.363054+00:00",
|
| 22 |
+
"exception": false,
|
| 23 |
+
"start_time": "2026-10-22T19:07:44.360775+00:00",
|
| 24 |
+
"status": "completed"
|
| 25 |
+
},
|
| 26 |
+
"tags": []
|
| 27 |
+
},
|
| 28 |
+
"source": [
|
| 29 |
+
"# exp39 / TrOCR-CTC trained on synthetic handwriting with a BANDIT DATA MIXER (2 arms: aggressive DiffusionPen words 20k vs aggressive cursive fonts 20k, same 20k texts, 10 participant styles, fitted to HHD geometry, LLMGen text), tested on HHD — training seed 43\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"**Model (same as exp38/exp39):** the ViT encoder of `microsoft/trocr-base-handwritten` (768-dim, 12 layers) + **one linear classifier** over the\n",
|
| 32 |
+
"reading-order frames, trained with CTC. No augmentation, no frozen phase.\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"**Arms (the same 20k texts, plan parts 1 + 2, drawn two ways; llmgen10k/build_join20k.py):**\n",
|
| 35 |
+
"- arm 0 `diffpen` — `cyttic/heb-llmgen20k-diffpenaug-hhdgeom`: 19,997 lines, every word generated by the aggressive-augmentation DiffusionPen word model\n",
|
| 36 |
+
" `cyttic/diffusionpen-uni10aug-words100k` and kept only if exp35 read it with CER 0 (3 tries, otherwise removed); punctuation/digits from the participants' fonts.\n",
|
| 37 |
+
"- arm 1 `fonts` — `cyttic/heb-llmgen20k-uni10aug-hhdgeom`: 20,000 lines rendered from the same 10 unigram fonts in the aggressive cursive style.\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"Both FITTED to the geometry of real HHD train lines (fit_hhd_geometry.py). The fixed-mix runs on the same texts: fonts 20k (0% DiffusionPen,\n",
|
| 40 |
+
"`cyttic/exp39-ctc-uni10aug20k-hhdgeom-llmgen`), joined 20k (50%, `cyttic/exp39-ctc-join20k-diffpenaug-uni10aug-hhdgeom-llmgen`),\n",
|
| 41 |
+
"DiffusionPen 20k (100%, `cyttic/exp39-ctc-diffpenaug20k-hhdgeom-llmgen`).\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"**Bandit mixer (discounted EXP3, 2 arms).** Every training step one arm is drawn with probabilities `p`; the batch (32 lines) comes from that arm only\n",
|
| 44 |
+
"(each arm is an endless stream, reshuffled after every pass over it). After the backward pass the **reward** is the cosine between the batch gradient and\n",
|
| 45 |
+
"the gradient of the CTC loss on a **reward set** = a fixed half of the HHD dev writers (gradient refreshed every 50 steps on 64 rotating reward lines;\n",
|
| 46 |
+
"no update is ever taken on it). The reward is normalised by a running mean / std, clipped to [-1, 1], and the pulled arm's log-weight is updated with the\n",
|
| 47 |
+
"importance-weighted reward: `logw <- 0.99 * logw; logw[i] += 0.05 * r / p[i]`; `p = 0.85 * softmax(logw) + 0.15 / 2` (exploration floor: no arm drops below 7.5%).\n",
|
| 48 |
+
"The first 100 steps alternate the arms (reward statistics warm-up). The other half of the dev writers (**holdout**) is scored greedily after every epoch, only\n",
|
| 49 |
+
"for monitoring. Logged every step: arm, reward, `p`, loss → `bandit_log.tsv`, `bandit_p.png`, and `results.json[\"bandit\"]` (pulls and DiffusionPen share per epoch).\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"**Budget = the fixed-mix 20k runs:** 4 epochs x 625 steps = 2,500 steps of batch 32, warm-up 5% + linear LR decay, training seed 43. Epoch count fixed\n",
|
| 52 |
+
"(= the joined/fonts/DiffusionPen 20k runs), no epoch search. **No HHD line is trained on;** the HHD dev labels enter only through the reward (which arm to\n",
|
| 53 |
+
"sample next), and the HHD test set (1,455 lines, 109 writers) is scored **once**: greedy, and beam search with the fixed character 6-gram LM (built from\n",
|
| 54 |
+
"LLMGen text only, no HHD text; alpha 1.5, beta 6.0 chosen on the HHD dev writers; beams 4 and 12), CER with and without punctuation, WER.\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"**Colab:** Runtime → **L4 GPU**; Secrets → `HF_TOKEN` (write); **Run all**. Output: public HF repo `cyttic/exp39-ctc-bandit20k-diffpenaug-uni10aug-hhdgeom-llmgen-seed43`."
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "markdown",
|
| 61 |
+
"id": "7a3afaa5",
|
| 62 |
+
"metadata": {
|
| 63 |
+
"papermill": {
|
| 64 |
+
"duration": 0.001989,
|
| 65 |
+
"end_time": "2026-10-22T19:07:44.367480+00:00",
|
| 66 |
+
"exception": false,
|
| 67 |
+
"start_time": "2026-10-22T19:07:44.365491+00:00",
|
| 68 |
+
"status": "completed"
|
| 69 |
+
},
|
| 70 |
+
"tags": []
|
| 71 |
+
},
|
| 72 |
+
"source": [
|
| 73 |
+
"### 1. Setup"
|
| 74 |
+
]
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"execution_count": 1,
|
| 79 |
+
"id": "a2207eac",
|
| 80 |
+
"metadata": {
|
| 81 |
+
"execution": {
|
| 82 |
+
"iopub.execute_input": "2026-10-22T19:07:44.372067Z",
|
| 83 |
+
"iopub.status.busy": "2026-10-22T19:07:44.371903Z",
|
| 84 |
+
"iopub.status.idle": "2026-10-22T19:07:45.200369Z",
|
| 85 |
+
"shell.execute_reply": "2026-10-22T19:07:45.199603Z"
|
| 86 |
+
},
|
| 87 |
+
"papermill": {
|
| 88 |
+
"duration": 0.831459,
|
| 89 |
+
"end_time": "2026-10-22T19:07:45.200931+00:00",
|
| 90 |
+
"exception": false,
|
| 91 |
+
"start_time": "2026-10-22T19:07:44.369472+00:00",
|
| 92 |
+
"status": "completed"
|
| 93 |
+
},
|
| 94 |
+
"tags": []
|
| 95 |
+
},
|
| 96 |
+
"outputs": [],
|
| 97 |
+
"source": [
|
| 98 |
+
"!pip install -q -U \"transformers==5.15.0\" datasets jiwer"
|
| 99 |
+
]
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"execution_count": 2,
|
| 104 |
+
"id": "96e77c5d",
|
| 105 |
+
"metadata": {
|
| 106 |
+
"execution": {
|
| 107 |
+
"iopub.execute_input": "2026-10-22T19:07:45.206799Z",
|
| 108 |
+
"iopub.status.busy": "2026-10-22T19:07:45.206623Z",
|
| 109 |
+
"iopub.status.idle": "2026-10-22T19:07:48.727558Z",
|
| 110 |
+
"shell.execute_reply": "2026-10-22T19:07:48.727023Z"
|
| 111 |
+
},
|
| 112 |
+
"papermill": {
|
| 113 |
+
"duration": 3.524291,
|
| 114 |
+
"end_time": "2026-10-22T19:07:48.728121+00:00",
|
| 115 |
+
"exception": false,
|
| 116 |
+
"start_time": "2026-10-22T19:07:45.203830+00:00",
|
| 117 |
+
"status": "completed"
|
| 118 |
+
},
|
| 119 |
+
"tags": []
|
| 120 |
+
},
|
| 121 |
+
"outputs": [
|
| 122 |
+
{
|
| 123 |
+
"name": "stderr",
|
| 124 |
+
"output_type": "stream",
|
| 125 |
+
"text": [
|
| 126 |
+
"/home/romanva1/env/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
| 127 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
| 128 |
+
]
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"name": "stdout",
|
| 132 |
+
"output_type": "stream",
|
| 133 |
+
"text": [
|
| 134 |
+
"HF user: cyttic\n",
|
| 135 |
+
"cuda NVIDIA RTX A5000 | amp torch.bfloat16\n"
|
| 136 |
+
]
|
| 137 |
+
}
|
| 138 |
+
],
|
| 139 |
+
"source": [
|
| 140 |
+
"import os, io, re, json, math, time, random\n",
|
| 141 |
+
"import numpy as np, torch, torch.nn as nn, torch.nn.functional as F, jiwer\n",
|
| 142 |
+
"from PIL import Image, ImageOps\n",
|
| 143 |
+
"from datasets import load_dataset, concatenate_datasets\n",
|
| 144 |
+
"from transformers import VisionEncoderDecoderModel\n",
|
| 145 |
+
"from huggingface_hub import hf_hub_download, HfApi, login, whoami\n",
|
| 146 |
+
"try:\n",
|
| 147 |
+
" from google.colab import userdata; login(userdata.get(\"HF_TOKEN\"))\n",
|
| 148 |
+
"except Exception:\n",
|
| 149 |
+
" from huggingface_hub import get_token\n",
|
| 150 |
+
" if get_token() is None:\n",
|
| 151 |
+
" from huggingface_hub import notebook_login; notebook_login()\n",
|
| 152 |
+
"print(\"HF user:\", whoami()[\"name\"])\n",
|
| 153 |
+
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 154 |
+
"BF16 = device == \"cuda\" and torch.cuda.get_device_capability()[0] >= 8 # Ampere+ (L4/A100): bf16; T4: fp16\n",
|
| 155 |
+
"AMP_DTYPE = torch.bfloat16 if BF16 else torch.float16\n",
|
| 156 |
+
"print(device, torch.cuda.get_device_name(0) if device == \"cuda\" else \"\", \"| amp\", AMP_DTYPE)"
|
| 157 |
+
]
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "markdown",
|
| 161 |
+
"id": "edf82c2a",
|
| 162 |
+
"metadata": {
|
| 163 |
+
"papermill": {
|
| 164 |
+
"duration": 0.002004,
|
| 165 |
+
"end_time": "2026-10-22T19:07:48.732846+00:00",
|
| 166 |
+
"exception": false,
|
| 167 |
+
"start_time": "2026-10-22T19:07:48.730842+00:00",
|
| 168 |
+
"status": "completed"
|
| 169 |
+
},
|
| 170 |
+
"tags": []
|
| 171 |
+
},
|
| 172 |
+
"source": [
|
| 173 |
+
"### 2. Config"
|
| 174 |
+
]
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"execution_count": 3,
|
| 179 |
+
"id": "517b2131",
|
| 180 |
+
"metadata": {
|
| 181 |
+
"execution": {
|
| 182 |
+
"iopub.execute_input": "2026-10-22T19:07:48.737908Z",
|
| 183 |
+
"iopub.status.busy": "2026-10-22T19:07:48.737632Z",
|
| 184 |
+
"iopub.status.idle": "2026-10-22T19:07:48.744177Z",
|
| 185 |
+
"shell.execute_reply": "2026-10-22T19:07:48.743649Z"
|
| 186 |
+
},
|
| 187 |
+
"papermill": {
|
| 188 |
+
"duration": 0.009848,
|
| 189 |
+
"end_time": "2026-10-22T19:07:48.744889+00:00",
|
| 190 |
+
"exception": false,
|
| 191 |
+
"start_time": "2026-10-22T19:07:48.735041+00:00",
|
| 192 |
+
"status": "completed"
|
| 193 |
+
},
|
| 194 |
+
"tags": []
|
| 195 |
+
},
|
| 196 |
+
"outputs": [
|
| 197 |
+
{
|
| 198 |
+
"name": "stdout",
|
| 199 |
+
"output_type": "stream",
|
| 200 |
+
"text": [
|
| 201 |
+
"OUT /home/romanva1/work/queue_fontfill/exp39_bandit20k_diffpenaug_uni10aug_hhdgeom_llmgen_seed43/exp39_run | {'enc': 'microsoft/trocr-base-handwritten', 'row_h': 64, 'sub': 2, 'batch': 32, 'lr_enc': 5e-05, 'lr_head': 0.0003, 'warmup': 0.05, 'aug': 0.0, 'seed': 43, 'max_epochs': 8, 'patience': 2, 'final_epochs': 4, 'bandit': {'arms': ['diffpen', 'fonts'], 'reward': 'cosine(batch grad, reward-set grad)', 'gamma': 0.15, 'eta': 0.05, 'decay': 0.99, 'explore_steps': 100, 'dev_every': 50, 'reward_batches': 2, 'stat_beta': 0.02}}\n"
|
| 202 |
+
]
|
| 203 |
+
}
|
| 204 |
+
],
|
| 205 |
+
"source": [
|
| 206 |
+
"CFG = json.loads('{\"enc\": \"microsoft/trocr-base-handwritten\", \"row_h\": 64, \"sub\": 2, \"batch\": 32, \"lr_enc\": 5e-05, \"lr_head\": 0.0003, \"warmup\": 0.05, \"aug\": 0.0, \"seed\": 43, \"max_epochs\": 8, \"patience\": 2, \"final_epochs\": 4, \"bandit\": {\"arms\": [\"diffpen\", \"fonts\"], \"reward\": \"cosine(batch grad, reward-set grad)\", \"gamma\": 0.15, \"eta\": 0.05, \"decay\": 0.99, \"explore_steps\": 100, \"dev_every\": 50, \"reward_batches\": 2, \"stat_beta\": 0.02}}')\n",
|
| 207 |
+
"ENC_SRC, ROW_H, SUB, BATCH = CFG[\"enc\"], CFG[\"row_h\"], CFG[\"sub\"], CFG[\"batch\"]\n",
|
| 208 |
+
"LR_ENC, LR_HEAD, WARMUP_FRAC, SEED = CFG[\"lr_enc\"], CFG[\"lr_head\"], CFG[\"warmup\"], CFG[\"seed\"]\n",
|
| 209 |
+
"MAX_EPOCHS, PATIENCE = CFG[\"max_epochs\"], CFG[\"patience\"] # phase 1 (skipped here)\n",
|
| 210 |
+
"FINAL_EPOCHS = CFG[\"final_epochs\"] # 4 = the fixed-mix 20k runs\n",
|
| 211 |
+
"AUGMENT = CFG[\"aug\"] > 0 # off\n",
|
| 212 |
+
"BAND = CFG[\"bandit\"]; ARM_NAMES = BAND[\"arms\"]; K = len(ARM_NAMES)\n",
|
| 213 |
+
"GAMMA, ETA, DECAY = BAND[\"gamma\"], BAND[\"eta\"], BAND[\"decay\"] # exploration floor GAMMA/K per arm; EXP3 step; log-weight discount (horizon ~100 steps)\n",
|
| 214 |
+
"EXPLORE_STEPS, DEV_EVERY, REWARD_BATCHES, STAT_BETA = BAND[\"explore_steps\"], BAND[\"dev_every\"], BAND[\"reward_batches\"], BAND[\"stat_beta\"]\n",
|
| 215 |
+
"OUT_REPO = \"cyttic/exp39-ctc-bandit20k-diffpenaug-uni10aug-hhdgeom-llmgen-seed43\" # public\n",
|
| 216 |
+
"ARM_IDS = [\"cyttic/heb-llmgen20k-diffpenaug-hhdgeom\", \"cyttic/heb-llmgen20k-uni10aug-hhdgeom\"] # arm 0 = DiffusionPen words, arm 1 = cursive fonts; the same 20k texts\n",
|
| 217 |
+
"LM_REPO, LM_FILE = \"cyttic/exp38-char-lms\", \"exp38_char6_gen.npz\" # character 6-gram LM, LLMGen (DictaGen, sentences_llm3) text ONLY; no HHD text (HHD test/dev lines removed)\n",
|
| 218 |
+
"LM_ALPHA, LM_BETA, LM_BEAMS = 1.5, 6.0, (4, 12) # fixed decoding setting: chosen for this LM on the HHD dev writers (exp39/eval_lm_nohhd.py, lm_gen)\n",
|
| 219 |
+
"HHD_ID = \"cyttic/trocr-hebrew-matan\"\n",
|
| 220 |
+
"CHARSET_REPO = \"cyttic/exp35-trocr-large-en-ctc-seqhead-allreal-synpunct\" # same 198 classes as exp32-37\n",
|
| 221 |
+
"SPLIT_SEED, TEST_FRAC, DEV_FRAC = 42, 0.20, 0.20 # FIXED: HHD dev/test writer split, identical to exp36/37\n",
|
| 222 |
+
"NUM_WORKERS, EVAL_BS = 8, 64\n",
|
| 223 |
+
"RUN_FINAL = True\n",
|
| 224 |
+
"PUSH = True\n",
|
| 225 |
+
"SMOKE = False # True = tiny run to test the pipeline end to end\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED)\n",
|
| 228 |
+
"OUT = \"/content/exp39\" if os.path.isdir(\"/content\") else os.path.abspath(\"exp39_run\")\n",
|
| 229 |
+
"os.makedirs(OUT, exist_ok=True); print(\"OUT\", OUT, \"|\", CFG)"
|
| 230 |
+
]
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "markdown",
|
| 234 |
+
"id": "473e8ee3",
|
| 235 |
+
"metadata": {
|
| 236 |
+
"papermill": {
|
| 237 |
+
"duration": 0.001941,
|
| 238 |
+
"end_time": "2026-10-22T19:07:48.748943+00:00",
|
| 239 |
+
"exception": false,
|
| 240 |
+
"start_time": "2026-10-22T19:07:48.747002+00:00",
|
| 241 |
+
"status": "completed"
|
| 242 |
+
},
|
| 243 |
+
"tags": []
|
| 244 |
+
},
|
| 245 |
+
"source": [
|
| 246 |
+
"### 3. Charset (the 198 classes of exp32-37; class 0 = CTC blank)"
|
| 247 |
+
]
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "code",
|
| 251 |
+
"execution_count": 4,
|
| 252 |
+
"id": "3434ddd3",
|
| 253 |
+
"metadata": {
|
| 254 |
+
"execution": {
|
| 255 |
+
"iopub.execute_input": "2026-10-22T19:07:48.753668Z",
|
| 256 |
+
"iopub.status.busy": "2026-10-22T19:07:48.753517Z",
|
| 257 |
+
"iopub.status.idle": "2026-10-22T19:07:48.919398Z",
|
| 258 |
+
"shell.execute_reply": "2026-10-22T19:07:48.918791Z"
|
| 259 |
+
},
|
| 260 |
+
"papermill": {
|
| 261 |
+
"duration": 0.168744,
|
| 262 |
+
"end_time": "2026-10-22T19:07:48.919811+00:00",
|
| 263 |
+
"exception": false,
|
| 264 |
+
"start_time": "2026-10-22T19:07:48.751067+00:00",
|
| 265 |
+
"status": "completed"
|
| 266 |
+
},
|
| 267 |
+
"tags": []
|
| 268 |
+
},
|
| 269 |
+
"outputs": [
|
| 270 |
+
{
|
| 271 |
+
"name": "stdout",
|
| 272 |
+
"output_type": "stream",
|
| 273 |
+
"text": [
|
| 274 |
+
"classes: 198\n"
|
| 275 |
+
]
|
| 276 |
+
}
|
| 277 |
+
],
|
| 278 |
+
"source": [
|
| 279 |
+
"CHARS = json.load(open(hf_hub_download(CHARSET_REPO, \"charset.json\")))[\"chars\"] # CHARS[k] = class k; CHARS[0] = blank\n",
|
| 280 |
+
"assert CHARS[0] == \"\"\n",
|
| 281 |
+
"C2I = {c: i for i, c in enumerate(CHARS) if i}\n",
|
| 282 |
+
"N_CLASSES = len(CHARS)\n",
|
| 283 |
+
"def encode(text): return [C2I[c] for c in text if c in C2I]\n",
|
| 284 |
+
"def greedy(lp, n):\n",
|
| 285 |
+
" best = lp[:n].argmax(-1).tolist(); out, prev = [], 0\n",
|
| 286 |
+
" for k in best:\n",
|
| 287 |
+
" if k != prev and k != 0: out.append(CHARS[k])\n",
|
| 288 |
+
" prev = k\n",
|
| 289 |
+
" return \"\".join(out)\n",
|
| 290 |
+
"print(\"classes:\", N_CLASSES)"
|
| 291 |
+
]
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
"cell_type": "markdown",
|
| 295 |
+
"id": "9367fbec",
|
| 296 |
+
"metadata": {
|
| 297 |
+
"papermill": {
|
| 298 |
+
"duration": 0.002172,
|
| 299 |
+
"end_time": "2026-10-22T19:07:48.924460+00:00",
|
| 300 |
+
"exception": false,
|
| 301 |
+
"start_time": "2026-10-22T19:07:48.922288+00:00",
|
| 302 |
+
"status": "completed"
|
| 303 |
+
},
|
| 304 |
+
"tags": []
|
| 305 |
+
},
|
| 306 |
+
"source": [
|
| 307 |
+
"### 4. Data: HHD split + tiling"
|
| 308 |
+
]
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"execution_count": 5,
|
| 313 |
+
"id": "7b37cefa",
|
| 314 |
+
"metadata": {
|
| 315 |
+
"execution": {
|
| 316 |
+
"iopub.execute_input": "2026-10-22T19:07:48.929390Z",
|
| 317 |
+
"iopub.status.busy": "2026-10-22T19:07:48.929236Z",
|
| 318 |
+
"iopub.status.idle": "2026-10-22T19:07:58.752590Z",
|
| 319 |
+
"shell.execute_reply": "2026-10-22T19:07:58.752266Z"
|
| 320 |
+
},
|
| 321 |
+
"papermill": {
|
| 322 |
+
"duration": 9.828442,
|
| 323 |
+
"end_time": "2026-10-22T19:07:58.755044+00:00",
|
| 324 |
+
"exception": false,
|
| 325 |
+
"start_time": "2026-10-22T19:07:48.926602+00:00",
|
| 326 |
+
"status": "completed"
|
| 327 |
+
},
|
| 328 |
+
"tags": []
|
| 329 |
+
},
|
| 330 |
+
"outputs": [
|
| 331 |
+
{
|
| 332 |
+
"name": "stdout",
|
| 333 |
+
"output_type": "stream",
|
| 334 |
+
"text": [
|
| 335 |
+
"rows 6 | max columns 144 | max CTC steps 288\n"
|
| 336 |
+
]
|
| 337 |
+
},
|
| 338 |
+
{
|
| 339 |
+
"name": "stdout",
|
| 340 |
+
"output_type": "stream",
|
| 341 |
+
"text": [
|
| 342 |
+
"arm diffpen: 19997 lines; lines per style: {'participant_01': 2000, 'participant_02': 1999, 'participant_03': 2000, 'participant_04': 1998, 'participant_05': 2000, 'participant_06': 2000, 'participant_07': 2000, 'participant_08': 2000, 'participant_09': 2000, 'participant_10': 2000}\n",
|
| 343 |
+
"arm fonts: 20000 lines; lines per style: {'participant_01': 2000, 'participant_02': 2000, 'participant_03': 2000, 'participant_04': 2000, 'participant_05': 2000, 'participant_06': 2000, 'participant_07': 2000, 'participant_08': 2000, 'participant_09': 2000, 'participant_10': 2000}\n",
|
| 344 |
+
"HHD dev 1091 lines / 109 writers -> reward 559 lines / 54 writers, holdout 532 lines / 55 writers | HHD test 1455 lines / 109 writers (scored once)\n"
|
| 345 |
+
]
|
| 346 |
+
},
|
| 347 |
+
{
|
| 348 |
+
"name": "stdout",
|
| 349 |
+
"output_type": "stream",
|
| 350 |
+
"text": [
|
| 351 |
+
"arm diffpen: CTC-feasible lines (first 400): 400/400\n"
|
| 352 |
+
]
|
| 353 |
+
},
|
| 354 |
+
{
|
| 355 |
+
"name": "stdout",
|
| 356 |
+
"output_type": "stream",
|
| 357 |
+
"text": [
|
| 358 |
+
"arm fonts: CTC-feasible lines (first 400): 400/400\n"
|
| 359 |
+
]
|
| 360 |
+
}
|
| 361 |
+
],
|
| 362 |
+
"source": [
|
| 363 |
+
"class Tiler:\n",
|
| 364 |
+
" '''mirror (RTL->LTR) -> ROW_H px high -> wrapped into the 384x384 square in rows of 384 px (no overlap, no autocrop).\n",
|
| 365 |
+
" Returns the image tensor + the number of 16 px columns that hold ink, in reading order.'''\n",
|
| 366 |
+
" C, P = 384, 16\n",
|
| 367 |
+
" def __init__(self, row_h):\n",
|
| 368 |
+
" self.H = row_h; self.R = self.C // row_h; self.max_cols = self.R * (self.C // self.P)\n",
|
| 369 |
+
" def __call__(self, image):\n",
|
| 370 |
+
" image = ImageOps.mirror(image.convert(\"RGB\")); w, h = image.size\n",
|
| 371 |
+
" nw = max(1, round(w * self.H / h)); image = image.resize((nw, self.H), Image.LANCZOS)\n",
|
| 372 |
+
" cont = Image.new(\"RGB\", (self.C, self.C), (255, 255, 255)); arr = np.array(image)\n",
|
| 373 |
+
" sx, r = 0, 0\n",
|
| 374 |
+
" while sx < nw and r < self.R:\n",
|
| 375 |
+
" seg = arr[:, sx:sx + self.C]; cont.paste(Image.fromarray(seg), (0, r * self.H)); sx += seg.shape[1]; r += 1\n",
|
| 376 |
+
" used = min(nw, self.R * self.C)\n",
|
| 377 |
+
" t = torch.tensor(np.array(cont), dtype=torch.float32).permute(2, 0, 1) / 255.0\n",
|
| 378 |
+
" return (t - 0.5) / 0.5, min(self.max_cols, math.ceil(used / self.P))\n",
|
| 379 |
+
"tiler = Tiler(ROW_H)\n",
|
| 380 |
+
"print(\"rows\", tiler.R, \"| max columns\", tiler.max_cols, \"| max CTC steps\", tiler.max_cols * SUB)\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"# ---- HHD: validation (dev writers) and test only; nothing of HHD is trained on. Split identical to exp36/37/38 ----\n",
|
| 383 |
+
"hhd = load_dataset(HHD_ID)\n",
|
| 384 |
+
"orig_test_w = set(\"hhd:\" + w for w in hhd[\"test\"][\"writer\"])\n",
|
| 385 |
+
"hhd_all = concatenate_datasets([hhd[\"train\"], hhd[\"test\"]])\n",
|
| 386 |
+
"hw = [\"hhd:\" + w for w in hhd_all[\"writer\"]]\n",
|
| 387 |
+
"wr = sorted(set(hw)); random.Random(SPLIT_SEED).shuffle(wr)\n",
|
| 388 |
+
"n_te, n_dev = int(len(wr) * TEST_FRAC), int(len(wr) * DEV_FRAC)\n",
|
| 389 |
+
"test_w, dev_w = set(wr[:n_te]), set(wr[n_te:n_te + n_dev])\n",
|
| 390 |
+
"assert test_w == orig_test_w, \"test writers differ from the original HHD test split\"\n",
|
| 391 |
+
"assert not (dev_w & orig_test_w)\n",
|
| 392 |
+
"test = hhd[\"test\"]\n",
|
| 393 |
+
"tw = [\"hhd:\" + w for w in hhd[\"train\"][\"writer\"]]\n",
|
| 394 |
+
"dev = hhd[\"train\"].select([i for i, w in enumerate(tw) if w in dev_w])\n",
|
| 395 |
+
"\n",
|
| 396 |
+
"# ---- the two arms: the same 20k texts, drawn by DiffusionPen (arm 0) and by the cursive fonts (arm 1) ----\n",
|
| 397 |
+
"_load = lambda r: load_dataset(r, data_files={\"train\": \"data/train-*.parquet\"}, split=\"train\").select_columns([\"image\", \"text\", \"style\"]).cast_column(\"image\", __import__(\"datasets\").Image()) # parquet written with plain pyarrow: declare the image feature\n",
|
| 398 |
+
"arms = [_load(r) for r in ARM_IDS]\n",
|
| 399 |
+
"import collections\n",
|
| 400 |
+
"for name, ds, n in zip(ARM_NAMES, arms, (19997, 20000)):\n",
|
| 401 |
+
" _per = collections.Counter(ds[\"style\"]); print(f\"arm {name}: {len(ds)} lines; lines per style: {dict(sorted(_per.items()))}\")\n",
|
| 402 |
+
" assert len(ds) == n and len(_per) == 10 and min(_per.values()) >= 1997\n",
|
| 403 |
+
"# ---- HHD dev writers -> reward half (bandit reward only) + holdout half (monitoring only); HHD test untouched ----\n",
|
| 404 |
+
"_dw = sorted(dev_w); random.Random(SPLIT_SEED + 1).shuffle(_dw); rew_w = set(_dw[:len(_dw) // 2])\n",
|
| 405 |
+
"_dvw = [\"hhd:\" + w for w in dev[\"writer\"]]\n",
|
| 406 |
+
"reward_set = dev.select([i for i, w in enumerate(_dvw) if w in rew_w]); holdout = dev.select([i for i, w in enumerate(_dvw) if w not in rew_w])\n",
|
| 407 |
+
"print(f\"HHD dev {len(dev)} lines / {len(dev_w)} writers -> reward {len(reward_set)} lines / {len(rew_w)} writers, holdout {len(holdout)} lines / {len(dev_w) - len(rew_w)} writers | HHD test {len(test)} lines / {len(orig_test_w)} writers (scored once)\")\n",
|
| 408 |
+
"STEPS_PER_EPOCH = math.ceil(sum(len(x) for x in arms) / K / BATCH) # 625 = the fixed-mix 20k runs\n",
|
| 409 |
+
"if SMOKE:\n",
|
| 410 |
+
" arms = [x.select(range(64)) for x in arms]; reward_set, holdout, test = reward_set.select(range(32)), holdout.select(range(32)), test.select(range(32))\n",
|
| 411 |
+
" BATCH = 4; FINAL_EPOCHS = 2; LM_BEAMS = (4,); STEPS_PER_EPOCH = 30; EXPLORE_STEPS = 10; DEV_EVERY = 10\n",
|
| 412 |
+
"train_full = arms[0] # (only for the feasibility check below)\n",
|
| 413 |
+
"\n",
|
| 414 |
+
"def collate(batch):\n",
|
| 415 |
+
" px, cols, labels, texts = [], [], [], []\n",
|
| 416 |
+
" for ex in batch:\n",
|
| 417 |
+
" t, c = tiler(ex[\"image\"]); px.append(t); cols.append(c); labels.append(encode(ex[\"text\"])); texts.append(ex[\"text\"])\n",
|
| 418 |
+
" return torch.stack(px), torch.tensor(cols), labels, texts\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"def loader(split, shuffle, bs=None):\n",
|
| 421 |
+
" return torch.utils.data.DataLoader(split, batch_size=bs or BATCH, shuffle=shuffle, num_workers=NUM_WORKERS,\n",
|
| 422 |
+
" collate_fn=collate, drop_last=False, persistent_workers=False)\n",
|
| 423 |
+
"\n",
|
| 424 |
+
"# how many training lines cannot be aligned (label longer than the available CTC steps)?\n",
|
| 425 |
+
"for name, ds in zip(ARM_NAMES, arms):\n",
|
| 426 |
+
" _chk = [(len(encode(ex[\"text\"])), tiler(ex[\"image\"])[1] * SUB) for ex in ds.select(range(min(len(ds), 400)))]\n",
|
| 427 |
+
" print(f\"arm {name}: CTC-feasible lines (first {len(_chk)}): {sum(1 for l, T in _chk if 0 < l <= T)}/{len(_chk)}\")"
|
| 428 |
+
]
|
| 429 |
+
},
|
| 430 |
+
{
|
| 431 |
+
"cell_type": "markdown",
|
| 432 |
+
"id": "6388e24d",
|
| 433 |
+
"metadata": {
|
| 434 |
+
"papermill": {
|
| 435 |
+
"duration": 0.002277,
|
| 436 |
+
"end_time": "2026-10-22T19:07:58.760522+00:00",
|
| 437 |
+
"exception": false,
|
| 438 |
+
"start_time": "2026-10-22T19:07:58.758245+00:00",
|
| 439 |
+
"status": "completed"
|
| 440 |
+
},
|
| 441 |
+
"tags": []
|
| 442 |
+
},
|
| 443 |
+
"source": [
|
| 444 |
+
"### 5. Model: TrOCR-base ViT encoder → reading-order frames → ONE linear classifier"
|
| 445 |
+
]
|
| 446 |
+
},
|
| 447 |
+
{
|
| 448 |
+
"cell_type": "code",
|
| 449 |
+
"execution_count": 6,
|
| 450 |
+
"id": "874fec2b",
|
| 451 |
+
"metadata": {
|
| 452 |
+
"execution": {
|
| 453 |
+
"iopub.execute_input": "2026-10-22T19:07:58.765989Z",
|
| 454 |
+
"iopub.status.busy": "2026-10-22T19:07:58.765606Z",
|
| 455 |
+
"iopub.status.idle": "2026-10-22T19:07:59.647868Z",
|
| 456 |
+
"shell.execute_reply": "2026-10-22T19:07:59.647278Z"
|
| 457 |
+
},
|
| 458 |
+
"papermill": {
|
| 459 |
+
"duration": 0.885479,
|
| 460 |
+
"end_time": "2026-10-22T19:07:59.648333+00:00",
|
| 461 |
+
"exception": false,
|
| 462 |
+
"start_time": "2026-10-22T19:07:58.762854+00:00",
|
| 463 |
+
"status": "completed"
|
| 464 |
+
},
|
| 465 |
+
"tags": []
|
| 466 |
+
},
|
| 467 |
+
"outputs": [
|
| 468 |
+
{
|
| 469 |
+
"name": "stderr",
|
| 470 |
+
"output_type": "stream",
|
| 471 |
+
"text": [
|
| 472 |
+
"\r",
|
| 473 |
+
"Loading weights: 0%| | 0/478 [00:00<?, ?it/s]"
|
| 474 |
+
]
|
| 475 |
+
},
|
| 476 |
+
{
|
| 477 |
+
"name": "stderr",
|
| 478 |
+
"output_type": "stream",
|
| 479 |
+
"text": [
|
| 480 |
+
"\r",
|
| 481 |
+
"Loading weights: 100%|██████████| 478/478 [00:00<00:00, 6858.81it/s]"
|
| 482 |
+
]
|
| 483 |
+
},
|
| 484 |
+
{
|
| 485 |
+
"name": "stderr",
|
| 486 |
+
"output_type": "stream",
|
| 487 |
+
"text": [
|
| 488 |
+
"\n",
|
| 489 |
+
"[transformers] \u001b[1mVisionEncoderDecoderModel LOAD REPORT\u001b[0m from: microsoft/trocr-base-handwritten\n",
|
| 490 |
+
"Key | Status | \n",
|
| 491 |
+
"----------------------------+---------+-\n",
|
| 492 |
+
"encoder.pooler.dense.weight | MISSING | \n",
|
| 493 |
+
"encoder.pooler.dense.bias | MISSING | \n",
|
| 494 |
+
"\n",
|
| 495 |
+
"Notes:\n",
|
| 496 |
+
"- MISSING:\tthose params were newly initialized because missing from the checkpoint. Consider training on your downstream task.\n"
|
| 497 |
+
]
|
| 498 |
+
},
|
| 499 |
+
{
|
| 500 |
+
"name": "stdout",
|
| 501 |
+
"output_type": "stream",
|
| 502 |
+
"text": [
|
| 503 |
+
"encoder 86.1M (vit, hidden 768) | classifier 1.217M\n"
|
| 504 |
+
]
|
| 505 |
+
}
|
| 506 |
+
],
|
| 507 |
+
"source": [
|
| 508 |
+
"class EncoderLinearCTC(nn.Module):\n",
|
| 509 |
+
" '''ViT patch tokens (24x24 grid) -> reading-order frames (one per 16 px column, the ROW_H//16 patch rows of a text row\n",
|
| 510 |
+
" concatenated) -> a single Linear giving SUB CTC steps per column. Nothing else.'''\n",
|
| 511 |
+
" def __init__(self, vit, n_classes):\n",
|
| 512 |
+
" super().__init__()\n",
|
| 513 |
+
" self.vit = vit\n",
|
| 514 |
+
" if getattr(self.vit, \"pooler\", None) is not None: self.vit.pooler = None\n",
|
| 515 |
+
" self.Hd = vit.config.hidden_size; self.n_special = 2 if vit.config.model_type == \"deit\" else 1 # CLS (+ distillation)\n",
|
| 516 |
+
" self.k = ROW_H // 16; self.n_classes = n_classes\n",
|
| 517 |
+
" self.classifier = nn.Linear(self.k * self.Hd, SUB * n_classes)\n",
|
| 518 |
+
" nn.init.trunc_normal_(self.classifier.weight, std=0.02); nn.init.zeros_(self.classifier.bias)\n",
|
| 519 |
+
" def forward(self, px):\n",
|
| 520 |
+
" tok = self.vit(pixel_values=px).last_hidden_state[:, self.n_special:] # (B, 576, H)\n",
|
| 521 |
+
" B, R = tok.shape[0], tiler.R\n",
|
| 522 |
+
" g = tok.reshape(B, 24, 24, self.Hd)[:, :R * self.k]\n",
|
| 523 |
+
" g = g.reshape(B, R, self.k, 24, self.Hd).permute(0, 1, 3, 2, 4).reshape(B, R * 24, self.k * self.Hd) # (B, 144, k*H)\n",
|
| 524 |
+
" y = self.classifier(g).reshape(B, R * 24 * SUB, self.n_classes)\n",
|
| 525 |
+
" return F.log_softmax(y.float(), dim=-1)\n",
|
| 526 |
+
"\n",
|
| 527 |
+
"def build_model():\n",
|
| 528 |
+
" '''a FRESH model: TrOCR-base encoder weights + a newly initialised classifier (called once per phase)'''\n",
|
| 529 |
+
" torch.manual_seed(SEED)\n",
|
| 530 |
+
" vit = VisionEncoderDecoderModel.from_pretrained(ENC_SRC).encoder\n",
|
| 531 |
+
" return EncoderLinearCTC(vit, N_CLASSES).to(device)\n",
|
| 532 |
+
"\n",
|
| 533 |
+
"model = build_model()\n",
|
| 534 |
+
"n_enc = sum(p.numel() for p in model.vit.parameters()); n_head = sum(p.numel() for p in model.classifier.parameters())\n",
|
| 535 |
+
"print(f\"encoder {n_enc/1e6:.1f}M ({model.vit.config.model_type}, hidden {model.vit.config.hidden_size}) | classifier {n_head/1e6:.3f}M\")"
|
| 536 |
+
]
|
| 537 |
+
},
|
| 538 |
+
{
|
| 539 |
+
"cell_type": "markdown",
|
| 540 |
+
"id": "f5e88ddf",
|
| 541 |
+
"metadata": {
|
| 542 |
+
"papermill": {
|
| 543 |
+
"duration": 0.002348,
|
| 544 |
+
"end_time": "2026-10-22T19:07:59.653942+00:00",
|
| 545 |
+
"exception": false,
|
| 546 |
+
"start_time": "2026-10-22T19:07:59.651594+00:00",
|
| 547 |
+
"status": "completed"
|
| 548 |
+
},
|
| 549 |
+
"tags": []
|
| 550 |
+
},
|
| 551 |
+
"source": [
|
| 552 |
+
"### 6. Metrics + training function"
|
| 553 |
+
]
|
| 554 |
+
},
|
| 555 |
+
{
|
| 556 |
+
"cell_type": "code",
|
| 557 |
+
"execution_count": 7,
|
| 558 |
+
"id": "1935e020",
|
| 559 |
+
"metadata": {
|
| 560 |
+
"execution": {
|
| 561 |
+
"iopub.execute_input": "2026-10-22T19:07:59.659620Z",
|
| 562 |
+
"iopub.status.busy": "2026-10-22T19:07:59.659463Z",
|
| 563 |
+
"iopub.status.idle": "2026-10-22T19:07:59.678340Z",
|
| 564 |
+
"shell.execute_reply": "2026-10-22T19:07:59.677764Z"
|
| 565 |
+
},
|
| 566 |
+
"papermill": {
|
| 567 |
+
"duration": 0.022442,
|
| 568 |
+
"end_time": "2026-10-22T19:07:59.678825+00:00",
|
| 569 |
+
"exception": false,
|
| 570 |
+
"start_time": "2026-10-22T19:07:59.656383+00:00",
|
| 571 |
+
"status": "completed"
|
| 572 |
+
},
|
| 573 |
+
"tags": []
|
| 574 |
+
},
|
| 575 |
+
"outputs": [
|
| 576 |
+
{
|
| 577 |
+
"name": "stdout",
|
| 578 |
+
"output_type": "stream",
|
| 579 |
+
"text": [
|
| 580 |
+
"ready\n"
|
| 581 |
+
]
|
| 582 |
+
}
|
| 583 |
+
],
|
| 584 |
+
"source": [
|
| 585 |
+
"def scores(R, H):\n",
|
| 586 |
+
" o = {}\n",
|
| 587 |
+
" for v, f in {\"raw\": lambda t: t, \"let\": lambda t: re.sub(r\" +\", \" \", re.sub(r\"[^א-ת ]\", \" \", t)).strip()}.items():\n",
|
| 588 |
+
" rr = [f(x) for x in R]; hh = [f(x) for x in H]; k = [i for i, x in enumerate(rr) if x]\n",
|
| 589 |
+
" o[f\"cer_{v}\"] = jiwer.cer([rr[i] for i in k], [hh[i] for i in k]); o[f\"wer_{v}\"] = jiwer.wer([rr[i] for i in k], [hh[i] for i in k])\n",
|
| 590 |
+
" return o\n",
|
| 591 |
+
"\n",
|
| 592 |
+
"@torch.no_grad()\n",
|
| 593 |
+
"def predict(model, split):\n",
|
| 594 |
+
" model.eval(); H, R = [], []\n",
|
| 595 |
+
" for px, cols, _, texts in loader(split, False, EVAL_BS):\n",
|
| 596 |
+
" with torch.autocast(\"cuda\", dtype=AMP_DTYPE, enabled=device == \"cuda\"):\n",
|
| 597 |
+
" lp = model(px.to(device))\n",
|
| 598 |
+
" lp = lp.float().cpu().numpy()\n",
|
| 599 |
+
" H += [greedy(lp[i], int(cols[i]) * SUB) for i in range(len(texts))]; R += texts\n",
|
| 600 |
+
" return R, H\n",
|
| 601 |
+
"\n",
|
| 602 |
+
"def ctc(lp, cols, labels):\n",
|
| 603 |
+
" return F.ctc_loss(lp.transpose(0, 1), torch.tensor(sum(labels, [])), cols * SUB,\n",
|
| 604 |
+
" torch.tensor([len(l) for l in labels]), blank=0, zero_infinity=True)\n",
|
| 605 |
+
"\n",
|
| 606 |
+
"class Stream:\n",
|
| 607 |
+
" \"\"\"endless batches of one dataset (one arm, or the reward set): reshuffled after every pass over it; `passes` = how many passes were started\"\"\"\n",
|
| 608 |
+
" def __init__(self, ds, seed, workers):\n",
|
| 609 |
+
" self.ds, self.g, self.w, self.it, self.passes, self.batches = ds, torch.Generator().manual_seed(seed), workers, None, 0, 0\n",
|
| 610 |
+
" def next(self):\n",
|
| 611 |
+
" while True:\n",
|
| 612 |
+
" if self.it is None:\n",
|
| 613 |
+
" self.it = iter(torch.utils.data.DataLoader(self.ds, batch_size=BATCH, shuffle=True, generator=self.g, num_workers=self.w,\n",
|
| 614 |
+
" collate_fn=collate, drop_last=True)); self.passes += 1\n",
|
| 615 |
+
" try:\n",
|
| 616 |
+
" b = next(self.it); self.batches += 1; return b\n",
|
| 617 |
+
" except StopIteration:\n",
|
| 618 |
+
" self.it = None\n",
|
| 619 |
+
"\n",
|
| 620 |
+
"def flat_grad(model):\n",
|
| 621 |
+
" return torch.cat([(p.grad.detach().float() if p.grad is not None else torch.zeros_like(p, dtype=torch.float32)).reshape(-1) for p in model.parameters()])\n",
|
| 622 |
+
"\n",
|
| 623 |
+
"def train_bandit(model, arms, epochs, tag, holdout=None):\n",
|
| 624 |
+
" \"\"\"Same optimiser / LR schedule / clipping as train(); the batch of each step comes from ONE arm chosen by discounted EXP3 on the gradient-alignment reward.\"\"\"\n",
|
| 625 |
+
" log = os.path.join(OUT, f\"train_log_{tag}.tsv\"); blog = os.path.join(OUT, \"bandit_log.tsv\")\n",
|
| 626 |
+
" open(log, \"w\").write(\"epoch\\tstep\\ttrain_loss\\tholdout_cer\\tholdout_wer\\tdiffpen_share\\tsec\\n\")\n",
|
| 627 |
+
" open(blog, \"w\").write(\"step\\tarm\\tloss\\treward\\treward_norm\\t\" + \"\\t\".join(f\"p_{n}\" for n in ARM_NAMES) + \"\\tlr_f\\n\")\n",
|
| 628 |
+
" head_params, enc_params = list(model.classifier.parameters()), list(model.vit.parameters())\n",
|
| 629 |
+
" opt = torch.optim.AdamW([{\"params\": enc_params, \"lr\": LR_ENC}, {\"params\": head_params, \"lr\": LR_HEAD}], weight_decay=0.01)\n",
|
| 630 |
+
" base_lr = [g[\"lr\"] for g in opt.param_groups]\n",
|
| 631 |
+
" scaler = torch.amp.GradScaler(\"cuda\", enabled=device == \"cuda\" and AMP_DTYPE == torch.float16)\n",
|
| 632 |
+
" total = epochs * STEPS_PER_EPOCH; warm = max(1, int(WARMUP_FRAC * total))\n",
|
| 633 |
+
" streams = [Stream(ds, SEED * 10 + k, max(1, NUM_WORKERS // 2)) for k, ds in enumerate(arms)]; rstream = Stream(reward_set, SEED * 10 + 9, 2)\n",
|
| 634 |
+
" rng = np.random.default_rng(SEED); logw = np.zeros(K); mu, var = 0.0, 1e-4; g_dev = None\n",
|
| 635 |
+
" pulls = np.zeros((epochs, K), int); rsum = np.zeros((epochs, K)); traj = []; t0 = time.time(); curve = []\n",
|
| 636 |
+
" def probs():\n",
|
| 637 |
+
" e = np.exp(logw - logw.max()); return (1 - GAMMA) * e / e.sum() + GAMMA / K\n",
|
| 638 |
+
" def scale(): return scaler.get_scale() if scaler.is_enabled() else 1.0\n",
|
| 639 |
+
" print(f\"[{tag}] arms {[len(a) for a in arms]} lines | {STEPS_PER_EPOCH} steps/epoch x {epochs} epochs = {total} steps of {BATCH}\")\n",
|
| 640 |
+
" losses = []\n",
|
| 641 |
+
" for step in range(total):\n",
|
| 642 |
+
" ep = step // STEPS_PER_EPOCH\n",
|
| 643 |
+
" if step % DEV_EVERY == 0: # reward-set gradient (no optimiser step on it)\n",
|
| 644 |
+
" model.eval(); rb = [rstream.next() for _ in range(REWARD_BATCHES)]\n",
|
| 645 |
+
" for amp in (True, False): # fp16 loss scaling can overflow (T4, first steps): then recompute in fp32\n",
|
| 646 |
+
" opt.zero_grad(set_to_none=True)\n",
|
| 647 |
+
" for px, cols, labels, _ in rb:\n",
|
| 648 |
+
" keep = [i for i, l in enumerate(labels) if 0 < len(l) <= int(cols[i]) * SUB]\n",
|
| 649 |
+
" with torch.autocast(\"cuda\", dtype=AMP_DTYPE, enabled=device == \"cuda\" and amp):\n",
|
| 650 |
+
" lp = model(px[keep].to(device))\n",
|
| 651 |
+
" l_ = ctc(lp, cols[keep], [labels[i] for i in keep]) / REWARD_BATCHES\n",
|
| 652 |
+
" (scaler.scale(l_) if amp else l_).backward()\n",
|
| 653 |
+
" g_dev = flat_grad(model) / (scale() if amp else 1.0)\n",
|
| 654 |
+
" if bool(torch.isfinite(g_dev).all()): break\n",
|
| 655 |
+
" opt.zero_grad(set_to_none=True)\n",
|
| 656 |
+
" p = probs(); i = step % K if step < EXPLORE_STEPS else int(rng.choice(K, p=p))\n",
|
| 657 |
+
" px, cols, labels, _ = streams[i].next()\n",
|
| 658 |
+
" keep = [j for j, l in enumerate(labels) if 0 < len(l) <= int(cols[j]) * SUB]\n",
|
| 659 |
+
" if not keep: continue\n",
|
| 660 |
+
" f = min(1.0, (step + 1) / warm) * max(0.0, (total - step) / max(1, total - warm))\n",
|
| 661 |
+
" for g, b in zip(opt.param_groups, base_lr): g[\"lr\"] = b * f\n",
|
| 662 |
+
" model.train()\n",
|
| 663 |
+
" with torch.autocast(\"cuda\", dtype=AMP_DTYPE, enabled=device == \"cuda\"):\n",
|
| 664 |
+
" lp = model(px[keep].to(device))\n",
|
| 665 |
+
" loss = ctc(lp, cols[keep], [labels[j] for j in keep])\n",
|
| 666 |
+
" opt.zero_grad(set_to_none=True); scaler.scale(loss).backward(); scaler.unscale_(opt)\n",
|
| 667 |
+
" r = float(F.cosine_similarity(flat_grad(model), g_dev, dim=0)) # batch gradient vs reward-set gradient (before clipping)\n",
|
| 668 |
+
" torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); scaler.step(opt); scaler.update()\n",
|
| 669 |
+
" rn = float(\"nan\")\n",
|
| 670 |
+
" if math.isfinite(r):\n",
|
| 671 |
+
" mu = (1 - STAT_BETA) * mu + STAT_BETA * r; var = (1 - STAT_BETA) * var + STAT_BETA * (r - mu) ** 2\n",
|
| 672 |
+
" rn = float(np.clip((r - mu) / math.sqrt(var + 1e-12), -3, 3) / 3)\n",
|
| 673 |
+
" if step >= EXPLORE_STEPS: logw *= DECAY; logw[i] += ETA * rn / p[i]\n",
|
| 674 |
+
" rsum[ep, i] += r\n",
|
| 675 |
+
" pulls[ep, i] += 1; losses.append(float(loss)); traj.append((step, *probs()))\n",
|
| 676 |
+
" open(blog, \"a\").write(f\"{step}\\t{ARM_NAMES[i]}\\t{float(loss):.4f}\\t{r:.5f}\\t{rn:.4f}\\t\" + \"\\t\".join(f\"{x:.4f}\" for x in probs()) + f\"\\t{f:.4f}\\n\")\n",
|
| 677 |
+
" if step % 250 == 0: print(f\" step {step}/{total} | arm {ARM_NAMES[i]} | reward {r:+.4f} | p {np.round(probs(), 3).tolist()} | loss {float(loss):.3f} | {time.time()-t0:.0f}s\", flush=True)\n",
|
| 678 |
+
" if (step + 1) % STEPS_PER_EPOCH == 0 or step + 1 == total:\n",
|
| 679 |
+
" tl = float(np.mean(losses)); losses = []; sh = pulls[ep, 0] / max(1, pulls[ep].sum()); s = {\"cer_raw\": float(\"nan\"), \"wer_raw\": float(\"nan\")}\n",
|
| 680 |
+
" if holdout is not None: R, H = predict(model, holdout); s = scores(R, H)\n",
|
| 681 |
+
" curve.append({\"epoch\": ep + 1, \"train_loss\": tl, \"diffpen_share\": sh, \"pulls\": pulls[ep].tolist(),\n",
|
| 682 |
+
" \"mean_reward\": (rsum[ep] / np.maximum(1, pulls[ep])).tolist(), \"p_end\": probs().tolist(), **s})\n",
|
| 683 |
+
" open(log, \"a\").write(f\"{ep+1}\\t{step+1}\\t{tl:.4f}\\t{s['cer_raw']:.4f}\\t{s['wer_raw']:.4f}\\t{sh:.3f}\\t{time.time()-t0:.0f}\\n\")\n",
|
| 684 |
+
" print(f\"[{tag} epoch {ep+1}/{epochs}] loss {tl:.3f} | DiffusionPen share {100*sh:.1f}% (pulls {pulls[ep].tolist()}) | mean reward {np.round(curve[-1]['mean_reward'], 4).tolist()} | holdout CER {100*s['cer_raw']:.2f} | {time.time()-t0:.0f}s\", flush=True)\n",
|
| 685 |
+
" # trajectory plot of p\n",
|
| 686 |
+
" import matplotlib.pyplot as plt\n",
|
| 687 |
+
" tr = np.array(traj); fig, ax = plt.subplots(figsize=(8, 3.2))\n",
|
| 688 |
+
" ax.plot(tr[:, 0], tr[:, 1], lw=0.8, label=\"p(diffpen)\"); w = max(1, min(100, len(tr) // 5))\n",
|
| 689 |
+
" ax.plot(tr[:, 0], np.convolve(tr[:, 1], np.ones(w) / w, mode=\"same\"), lw=2, label=f\"p(diffpen), {w}-step mean\")\n",
|
| 690 |
+
" for e in range(1, epochs): ax.axvline(e * STEPS_PER_EPOCH, color=\"grey\", lw=0.5, ls=\":\")\n",
|
| 691 |
+
" ax.axhline(0.5, color=\"k\", lw=0.5); ax.set_ylim(0, 1); ax.set_xlabel(\"step\"); ax.set_ylabel(\"probability of the DiffusionPen arm\"); ax.legend(loc=\"upper right\", fontsize=8)\n",
|
| 692 |
+
" fig.tight_layout(); fig.savefig(os.path.join(OUT, \"bandit_p.png\"), dpi=130); plt.show()\n",
|
| 693 |
+
" return {\"steps\": total, \"epochs\": epochs, \"pulls_total\": pulls.sum(0).tolist(), \"diffpen_share_total\": float(pulls[:, 0].sum() / max(1, pulls.sum())),\n",
|
| 694 |
+
" \"arm_passes\": [s_.passes for s_ in streams], \"curve\": curve}\n",
|
| 695 |
+
"print(\"ready\")"
|
| 696 |
+
]
|
| 697 |
+
},
|
| 698 |
+
{
|
| 699 |
+
"cell_type": "markdown",
|
| 700 |
+
"id": "971ac0dc",
|
| 701 |
+
"metadata": {
|
| 702 |
+
"papermill": {
|
| 703 |
+
"duration": 0.002254,
|
| 704 |
+
"end_time": "2026-10-22T19:07:59.683545+00:00",
|
| 705 |
+
"exception": false,
|
| 706 |
+
"start_time": "2026-10-22T19:07:59.681291+00:00",
|
| 707 |
+
"status": "completed"
|
| 708 |
+
},
|
| 709 |
+
"tags": []
|
| 710 |
+
},
|
| 711 |
+
"source": [
|
| 712 |
+
"### 7. Phase 1 — SKIPPED (epoch count fixed to 4 = the fixed-mix 20k runs)"
|
| 713 |
+
]
|
| 714 |
+
},
|
| 715 |
+
{
|
| 716 |
+
"cell_type": "code",
|
| 717 |
+
"execution_count": 8,
|
| 718 |
+
"id": "fd4d15bf",
|
| 719 |
+
"metadata": {
|
| 720 |
+
"execution": {
|
| 721 |
+
"iopub.execute_input": "2026-10-22T19:07:59.708778Z",
|
| 722 |
+
"iopub.status.busy": "2026-10-22T19:07:59.708551Z",
|
| 723 |
+
"iopub.status.idle": "2026-10-22T19:07:59.723399Z",
|
| 724 |
+
"shell.execute_reply": "2026-10-22T19:07:59.722847Z"
|
| 725 |
+
},
|
| 726 |
+
"papermill": {
|
| 727 |
+
"duration": 0.03786,
|
| 728 |
+
"end_time": "2026-10-22T19:07:59.723840+00:00",
|
| 729 |
+
"exception": false,
|
| 730 |
+
"start_time": "2026-10-22T19:07:59.685980+00:00",
|
| 731 |
+
"status": "completed"
|
| 732 |
+
},
|
| 733 |
+
"tags": []
|
| 734 |
+
},
|
| 735 |
+
"outputs": [
|
| 736 |
+
{
|
| 737 |
+
"name": "stdout",
|
| 738 |
+
"output_type": "stream",
|
| 739 |
+
"text": [
|
| 740 |
+
"phase 1 skipped; final epochs = 4\n"
|
| 741 |
+
]
|
| 742 |
+
}
|
| 743 |
+
],
|
| 744 |
+
"source": [
|
| 745 |
+
"sel = {\"skipped\": True, \"best_epoch\": 4, \"epochs_run\": 0, \"epochs_from\": \"the fixed-mix 20k runs (joined / fonts / DiffusionPen 20k, 4 epochs)\"}\n",
|
| 746 |
+
"BEST_EPOCH = 4\n",
|
| 747 |
+
"json.dump({\"config\": CFG, \"arm_lines\": [len(a) for a in arms], \"reward_lines\": len(reward_set), \"holdout_lines\": len(holdout), **sel}, open(os.path.join(OUT, \"results_select.json\"), \"w\"), indent=1)\n",
|
| 748 |
+
"print(\"phase 1 skipped; final epochs =\", BEST_EPOCH)\n",
|
| 749 |
+
"del model; torch.cuda.empty_cache()"
|
| 750 |
+
]
|
| 751 |
+
},
|
| 752 |
+
{
|
| 753 |
+
"cell_type": "markdown",
|
| 754 |
+
"id": "78a26b6f",
|
| 755 |
+
"metadata": {
|
| 756 |
+
"papermill": {
|
| 757 |
+
"duration": 0.002421,
|
| 758 |
+
"end_time": "2026-10-22T19:07:59.729084+00:00",
|
| 759 |
+
"exception": false,
|
| 760 |
+
"start_time": "2026-10-22T19:07:59.726663+00:00",
|
| 761 |
+
"status": "completed"
|
| 762 |
+
},
|
| 763 |
+
"tags": []
|
| 764 |
+
},
|
| 765 |
+
"source": [
|
| 766 |
+
"### 8. Final run with the bandit mixer (fresh model, 4 x 625 steps, LR decay; HHD test scored once)"
|
| 767 |
+
]
|
| 768 |
+
},
|
| 769 |
+
{
|
| 770 |
+
"cell_type": "markdown",
|
| 771 |
+
"id": "81aec26e",
|
| 772 |
+
"metadata": {
|
| 773 |
+
"tags": [
|
| 774 |
+
"papermill-error-cell-tag"
|
| 775 |
+
]
|
| 776 |
+
},
|
| 777 |
+
"source": [
|
| 778 |
+
"<span id=\"papermill-error-cell\" style=\"color:red; font-family:Helvetica Neue, Helvetica, Arial, sans-serif; font-size:2em;\">Execution using papermill encountered an exception here and stopped:</span>"
|
| 779 |
+
]
|
| 780 |
+
},
|
| 781 |
+
{
|
| 782 |
+
"cell_type": "code",
|
| 783 |
+
"execution_count": 9,
|
| 784 |
+
"id": "9c7cf0c7",
|
| 785 |
+
"metadata": {
|
| 786 |
+
"execution": {
|
| 787 |
+
"iopub.execute_input": "2026-10-22T19:07:59.735037Z",
|
| 788 |
+
"iopub.status.busy": "2026-10-22T19:07:59.734881Z",
|
| 789 |
+
"iopub.status.idle": "2026-10-22T19:19:46.719479Z",
|
| 790 |
+
"shell.execute_reply": "2026-10-22T19:19:46.718634Z"
|
| 791 |
+
},
|
| 792 |
+
"papermill": {
|
| 793 |
+
"duration": 706.988605,
|
| 794 |
+
"end_time": "2026-10-22T19:19:46.720201+00:00",
|
| 795 |
+
"exception": true,
|
| 796 |
+
"start_time": "2026-10-22T19:07:59.731596+00:00",
|
| 797 |
+
"status": "failed"
|
| 798 |
+
},
|
| 799 |
+
"tags": []
|
| 800 |
+
},
|
| 801 |
+
"outputs": [
|
| 802 |
+
{
|
| 803 |
+
"name": "stdout",
|
| 804 |
+
"output_type": "stream",
|
| 805 |
+
"text": [
|
| 806 |
+
"FINAL: re-initialising from TrOCR-base; bandit over ['diffpen', 'fonts'] for 4 epochs\n"
|
| 807 |
+
]
|
| 808 |
+
},
|
| 809 |
+
{
|
| 810 |
+
"name": "stderr",
|
| 811 |
+
"output_type": "stream",
|
| 812 |
+
"text": [
|
| 813 |
+
"\r",
|
| 814 |
+
"Loading weights: 0%| | 0/478 [00:00<?, ?it/s]"
|
| 815 |
+
]
|
| 816 |
+
},
|
| 817 |
+
{
|
| 818 |
+
"name": "stderr",
|
| 819 |
+
"output_type": "stream",
|
| 820 |
+
"text": [
|
| 821 |
+
"\r",
|
| 822 |
+
"Loading weights: 100%|██████████| 478/478 [00:00<00:00, 7590.55it/s]"
|
| 823 |
+
]
|
| 824 |
+
},
|
| 825 |
+
{
|
| 826 |
+
"name": "stderr",
|
| 827 |
+
"output_type": "stream",
|
| 828 |
+
"text": [
|
| 829 |
+
"\n",
|
| 830 |
+
"[transformers] \u001b[1mVisionEncoderDecoderModel LOAD REPORT\u001b[0m from: microsoft/trocr-base-handwritten\n",
|
| 831 |
+
"Key | Status | \n",
|
| 832 |
+
"----------------------------+---------+-\n",
|
| 833 |
+
"encoder.pooler.dense.weight | MISSING | \n",
|
| 834 |
+
"encoder.pooler.dense.bias | MISSING | \n",
|
| 835 |
+
"\n",
|
| 836 |
+
"Notes:\n",
|
| 837 |
+
"- MISSING:\tthose params were newly initialized because missing from the checkpoint. Consider training on your downstream task.\n"
|
| 838 |
+
]
|
| 839 |
+
},
|
| 840 |
+
{
|
| 841 |
+
"name": "stdout",
|
| 842 |
+
"output_type": "stream",
|
| 843 |
+
"text": [
|
| 844 |
+
"[final] arms [19997, 20000] lines | 625 steps/epoch x 4 epochs = 2500 steps of 32\n"
|
| 845 |
+
]
|
| 846 |
+
},
|
| 847 |
+
{
|
| 848 |
+
"name": "stdout",
|
| 849 |
+
"output_type": "stream",
|
| 850 |
+
"text": [
|
| 851 |
+
" step 0/2500 | arm diffpen | reward +0.8238 | p [0.5, 0.5] | loss 13.776 | 1s\n"
|
| 852 |
+
]
|
| 853 |
+
},
|
| 854 |
+
{
|
| 855 |
+
"name": "stderr",
|
| 856 |
+
"output_type": "stream",
|
| 857 |
+
"text": [
|
| 858 |
+
"/tmp/ipykernel_5097/1488731010.py:91: UserWarning: Converting a tensor with requires_grad=True to a scalar may lead to unexpected behavior.\n",
|
| 859 |
+
"Consider using tensor.detach() first. (Triggered internally at /__w/pytorch/pytorch/torch/csrc/autograd/generated/python_variable_methods.cpp:820.)\n",
|
| 860 |
+
" pulls[ep, i] += 1; losses.append(float(loss)); traj.append((step, *probs()))\n"
|
| 861 |
+
]
|
| 862 |
+
},
|
| 863 |
+
{
|
| 864 |
+
"name": "stdout",
|
| 865 |
+
"output_type": "stream",
|
| 866 |
+
"text": [
|
| 867 |
+
" step 250/2500 | arm fonts | reward -0.0244 | p [0.471, 0.529] | loss 0.396 | 70s\n"
|
| 868 |
+
]
|
| 869 |
+
},
|
| 870 |
+
{
|
| 871 |
+
"name": "stdout",
|
| 872 |
+
"output_type": "stream",
|
| 873 |
+
"text": [
|
| 874 |
+
" step 500/2500 | arm fonts | reward -0.1458 | p [0.639, 0.361] | loss 0.299 | 139s\n"
|
| 875 |
+
]
|
| 876 |
+
},
|
| 877 |
+
{
|
| 878 |
+
"name": "stderr",
|
| 879 |
+
"output_type": "stream",
|
| 880 |
+
"text": [
|
| 881 |
+
"/home/romanva1/env/lib/python3.12/site-packages/torch/utils/data/dataloader.py:431: UserWarning: This DataLoader will create 8 worker processes in total. Our suggested max number of worker in current system is 4, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n",
|
| 882 |
+
" self.check_worker_number_rationality()\n",
|
| 883 |
+
"/home/romanva1/env/lib/python3.12/site-packages/torch/utils/data/dataloader.py:437: UserWarning: This DataLoader will create 8 worker processes in total. Our suggested max number of worker in current system is 4, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n",
|
| 884 |
+
" self.check_worker_number_rationality()\n"
|
| 885 |
+
]
|
| 886 |
+
},
|
| 887 |
+
{
|
| 888 |
+
"name": "stdout",
|
| 889 |
+
"output_type": "stream",
|
| 890 |
+
"text": [
|
| 891 |
+
"[final epoch 1/4] loss 1.014 | DiffusionPen share 55.4% (pulls [346, 279]) | mean reward [0.0368, 0.0095] | holdout CER 30.10 | 176s\n"
|
| 892 |
+
]
|
| 893 |
+
},
|
| 894 |
+
{
|
| 895 |
+
"name": "stdout",
|
| 896 |
+
"output_type": "stream",
|
| 897 |
+
"text": [
|
| 898 |
+
" step 750/2500 | arm diffpen | reward +0.2173 | p [0.634, 0.366] | loss 0.214 | 211s\n"
|
| 899 |
+
]
|
| 900 |
+
},
|
| 901 |
+
{
|
| 902 |
+
"name": "stdout",
|
| 903 |
+
"output_type": "stream",
|
| 904 |
+
"text": [
|
| 905 |
+
" step 1000/2500 | arm fonts | reward -0.1770 | p [0.726, 0.274] | loss 0.134 | 281s\n"
|
| 906 |
+
]
|
| 907 |
+
},
|
| 908 |
+
{
|
| 909 |
+
"name": "stdout",
|
| 910 |
+
"output_type": "stream",
|
| 911 |
+
"text": [
|
| 912 |
+
"[final epoch 2/4] loss 0.154 | DiffusionPen share 66.6% (pulls [416, 209]) | mean reward [0.0226, -0.0397] | holdout CER 28.95 | 352s\n"
|
| 913 |
+
]
|
| 914 |
+
},
|
| 915 |
+
{
|
| 916 |
+
"name": "stdout",
|
| 917 |
+
"output_type": "stream",
|
| 918 |
+
"text": [
|
| 919 |
+
" step 1250/2500 | arm diffpen | reward +0.1427 | p [0.656, 0.344] | loss 0.096 | 353s\n"
|
| 920 |
+
]
|
| 921 |
+
},
|
| 922 |
+
{
|
| 923 |
+
"name": "stdout",
|
| 924 |
+
"output_type": "stream",
|
| 925 |
+
"text": [
|
| 926 |
+
" step 1500/2500 | arm fonts | reward -0.0915 | p [0.641, 0.359] | loss 0.073 | 423s\n"
|
| 927 |
+
]
|
| 928 |
+
},
|
| 929 |
+
{
|
| 930 |
+
"name": "stdout",
|
| 931 |
+
"output_type": "stream",
|
| 932 |
+
"text": [
|
| 933 |
+
" step 1750/2500 | arm diffpen | reward +0.0103 | p [0.662, 0.338] | loss 0.088 | 493s\n"
|
| 934 |
+
]
|
| 935 |
+
},
|
| 936 |
+
{
|
| 937 |
+
"name": "stdout",
|
| 938 |
+
"output_type": "stream",
|
| 939 |
+
"text": [
|
| 940 |
+
"[final epoch 3/4] loss 0.087 | DiffusionPen share 63.0% (pulls [394, 231]) | mean reward [0.014, -0.0236] | holdout CER 29.45 | 529s\n"
|
| 941 |
+
]
|
| 942 |
+
},
|
| 943 |
+
{
|
| 944 |
+
"name": "stdout",
|
| 945 |
+
"output_type": "stream",
|
| 946 |
+
"text": [
|
| 947 |
+
" step 2000/2500 | arm diffpen | reward +0.0499 | p [0.625, 0.375] | loss 0.068 | 564s\n"
|
| 948 |
+
]
|
| 949 |
+
},
|
| 950 |
+
{
|
| 951 |
+
"name": "stdout",
|
| 952 |
+
"output_type": "stream",
|
| 953 |
+
"text": [
|
| 954 |
+
" step 2250/2500 | arm diffpen | reward +0.0635 | p [0.641, 0.359] | loss 0.027 | 635s\n"
|
| 955 |
+
]
|
| 956 |
+
},
|
| 957 |
+
{
|
| 958 |
+
"name": "stdout",
|
| 959 |
+
"output_type": "stream",
|
| 960 |
+
"text": [
|
| 961 |
+
"[final epoch 4/4] loss 0.050 | DiffusionPen share 62.1% (pulls [388, 237]) | mean reward [0.0135, -0.0211] | holdout CER 27.47 | 706s\n"
|
| 962 |
+
]
|
| 963 |
+
},
|
| 964 |
+
{
|
| 965 |
+
"ename": "ModuleNotFoundError",
|
| 966 |
+
"evalue": "No module named 'matplotlib'",
|
| 967 |
+
"output_type": "error",
|
| 968 |
+
"traceback": [
|
| 969 |
+
"\u001b[31m---------------------------------------------------------------------------\u001b[39m",
|
| 970 |
+
"\u001b[31mModuleNotFoundError\u001b[39m Traceback (most recent call last)",
|
| 971 |
+
"\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[9]\u001b[39m\u001b[32m, line 6\u001b[39m\n\u001b[32m 2\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m RUN_FINAL:\n\u001b[32m 3\u001b[39m n_final = FINAL_EPOCHS \u001b[38;5;28;01mor\u001b[39;00m BEST_EPOCH\n\u001b[32m 4\u001b[39m print(\u001b[33m\"FINAL: re-initialising from TrOCR-base; bandit over\"\u001b[39m, ARM_NAMES, \u001b[33m\"for\"\u001b[39m, n_final, \u001b[33m\"epochs\"\u001b[39m)\n\u001b[32m 5\u001b[39m model = build_model()\n\u001b[32m----> \u001b[39m\u001b[32m6\u001b[39m fin = train_bandit(model, arms, n_final, \u001b[33m\"final\"\u001b[39m, holdout=holdout)\n\u001b[32m 7\u001b[39m results[\u001b[33m\"bandit\"\u001b[39m] = fin\n\u001b[32m 8\u001b[39m R, H = predict(model, test); test_scores = scores(R, H)\n\u001b[32m 9\u001b[39m results[\u001b[33m\"final\"\u001b[39m] = {\u001b[33m\"epochs\"\u001b[39m: n_final, \u001b[33m\"steps\"\u001b[39m: fin[\u001b[33m\"steps\"\u001b[39m], \u001b[33m\"test\"\u001b[39m: test_scores}\n",
|
| 972 |
+
"\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 102\u001b[39m, in \u001b[36mtrain_bandit\u001b[39m\u001b[34m(model, arms, epochs, tag, holdout)\u001b[39m\n\u001b[32m 98\u001b[39m \u001b[33m\"mean_reward\"\u001b[39m: (rsum[ep] / np.maximum(\u001b[32m1\u001b[39m, pulls[ep])).tolist(), \u001b[33m\"p_end\"\u001b[39m: probs().tolist(), **s})\n\u001b[32m 99\u001b[39m open(log, \u001b[33m\"a\"\u001b[39m).write(f\"{ep+\u001b[32m1\u001b[39m}\\t{step+\u001b[32m1\u001b[39m}\\t{tl:.4f}\\t{s[\u001b[33m'cer_raw'\u001b[39m]:.4f}\\t{s[\u001b[33m'wer_raw'\u001b[39m]:.4f}\\t{sh:.3f}\\t{time.time()-t0:.0f}\\n\")\n\u001b[32m 100\u001b[39m print(f\"[{tag} epoch {ep+\u001b[32m1\u001b[39m}/{epochs}] loss {tl:.3f} | DiffusionPen share {\u001b[32m100\u001b[39m*sh:.1f}% (pulls {pulls[ep].tolist()}) | mean reward {np.round(curve[-\u001b[32m1\u001b[39m][\u001b[33m'mean_reward'\u001b[39m], \u001b[32m4\u001b[39m).tolist()} | holdout CER {\u001b[32m100\u001b[39m*s[\u001b[33m'cer_raw'\u001b[39m]:.2f} | {time.time()-t0:.0f}s\", flush=\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[32m 101\u001b[39m \u001b[38;5;66;03m# trajectory plot of p\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m102\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m matplotlib.pyplot \u001b[38;5;28;01mas\u001b[39;00m plt\n\u001b[32m 103\u001b[39m tr = np.array(traj); fig, ax = plt.subplots(figsize=(\u001b[32m8\u001b[39m, \u001b[32m3.2\u001b[39m))\n\u001b[32m 104\u001b[39m ax.plot(tr[:, \u001b[32m0\u001b[39m], tr[:, \u001b[32m1\u001b[39m], lw=\u001b[32m0.8\u001b[39m, label=\u001b[33m\"p(diffpen)\"\u001b[39m); w = max(\u001b[32m1\u001b[39m, min(\u001b[32m100\u001b[39m, len(tr) // \u001b[32m5\u001b[39m))\n\u001b[32m 105\u001b[39m ax.plot(tr[:, \u001b[32m0\u001b[39m], np.convolve(tr[:, \u001b[32m1\u001b[39m], np.ones(w) / w, mode=\u001b[33m\"same\"\u001b[39m), lw=\u001b[32m2\u001b[39m, label=f\"p(diffpen), {w}-step mean\")\n",
|
| 973 |
+
"\u001b[31mModuleNotFoundError\u001b[39m: No module named 'matplotlib'"
|
| 974 |
+
]
|
| 975 |
+
}
|
| 976 |
+
],
|
| 977 |
+
"source": [
|
| 978 |
+
"results = {\"config\": CFG, \"select\": sel}\n",
|
| 979 |
+
"if RUN_FINAL:\n",
|
| 980 |
+
" n_final = FINAL_EPOCHS or BEST_EPOCH\n",
|
| 981 |
+
" print(\"FINAL: re-initialising from TrOCR-base; bandit over\", ARM_NAMES, \"for\", n_final, \"epochs\")\n",
|
| 982 |
+
" model = build_model()\n",
|
| 983 |
+
" fin = train_bandit(model, arms, n_final, \"final\", holdout=holdout)\n",
|
| 984 |
+
" results[\"bandit\"] = fin\n",
|
| 985 |
+
" R, H = predict(model, test); test_scores = scores(R, H)\n",
|
| 986 |
+
" results[\"final\"] = {\"epochs\": n_final, \"steps\": fin[\"steps\"], \"test\": test_scores}\n",
|
| 987 |
+
" print(\"DiffusionPen share over the run:\", round(100 * fin[\"diffpen_share_total\"], 1), \"% | pulls\", fin[\"pulls_total\"], \"| passes per arm\", fin[\"arm_passes\"])\n",
|
| 988 |
+
" print(\"HHD TEST (greedy, raw CER/WER and Hebrew-letters-only CER):\", {k: round(v, 4) for k, v in test_scores.items()})\n",
|
| 989 |
+
" with open(os.path.join(OUT, \"test_predictions.tsv\"), \"w\", encoding=\"utf-8\") as fh:\n",
|
| 990 |
+
" fh.write(\"ref\\thyp\\n\"); [fh.write(f\"{r}\\t{h}\\n\") for r, h in zip(R, H)]\n",
|
| 991 |
+
" for i in range(3): print(\"REF\", R[i]); print(\"OUT\", H[i])\n",
|
| 992 |
+
"json.dump(results, open(os.path.join(OUT, \"results.json\"), \"w\"), indent=1)"
|
| 993 |
+
]
|
| 994 |
+
},
|
| 995 |
+
{
|
| 996 |
+
"cell_type": "markdown",
|
| 997 |
+
"id": "84e49a66",
|
| 998 |
+
"metadata": {
|
| 999 |
+
"papermill": {
|
| 1000 |
+
"duration": null,
|
| 1001 |
+
"end_time": null,
|
| 1002 |
+
"exception": null,
|
| 1003 |
+
"start_time": null,
|
| 1004 |
+
"status": "pending"
|
| 1005 |
+
},
|
| 1006 |
+
"tags": []
|
| 1007 |
+
},
|
| 1008 |
+
"source": [
|
| 1009 |
+
"### 8b. HHD test with a character LM (fixed setting) — CER with and without punctuation, WER"
|
| 1010 |
+
]
|
| 1011 |
+
},
|
| 1012 |
+
{
|
| 1013 |
+
"cell_type": "code",
|
| 1014 |
+
"execution_count": null,
|
| 1015 |
+
"id": "195c7a52",
|
| 1016 |
+
"metadata": {
|
| 1017 |
+
"papermill": {
|
| 1018 |
+
"duration": null,
|
| 1019 |
+
"end_time": null,
|
| 1020 |
+
"exception": null,
|
| 1021 |
+
"start_time": null,
|
| 1022 |
+
"status": "pending"
|
| 1023 |
+
},
|
| 1024 |
+
"tags": []
|
| 1025 |
+
},
|
| 1026 |
+
"outputs": [],
|
| 1027 |
+
"source": [
|
| 1028 |
+
"%%writefile charlm.py\n",
|
| 1029 |
+
"# -*- coding: utf-8 -*-\n",
|
| 1030 |
+
"\"\"\"Character n-gram language model with interpolated Kneser-Ney smoothing -- our own\n",
|
| 1031 |
+
"implementation (training + querying), used for shallow fusion in CTC beam search.\n",
|
| 1032 |
+
"\n",
|
| 1033 |
+
"Training is vectorised with numpy: every n-gram of order <= N is hashed into one int64 key\n",
|
| 1034 |
+
"(base 256, one \"digit\" per character code), counted with np.unique, and turned into\n",
|
| 1035 |
+
"interpolated-KN probabilities stored ARPA-style -- log P(w | h) for every kept n-gram and a log\n",
|
| 1036 |
+
"back-off weight for every kept history. Querying walks from the longest context down:\n",
|
| 1037 |
+
" P(w | h) = P_n(w | h) if the n-gram (h, w) is stored\n",
|
| 1038 |
+
" = bow(h) * P(w | h[1:]) otherwise (bow = 1 if h is unseen)\n",
|
| 1039 |
+
"Interpolated KN (Chen & Goodman 1999): the top order uses raw counts, lower orders use\n",
|
| 1040 |
+
"continuation counts N1+(. g); one absolute discount per order, D = n1 / (n1 + 2 n2).\n",
|
| 1041 |
+
"\n",
|
| 1042 |
+
"Lines are left-padded with N-1 <s> symbols, so the first characters of a line have context and\n",
|
| 1043 |
+
"every lower-order n-gram has a left extension. Saved as .npz (plain arrays, no pickle).\n",
|
| 1044 |
+
"\"\"\"\n",
|
| 1045 |
+
"\n",
|
| 1046 |
+
"import functools\n",
|
| 1047 |
+
"import math\n",
|
| 1048 |
+
"import re\n",
|
| 1049 |
+
"import unicodedata\n",
|
| 1050 |
+
"\n",
|
| 1051 |
+
"import numpy as np\n",
|
| 1052 |
+
"\n",
|
| 1053 |
+
"B = 256 # key base: one byte per character code\n",
|
| 1054 |
+
"DICT_MAX = 2_000_000 # tables up to this size become Python dicts (fast); larger stay arrays\n",
|
| 1055 |
+
"\n",
|
| 1056 |
+
"\n",
|
| 1057 |
+
"class _Table:\n",
|
| 1058 |
+
" \"\"\"key -> value lookup over sorted int64 keys: a dict for small tables, binary search else.\"\"\"\n",
|
| 1059 |
+
"\n",
|
| 1060 |
+
" def __init__(self, keys, vals, as_dict):\n",
|
| 1061 |
+
" self.d = dict(zip(keys.tolist(), vals.tolist())) if as_dict else None\n",
|
| 1062 |
+
" self.k, self.v = keys, vals\n",
|
| 1063 |
+
"\n",
|
| 1064 |
+
" def get(self, key, default=None):\n",
|
| 1065 |
+
" if self.d is not None:\n",
|
| 1066 |
+
" return self.d.get(key, default)\n",
|
| 1067 |
+
" i = int(np.searchsorted(self.k, key))\n",
|
| 1068 |
+
" return float(self.v[i]) if i < len(self.k) and int(self.k[i]) == key else default\n",
|
| 1069 |
+
"\n",
|
| 1070 |
+
" def __len__(self):\n",
|
| 1071 |
+
" return len(self.k)\n",
|
| 1072 |
+
"BOS = 255 # <s> code; real characters are 1..len(alphabet)\n",
|
| 1073 |
+
"\n",
|
| 1074 |
+
"\n",
|
| 1075 |
+
"# ---- text normalisation shared by training and decoding ------------------------------------\n",
|
| 1076 |
+
"_MAP = str.maketrans({\"״\": '\"', \"׳\": \"'\", \"־\": \"-\", \"–\": \"-\", \"—\": \"-\", \"‒\": \"-\", \"―\": \"-\",\n",
|
| 1077 |
+
" \"“\": '\"', \"”\": '\"', \"„\": '\"', \"‘\": \"'\", \"’\": \"'\", \" \": \" \"})\n",
|
| 1078 |
+
"_NIQQUD = re.compile(r\"[֑-ׇ]\")\n",
|
| 1079 |
+
"\n",
|
| 1080 |
+
"\n",
|
| 1081 |
+
"def normalize(text: str) -> str:\n",
|
| 1082 |
+
" \"\"\"NFC, Hebrew points and cantillation removed, gershayim/geresh/maqaf/typographic quotes and\n",
|
| 1083 |
+
" dashes mapped to ASCII, whitespace collapsed.\"\"\"\n",
|
| 1084 |
+
" t = _NIQQUD.sub(\"\", unicodedata.normalize(\"NFC\", text)).translate(_MAP)\n",
|
| 1085 |
+
" return re.sub(r\"\\s+\", \" \", t).strip()\n",
|
| 1086 |
+
"\n",
|
| 1087 |
+
"\n",
|
| 1088 |
+
"class CharKN:\n",
|
| 1089 |
+
" def __init__(self, alphabet: str, order: int, logp: list, bow: list):\n",
|
| 1090 |
+
" self.alphabet, self.N = alphabet, order\n",
|
| 1091 |
+
" self.code = {c: i + 1 for i, c in enumerate(alphabet)}\n",
|
| 1092 |
+
" # per order n (index n-1): sorted keys + values (compact); small orders also as dicts\n",
|
| 1093 |
+
" self._arr_p = [(np.asarray(k, np.int64), np.asarray(v, np.float32)) for k, v in logp]\n",
|
| 1094 |
+
" self._arr_b = [(np.asarray(k, np.int64), np.asarray(v, np.float32)) for k, v in bow]\n",
|
| 1095 |
+
" self.logp = [_Table(k, v, as_dict=len(k) <= DICT_MAX) for k, v in self._arr_p]\n",
|
| 1096 |
+
" self.bow = [_Table(k, v, as_dict=len(k) <= DICT_MAX) for k, v in self._arr_b]\n",
|
| 1097 |
+
" # never-seen character: the unigram level's share for unseen symbols, spread uniformly\n",
|
| 1098 |
+
" self.unk = (float(self._arr_b[0][1][0]) if len(self._arr_b[0][1]) else 0.0) - math.log(max(1, len(alphabet)))\n",
|
| 1099 |
+
"\n",
|
| 1100 |
+
" # ---- querying ------------------------------------------------------------------------\n",
|
| 1101 |
+
" def logprob(self, context: str, char: str) -> float:\n",
|
| 1102 |
+
" \"\"\"ln P(char | context); `context` is the text so far (any length).\"\"\"\n",
|
| 1103 |
+
" return self._lp(context[-(self.N - 1):] if self.N > 1 else \"\", char)\n",
|
| 1104 |
+
"\n",
|
| 1105 |
+
" @functools.lru_cache(maxsize=200_000)\n",
|
| 1106 |
+
" def _lp(self, ctx: str, char: str) -> float:\n",
|
| 1107 |
+
" w = self.code.get(char)\n",
|
| 1108 |
+
" if w is None:\n",
|
| 1109 |
+
" return self.unk\n",
|
| 1110 |
+
" codes = [self.code.get(c, 0) for c in ctx]\n",
|
| 1111 |
+
" if 0 in codes: # unknown char: context restarts after it\n",
|
| 1112 |
+
" codes = codes[len(codes) - codes[::-1].index(0):]\n",
|
| 1113 |
+
" codes = [BOS] * (self.N - 1 - len(codes)) + codes\n",
|
| 1114 |
+
" acc = 0.0\n",
|
| 1115 |
+
" for n in range(self.N, 0, -1): # longest context first\n",
|
| 1116 |
+
" h = codes[len(codes) - (n - 1):] if n > 1 else []\n",
|
| 1117 |
+
" hk = 0\n",
|
| 1118 |
+
" for c in h:\n",
|
| 1119 |
+
" hk = hk * B + c\n",
|
| 1120 |
+
" gk = hk * B + w\n",
|
| 1121 |
+
" lp = self.logp[n - 1].get(gk)\n",
|
| 1122 |
+
" if lp is not None:\n",
|
| 1123 |
+
" return acc + lp\n",
|
| 1124 |
+
" if n > 1:\n",
|
| 1125 |
+
" acc += self.bow[n - 1].get(hk, 0.0)\n",
|
| 1126 |
+
" return acc + self.unk # acc already holds every bow on the way down\n",
|
| 1127 |
+
"\n",
|
| 1128 |
+
" # ---- persistence ---------------------------------------------------------------------\n",
|
| 1129 |
+
" def save(self, path):\n",
|
| 1130 |
+
" arrs = {\"alphabet\": np.array(self.alphabet), \"order\": np.array(self.N)}\n",
|
| 1131 |
+
" for n in range(self.N):\n",
|
| 1132 |
+
" for name, (k, v) in ((\"p\", self._arr_p[n]), (\"b\", self._arr_b[n])):\n",
|
| 1133 |
+
" arrs[f\"{name}{n+1}_k\"], arrs[f\"{name}{n+1}_v\"] = k, v\n",
|
| 1134 |
+
" np.savez_compressed(path, **arrs)\n",
|
| 1135 |
+
"\n",
|
| 1136 |
+
" @classmethod\n",
|
| 1137 |
+
" def load(cls, path):\n",
|
| 1138 |
+
" z = np.load(path, allow_pickle=False)\n",
|
| 1139 |
+
" N = int(z[\"order\"])\n",
|
| 1140 |
+
" return cls(str(z[\"alphabet\"]), N,\n",
|
| 1141 |
+
" [(z[f\"p{n}_k\"], z[f\"p{n}_v\"]) for n in range(1, N + 1)],\n",
|
| 1142 |
+
" [(z[f\"b{n}_k\"], z[f\"b{n}_v\"]) for n in range(1, N + 1)])\n",
|
| 1143 |
+
"\n",
|
| 1144 |
+
"\n",
|
| 1145 |
+
"# ---- training ------------------------------------------------------------------------------\n",
|
| 1146 |
+
"def _encode(lines, code, N):\n",
|
| 1147 |
+
" \"\"\"-> one int16 array: each line = (N-1) x <s> + its codes, lines separated by 0.\"\"\"\n",
|
| 1148 |
+
" parts = []\n",
|
| 1149 |
+
" pad = [BOS] * (N - 1)\n",
|
| 1150 |
+
" for ln in lines:\n",
|
| 1151 |
+
" parts.append(np.array(pad + [code[c] for c in ln] + [0], np.int64))\n",
|
| 1152 |
+
" return np.concatenate(parts) if parts else np.zeros(0, np.int64)\n",
|
| 1153 |
+
"\n",
|
| 1154 |
+
"\n",
|
| 1155 |
+
"def _count(arr, n):\n",
|
| 1156 |
+
" \"\"\"Unique n-gram keys (no separator inside, not ending in <s>) with their counts.\"\"\"\n",
|
| 1157 |
+
" L = len(arr) - n + 1\n",
|
| 1158 |
+
" if L <= 0:\n",
|
| 1159 |
+
" return np.zeros(0, np.int64), np.zeros(0, np.int64)\n",
|
| 1160 |
+
" key = np.zeros(L, np.int64); ok = np.ones(L, bool)\n",
|
| 1161 |
+
" for j in range(n):\n",
|
| 1162 |
+
" seg = arr[j:j + L]\n",
|
| 1163 |
+
" key = key * B + seg; ok &= seg != 0\n",
|
| 1164 |
+
" ok &= arr[n - 1:n - 1 + L] != BOS # never predict <s>\n",
|
| 1165 |
+
" return np.unique(key[ok], return_counts=True)\n",
|
| 1166 |
+
"\n",
|
| 1167 |
+
"\n",
|
| 1168 |
+
"def train(lines, alphabet: str, order: int = 6, prune_min=(1, 1, 1, 2, 2, 2), chunk_chars=8_000_000, log=print):\n",
|
| 1169 |
+
" code = {c: i + 1 for i, c in enumerate(alphabet)}\n",
|
| 1170 |
+
" assert len(alphabet) < BOS\n",
|
| 1171 |
+
" # 1. raw counts per order, chunked, merged\n",
|
| 1172 |
+
" raw = [None] * order\n",
|
| 1173 |
+
" buf, size = [], 0\n",
|
| 1174 |
+
" def flush():\n",
|
| 1175 |
+
" arr = _encode(buf, code, order)\n",
|
| 1176 |
+
" for n in range(1, order + 1):\n",
|
| 1177 |
+
" k, c = _count(arr, n)\n",
|
| 1178 |
+
" if raw[n - 1] is None:\n",
|
| 1179 |
+
" raw[n - 1] = (k, c)\n",
|
| 1180 |
+
" else:\n",
|
| 1181 |
+
" kk = np.concatenate([raw[n - 1][0], k]); cc = np.concatenate([raw[n - 1][1], c])\n",
|
| 1182 |
+
" u, inv = np.unique(kk, return_inverse=True)\n",
|
| 1183 |
+
" raw[n - 1] = (u, np.bincount(inv, weights=cc).astype(np.int64))\n",
|
| 1184 |
+
" for ln in lines:\n",
|
| 1185 |
+
" buf.append(ln); size += len(ln)\n",
|
| 1186 |
+
" if size >= chunk_chars:\n",
|
| 1187 |
+
" flush(); buf, size = [], 0; log(f\" counted ... {len(raw[-1][0]):,} distinct {order}-grams\")\n",
|
| 1188 |
+
" if buf:\n",
|
| 1189 |
+
" flush()\n",
|
| 1190 |
+
" # 2. KN \"counts\": raw at the top order, continuation counts below\n",
|
| 1191 |
+
" a = [None] * order\n",
|
| 1192 |
+
" a[order - 1] = raw[order - 1]\n",
|
| 1193 |
+
" for n in range(order - 1, 0, -1):\n",
|
| 1194 |
+
" k_up = raw[n][0] # distinct (n+1)-grams\n",
|
| 1195 |
+
" suf = k_up % (B ** n) # drop their first character\n",
|
| 1196 |
+
" u, c = np.unique(suf, return_counts=True)\n",
|
| 1197 |
+
" a[n - 1] = (u, c.astype(np.int64))\n",
|
| 1198 |
+
" # 3. interpolated KN probabilities, lowest order first\n",
|
| 1199 |
+
" V = len(alphabet)\n",
|
| 1200 |
+
" logp, bow = [], []\n",
|
| 1201 |
+
" P_prev = None # (sorted keys, probs) of order n-1\n",
|
| 1202 |
+
" for n in range(1, order + 1):\n",
|
| 1203 |
+
" k, c = a[n - 1]\n",
|
| 1204 |
+
" n1, n2 = int((c == 1).sum()), int((c == 2).sum())\n",
|
| 1205 |
+
" D = n1 / (n1 + 2 * n2) if n1 + 2 * n2 > 0 else 0.5\n",
|
| 1206 |
+
" hist = k // B\n",
|
| 1207 |
+
" hu, hinv = np.unique(hist, return_inverse=True)\n",
|
| 1208 |
+
" denom = np.bincount(hinv, weights=c)\n",
|
| 1209 |
+
" nfollow = np.bincount(hinv)\n",
|
| 1210 |
+
" bw = D * nfollow / denom # interpolation weight per history\n",
|
| 1211 |
+
" if n == 1:\n",
|
| 1212 |
+
" lower = np.full(len(k), 1.0 / V)\n",
|
| 1213 |
+
" else:\n",
|
| 1214 |
+
" idx = np.searchsorted(P_prev[0], k % (B ** (n - 1)))\n",
|
| 1215 |
+
" lower = P_prev[1][idx]\n",
|
| 1216 |
+
" p = np.maximum(c - D, 0) / denom[hinv] + bw[hinv] * lower\n",
|
| 1217 |
+
" P_prev = (k, p)\n",
|
| 1218 |
+
" keep = c >= prune_min[n - 1]\n",
|
| 1219 |
+
" logp.append((k[keep], np.log(p[keep]).astype(np.float32)))\n",
|
| 1220 |
+
" hk = hu if n > 1 else np.array([0], np.int64)\n",
|
| 1221 |
+
" bow.append((hk, np.log(bw).astype(np.float32) if n > 1 else np.log(bw[:1]).astype(np.float32)))\n",
|
| 1222 |
+
" log(f\" order {n}: D={D:.3f} | {len(k):,} n-grams ({int(keep.sum()):,} kept) | {len(hu):,} histories\")\n",
|
| 1223 |
+
" return CharKN(alphabet, order, logp, bow)\n"
|
| 1224 |
+
]
|
| 1225 |
+
},
|
| 1226 |
+
{
|
| 1227 |
+
"cell_type": "code",
|
| 1228 |
+
"execution_count": null,
|
| 1229 |
+
"id": "6f1e7438",
|
| 1230 |
+
"metadata": {
|
| 1231 |
+
"papermill": {
|
| 1232 |
+
"duration": null,
|
| 1233 |
+
"end_time": null,
|
| 1234 |
+
"exception": null,
|
| 1235 |
+
"start_time": null,
|
| 1236 |
+
"status": "pending"
|
| 1237 |
+
},
|
| 1238 |
+
"tags": []
|
| 1239 |
+
},
|
| 1240 |
+
"outputs": [],
|
| 1241 |
+
"source": [
|
| 1242 |
+
"# ---- test-set decoding with a character LM: CTC prefix beam search (identical to exp38/eval_ctc_wordlm.py, word term off) ----\n",
|
| 1243 |
+
"import sys, multiprocessing as mp, unicodedata\n",
|
| 1244 |
+
"sys.path.insert(0, os.getcwd())\n",
|
| 1245 |
+
"import charlm\n",
|
| 1246 |
+
"NEG = -1e30\n",
|
| 1247 |
+
"LM = charlm.CharKN.load(hf_hub_download(LM_REPO, LM_FILE))\n",
|
| 1248 |
+
"def _lse(a, b):\n",
|
| 1249 |
+
" if a < b: a, b = b, a\n",
|
| 1250 |
+
" return a if b <= NEG else a + math.log1p(math.exp(b - a))\n",
|
| 1251 |
+
"GG = {\"chars\": CHARS, \"lm\": LM, \"beam\": 12}\n",
|
| 1252 |
+
"def beam_search(args):\n",
|
| 1253 |
+
" logprobs_, length, alpha, beta = args\n",
|
| 1254 |
+
" chars, lm = GG[\"chars\"], GG[\"lm\"]; beam, top_k, min_logp, blank = GG[\"beam\"], 8, -12.0, 0\n",
|
| 1255 |
+
" lp = np.asarray(logprobs_[:length], np.float64); lm_cache = {}\n",
|
| 1256 |
+
" def fuse(prefix, c):\n",
|
| 1257 |
+
" key = (prefix[-12:], c); v = lm_cache.get(key)\n",
|
| 1258 |
+
" if v is None:\n",
|
| 1259 |
+
" v = alpha * lm.logprob(prefix, c) + beta; lm_cache[key] = v\n",
|
| 1260 |
+
" return v\n",
|
| 1261 |
+
" beams = {\"\": (0.0, NEG)}\n",
|
| 1262 |
+
" for t in range(lp.shape[0]):\n",
|
| 1263 |
+
" row = lp[t]; cand = np.argpartition(row, -top_k)[-top_k:]; cand = [int(k) for k in cand if row[k] > min_logp]; nxt = {}\n",
|
| 1264 |
+
" for prefix, (pb, pnb) in beams.items():\n",
|
| 1265 |
+
" ptot = _lse(pb, pnb)\n",
|
| 1266 |
+
" for k in cand:\n",
|
| 1267 |
+
" p = row[k]\n",
|
| 1268 |
+
" if k == blank:\n",
|
| 1269 |
+
" b, nb = nxt.get(prefix, (NEG, NEG)); nxt[prefix] = (_lse(b, ptot + p), nb); continue\n",
|
| 1270 |
+
" c = chars[k]\n",
|
| 1271 |
+
" if prefix and c == prefix[-1]:\n",
|
| 1272 |
+
" b, nb = nxt.get(prefix, (NEG, NEG)); nxt[prefix] = (b, _lse(nb, pnb + p)); src = pb\n",
|
| 1273 |
+
" else:\n",
|
| 1274 |
+
" src = ptot\n",
|
| 1275 |
+
" if src <= NEG: continue\n",
|
| 1276 |
+
" ext = prefix + c; b, nb = nxt.get(ext, (NEG, NEG)); nxt[ext] = (b, _lse(nb, src + p + fuse(prefix, c)))\n",
|
| 1277 |
+
" beams = dict(sorted(nxt.items(), key=lambda kv: _lse(*kv[1]), reverse=True)[:beam]) or {\"\": (0.0, NEG)}\n",
|
| 1278 |
+
" return max(beams.items(), key=lambda kv: _lse(*kv[1]))[0]\n",
|
| 1279 |
+
"\n",
|
| 1280 |
+
"def scores_full(R, H):\n",
|
| 1281 |
+
" \"\"\"CER with punctuation (raw), CER without punctuation (every Unicode punctuation character removed from reference AND hypothesis),\n",
|
| 1282 |
+
" WER on the raw text. Lines whose reference is empty are skipped.\"\"\"\n",
|
| 1283 |
+
" nop = lambda t: re.sub(r\" +\", \" \", \"\".join(c for c in t if not unicodedata.category(c).startswith(\"P\"))).strip()\n",
|
| 1284 |
+
" def cer_of(f):\n",
|
| 1285 |
+
" k = [i for i in range(len(R)) if f(R[i]).strip()]\n",
|
| 1286 |
+
" return jiwer.cer([f(R[i]) for i in k], [f(H[i]) for i in k])\n",
|
| 1287 |
+
" k = [i for i, r in enumerate(R) if r.strip()]\n",
|
| 1288 |
+
" return {\"cer\": jiwer.cer([R[i] for i in k], [H[i] for i in k]), \"wer\": jiwer.wer([R[i] for i in k], [H[i] for i in k]), \"cer_nopunct\": cer_of(nop)}\n",
|
| 1289 |
+
"\n",
|
| 1290 |
+
"@torch.no_grad()\n",
|
| 1291 |
+
"def test_logprobs(model, split):\n",
|
| 1292 |
+
" model.eval(); out, R = [], []\n",
|
| 1293 |
+
" for px, cols, _, texts in loader(split, False, EVAL_BS):\n",
|
| 1294 |
+
" with torch.autocast(\"cuda\", dtype=AMP_DTYPE, enabled=device == \"cuda\"):\n",
|
| 1295 |
+
" lp = model(px.to(device))\n",
|
| 1296 |
+
" lp = lp.float().cpu().numpy(); out += [(lp[i], int(cols[i]) * SUB) for i in range(len(texts))]; R += texts\n",
|
| 1297 |
+
" return out, R\n",
|
| 1298 |
+
"\n",
|
| 1299 |
+
"if RUN_FINAL:\n",
|
| 1300 |
+
" L, R = test_logprobs(model, test)\n",
|
| 1301 |
+
" final_decoding = {\"greedy (no LM)\": scores_full(R, [greedy(lp, n) for lp, n in L])}\n",
|
| 1302 |
+
" for bw in LM_BEAMS:\n",
|
| 1303 |
+
" GG[\"beam\"] = bw\n",
|
| 1304 |
+
" with mp.get_context(\"fork\").Pool(os.cpu_count()) as pool:\n",
|
| 1305 |
+
" H = pool.map(beam_search, [(lp, n, LM_ALPHA, LM_BETA) for lp, n in L], chunksize=8)\n",
|
| 1306 |
+
" final_decoding[f\"beam {bw} + LM (alpha {LM_ALPHA}, beta {LM_BETA})\"] = scores_full(R, H)\n",
|
| 1307 |
+
" with open(os.path.join(OUT, f\"test_predictions_beam{bw}.tsv\"), \"w\", encoding=\"utf-8\") as fh:\n",
|
| 1308 |
+
" fh.write(\"ref\\thyp\\n\"); [fh.write(f\"{r}\\t{h}\\n\") for r, h in zip(R, H)]\n",
|
| 1309 |
+
" results[\"final\"][\"test_decoding\"] = final_decoding\n",
|
| 1310 |
+
" print(\"HHD TEST\", \"(LM = \" + LM_REPO + \"/\" + LM_FILE + \")\")\n",
|
| 1311 |
+
" for name, s in final_decoding.items():\n",
|
| 1312 |
+
" print(f\" {name:48s} CER {100*s['cer']:.2f} | CER w/o punct {100*s['cer_nopunct']:.2f} | WER {100*s['wer']:.2f}\")\n",
|
| 1313 |
+
" json.dump(results, open(os.path.join(OUT, \"results.json\"), \"w\"), indent=1)\n"
|
| 1314 |
+
]
|
| 1315 |
+
},
|
| 1316 |
+
{
|
| 1317 |
+
"cell_type": "markdown",
|
| 1318 |
+
"id": "8927bff1",
|
| 1319 |
+
"metadata": {
|
| 1320 |
+
"papermill": {
|
| 1321 |
+
"duration": null,
|
| 1322 |
+
"end_time": null,
|
| 1323 |
+
"exception": null,
|
| 1324 |
+
"start_time": null,
|
| 1325 |
+
"status": "pending"
|
| 1326 |
+
},
|
| 1327 |
+
"tags": []
|
| 1328 |
+
},
|
| 1329 |
+
"source": [
|
| 1330 |
+
"### 9. Save to the public HF repo"
|
| 1331 |
+
]
|
| 1332 |
+
},
|
| 1333 |
+
{
|
| 1334 |
+
"cell_type": "code",
|
| 1335 |
+
"execution_count": null,
|
| 1336 |
+
"id": "612d1f05",
|
| 1337 |
+
"metadata": {
|
| 1338 |
+
"papermill": {
|
| 1339 |
+
"duration": null,
|
| 1340 |
+
"end_time": null,
|
| 1341 |
+
"exception": null,
|
| 1342 |
+
"start_time": null,
|
| 1343 |
+
"status": "pending"
|
| 1344 |
+
},
|
| 1345 |
+
"tags": []
|
| 1346 |
+
},
|
| 1347 |
+
"outputs": [],
|
| 1348 |
+
"source": [
|
| 1349 |
+
"from safetensors.torch import save_file\n",
|
| 1350 |
+
"json.dump({\"chars\": CHARS}, open(os.path.join(OUT, \"charset.json\"), \"w\"), ensure_ascii=False)\n",
|
| 1351 |
+
"if RUN_FINAL: # weights of the FINAL model (full train set, last epoch); the select-phase model is not kept\n",
|
| 1352 |
+
" save_file({k: v.contiguous() for k, v in model.state_dict().items()}, os.path.join(OUT, \"model.safetensors\"))\n",
|
| 1353 |
+
"if PUSH and not SMOKE:\n",
|
| 1354 |
+
" api = HfApi(); api.create_repo(OUT_REPO, private=False, exist_ok=True)\n",
|
| 1355 |
+
" api.upload_folder(repo_id=OUT_REPO, folder_path=OUT, commit_message=\"exp39 TrOCR-CTC, bandit data mixer (DiffusionPen vs fonts, 20k texts), HHD test\")\n",
|
| 1356 |
+
" print(\"pushed -> https://huggingface.co/\" + OUT_REPO)\n",
|
| 1357 |
+
"else:\n",
|
| 1358 |
+
" print(\"not pushed (SMOKE or PUSH=False); files in\", OUT)"
|
| 1359 |
+
]
|
| 1360 |
+
}
|
| 1361 |
+
],
|
| 1362 |
+
"metadata": {
|
| 1363 |
+
"accelerator": "GPU",
|
| 1364 |
+
"kernelspec": {
|
| 1365 |
+
"display_name": "Python 3",
|
| 1366 |
+
"name": "python3"
|
| 1367 |
+
},
|
| 1368 |
+
"language_info": {
|
| 1369 |
+
"codemirror_mode": {
|
| 1370 |
+
"name": "ipython",
|
| 1371 |
+
"version": 3
|
| 1372 |
+
},
|
| 1373 |
+
"file_extension": ".py",
|
| 1374 |
+
"mimetype": "text/x-python",
|
| 1375 |
+
"name": "python",
|
| 1376 |
+
"nbconvert_exporter": "python",
|
| 1377 |
+
"pygments_lexer": "ipython3",
|
| 1378 |
+
"version": "3.12.3"
|
| 1379 |
+
},
|
| 1380 |
+
"papermill": {
|
| 1381 |
+
"default_parameters": {},
|
| 1382 |
+
"duration": 725.466766,
|
| 1383 |
+
"end_time": "2026-10-22T19:19:49.438679+00:00",
|
| 1384 |
+
"environment_variables": {},
|
| 1385 |
+
"exception": true,
|
| 1386 |
+
"input_path": "/home/romanva1/hwrt-exp-trocr-ctc/diffpen_words/exp39_bandit20k_diffpenaug_uni10aug_hhdgeom_llmgen_seed43_colab.ipynb",
|
| 1387 |
+
"output_path": "/home/romanva1/work/queue_fontfill/exp39_bandit20k_diffpenaug_uni10aug_hhdgeom_llmgen_seed43/exp39_bandit20k_diffpenaug_uni10aug_hhdgeom_llmgen_seed43_colab.ipynb",
|
| 1388 |
+
"parameters": {},
|
| 1389 |
+
"start_time": "2026-10-22T19:07:43.971913+00:00",
|
| 1390 |
+
"version": "2.7.0"
|
| 1391 |
+
}
|
| 1392 |
+
},
|
| 1393 |
+
"nbformat": 4,
|
| 1394 |
+
"nbformat_minor": 5
|
| 1395 |
+
}
|