BeardedMonster commited on
Commit
ffdc21e
·
verified ·
1 Parent(s): d8e5d37

Standalone in-process notebook; train split also loads train_extra

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. generate_train_extra.ipynb +111 -107
README.md CHANGED
@@ -62,7 +62,7 @@ configs:
62
  - config_name: default
63
  data_files:
64
  - split: train
65
- path: data/train.jsonl.gz
66
  - split: test
67
  path: data/test.jsonl.gz
68
  ---
 
62
  - config_name: default
63
  data_files:
64
  - split: train
65
+ path: data/train*.jsonl.gz
66
  - split: test
67
  path: data/test.jsonl.gz
68
  ---
generate_train_extra.ipynb CHANGED
@@ -20,33 +20,37 @@
20
  "cell_type": "markdown",
21
  "metadata": {},
22
  "source": [
23
- "# Grow the train set with new English texts\n",
24
  "\n",
25
- "This notebook writes code-switched (`hm`) and idiom-rich (`ood`) versions of the new English texts in\n",
26
- "[`AletheiaAING/african-code-switch-benchmark`](https://huggingface.co/datasets/AletheiaAING/african-code-switch-benchmark), using our 8-bit model\n",
27
- "[`AletheiaAING/gemma-3-0.8b-csw`](https://huggingface.co/AletheiaAING/gemma-3-0.8b-csw) with llama.cpp.\n",
28
  "\n",
29
- "**What it does**\n",
30
- "1. Builds llama.cpp with CUDA and starts a local server with the 8-bit model.\n",
31
- "2. Reads `data/new_english_prompts.jsonl.gz` from the dataset repo: about 25,000 new English texts, each assigned a base language and a switch language, so 2 prompts per text.\n",
32
- "3. Generates `N_CANDIDATES` candidates per prompt (the first is greedy, the rest are sampled) and cleans them into the same columns as the train set (`candidates`, `output`, ...).\n",
33
- "4. Saves shards as it goes, so you can stop and resume. Writes `train_extra.jsonl.gz` at the end and can upload it to the dataset repo.\n",
34
  "\n",
35
- "**Runtime.** Use a GPU runtime (T4 is enough). Speed is roughly 1,000 to 2,000 generated tokens per second on a T4, so with `N_CANDIDATES = 2` expect around 6 to 8 hours for everything. Run a part first with `MAX_TEXTS` and raise it later. Rows have no `ev` score, because the scoring model is private."
 
 
36
  ]
37
  },
38
  {
39
  "cell_type": "code",
40
  "metadata": {},
41
  "source": [
42
- "import subprocess, shutil, os\n",
43
- "# Build llama.cpp with CUDA (about 10 minutes the first time)\n",
44
- "if not os.path.exists(\"llama.cpp/build/bin/llama-server\"):\n",
45
- " subprocess.run(\"git clone --depth 1 https://github.com/ggml-org/llama.cpp\", shell=True, check=True)\n",
46
- " subprocess.run(\"cmake -S llama.cpp -B llama.cpp/build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=native -DLLAMA_CURL=OFF\", shell=True, check=True)\n",
47
- " subprocess.run(\"cmake --build llama.cpp/build --config Release -j 4 --target llama-server\", shell=True, check=True)\n",
 
 
 
48
  "subprocess.run(\"pip -q install huggingface_hub\", shell=True, check=True)\n",
49
- "print(\"ready\")"
50
  ],
51
  "outputs": [],
52
  "execution_count": null
@@ -56,14 +60,14 @@
56
  "metadata": {},
57
  "source": [
58
  "# ---- settings ----\n",
59
- "DATASET = \"AletheiaAING/african-code-switch-benchmark\"\n",
60
- "MODEL = \"AletheiaAING/gemma-3-0.8b-csw\"\n",
61
- "GGUF = \"csw-gemma3-1b-rl3-pruned-Q8_0.gguf\"\n",
62
- "N_CANDIDATES = 2 # 1 greedy + (N-1) sampled at temperature 0.8. The main dataset has 8; raise it if you have time.\n",
63
- "MAX_TEXTS = None # for a quick test use e.g. 200; None = all texts\n",
64
- "PARALLEL = 16 # simultaneous requests handled by the server\n",
65
- "SAVE_DIR = \"/content/drive/MyDrive/csw_extra\" # shards are saved here so a disconnect doesn't lose work\n",
66
- "UPLOAD = False # True: upload train_extra.jsonl.gz to the dataset repo at the end (needs an HF write token in Colab secrets named HF_TOKEN)"
67
  ],
68
  "outputs": [],
69
  "execution_count": null
@@ -72,13 +76,19 @@
72
  "cell_type": "code",
73
  "metadata": {},
74
  "source": [
75
- "# Save shards to Google Drive (skip this cell to save to the local disk instead)\n",
 
 
 
76
  "try:\n",
77
- " from google.colab import drive\n",
78
- " drive.mount(\"/content/drive\")\n",
79
- "except Exception as e:\n",
80
- " SAVE_DIR = \"csw_extra\"; print(\"no Drive, saving to\", SAVE_DIR)\n",
81
- "os.makedirs(SAVE_DIR, exist_ok=True)"
 
 
 
82
  ],
83
  "outputs": [],
84
  "execution_count": null
@@ -87,16 +97,15 @@
87
  "cell_type": "code",
88
  "metadata": {},
89
  "source": [
90
- "import gzip, json, re, time, subprocess, threading, urllib.request, collections as C\n",
91
- "from concurrent.futures import ThreadPoolExecutor\n",
92
- "from huggingface_hub import hf_hub_download\n",
93
- "\n",
94
  "gguf_path = hf_hub_download(MODEL, GGUF)\n",
95
- "prompts_path = hf_hub_download(DATASET, \"data/new_english_prompts.jsonl.gz\", repo_type=\"dataset\")\n",
96
  "rows = [json.loads(l) for l in gzip.open(prompts_path, \"rt\", encoding=\"utf-8\")]\n",
97
  "if MAX_TEXTS:\n",
98
- " keep = sorted({r[\"id\"] for r in rows})[:MAX_TEXTS]; keep = set(keep); rows = [r for r in rows if r[\"id\"] in keep]\n",
99
- "print(len(rows), \"prompts,\", len({r[\"id\"] for r in rows}), \"texts,\", len({r[\"lang\"] for r in rows}), \"languages\")"
 
 
100
  ],
101
  "outputs": [],
102
  "execution_count": null
@@ -105,18 +114,15 @@
105
  "cell_type": "code",
106
  "metadata": {},
107
  "source": [
108
- "# Start the server with the 8-bit model (context is shared between the parallel slots)\n",
109
- "SERVER = os.environ.get(\"LLAMA_SERVER\", \"llama.cpp/build/bin/llama-server\")\n",
110
- "NGL = os.environ.get(\"NGL\", \"99\")\n",
111
- "proc = subprocess.Popen([SERVER, \"-m\", gguf_path, \"-c\", str(1536 * PARALLEL), \"-np\", str(PARALLEL), \"-ngl\", NGL, \"--port\", \"8089\", \"--host\", \"127.0.0.1\"],\n",
112
- " stdout=open(\"server.log\", \"w\"), stderr=subprocess.STDOUT)\n",
113
- "for _ in range(180):\n",
114
- " try:\n",
115
- " urllib.request.urlopen(\"http://127.0.0.1:8089/health\", timeout=2); break\n",
116
- " except Exception: time.sleep(2)\n",
117
- "else:\n",
118
- " raise RuntimeError(\"server did not start, see server.log\")\n",
119
- "print(\"server up\")"
120
  ],
121
  "outputs": [],
122
  "execution_count": null
@@ -126,52 +132,36 @@
126
  "metadata": {},
127
  "source": [
128
  "TAGS = re.compile(r\"^((?:<(?!/?dev>)\\w{1,8}>)+)\"); DEV = re.compile(r\"^\\s*<dev>(.*?)</dev>\", re.S)\n",
129
- "URL = \"http://127.0.0.1:8089/v1/chat/completions\"\n",
130
  "\n",
131
- "def ask(prompt, temperature, seed):\n",
132
- " body = {\"messages\": [{\"role\": \"user\", \"content\": prompt}], \"temperature\": temperature, \"max_tokens\": 640, \"seed\": seed}\n",
133
- " if temperature > 0: body[\"top_p\"] = 1.0; body[\"top_k\"] = 0\n",
134
- " req = urllib.request.Request(URL, json.dumps(body).encode(), {\"Content-Type\": \"application/json\"})\n",
135
- " for attempt in range(3):\n",
136
- " try:\n",
137
- " r = json.loads(urllib.request.urlopen(req, timeout=900).read())[\"choices\"][0]; return r[\"message\"][\"content\"], r.get(\"finish_reason\") == \"stop\"\n",
138
- " except Exception: time.sleep(2)\n",
139
- " return \"\", False\n",
140
  "\n",
141
- "def clean(text):\n",
142
- " c = text.replace(\"<end_of_turn>\", \"\").strip(); m = TAGS.match(c); c = c[m.end():].lstrip() if m else c\n",
143
- " d = DEV.match(c); return (c[d.end():].strip() if d else c), ([x.strip() for x in d.group(1).split(\"|\") if x.strip()] if d else [])\n",
 
144
  "\n",
145
  "def make_row(r):\n",
146
- " cands = []\n",
147
- " for k in range(N_CANDIDATES):\n",
148
- " text, finished = ask(r[\"prompt\"], 0.0 if k == 0 else 0.8, 1000 + k)\n",
149
- " final, devices = clean(text)\n",
150
- " c = {\"k\": k, \"greedy\": k == 0, \"text\": text, \"finished\": finished, \"devices\": devices, \"final\": final,\n",
151
- " \"format_ok\": bool(TAGS.match(text.strip()) and DEV.search(TAGS.sub(\"\", text.strip(), count=1).lstrip()) and final and finished)}\n",
152
- " cands.append(c)\n",
153
- " out = dict(r); out[\"pair_in_training_table\"] = True; out[\"candidates\"] = cands; out[\"output\"] = [c[\"final\"] for c in cands]\n",
154
- " return out"
155
- ],
156
- "outputs": [],
157
- "execution_count": null
158
- },
159
- {
160
- "cell_type": "code",
161
- "metadata": {},
162
- "source": [
163
- "# Generate in shards of 1,000 rows. Finished shards are skipped when you run this cell again.\n",
164
- "SHARD = 1000\n",
165
- "todo = sorted(rows, key=lambda r: (r[\"id\"], r[\"task\"]))\n",
166
- "t0 = time.time()\n",
167
- "for s in range(0, len(todo), SHARD):\n",
168
- " path = os.path.join(SAVE_DIR, f\"shard_{s // SHARD:04d}.jsonl.gz\")\n",
169
- " if os.path.exists(path): continue\n",
170
- " with ThreadPoolExecutor(PARALLEL) as ex: done = list(ex.map(make_row, todo[s:s + SHARD]))\n",
171
- " with gzip.open(path + \".tmp\", \"wt\", encoding=\"utf-8\") as fo:\n",
172
- " for r in done: fo.write(json.dumps(r, ensure_ascii=False) + \"\\n\")\n",
173
- " os.replace(path + \".tmp\", path)\n",
174
- " print(f\"shard {s // SHARD} done, {s + len(done)} / {len(todo)} rows, {(time.time() - t0) / 60:.1f} min\", flush=True)"
175
  ],
176
  "outputs": [],
177
  "execution_count": null
@@ -180,16 +170,20 @@
180
  "cell_type": "code",
181
  "metadata": {},
182
  "source": [
183
- "# Collect the shards into train_extra.jsonl.gz and print a summary\n",
184
- "import glob\n",
185
- "out_rows = [json.loads(l) for p in sorted(glob.glob(os.path.join(SAVE_DIR, \"shard_*.jsonl.gz\"))) for l in gzip.open(p, \"rt\", encoding=\"utf-8\")]\n",
186
- "final_path = os.path.join(SAVE_DIR, \"train_extra.jsonl.gz\")\n",
187
- "with gzip.open(final_path, \"wt\", encoding=\"utf-8\") as fo:\n",
188
- " for r in out_rows: fo.write(json.dumps(r, ensure_ascii=False) + \"\\n\")\n",
189
- "cs = [c for r in out_rows for c in r[\"candidates\"]]\n",
190
- "print(len(out_rows), \"rows,\", len(cs), \"candidates, format ok:\", round(sum(c[\"format_ok\"] for c in cs) / max(1, len(cs)), 3))\n",
191
- "print(C.Counter(r[\"lang\"] for r in out_rows).most_common(3), \"...\")\n",
192
- "r = out_rows[0]; print(r[\"prompt\"][:120]); print(r[\"output\"][0][:200])"
 
 
 
 
193
  ],
194
  "outputs": [],
195
  "execution_count": null
@@ -198,12 +192,22 @@
198
  "cell_type": "code",
199
  "metadata": {},
200
  "source": [
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  "if UPLOAD:\n",
202
- " from google.colab import userdata\n",
203
- " from huggingface_hub import HfApi\n",
204
- " HfApi(token=userdata.get(\"HF_TOKEN\")).upload_file(path_or_fileobj=final_path, path_in_repo=\"data/train_extra.jsonl.gz\", repo_id=DATASET, repo_type=\"dataset\", commit_message=\"Add generated train_extra\")\n",
205
- " print(\"uploaded\")\n",
206
- "proc.terminate()"
207
  ],
208
  "outputs": [],
209
  "execution_count": null
 
20
  "cell_type": "markdown",
21
  "metadata": {},
22
  "source": [
23
+ "# Grow the train set of the African Code-Switch Benchmark\n",
24
  "\n",
25
+ "This notebook runs **our 8-bit model on the Colab GPU itself** (no server, no API) to write code-switched (`hm`) and idiom-rich (`ood`) versions of about 20,000 new English texts, then **pushes the results to the dataset repo**\n",
26
+ "[`AletheiaAING/african-code-switch-benchmark`](https://huggingface.co/datasets/AletheiaAING/african-code-switch-benchmark).\n",
 
27
  "\n",
28
+ "**What happens**\n",
29
+ "1. The model [`AletheiaAING/gemma-3-0.8b-csw`](https://huggingface.co/AletheiaAING/gemma-3-0.8b-csw) (8-bit GGUF, 877 MB) is downloaded from the Hub and loaded on the GPU with `llama-cpp-python`.\n",
30
+ "2. The new English texts (`data/new_english_prompts.jsonl.gz` in the dataset repo, each with a base language and a switch language) are read and turned into rows.\n",
31
+ "3. Every 1,000 rows are written as one shard and uploaded to `data/train_extra/` in the dataset repo, so nothing is lost if Colab disconnects. Run the notebook again and it picks up where it stopped.\n",
32
+ "4. At the end the shards are merged into `data/train_extra.jsonl.gz`, which the dataset's `train` split loads.\n",
33
  "\n",
34
+ "**Before you run:** choose a GPU runtime (Runtime > Change runtime type > T4 GPU is enough) and add your Hugging Face **write** token as a Colab secret named `HF_TOKEN` (key icon in the left bar), or paste it when asked.\n",
35
+ "\n",
36
+ "**Time.** Several copies of the model run in parallel on the GPU. Expect very roughly 1,000 generated tokens per second on a T4, so about 3 to 5 hours for everything with `N_CANDIDATES = 2`. Test first with `MAX_TEXTS = 100`; a test run does not upload anything. New rows have no `ev` score, because the scoring model is private."
37
  ]
38
  },
39
  {
40
  "cell_type": "code",
41
  "metadata": {},
42
  "source": [
43
+ "import subprocess, sys\n",
44
+ "# Install llama-cpp-python with CUDA: try the prebuilt GPU wheel first, otherwise build it (about 10 minutes)\n",
45
+ "try:\n",
46
+ " import llama_cpp\n",
47
+ "except ImportError:\n",
48
+ " r = subprocess.run(\"pip -q install llama-cpp-python --only-binary=:all: --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124\", shell=True)\n",
49
+ " if r.returncode != 0:\n",
50
+ " subprocess.run('CMAKE_ARGS=\"-DGGML_CUDA=on\" pip -q install llama-cpp-python --no-cache-dir', shell=True, check=True)\n",
51
+ " import llama_cpp\n",
52
  "subprocess.run(\"pip -q install huggingface_hub\", shell=True, check=True)\n",
53
+ "print(\"llama-cpp-python\", llama_cpp.__version__, \"| GPU offload supported:\", llama_cpp.llama_supports_gpu_offload())"
54
  ],
55
  "outputs": [],
56
  "execution_count": null
 
60
  "metadata": {},
61
  "source": [
62
  "# ---- settings ----\n",
63
+ "DATASET = \"AletheiaAING/african-code-switch-benchmark\"\n",
64
+ "MODEL = \"AletheiaAING/gemma-3-0.8b-csw\"\n",
65
+ "GGUF = \"csw-gemma3-1b-rl3-pruned-Q8_0.gguf\"\n",
66
+ "N_CANDIDATES = 2 # 1 greedy + (N-1) sampled at temperature 0.8. The main dataset has 8 per row; raise it if you have time.\n",
67
+ "WORKERS = 6 # model copies running in parallel on the GPU (6 is fine on a T4; use 3 if you run out of GPU memory)\n",
68
+ "MAX_NEW = 640 # maximum new tokens per output\n",
69
+ "SHARD = 1000 # rows per uploaded shard\n",
70
+ "MAX_TEXTS = None # for a quick test use e.g. 100 (nothing is uploaded); None = all texts"
71
  ],
72
  "outputs": [],
73
  "execution_count": null
 
76
  "cell_type": "code",
77
  "metadata": {},
78
  "source": [
79
+ "import os, io, gzip, json, re, time, queue, glob, getpass, collections as C\n",
80
+ "from concurrent.futures import ThreadPoolExecutor\n",
81
+ "from huggingface_hub import HfApi, hf_hub_download\n",
82
+ "\n",
83
  "try:\n",
84
+ " from google.colab import userdata\n",
85
+ " HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
86
+ "except Exception:\n",
87
+ " HF_TOKEN = os.environ.get(\"HF_TOKEN\") or getpass.getpass(\"Hugging Face write token: \")\n",
88
+ "api = HfApi(token=HF_TOKEN)\n",
89
+ "print(\"logged in as\", api.whoami()[\"name\"])\n",
90
+ "UPLOAD = MAX_TEXTS is None\n",
91
+ "WORK = \"csw_extra\"; os.makedirs(WORK, exist_ok=True)"
92
  ],
93
  "outputs": [],
94
  "execution_count": null
 
97
  "cell_type": "code",
98
  "metadata": {},
99
  "source": [
100
+ "# Download the model and the new English prompts (runs once)\n",
 
 
 
101
  "gguf_path = hf_hub_download(MODEL, GGUF)\n",
102
+ "prompts_path = hf_hub_download(DATASET, \"data/new_english_prompts.jsonl.gz\", repo_type=\"dataset\", token=HF_TOKEN)\n",
103
  "rows = [json.loads(l) for l in gzip.open(prompts_path, \"rt\", encoding=\"utf-8\")]\n",
104
  "if MAX_TEXTS:\n",
105
+ " keep = set(sorted({r[\"id\"] for r in rows})[:MAX_TEXTS]); rows = [r for r in rows if r[\"id\"] in keep]\n",
106
+ "rows.sort(key=lambda r: (r[\"id\"], r[\"task\"]))\n",
107
+ "print(len(rows), \"prompts,\", len({r[\"id\"] for r in rows}), \"texts,\", len({r[\"lang\"] for r in rows}), \"languages\")\n",
108
+ "print(\"model file:\", gguf_path)"
109
  ],
110
  "outputs": [],
111
  "execution_count": null
 
114
  "cell_type": "code",
115
  "metadata": {},
116
  "source": [
117
+ "# Load WORKERS copies of the model on the GPU (each copy is about 1 GB)\n",
118
+ "from llama_cpp import Llama\n",
119
+ "N_GPU = int(os.environ.get(\"N_GPU_LAYERS\", \"-1\"))\n",
120
+ "pool = queue.Queue()\n",
121
+ "for _ in range(WORKERS):\n",
122
+ " pool.put(Llama(model_path=gguf_path, n_ctx=1536, n_gpu_layers=N_GPU, n_batch=512, verbose=False))\n",
123
+ "probe = pool.queue[0]\n",
124
+ "EOT = probe.tokenize(b\"<end_of_turn>\", add_bos=False, special=True)[0]; EOS = probe.token_eos()\n",
125
+ "print(\"loaded\", WORKERS, \"copies; end-of-turn token id\", EOT)"
 
 
 
126
  ],
127
  "outputs": [],
128
  "execution_count": null
 
132
  "metadata": {},
133
  "source": [
134
  "TAGS = re.compile(r\"^((?:<(?!/?dev>)\\w{1,8}>)+)\"); DEV = re.compile(r\"^\\s*<dev>(.*?)</dev>\", re.S)\n",
 
135
  "\n",
136
+ "def generate(llm, prompt, temperature, seed):\n",
137
+ " text = f\"<start_of_turn>user\\n{prompt}<end_of_turn>\\n<start_of_turn>model\\n\" # the Gemma chat format the model was trained on\n",
138
+ " toks = llm.tokenize(text.encode(\"utf-8\"), add_bos=True, special=True)\n",
139
+ " llm.set_seed(seed); out, finished = [], False\n",
140
+ " for t in llm.generate(toks, top_k=1 if temperature == 0 else 0, top_p=1.0, min_p=0.0, temp=temperature, repeat_penalty=1.0, reset=True):\n",
141
+ " if t in (EOT, EOS): finished = True; break\n",
142
+ " out.append(t)\n",
143
+ " if len(out) >= MAX_NEW: break\n",
144
+ " return llm.detokenize(out, special=True).decode(\"utf-8\", errors=\"ignore\").strip(), finished\n",
145
  "\n",
146
+ "def parse(text):\n",
147
+ " m = TAGS.match(text); has_tags = bool(m); c = text[m.end():].lstrip() if m else text\n",
148
+ " d = DEV.match(c); final = c[d.end():].strip() if d else c\n",
149
+ " return final, ([x.strip() for x in d.group(1).split(\"|\") if x.strip()] if d else []), bool(has_tags and d and final)\n",
150
  "\n",
151
  "def make_row(r):\n",
152
+ " llm = pool.get()\n",
153
+ " try:\n",
154
+ " cands = []\n",
155
+ " for k in range(N_CANDIDATES):\n",
156
+ " text, finished = generate(llm, r[\"prompt\"], 0.0 if k == 0 else 0.8, 1000 + k)\n",
157
+ " final, devices, ok = parse(text)\n",
158
+ " cands.append({\"k\": k, \"greedy\": k == 0, \"text\": text, \"finished\": finished, \"devices\": devices, \"final\": final,\n",
159
+ " \"format_ok\": ok and finished, \"ev\": None, \"system\": None, \"reward\": None, \"chrf\": None, \"judge\": None})\n",
160
+ " finally:\n",
161
+ " pool.put(llm)\n",
162
+ " return {\"id\": r[\"id\"], \"subset\": \"generated\", \"task\": r[\"task\"], \"task_type\": \"eng_\" + r[\"task\"], \"input_type\": \"english\", \"lang\": r[\"lang\"], \"switch\": r[\"switch\"],\n",
163
+ " \"pair_in_training_table\": True, \"prompt\": r[\"prompt\"], \"input\": r[\"english\"], \"english\": r[\"english\"], \"source_dataset\": r[\"source_dataset\"],\n",
164
+ " \"source_register\": r[\"source_register\"], \"reference\": None, \"reference_judge\": None, \"candidates\": cands, \"output\": [c[\"final\"] for c in cands]}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  ],
166
  "outputs": [],
167
  "execution_count": null
 
170
  "cell_type": "code",
171
  "metadata": {},
172
  "source": [
173
+ "# Generate in shards. Finished shards are uploaded to the dataset repo and skipped when you run this cell again.\n",
174
+ "done_remote = set(f for f in api.list_repo_files(DATASET, repo_type=\"dataset\") if f.startswith(\"data/train_extra/shard_\")) if UPLOAD else set()\n",
175
+ "n_shards = (len(rows) + SHARD - 1) // SHARD; t0 = time.time(); n_done = 0\n",
176
+ "for s in range(n_shards):\n",
177
+ " name = f\"shard_{s:04d}.jsonl.gz\"; local = os.path.join(WORK, name)\n",
178
+ " if f\"data/train_extra/{name}\" in done_remote: continue\n",
179
+ " chunk = rows[s * SHARD:(s + 1) * SHARD]\n",
180
+ " with ThreadPoolExecutor(WORKERS) as ex: out = list(ex.map(make_row, chunk))\n",
181
+ " with gzip.open(local, \"wt\", encoding=\"utf-8\") as fo:\n",
182
+ " for r in out: fo.write(json.dumps(r, ensure_ascii=False) + \"\\n\")\n",
183
+ " if UPLOAD:\n",
184
+ " api.upload_file(path_or_fileobj=local, path_in_repo=f\"data/train_extra/{name}\", repo_id=DATASET, repo_type=\"dataset\", commit_message=f\"train_extra shard {s}\")\n",
185
+ " n_done += len(chunk)\n",
186
+ " print(f\"shard {s + 1}/{n_shards} done and {'uploaded' if UPLOAD else 'saved'} | {n_done} rows | {(time.time() - t0) / 60:.1f} min\", flush=True)"
187
  ],
188
  "outputs": [],
189
  "execution_count": null
 
192
  "cell_type": "code",
193
  "metadata": {},
194
  "source": [
195
+ "# Merge all shards into data/train_extra.jsonl.gz (the train split loads this file) and print a summary\n",
196
+ "merged = os.path.join(WORK, \"train_extra.jsonl.gz\"); allrows = []\n",
197
+ "for s in range(n_shards):\n",
198
+ " name = f\"shard_{s:04d}.jsonl.gz\"; local = os.path.join(WORK, name)\n",
199
+ " if not os.path.exists(local) and UPLOAD:\n",
200
+ " local = hf_hub_download(DATASET, f\"data/train_extra/{name}\", repo_type=\"dataset\", token=HF_TOKEN)\n",
201
+ " allrows += [json.loads(l) for l in gzip.open(local, \"rt\", encoding=\"utf-8\")]\n",
202
+ "with gzip.open(merged, \"wt\", encoding=\"utf-8\") as fo:\n",
203
+ " for r in allrows: fo.write(json.dumps(r, ensure_ascii=False) + \"\\n\")\n",
204
+ "cs = [c for r in allrows for c in r[\"candidates\"]]\n",
205
+ "print(len(allrows), \"rows,\", len({r[\"id\"] for r in allrows}), \"texts,\", len(cs), \"candidates, format ok:\", round(sum(c[\"format_ok\"] for c in cs) / max(1, len(cs)), 3))\n",
206
+ "print(\"rows per language, lowest and highest:\", C.Counter(r[\"lang\"] for r in allrows).most_common()[-1], C.Counter(r[\"lang\"] for r in allrows).most_common()[0])\n",
207
+ "print(allrows[0][\"prompt\"][:100]); print(allrows[0][\"output\"][0][:200])\n",
208
  "if UPLOAD:\n",
209
+ " api.upload_file(path_or_fileobj=merged, path_in_repo=\"data/train_extra.jsonl.gz\", repo_id=DATASET, repo_type=\"dataset\", commit_message=\"Add train_extra (generated with gemma-3-0.8b-csw)\")\n",
210
+ " print(\"uploaded data/train_extra.jsonl.gz\")"
 
 
 
211
  ],
212
  "outputs": [],
213
  "execution_count": null