Datasets:
File size: 11,736 Bytes
a7b155e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | {
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {
"accelerator": "GPU",
"colab": {
"gpuType": "T4",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Grow the train set of the African Code-Switch Benchmark\n",
"\n",
"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",
"[`BeardedMonster/african-code-switch-benchmark`](https://huggingface.co/datasets/BeardedMonster/african-code-switch-benchmark).\n",
"\n",
"**What happens**\n",
"1. The model [`BeardedMonster/gemma-3-0.8b-csw`](https://huggingface.co/BeardedMonster/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",
"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",
"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",
"4. At the end the shards are merged into `data/train_extra.jsonl.gz`, which the dataset's `train` split loads.\n",
"\n",
"**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",
"\n",
"**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."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"import subprocess, sys\n",
"# Install llama-cpp-python with CUDA: try the prebuilt GPU wheel first, otherwise build it (about 10 minutes)\n",
"try:\n",
" import llama_cpp\n",
"except ImportError:\n",
" 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",
" if r.returncode != 0:\n",
" subprocess.run('CMAKE_ARGS=\"-DGGML_CUDA=on\" pip -q install llama-cpp-python --no-cache-dir', shell=True, check=True)\n",
" import llama_cpp\n",
"subprocess.run(\"pip -q install huggingface_hub\", shell=True, check=True)\n",
"print(\"llama-cpp-python\", llama_cpp.__version__, \"| GPU offload supported:\", llama_cpp.llama_supports_gpu_offload())"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# ---- settings ----\n",
"DATASET = \"BeardedMonster/african-code-switch-benchmark\"\n",
"MODEL = \"BeardedMonster/gemma-3-0.8b-csw\"\n",
"GGUF = \"csw-gemma3-1b-rl3-pruned-Q8_0.gguf\"\n",
"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",
"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",
"MAX_NEW = 640 # maximum new tokens per output\n",
"SHARD = 1000 # rows per uploaded shard\n",
"MAX_TEXTS = None # for a quick test use e.g. 100 (nothing is uploaded); None = all texts"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"metadata": {},
"source": [
"import os, io, gzip, json, re, time, queue, glob, getpass, collections as C\n",
"from concurrent.futures import ThreadPoolExecutor\n",
"from huggingface_hub import HfApi, hf_hub_download\n",
"\n",
"try:\n",
" from google.colab import userdata\n",
" HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
"except Exception:\n",
" HF_TOKEN = os.environ.get(\"HF_TOKEN\") or getpass.getpass(\"Hugging Face write token: \")\n",
"api = HfApi(token=HF_TOKEN)\n",
"print(\"logged in as\", api.whoami()[\"name\"])\n",
"UPLOAD = MAX_TEXTS is None\n",
"WORK = \"csw_extra\"; os.makedirs(WORK, exist_ok=True)"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Download the model and the new English prompts (runs once)\n",
"gguf_path = hf_hub_download(MODEL, GGUF)\n",
"prompts_path = hf_hub_download(DATASET, \"data/new_english_prompts.jsonl.gz\", repo_type=\"dataset\", token=HF_TOKEN)\n",
"rows = [json.loads(l) for l in gzip.open(prompts_path, \"rt\", encoding=\"utf-8\")]\n",
"if MAX_TEXTS:\n",
" keep = set(sorted({r[\"id\"] for r in rows})[:MAX_TEXTS]); rows = [r for r in rows if r[\"id\"] in keep]\n",
"rows.sort(key=lambda r: (r[\"id\"], r[\"task\"]))\n",
"print(len(rows), \"prompts,\", len({r[\"id\"] for r in rows}), \"texts,\", len({r[\"lang\"] for r in rows}), \"languages\")\n",
"print(\"model file:\", gguf_path)"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Load WORKERS copies of the model on the GPU (each copy is about 1 GB)\n",
"from llama_cpp import Llama\n",
"N_GPU = int(os.environ.get(\"N_GPU_LAYERS\", \"-1\"))\n",
"pool = queue.Queue()\n",
"for _ in range(WORKERS):\n",
" pool.put(Llama(model_path=gguf_path, n_ctx=1536, n_gpu_layers=N_GPU, n_batch=512, verbose=False))\n",
"probe = pool.queue[0]\n",
"EOT = probe.tokenize(b\"<end_of_turn>\", add_bos=False, special=True)[0]; EOS = probe.token_eos()\n",
"print(\"loaded\", WORKERS, \"copies; end-of-turn token id\", EOT)"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"metadata": {},
"source": [
"TAGS = re.compile(r\"^((?:<(?!/?dev>)\\w{1,8}>)+)\"); DEV = re.compile(r\"^\\s*<dev>(.*?)</dev>\", re.S)\n",
"\n",
"def generate(llm, prompt, temperature, seed):\n",
" 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",
" toks = llm.tokenize(text.encode(\"utf-8\"), add_bos=True, special=True)\n",
" llm.set_seed(seed); out, finished = [], False\n",
" 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",
" if t in (EOT, EOS): finished = True; break\n",
" out.append(t)\n",
" if len(out) >= MAX_NEW: break\n",
" return llm.detokenize(out, special=True).decode(\"utf-8\", errors=\"ignore\").strip(), finished\n",
"\n",
"def parse(text):\n",
" m = TAGS.match(text); has_tags = bool(m); c = text[m.end():].lstrip() if m else text\n",
" d = DEV.match(c); final = c[d.end():].strip() if d else c\n",
" 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",
"\n",
"def make_row(r):\n",
" llm = pool.get()\n",
" try:\n",
" cands = []\n",
" for k in range(N_CANDIDATES):\n",
" text, finished = generate(llm, r[\"prompt\"], 0.0 if k == 0 else 0.8, 1000 + k)\n",
" final, devices, ok = parse(text)\n",
" cands.append({\"k\": k, \"greedy\": k == 0, \"text\": text, \"finished\": finished, \"devices\": devices, \"final\": final,\n",
" \"format_ok\": ok and finished, \"ev\": None, \"system\": None, \"reward\": None, \"chrf\": None, \"judge\": None})\n",
" finally:\n",
" pool.put(llm)\n",
" return {\"id\": r[\"id\"], \"subset\": \"generated\", \"task\": r[\"task\"], \"task_type\": \"eng_\" + r[\"task\"], \"input_type\": \"english\", \"lang\": r[\"lang\"], \"switch\": r[\"switch\"],\n",
" \"pair_in_training_table\": True, \"prompt\": r[\"prompt\"], \"input\": r[\"english\"], \"english\": r[\"english\"], \"source_dataset\": r[\"source_dataset\"],\n",
" \"source_register\": r[\"source_register\"], \"reference\": None, \"reference_judge\": None, \"candidates\": cands, \"output\": [c[\"final\"] for c in cands]}"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Generate in shards. Finished shards are uploaded to the dataset repo and skipped when you run this cell again.\n",
"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",
"n_shards = (len(rows) + SHARD - 1) // SHARD; t0 = time.time(); n_done = 0\n",
"for s in range(n_shards):\n",
" name = f\"shard_{s:04d}.jsonl.gz\"; local = os.path.join(WORK, name)\n",
" if f\"data/train_extra/{name}\" in done_remote: continue\n",
" chunk = rows[s * SHARD:(s + 1) * SHARD]\n",
" with ThreadPoolExecutor(WORKERS) as ex: out = list(ex.map(make_row, chunk))\n",
" with gzip.open(local, \"wt\", encoding=\"utf-8\") as fo:\n",
" for r in out: fo.write(json.dumps(r, ensure_ascii=False) + \"\\n\")\n",
" if UPLOAD:\n",
" 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",
" n_done += len(chunk)\n",
" 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)"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Merge all shards into data/train_extra.jsonl.gz (the train split loads this file) and print a summary\n",
"merged = os.path.join(WORK, \"train_extra.jsonl.gz\"); allrows = []\n",
"for s in range(n_shards):\n",
" name = f\"shard_{s:04d}.jsonl.gz\"; local = os.path.join(WORK, name)\n",
" if not os.path.exists(local) and UPLOAD:\n",
" local = hf_hub_download(DATASET, f\"data/train_extra/{name}\", repo_type=\"dataset\", token=HF_TOKEN)\n",
" allrows += [json.loads(l) for l in gzip.open(local, \"rt\", encoding=\"utf-8\")]\n",
"with gzip.open(merged, \"wt\", encoding=\"utf-8\") as fo:\n",
" for r in allrows: fo.write(json.dumps(r, ensure_ascii=False) + \"\\n\")\n",
"cs = [c for r in allrows for c in r[\"candidates\"]]\n",
"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",
"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",
"print(allrows[0][\"prompt\"][:100]); print(allrows[0][\"output\"][0][:200])\n",
"if UPLOAD:\n",
" 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",
" print(\"uploaded data/train_extra.jsonl.gz\")"
],
"outputs": [],
"execution_count": null
}
]
} |