{ "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", "[`AletheiaAING/african-code-switch-benchmark`](https://huggingface.co/datasets/AletheiaAING/african-code-switch-benchmark).\n", "\n", "**What happens**\n", "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", "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 = \"AletheiaAING/african-code-switch-benchmark\"\n", "MODEL = \"AletheiaAING/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\"\", 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*(.*?)\", re.S)\n", "\n", "def generate(llm, prompt, temperature, seed):\n", " text = f\"user\\n{prompt}\\nmodel\\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 } ] }