{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# DPO dataset creation\n", "\n", "Notebook for **Kaggle 2×T4 GPU**. It builds a 900-sample multilingual DPO dataset (GSM8K socratic, translated into 8 languages with gpt-oss-20b), publishes it to the Hugging Face Hub.\n", "\n", "| Section | Stage |\n", "|---------|-------|\n", "| 1–2 | Dependencies, GPU check, HuggingFace login, configuration |\n", "| 3–4 | GSM8K subset → DPO triplets (prompt / chosen / rejected) |\n", "| 5 | Translation with gpt-oss-20b (llama.cpp), validation & reconciliation |\n", "| 6 | Dataset assembly, preview, push to the Hub |\n", "\n", "> **Setup**: Select the **GPU T4 ×2** accelerator and enable **Internet** in the Kaggle notebook settings. Add your `HF_TOKEN` as a Kaggle Secret with **write**. Run the cells top to bottom; if Section 1 installs packages, restart the session once and continue from Section 2." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Dependencies" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import importlib.metadata as md, subprocess, sys\n", "\n", "PINS = {\n", " \"torch\": \"2.4.0\", \"transformers\": \"4.56.1\",\n", " \"trl\": \"0.23.0\", \"datasets\": \"4.1.0\", \"accelerate\": \"1.10.1\",\n", " \"peft\": \"0.17.0\", \"numpy\": \"1.26.4\",\n", " \"huggingface_hub\": \"0.34.0\", \"bitsandbytes\": \"0.45.5\", \"trackio\": \"0.20.2\",\n", "}\n", "\n", "def ver(p):\n", " try: return md.version(p).split(\"+\")[0]\n", " except md.PackageNotFoundError: return None\n", "\n", "bad = {p: (ver(p), v) for p, v in PINS.items() if ver(p) != v}\n", "# wandb: preinstalled on Kaggle, breaks TRL's import (circular import) and isn't needed (report_to=\"trackio\")\n", "junk = [p for p in (\"torchao\", \"torchaudio\", \"wandb\") if ver(p)]\n", "\n", "if not bad and not junk:\n", " print(\"✅ Environment already correct. Continue to the next cell.\")\n", "else:\n", " print(\"Fixing:\", bad, \"| removing:\", junk)\n", " if junk:\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", *junk])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n", " \"--disable-pip-version-check\",\n", " *[f\"{p}=={v}\" for p, v in PINS.items()]])\n", " print(\"\\n⚠️ INSTALL DONE. Restart the session (Run ▸ Restart Session), then continue from Section 2 — re-running this cell will only print ✅.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. GPU check, HuggingFace login & configuration" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import torch\n", "from huggingface_hub import login\n", "\n", "# Verify GPU setup\n", "print(f\"PyTorch version: {torch.__version__}\")\n", "print(f\"CUDA available: {torch.cuda.is_available()}\")\n", "if torch.cuda.is_available():\n", " print(f\"CUDA version: {torch.version.cuda}\")\n", " print(f\"GPU count: {torch.cuda.device_count()}\")\n", " for i in range(torch.cuda.device_count()):\n", " print(f\" GPU {i}: {torch.cuda.get_device_name(i)}\")\n", " print(f\" Memory: {torch.cuda.get_device_properties(i).total_memory / 1024**3:.1f} GB\")\n", "\n", "# Prefer Kaggle Secrets, fall back to env var\n", "try:\n", " from kaggle_secrets import UserSecretsClient\n", " hf_token = UserSecretsClient().get_secret(\"HF_TOKEN\")\n", "except Exception:\n", " hf_token = os.environ.get(\"HF_TOKEN\", \"\")\n", "\n", "if not hf_token:\n", " raise ValueError(\"HF_TOKEN not found! Add it as a Kaggle Secret named 'HF_TOKEN' with write scope.\")\n", "\n", "login(token=hf_token)\n", "print(\"Logged in to HuggingFace Hub.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ── Hub repos ────────────────────────────────────────────────────────────\n", "DATASET_REPO = \"mzoelfakar/Mini-GSM8K-Multilingual-Alignment\"\n", "\n", "# ── Dataset layout: consecutive blocks of SAMPLES_PER_LANG rows per language, in this order ──\n", "LANGUAGES = [\n", " (\"Arabic\", \"ar\"),\n", " (\"French\", \"fr\"),\n", " (\"Spanish\", \"es\"),\n", " (\"German\", \"de\"),\n", " (\"Italian\", \"it\"),\n", " (\"Portuguese\", \"pt\"),\n", " (\"Chinese\", \"zh\"),\n", " (\"Russian\", \"ru\"),\n", " (\"English\", \"en\"),\n", "]\n", "SAMPLES_PER_LANG = 100\n", "N_SAMPLES = SAMPLES_PER_LANG * len(LANGUAGES) # 900" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Load & filter GSM8K (900 socratic samples)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from datasets import load_dataset\n", "import re\n", "\n", "ds = load_dataset(\"openai/gsm8k\", \"socratic\", split=\"train\")\n", "print(f\"Total GSM8K socratic samples: {len(ds)}\")\n", "\n", "# Keep only samples whose answer contains at least one digit\n", "ds_filtered = ds.filter(lambda x: bool(re.search(r\"\\d\", x[\"answer\"])))\n", "print(f\"After digit filter: {len(ds_filtered)}\")\n", "\n", "if len(ds_filtered) < N_SAMPLES:\n", " raise ValueError(f\"Only {len(ds_filtered)} samples after filtering, need at least {N_SAMPLES}\")\n", "\n", "# Deterministic shuffle: the first N_SAMPLES rows form the dataset, the rest feed the replacement pool used in 5d\n", "ds_shuffled = ds_filtered.shuffle(seed=42)\n", "ds_selected = ds_shuffled.select(range(N_SAMPLES))\n", "print(f\"Selected {len(ds_selected)} samples for the DPO dataset.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Build DPO triplets (prompt / chosen / rejected)\n", "- **Prompt**: the math problem\n", "- **Chosen**: the full socratic solution\n", "- **Rejected**: the solution stripped of English letters (also `?`, stray apostrophes, line breaks, repeated spaces and any leading `**`) → digits & symbols only" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import re\n", "\n", "APOS = re.compile(r\"[’']\") # stray apostrophes left behind once the letters are gone\n", "LEAD_STARS = re.compile(r\"^(?:\\s*\\*\\*)+\\s*\") # leading \"**\" run only\n", "\n", "def strip_en_letters(text):\n", " \"\"\"Remove all English letters, ?, 2+ consecutive spaces, and line separators.\n", " Keep digits, symbols, single spaces, and mathematical markers.\"\"\"\n", " text = re.sub(r\"[a-zA-Z]+\", \"\", text) # English letters\n", " text = re.sub(r\"\\?\", \"\", text) # question marks\n", " text = re.sub(r\" {2,}\", \" \", text) # 2+ consecutive spaces → one\n", " text = re.sub(r\"[\\r\\n]+\", \" \", text) # line separators → one space\n", " return text.strip()\n", "\n", "def make_rejected(answer):\n", " r = APOS.sub(\"\", strip_en_letters(answer)) # apostrophes first: removing them can expose a leading \"**\"\n", " return LEAD_STARS.sub(\"\", r).strip() # mid-entry \"**\" is left untouched\n", "\n", "# Plain lists: the reconciliation step (5d) swaps rows in place\n", "prompts = list(ds_selected[\"question\"])\n", "chosens = list(ds_selected[\"answer\"])\n", "rejecteds = [make_rejected(a) for a in chosens]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Multilingual translation with gpt-oss-20b (llama.cpp)\n", "Translates **prompt** and **chosen** into 8 languages (100 samples each) and adds friendly openers to the last 100 English samples. Sub-sections run in order: 5a serve the model → 5b helpers & templates → 5c translation loop → 5d validation & reconciliation → 5e free the GPU.\n", "\n", "| Rows | Language | Samples |\n", "|------|----------|---------|\n", "| 0–99 | Arabic | 100 |\n", "| 100–199 | French | 100 |\n", "| 200–299 | Spanish | 100 |\n", "| 300–399 | German | 100 |\n", "| 400–499 | Italian | 100 |\n", "| 500–599 | Portuguese | 100 |\n", "| 600–699 | Chinese | 100 |\n", "| 700–799 | Russian | 100 |\n", "| 800–899 | English | 100 |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5a. Serve gpt-oss-20b (F16 GGUF) with llama-server (parallel slots)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os, shutil, subprocess, time, requests\n", "from huggingface_hub import hf_hub_download\n", "\n", "TRANSLATOR_REPO, TRANSLATOR_FILE = \"unsloth/gpt-oss-20b-GGUF\", \"gpt-oss-20b-F16.gguf\"\n", "N_PARALLEL = 4 # llama-server slots = concurrent requests\n", "CTX_PER_SLOT = 12288 # prompt + reasoning + answer tokens per slot\n", "PORT = 8080\n", "LLAMA_DIR = \"./llama.cpp\"\n", "SERVER_BIN = f\"{LLAMA_DIR}/build/bin/llama-server\"\n", "\n", "def run(cmd, what):\n", " \"\"\"Run a command, capture all output, and print the real error if it fails.\"\"\"\n", " r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,\n", " env={**os.environ, \"PYTHONUNBUFFERED\": \"1\"})\n", " if r.returncode:\n", " print(f\"❌ {what} failed (exit code {r.returncode}). Last output:\\n\")\n", " print(r.stdout[-4000:] or \"(no output captured)\")\n", " raise RuntimeError(f\"{what} failed — see the output above\")\n", " return r.stdout\n", "\n", "# Recent llama.cpp (gpt-oss support): server only, CUDA for T4 (sm_75)\n", "if not os.path.exists(LLAMA_DIR):\n", " run([\"git\", \"clone\", \"--depth\", \"1\", \"https://github.com/ggml-org/llama.cpp.git\", LLAMA_DIR], \"git clone\")\n", "if not os.path.exists(SERVER_BIN):\n", " nvcc = shutil.which(\"nvcc\") or \"/usr/local/cuda/bin/nvcc\"\n", " run([\"cmake\", \"-B\", f\"{LLAMA_DIR}/build\", \"-S\", LLAMA_DIR, \"-DGGML_CUDA=ON\",\n", " \"-DCMAKE_CUDA_ARCHITECTURES=75\", \"-DGGML_CUDA_NO_VMM=ON\", # NO_VMM: Kaggle has no libcuda stub to link\n", " \"-DLLAMA_OPENSSL=OFF\", \"-DLLAMA_CURL=OFF\",\n", " *([f\"-DCMAKE_CUDA_COMPILER={nvcc}\"] if os.path.exists(nvcc) else [])], \"cmake configure\")\n", " run([\"cmake\", \"--build\", f\"{LLAMA_DIR}/build\", \"--config\", \"Release\",\n", " \"-j\", str(os.cpu_count()), \"--target\", \"llama-server\"], \"cmake build\")\n", "\n", "gguf_path = hf_hub_download(TRANSLATOR_REPO, TRANSLATOR_FILE)\n", "llama_server = subprocess.Popen([\n", " SERVER_BIN, \"-m\", gguf_path, \"--port\", str(PORT), \"--jinja\", \"-ngl\", \"99\", \"-fa\", \"on\",\n", " \"-np\", str(N_PARALLEL), \"-c\", str(N_PARALLEL * CTX_PER_SLOT),\n", " \"--chat-template-kwargs\", '{\"reasoning_effort\": \"medium\"}',\n", "], stdout=open(\"llama_server.log\", \"a\"), stderr=subprocess.STDOUT)\n", "\n", "print(\"Loading gpt-oss-20b-F16 with llama-server across 2×T4...\")\n", "for _ in range(300): # wait until the model is loaded\n", " if llama_server.poll() is not None:\n", " raise RuntimeError(\"llama-server exited — see llama_server.log\")\n", " try:\n", " if requests.get(f\"http://localhost:{PORT}/health\").status_code == 200:\n", " break\n", " except requests.ConnectionError:\n", " pass\n", " time.sleep(2)\n", "else:\n", " raise RuntimeError(\"llama-server did not become ready — see llama_server.log\")\n", "print(f\"llama-server ready ({N_PARALLEL} parallel slots).\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5b. Translation helpers & prompt templates" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import requests\n", "from concurrent.futures import ThreadPoolExecutor\n", "\n", "# ── Generation config (prompt/problem AND chosen/solution) ───────────────\n", "TEMPERATURE = 0.7\n", "REASONING_EFFORT = \"medium\"\n", "REASONING_HEADROOM = 2048 # extra tokens so reasoning never eats the answer budget\n", "\n", "# ── Generation helpers (llama-server, one request per parallel slot) ─────\n", "def chat(messages, max_new_tokens, temperature=TEMPERATURE, effort=REASONING_EFFORT, headroom=REASONING_HEADROOM):\n", " \"\"\"One chat completion → (answer text, finish_reason).\"\"\"\n", " r = requests.post(f\"http://localhost:{PORT}/v1/chat/completions\", json={\n", " \"messages\": messages, \"temperature\": temperature, \"top_p\": 0.9,\n", " \"max_tokens\": max_new_tokens + headroom,\n", " \"chat_template_kwargs\": {\"reasoning_effort\": effort},\n", " }, timeout=1800)\n", " r.raise_for_status()\n", " choice = r.json()[\"choices\"][0]\n", " return (choice[\"message\"].get(\"content\") or \"\").strip(), choice.get(\"finish_reason\")\n", "\n", "def batch_generate(messages_list, max_new_tokens=1024, temperature=TEMPERATURE):\n", " \"\"\"Generate one reply per chat (a list of messages); requests fill the parallel slots concurrently.\"\"\"\n", " with ThreadPoolExecutor(N_PARALLEL) as ex:\n", " return list(ex.map(lambda m: chat(m, max_new_tokens, temperature)[0], messages_list))\n", "\n", "# ── Prompt templates ─────────────────────────────────────────────────────\n", "PROBLEM_TRANSLATION_PROMPT = \"\"\"You are a professional math problem translator. Translate the following math problem into {language}.\n", "\n", "Rules:\n", "- Translate ONLY the natural language text\n", "- Keep ALL mathematical symbols, numbers, operators, and special markers exactly as they are: $, <<>>, ####, =, +, -, *, etc.\n", "- Do NOT modify any numbers or mathematical expressions\n", "- Don't add any extras after sharing the translated text (for example, never add: would you like more help?)\n", "\n", "Example (English → Arabic):\n", "\n", "English:\n", "Mr. Sam shared a certain amount of money between his two sons, Ken and Tony. If Ken got $1750, and Tony got twice as much as Ken, how much was the money shared?\n", "\n", "Arabic:\n", "قام السيد سام بتقسيم مبلغ من المال بين ابنيه، كين وتوني. إذا كين حصل على $1750، وتوني حصل على ضعف ما حصل عليه كين، فكم كان إجمالي المبلغ الذي تم توزيعه؟\n", "\n", "Now translate this problem into {language}:\n", "{problem}\"\"\"\n", "\n", "SOLUTION_TRANSLATION_PROMPT = \"\"\"You are a professional math solution translator. Below is a math problem (for context) and its step-by-step solution. Translate the solution into {language}.\n", "\n", "Rules:\n", "- Add a brief, varying, friendly opening sentence in {language} at the very start (e.g. equivalent of \"glad to help!\", \"let me explain step by step\", \"sure, let's work through this\", etc.)\n", "- Translate ONLY the natural language text in the solution\n", "- Keep ALL mathematical symbols, numbers, operators, and special markers exactly as they are: $, <<>>, ####, =, +, -, *, etc.\n", "- Preserve the original line structure\n", "- Don't add any extras after sharing the translated text (for example, never add: would you like more help?)\n", "\n", "Example (English → Arabic):\n", "\n", "English problem:\n", "Mr. Sam shared a certain amount of money between his two sons, Ken and Tony. If Ken got $1750, and Tony got twice as much as Ken, how much was the money shared?\n", "\n", "English solution:\n", "How much did Tony get? ** Tony got twice $1750 which is 2*$1750 = $<<2*1750=3500>>3500\n", "How much was the money shared? ** The total amount shared was $1750+$3500 = $<<1750+3500=5250>>5250\n", "#### 5250\n", "\n", "Arabic translation:\n", "تسرني مساعدتك، سأشرح لك\n", "كم الذي حصل عليه توني؟ ** توني حصل على ضعف $1750، إذا 2*$1750 = $<<2*1750=3500>>3500\n", "كم كان إجمالي المبلغ الذي تم توزيعه؟ ** إجمالي المبلغ الموزع كان $1750+$3500 = $<<1750+3500=5250>>5250\n", "#### 5250\n", "\n", "Math problem (context, do NOT include in your output):\n", "{problem}\n", "\n", "Solution to translate into {language}:\n", "{solution}\"\"\"\n", "\n", "EN_FRIENDLY_OPENER_PROMPT = \"\"\"Rewrite the following math solution by adding ONLY a brief, friendly opening sentence at the very start (e.g. \"Glad to help!\", \"Let me walk you through this!\", \"Sure, let's solve this step by step!\", etc.). Keep EVERYTHING else exactly the same — do not change any words, numbers, symbols, or formatting in the rest of the solution.\n", "\n", "Solution:\n", "{solution}\"\"\"\n", "\n", "print(\"Translation helpers defined.\")\n", "print(f\"Languages: {[name for name, _ in LANGUAGES]}\")\n", "print(f\"Samples per language: {SAMPLES_PER_LANG}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5c. Run translation loop (with checkpointing)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json, os\n", "from tqdm.auto import tqdm\n", "\n", "BATCH_SIZE = 32\n", "\n", "# Working copies: English rows keep their source problem; only the solution gets a friendly opener\n", "translated_prompts = list(prompts)\n", "translated_chosens = list(chosens)\n", "\n", "# ── Checkpointing: progress is saved after every language and picked up again on restart ──\n", "checkpoint_file = \"./translation_checkpoint.json\"\n", "\n", "def save_checkpoint(lang_idx):\n", " with open(checkpoint_file, \"w\", encoding=\"utf-8\") as f:\n", " json.dump({\"prompts\": translated_prompts, \"chosens\": translated_chosens, \"last_lang_idx\": lang_idx}, f, ensure_ascii=False)\n", " print(f\" ✓ Checkpoint saved (through language index {lang_idx})\")\n", "\n", "start_lang_idx = 0\n", "if os.path.exists(checkpoint_file):\n", " with open(checkpoint_file, \"r\", encoding=\"utf-8\") as f:\n", " ckpt = json.load(f)\n", " assert len(ckpt[\"prompts\"]) == len(ckpt[\"chosens\"]) == N_SAMPLES, \"Checkpoint does not match this dataset layout\"\n", " translated_prompts, translated_chosens = ckpt[\"prompts\"], ckpt[\"chosens\"]\n", " start_lang_idx = ckpt[\"last_lang_idx\"] + 1\n", " print(f\"Resumed from checkpoint — starting at language index {start_lang_idx}\")\n", "\n", "def generate_into(target, rows, build_message, desc, max_new_tokens=1024):\n", " \"\"\"Fill target[i] with one model reply per row i, in batches that keep every slot busy.\"\"\"\n", " for s in tqdm(range(0, len(rows), BATCH_SIZE), desc=desc):\n", " chunk = rows[s:s + BATCH_SIZE]\n", " replies = batch_generate([[{\"role\": \"user\", \"content\": build_message(i)}] for i in chunk],\n", " max_new_tokens=max_new_tokens)\n", " for i, reply in zip(chunk, replies):\n", " target[i] = reply.strip()\n", "\n", "for lang_idx, (lang_name, lang_code) in enumerate(LANGUAGES):\n", " if lang_idx < start_lang_idx:\n", " continue\n", " rows = list(range(lang_idx * SAMPLES_PER_LANG, (lang_idx + 1) * SAMPLES_PER_LANG))\n", " print(f\"\\n{'=' * 60}\")\n", " print(f\"[{lang_idx + 1}/{len(LANGUAGES)}] {lang_name} — samples {rows[0]}..{rows[-1]}\")\n", "\n", " if lang_code == \"en\":\n", " generate_into(translated_chosens, rows,\n", " lambda i: EN_FRIENDLY_OPENER_PROMPT.format(solution=chosens[i]),\n", " f\"{lang_name} (chosen)\")\n", " else:\n", " generate_into(translated_prompts, rows,\n", " lambda i: PROBLEM_TRANSLATION_PROMPT.format(language=lang_name, problem=prompts[i]),\n", " f\"{lang_name} (prompt)\", max_new_tokens=512)\n", " generate_into(translated_chosens, rows,\n", " lambda i: SOLUTION_TRANSLATION_PROMPT.format(language=lang_name, problem=prompts[i], solution=chosens[i]),\n", " f\"{lang_name} (chosen)\")\n", " save_checkpoint(lang_idx)\n", "\n", "print(f\"\\n{'=' * 60}\")\n", "print(\"All translations complete.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5d. Validation & reconciliation\n", "One pass over the whole dataset: deterministic cleanup → audit (empty, untranslated, stray-script, English-leak and Latin-script-name checks, translator commentary, number preservation, `####` / final-answer checks) → targeted repair of every flagged field → swap of still-failing rows for fresh GSM8K samples → retry → any swap that is not strictly better is reverted. Ends with hard integrity checks and a list of any fields that remain flagged." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import re, unicodedata\n", "from collections import Counter\n", "from concurrent.futures import ThreadPoolExecutor\n", "from tqdm.auto import tqdm\n", "\n", "# ── Config ───────────────────────────────────────────────────────────────────\n", "# Generation ladder: (reasoning effort, reasoning headroom tokens, temperature). Rung 1 is the full-strength attempt;\n", "# a lower rung re-runs only the requests that came back empty, truncated (finish_reason=length) or with reasoning\n", "# leaked into the answer.\n", "LADDER = [(\"high\", 6144, 1.0), (\"medium\", 2048, 1.0), (\"medium\", 2048, 0.7)]\n", "RETRY_PASSES = 1 # targeted repair passes after swapping\n", "POOL_SIZE = 600 # fresh GSM8K rows available for swaps (rows N_SAMPLES.. of the seed-42 shuffle)\n", "MAX_SWAP_ROWS = 60 # safety cap: never swap more rows than this (worst first)\n", "NON_LATIN = {\"ar\", \"ru\", \"zh\"}\n", "\n", "def lang_of(i):\n", " return LANGUAGES[i // SAMPLES_PER_LANG] # (name, code)\n", "\n", "# ── Deterministic cleanup ────────────────────────────────────────────────────\n", "CALC = re.compile(r\"<<.*?>>\", re.DOTALL)\n", "META = re.compile(r\"(translat|traduc|traduç|traduz|traduir|tradur|übersetz|перевод|翻译|ترجم)\", re.I)\n", "\n", "def clean_prompt(t):\n", " lines = t.strip().split(\"\\n\")\n", " if len(lines) > 1 and lines[0].strip().endswith((\":\", \":\")) and len(lines[0]) < 200:\n", " lines = lines[1:] # \"Here is the translation:\" preamble\n", " return \"\\n\".join(lines).split(\"####\")[0].strip() # trailing \"#### ...\" commentary\n", "\n", "def clean_chosen(t):\n", " return re.sub(r\"(?im)^\\s*solution:\\s*\\n\", \"\", t).strip() # stray \"Solution:\" label line\n", "\n", "def dedupe(seq):\n", " seen, out = set(), []\n", " for x in seq:\n", " if x not in seen:\n", " seen.add(x); out.append(x)\n", " return out\n", "\n", "# ── Number handling: unicode digits, thousands separators, decimal commas ────\n", "NUM = re.compile(r\"[0-9]{1,3}(?:[ \\u00a0\\u202f\\u2009,.'’][0-9]{3})+(?![0-9])|[0-9]+(?:[.,][0-9]+)?\")\n", "\n", "def ascii_digits(t):\n", " out = []\n", " for ch in t:\n", " if ch.isdigit() and not (\"0\" <= ch <= \"9\"):\n", " d = unicodedata.digit(ch, None)\n", " out.append(str(d) if d is not None else ch)\n", " elif ch == \"\\u066b\": out.append(\".\")\n", " elif ch == \"\\u066c\": out.append(\",\")\n", " else: out.append(ch)\n", " return \"\".join(out)\n", "\n", "def canon(tok): # digits only, no leading zeros (\"0.25\" == \".25\" == \"25\")\n", " return re.sub(r\"[^0-9]\", \"\", tok).lstrip(\"0\") or \"0\"\n", "\n", "def nums(text):\n", " return Counter(canon(m) for m in NUM.findall(ascii_digits(text)))\n", "\n", "def final_raw(text):\n", " m = re.findall(r\"####\\s*([^\\n]*)\", text)\n", " return m[-1].strip() if m else \"\"\n", "\n", "def final_value(text):\n", " n = NUM.findall(ascii_digits(final_raw(text)))\n", " return canon(n[0]) if n else None\n", "\n", "NUMWORDS = {\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4, \"five\": 5, \"six\": 6, \"seven\": 7, \"eight\": 8, \"nine\": 9, \"ten\": 10,\n", " \"eleven\": 11, \"twelve\": 12, \"thirteen\": 13, \"fourteen\": 14, \"fifteen\": 15, \"sixteen\": 16, \"seventeen\": 17,\n", " \"eighteen\": 18, \"nineteen\": 19, \"twenty\": 20, \"thirty\": 30, \"forty\": 40, \"fifty\": 50, \"sixty\": 60,\n", " \"seventy\": 70, \"eighty\": 80, \"ninety\": 90, \"hundred\": 100, \"twice\": 2, \"double\": 2, \"thrice\": 3,\n", " \"triple\": 3, \"dozen\": 12, \"half\": 2, \"third\": 3, \"thirds\": 3, \"quarter\": 4, \"fourth\": 4, \"fifth\": 5}\n", "\n", "# ── English-leak vocabulary ──────────────────────────────────────────────────\n", "UNITS_OK = {\"cm\", \"kg\", \"km\", \"mm\", \"ml\", \"mph\", \"gb\", \"mb\", \"tv\", \"pc\", \"am\", \"pm\"}\n", "BRANDS_OK = {\"iphone\", \"ipad\", \"youtube\", \"wifi\", \"ebay\", \"xbox\", \"tiktok\", \"facebook\", \"instagram\",\n", " \"google\", \"amazon\", \"netflix\", \"uber\", \"lego\", \"tesla\", \"microsoft\", \"playstation\"}\n", "# English-only tokens that are NOT valid words in fr/es/de/it/pt (collisions like was/will/can/has/but/meter/miles left out)\n", "EN_STRONG = set(\"\"\"the and of is are were been being with that this these those then than how many much each every\n", "after before from into between about which what when where whose while because they their them she his him its your\n", "not could should would does did have having there here only more less most some any other another both twice\n", "meters metres feet foot inches inch ounces ounce pounds hours hour days weeks week months years year dozen percent\n", "remaining left costs cost spent bought sold gave took made found need needs gets answer steps\n", "apples books students people friends bags eggs dogs trees cups\"\"\".split())\n", "\n", "def build_stats():\n", " \"\"\"English lexicon (lowercase words seen in the sources) + per-language row frequency of tokens.\"\"\"\n", " lex = set(re.findall(r\"\\b[a-z]{2,}\\b\", CALC.sub(\" \", \" \".join(prompts + chosens))))\n", " df = {code: Counter() for _, code in LANGUAGES}\n", " for i in range(N_SAMPLES):\n", " c = lang_of(i)[1]\n", " df[c].update(set(re.findall(r\"\\b[a-z]{5,}\\b\", (translated_prompts[i] + \" \" + translated_chosens[i]).lower())))\n", " return lex, df\n", "\n", "SCRIPTS = {\n", " \"cjk\": re.compile(r\"[\\u3000-\\u303f\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uac00-\\ud7af\\uff00-\\uffef]\"),\n", " \"cyrillic\": re.compile(r\"[\\u0400-\\u04ff]\"),\n", " \"arabic\": re.compile(r\"[\\u0600-\\u06ff\\u0750-\\u077f]\"),\n", "}\n", "OWN_SCRIPT = {\"ar\": {\"arabic\"}, \"ru\": {\"cyrillic\"}, \"zh\": {\"cjk\"}}\n", "\n", "def stray_chars(text, code):\n", " out = []\n", " for n, rx in SCRIPTS.items():\n", " if n not in OWN_SCRIPT.get(code, set()):\n", " out += rx.findall(text)\n", " return dedupe(out)[:8]\n", "\n", "def leaks(text, code):\n", " \"\"\"→ (english_words, latin_script_names) still present in a non-English translation.\"\"\"\n", " t = CALC.sub(\" \", text)\n", " words, names = [], []\n", " if code in NON_LATIN: # any Latin word in ar/ru/zh is a leak\n", " for w in re.findall(r\"[A-Za-z]{2,}\", t):\n", " lw = w.lower()\n", " if lw in UNITS_OK or lw in BRANDS_OK or (w.isupper() and len(w) <= 5):\n", " continue\n", " if w[0].isupper() and lw not in en_lex: # never seen lowercase in the sources → a proper name\n", " names.append(w)\n", " else:\n", " words.append(w)\n", " else: # fr/es/de/it/pt: English-only vocabulary + runs of English words\n", " words += [w for w in re.findall(r\"\\b[a-z]+\\b\", t.lower()) if w in EN_STRONG]\n", " run = []\n", " for tok in re.findall(r\"[^\\W\\d_]+|\\d+|[^\\w\\s]\", t) + [\".\"]:\n", " if tok.isascii() and tok.isalpha() and tok.islower() and len(tok) >= 2 and tok in en_lex and lang_df[code][tok] < 3:\n", " run.append(tok)\n", " else: # ≥3 consecutive English words = a copied English phrase\n", " if len(run) >= 3:\n", " words += run\n", " run = []\n", " return dedupe(words), dedupe(names)\n", "\n", "# ── Audit ────────────────────────────────────────────────────────────────────\n", "WEIGHTS = {\"empty\": 1000, \"untranslated\": 1000, \"missing_hash\": 300, \"final_answer\": 300, \"stray_script\": 200,\n", " \"meta\": 150, \"hash_in_prompt\": 150, \"digits\": 100, \"solution_label\": 50, \"bad_opener\": 50,\n", " \"en_words\": 30, \"en_names\": 10}\n", "\n", "def issue(t, items=None, **kw):\n", " d = {\"type\": t, \"items\": items or []}\n", " d.update(kw)\n", " return d\n", "\n", "def score(iss):\n", " return sum(WEIGHTS[x[\"type\"]] + 5 * (len(x.get(\"items\", [])) + len(x.get(\"missing\", [])) + len(x.get(\"extra\", [])))\n", " for x in iss)\n", "\n", "def audit_field(i, kind, text):\n", " name, code = lang_of(i)\n", " src = prompts[i] if kind == \"prompt\" else chosens[i]\n", " if kind == \"prompt\" and code == \"en\":\n", " return []\n", " if not text.strip():\n", " return [issue(\"empty\")]\n", " if text.strip() == src.strip():\n", " return [issue(\"untranslated\")]\n", " iss = []\n", " stray = stray_chars(text, code)\n", " if stray:\n", " iss.append(issue(\"stray_script\", stray))\n", " first = text.strip().split(\"\\n\", 1)[0]\n", " brackets = bool(re.search(r\"[\\[【][^\\]】]{3,}[\\]】]\", text)) and not re.search(r\"[\\[【]\", src)\n", " if kind == \"prompt\":\n", " if META.search(first) or brackets:\n", " iss.append(issue(\"meta\"))\n", " if \"####\" in text:\n", " iss.append(issue(\"hash_in_prompt\"))\n", " else:\n", " if brackets:\n", " iss.append(issue(\"meta\"))\n", " if \"**\" not in first and META.search(first):\n", " iss.append(issue(\"bad_opener\"))\n", " if re.search(r\"(?im)^\\s*solution:\", text):\n", " iss.append(issue(\"solution_label\"))\n", " exp = final_raw(src)\n", " if \"####\" not in text:\n", " iss.append(issue(\"missing_hash\", expected=exp))\n", " elif final_value(text) != final_value(src):\n", " iss.append(issue(\"final_answer\", expected=exp, got=final_raw(text)))\n", " if code != \"en\":\n", " words, names = leaks(text, code)\n", " if words: iss.append(issue(\"en_words\", words))\n", " if names: iss.append(issue(\"en_names\", names))\n", " a, b = nums(src), nums(text)\n", " said = Counter(str(NUMWORDS[w]) for w in re.findall(r\"[a-z]+\", src.lower()) if w in NUMWORDS)\n", " miss_c, extra_c = a - b, (b - a) - said # \"ten oranges\" → \"10 апельсинов\" is fine\n", " miss_c.pop(\"1\", None); extra_c.pop(\"1\", None) # \"1 minute\" ↔ \"one minute\" idioms (the #### line is checked separately)\n", " missing, extra = sorted(miss_c.elements()), sorted(extra_c.elements())\n", " if missing or extra:\n", " iss.append(issue(\"digits\", missing=missing, extra=extra))\n", " return iss\n", "\n", "def audit_all():\n", " global en_lex, lang_df\n", " en_lex, lang_df = build_stats()\n", " flags = {}\n", " for i in range(N_SAMPLES):\n", " for kind, txt in ((\"prompt\", translated_prompts[i]), (\"chosen\", translated_chosens[i])):\n", " iss = audit_field(i, kind, txt)\n", " if iss:\n", " flags[(i, kind)] = iss\n", " return flags\n", "\n", "def summarize(flags, title):\n", " by_t, by_l = Counter(), Counter()\n", " for (i, k), iss in flags.items():\n", " by_l[lang_of(i)[1]] += 1\n", " for x in iss:\n", " by_t[x[\"type\"]] += 1\n", " rows = sorted({i for i, _ in flags})\n", " print(f\"{title}: {len(flags)} flagged fields in {len(rows)} rows | issues={dict(by_t)} | langs={dict(by_l)}\")\n", "\n", "# ── Issue-specific fixing prompts ────────────────────────────────────────────\n", "def instr(it, L, what):\n", " t, w = it[\"type\"], \", \".join(it.get(\"items\", []))\n", " if t == \"en_words\":\n", " return (f\"UNTRANSLATED ENGLISH — these English words are still in the text: {w}. Translate each one (and any English \"\n", " f\"phrase around it) into natural {L}, including unit names such as meters, feet, hours, gallons. No English word \"\n", " f\"may remain (unit abbreviations like cm/kg/km and acronyms are fine).\")\n", " if t == \"en_names\":\n", " return (f\"LATIN-SCRIPT NAMES — {L} is not written in the Latin alphabet, but these are: {w}. Write each one in {L} script \"\n", " f\"(transliterate people and place names, translate days/months/holidays) and spell every name identically \"\n", " f\"everywhere it appears.\")\n", " if t == \"stray_script\":\n", " return f\"WRONG WRITING SYSTEM — these characters do not belong in {L}: {w}. Rewrite every phrase containing them in {L} only.\"\n", " if t == \"digits\":\n", " return (f\"NUMBERS DO NOT MATCH THE SOURCE — numbers missing from the text: {', '.join(it.get('missing', [])) or 'none'}; \"\n", " f\"numbers in the text that are NOT in the source: {', '.join(it.get('extra', [])) or 'none'}. Restore the source \"\n", " f\"numbers exactly (Western digits 0-9, same count of each number) and remove the invented ones.\")\n", " if t == \"final_answer\":\n", " return f\"WRONG FINAL ANSWER — the last line must be exactly `#### {it.get('expected', '')}` (same value as the source), nothing after it.\"\n", " if t == \"missing_hash\":\n", " return f\"MISSING FINAL ANSWER — end the solution with a new last line `#### {it.get('expected', '')}` and nothing after it.\"\n", " if t == \"hash_in_prompt\":\n", " return \"REMOVE MARKERS — the problem must not contain '####' or any answer; output only the translated problem text.\"\n", " if t == \"meta\":\n", " return (f\"TRANSLATOR COMMENTARY — the text contains notes, brackets or explanations that are not part of the {what} \"\n", " f\"(e.g. 'here is the translation', [notes]). Delete all of it; keep only the {what} itself.\")\n", " if t == \"solution_label\":\n", " return \"STRAY LABEL — delete any line that only says 'Solution:' (or its translation).\"\n", " if t == \"bad_opener\":\n", " return (f\"BAD OPENING — the first line mentions translating. Replace ONLY that first line with one short, friendly sentence \"\n", " f\"in {L} saying you will explain step by step (never mention translation).\")\n", " return t\n", "\n", "RULES = \"\"\"Universal rules:\n", "- Output ONLY the corrected {what}: no notes, no quotes, no code fences, no preamble, no closing question.\n", "- Keep every number, currency sign, <<...>> expression, =, +, -, *, / and every #### marker exactly as in the English source; never turn number words into digits or digits into number words; never add or remove thousands separators.\n", "- Keep the line structure of the source (one line per source line).\"\"\"\n", "\n", "def scratch_msg(i, kind):\n", " name, code = lang_of(i)\n", " if kind == \"prompt\":\n", " return PROBLEM_TRANSLATION_PROMPT.format(language=name, problem=prompts[i])\n", " if code == \"en\":\n", " return EN_FRIENDLY_OPENER_PROMPT.format(solution=chosens[i])\n", " m = SOLUTION_TRANSLATION_PROMPT.format(language=name, problem=prompts[i], solution=chosens[i])\n", " tp = translated_prompts[i]\n", " if tp.strip() and tp.strip() != prompts[i].strip():\n", " m += (f\"\\n\\nThe {name} problem is already translated — spell every person name EXACTLY as in it \"\n", " f\"(context only, do NOT output it):\\n{tp}\")\n", " return m\n", "\n", "def fix_prompt(i, kind, issues):\n", " name, code = lang_of(i)\n", " what = \"problem\" if kind == \"prompt\" else \"solution\"\n", " types = {x[\"type\"] for x in issues}\n", " if types & {\"empty\", \"untranslated\"}: # nothing usable → clean re-translation\n", " return scratch_msg(i, kind)\n", " src = prompts[i] if kind == \"prompt\" else chosens[i]\n", " cur = translated_prompts[i] if kind == \"prompt\" else translated_chosens[i]\n", " ctx = f\"English problem (context only, do NOT output it):\\n{prompts[i]}\\n\\n\" if kind == \"chosen\" else \"\"\n", " ref = (f\"{name} problem (its name spellings are final — reuse them exactly; context only, do NOT output it):\\n\"\n", " f\"{translated_prompts[i]}\\n\\n\") if (kind == \"chosen\" and code != \"en\") else \"\"\n", " defects = \"\\n\".join(f\"{n}. {instr(x, name, what)}\" for n, x in enumerate(issues, 1))\n", " return (f\"You are repairing a {name} translation of a GSM8K math {what}. Fix ONLY the defects listed below and keep everything \"\n", " f\"that is already correct exactly as it is (wording, opening sentence, line breaks).\\n\\n\"\n", " f\"{ctx}English {what} (authoritative source; context only, do NOT output it):\\n{src}\\n\\n\"\n", " f\"{ref}Current {name} text to repair:\\n{cur}\\n\\n\"\n", " f\"DEFECTS TO FIX:\\n{defects}\\n\\n\" + RULES.format(what=what))\n", "\n", "# ── Generation helpers ───────────────────────────────────────────────────────\n", "REASONING_LEAK = re.compile(r\"\\b(we need to|we should (produce|translate)|the user (wants|says|asked|specifically)|let's (translate|craft|produce))\\b\", re.I)\n", "\n", "def generate_ladder(msgs, mx):\n", " \"\"\"Rung 1 = full strength. Empty, truncated (finish_reason=length) or reasoning-leaked answers are discarded and only\n", " those requests are re-run on the next rung, so a broken generation can never overwrite a row.\"\"\"\n", " out, pending = [\"\"] * len(msgs), list(range(len(msgs)))\n", " for rung, (effort, headroom, temp) in enumerate(LADDER):\n", " if not pending:\n", " break\n", " def work(k):\n", " try:\n", " txt, fin = chat([{\"role\": \"user\", \"content\": msgs[k]}], mx, temp, effort, headroom)\n", " except Exception:\n", " return k, \"\"\n", " ok = bool(txt) and fin != \"length\" and not REASONING_LEAK.search(txt[:400])\n", " return k, (txt if ok else \"\")\n", " with ThreadPoolExecutor(N_PARALLEL) as ex:\n", " res = list(ex.map(work, pending))\n", " for k, t in res:\n", " out[k] = t\n", " pending = [k for k, t in res if not t]\n", " if pending and rung + 1 < len(LADDER):\n", " print(f\" ↳ {len(pending)}/{len(res)} answers empty/truncated/leaked on rung {rung + 1} → retrying on rung {rung + 2}\")\n", " return out\n", "\n", "def fix_pass(flags, label):\n", " \"\"\"Targeted repair of every flagged field; a candidate is kept only if its audit score is strictly lower.\"\"\"\n", " accepted = 0\n", " for kind, mx, cleaner in ((\"prompt\", 512, clean_prompt), (\"chosen\", 1280, clean_chosen)):\n", " arr = translated_prompts if kind == \"prompt\" else translated_chosens\n", " keys = sorted(i for (i, k) in flags if k == kind)\n", " for s in tqdm(range(0, len(keys), 32), desc=f\"{label}:{kind}\", leave=False):\n", " chunk = keys[s:s + 32]\n", " outs = generate_ladder([fix_prompt(i, kind, flags[(i, kind)]) for i in chunk], mx)\n", " for i, cand in zip(chunk, outs):\n", " cand = cleaner(cand or \"\")\n", " if score(audit_field(i, kind, cand)) < score(audit_field(i, kind, arr[i])):\n", " arr[i] = cand\n", " accepted += 1\n", " return accepted\n", "\n", "old_rows, old_score, reverted = {}, {}, []\n", "\n", "def row_score(i):\n", " return (score(audit_field(i, \"prompt\", translated_prompts[i])) +\n", " score(audit_field(i, \"chosen\", translated_chosens[i])))\n", "\n", "def swap_in(i):\n", " global pool_pos\n", " old_score[i] = row_score(i)\n", " old_rows[i] = (prompts[i], chosens[i], rejecteds[i], translated_prompts[i], translated_chosens[i])\n", " while pool_pos < len(pool):\n", " row = pool[pool_pos]; pool_pos += 1\n", " if row[\"question\"] not in used_questions:\n", " break\n", " else:\n", " raise RuntimeError(\"Replacement pool exhausted — raise POOL_SIZE\")\n", " used_questions.add(row[\"question\"])\n", " prompts[i], chosens[i] = row[\"question\"], row[\"answer\"]\n", " rejecteds[i] = make_rejected(row[\"answer\"])\n", " translated_prompts[i] = prompts[i] if lang_of(i)[1] == \"en\" else \"\"\n", " translated_chosens[i] = \"\"\n", "\n", "def translate_rows(rows):\n", " for kind, mx, cleaner in ((\"prompt\", 512, clean_prompt), (\"chosen\", 1280, clean_chosen)):\n", " arr = translated_prompts if kind == \"prompt\" else translated_chosens\n", " todo = [i for i in rows if not (kind == \"prompt\" and lang_of(i)[1] == \"en\")]\n", " for s in tqdm(range(0, len(todo), 32), desc=f\"swap:{kind}\", leave=False):\n", " chunk = todo[s:s + 32]\n", " for i, out in zip(chunk, generate_ladder([scratch_msg(i, kind) for i in chunk], mx)):\n", " arr[i] = cleaner(out or \"\")\n", "\n", "\n", "# ── Run ──────────────────────────────────────────────────────────────────────\n", "print(\"═\" * 78 + \"\\nVALIDATION & RECONCILIATION\\n\" + \"═\" * 78)\n", "\n", "pool = ds_shuffled.select(range(N_SAMPLES, N_SAMPLES + POOL_SIZE))\n", "used_questions = set(prompts)\n", "pool_pos = 0\n", "swapped = []\n", "\n", "# ① deterministic cleanup (English problems are the untouched GSM8K sources)\n", "for i in range(N_SAMPLES):\n", " if lang_of(i)[1] != \"en\":\n", " translated_prompts[i] = clean_prompt(translated_prompts[i])\n", " translated_chosens[i] = clean_chosen(translated_chosens[i])\n", "\n", "flags = audit_all()\n", "summarize(flags, \"① BASELINE \")\n", "\n", "if flags:\n", " # ② full-strength repair of every flagged field (issue-specific prompts)\n", " n = fix_pass(flags, \"repair\")\n", " flags = audit_all()\n", " summarize(flags, f\"② AFTER REPAIR ({n} fields improved)\")\n", "\n", " # ③ every row that is still flagged gets a fresh GSM8K sample, translated from scratch\n", " if flags:\n", " by_row = Counter()\n", " for (i, _), iss in flags.items():\n", " by_row[i] += score(iss)\n", " rows = sorted(sorted(by_row), key=lambda r: -by_row[r])[:MAX_SWAP_ROWS]\n", " skipped = len(by_row) - len(rows)\n", " print(f\"③ SWAPPING {len(rows)} rows for fresh samples\" + (f\" (cap hit — {skipped} rows left as-is)\" if skipped else \"\"))\n", " rows = sorted(rows)\n", " for i in rows:\n", " swap_in(i)\n", " translate_rows(rows)\n", " swapped = list(rows)\n", " flags = audit_all()\n", " summarize(flags, \"③ AFTER SWAP \")\n", "\n", " # ④ targeted repair of whatever is left\n", " for p in range(RETRY_PASSES):\n", " if not flags:\n", " break\n", " n = fix_pass(flags, f\"retry{p + 1}\")\n", " flags = audit_all()\n", " summarize(flags, f\"④ AFTER RETRY {p + 1} ({n} fields improved)\")\n", "\n", " # ⑤ a swap is kept ONLY if the new row scores strictly better than the row it replaced; otherwise the old row comes back\n", " for i in list(swapped):\n", " if row_score(i) >= old_score[i]:\n", " prompts[i], chosens[i], rejecteds[i], translated_prompts[i], translated_chosens[i] = old_rows[i]\n", " swapped.remove(i); reverted.append(i)\n", " flags = audit_all()\n", " summarize(flags, f\"⑤ FINAL ({len(swapped)} swaps kept, {len(reverted)} reverted to the original row)\")\n", "\n", "# ── Integrity checks (hard) ──────────────────────────────────────────────────\n", "en_rows = [i for i in range(N_SAMPLES) if lang_of(i)[1] == \"en\"]\n", "checks = {\n", " f\"{N_SAMPLES} rows in every column\": len(translated_prompts) == len(translated_chosens) == len(rejecteds) == len(prompts) == len(chosens) == N_SAMPLES,\n", " \"no empty field\": all(translated_prompts[i].strip() and translated_chosens[i].strip() and rejecteds[i].strip() for i in range(N_SAMPLES)),\n", " \"no duplicate English problems\": len(set(prompts)) == N_SAMPLES,\n", " \"English rows match their sources\": all(translated_prompts[i].strip() == prompts[i].strip() for i in en_rows),\n", " \"rejected == stripped English solution\": all(rejecteds[i] == make_rejected(chosens[i]) for i in range(N_SAMPLES)),\n", "}\n", "print(\"\\n\" + \"─\" * 78)\n", "for name, ok in checks.items():\n", " print((\"✓ \" if ok else \"✗ \") + name)\n", "assert all(checks.values()), \"Integrity checks failed — see the ✗ lines above\"\n", "\n", "# ── Fields that are still flagged after all rounds (soft) ────────────────────\n", "print(f\"Swapped rows: {swapped}\")\n", "if flags:\n", " print(f\"\\n⚠️ {len(flags)} fields in {len({i for i, _ in flags})} rows are still flagged (worst first, max 40 shown):\")\n", " for (i, kind), iss in sorted(flags.items(), key=lambda kv: (-score(kv[1]), kv[0]))[:40]:\n", " print(f\" row {i:>3} [{lang_of(i)[1]}] {kind:<6} → \" + \", \".join(x[\"type\"] for x in iss))\n", "else:\n", " print(\"\\n✅ Nothing flagged — every field passed the audit.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5e. Stop llama-server (free VRAM)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import subprocess\n", "\n", "llama_server.terminate()\n", "llama_server.wait()\n", "\n", "print(\"llama-server (gpt-oss-20b) stopped — GPU memory freed for DPO training.\")\n", "print(subprocess.run([\"nvidia-smi\", \"--query-gpu=index,memory.used\", \"--format=csv\"],\n", " capture_output=True, text=True).stdout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Assemble & publish the dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6a. Assemble" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from datasets import Dataset\n", "from collections import Counter\n", "\n", "languages = [code for _, code in LANGUAGES for _ in range(SAMPLES_PER_LANG)]\n", "\n", "dataset = Dataset.from_dict({\n", " \"prompt\": translated_prompts,\n", " \"chosen\": translated_chosens,\n", " \"rejected\": rejecteds,\n", " \"language\": languages,\n", " \"prompt_en\": prompts, # original English GSM8K problem\n", " \"chosen_en\": chosens, # original English GSM8K solution\n", "})\n", "\n", "lang_counts = Counter(dataset[\"language\"])\n", "assert len(dataset) == N_SAMPLES, f\"Expected {N_SAMPLES} rows, got {len(dataset)}\"\n", "assert all(lang_counts[code] == SAMPLES_PER_LANG for _, code in LANGUAGES), f\"Unexpected language counts: {dict(lang_counts)}\"\n", "\n", "print(f\"Dataset: {len(dataset)} rows × {len(dataset.column_names)} columns\")\n", "print(f\"Columns: {dataset.column_names}\")\n", "print(f\"Language distribution: {dict(lang_counts)}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6b. Dataset preview (2 samples per language)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from collections import Counter\n", "\n", "PREVIEW_PER_LANG = 2 # samples shown per language — the dataset itself is never printed in full\n", "PREVIEW_CHARS = 500 # max characters shown per field\n", "\n", "def clip(text):\n", " return text if len(text) <= PREVIEW_CHARS else text[:PREVIEW_CHARS] + \"…\"\n", "\n", "row_langs = list(dataset[\"language\"])\n", "lang_counts = Counter(row_langs)\n", "\n", "print(\"=\" * 80)\n", "print(f\"DATASET PREVIEW — {PREVIEW_PER_LANG} samples per language (prompt / chosen / rejected)\")\n", "print(\"=\" * 80)\n", "\n", "for _, code in LANGUAGES:\n", " idx = [i for i, l in enumerate(row_langs) if l == code][:PREVIEW_PER_LANG]\n", " print(f\"\\n{'=' * 80}\")\n", " print(f\"LANGUAGE: {code.upper()} (total samples: {lang_counts[code]})\")\n", " print(\"=\" * 80)\n", " for n, i in enumerate(idx, start=1):\n", " row = dataset[i]\n", " print(f\"\\n--- Sample {n} ---\")\n", " print(f\"PROMPT:\\n{clip(row['prompt'])}\")\n", " print(f\"\\nCHOSEN:\\n{clip(row['chosen'])}\")\n", " print(f\"\\nREJECTED:\\n{clip(row['rejected'])}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6c. Push dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dataset.push_to_hub(DATASET_REPO, private=False)\n", "print(f\"Dataset pushed to https://huggingface.co/datasets/{DATASET_REPO}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6d. Push dataset card" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import HfApi\n", "\n", "DATASET_CARD = \"\"\"---\n", "language:\n", "- en\n", "- ar\n", "- fr\n", "- es\n", "- de\n", "- it\n", "- pt\n", "- zh\n", "- ru\n", "license: apache-2.0\n", "annotations_creators:\n", "- machine-generated\n", "language_creators:\n", "- machine-generated\n", "multilinguality:\n", "- multilingual\n", "source_datasets:\n", "- openai/gsm8k\n", "task_categories:\n", "- text-generation\n", "tags:\n", "- dpo\n", "- math\n", "- multilingual\n", "- alignment\n", "- gsm8k\n", "- synthetic\n", "- translation\n", "- gpt-oss\n", "- gpt-oss-20b\n", "- llama-cpp\n", "dataset_info:\n", " features:\n", " - name: prompt\n", " dtype: string\n", " - name: chosen\n", " dtype: string\n", " - name: rejected\n", " dtype: string\n", " - name: language\n", " dtype: string\n", " - name: prompt_en\n", " dtype: string\n", " - name: chosen_en\n", " dtype: string\n", " splits:\n", " - name: train\n", " num_examples: 900\n", "size_categories:\n", "- n<1K\n", "---\n", "\n", "# Mini-GSM8K-Multilingual-Alignment\n", "\n", "A compact, multilingual DPO (Direct Preference Optimization) alignment dataset designed for training small language models to produce high-quality, step-by-step mathematical reasoning across multiple languages.\n", "\n", "## Purpose\n", "\n", "This dataset was created to improve multilingual math reasoning in small language models such as [Al-Khwarizmi-3B](https://huggingface.co/mzoelfakar/Al-Khwarizmi-3B) — a 3B-parameter math tutor model named after the 9th-century mathematician. The goal is to teach the model to prefer detailed, friendly, well-structured solutions over vague, uninformative responses, across 9 languages.\n", "\n", "## How It Was Created\n", "\n", "1. **Source**: 900 samples were drawn from [OpenAI/GSM8K](https://huggingface.co/datasets/openai/gsm8k) (socratic split), filtered to include only samples whose answers contain digits.\n", "\n", "2. **DPO Triplet Construction** (English):\n", " - **Prompt**: The math problem\n", " - **Chosen**: The full socratic step-by-step solution\n", " - **Rejected**: The solution stripped of all English letters — leaving only digits, symbols, and whitespace — creating an abstract, vague, uninformative response\n", "\n", "3. **Multilingual Translation**: [gpt-oss-20b](https://huggingface.co/openai/gpt-oss-20b) (F16 GGUF from [unsloth/gpt-oss-20b-GGUF](https://huggingface.co/unsloth/gpt-oss-20b-GGUF), served with llama.cpp `llama-server` and parallel slots; temperature 0.7, reasoning effort medium) was used to translate the `prompt` and `chosen` columns into 8 languages (100 samples each), with careful instructions to:\n", " - Preserve all mathematical symbols (`$`, `<<>>`, `####`, etc.)\n", " - Add a brief, varying, friendly opening sentence to each solution\n", " - Use context-aware translation (the model receives the original English problem when translating solutions)\n", "\n", "4. **English Samples**: The final 100 samples remain in English, with friendly opening sentences added to the solutions by the same model.\n", "\n", "## Language Distribution\n", "\n", "| Language | Code | Samples |\n", "|----------|------|---------|\n", "| Arabic | ar | 100 |\n", "| French | fr | 100 |\n", "| Spanish | es | 100 |\n", "| German | de | 100 |\n", "| Italian | it | 100 |\n", "| Portuguese | pt | 100 |\n", "| Chinese | zh | 100 |\n", "| Russian | ru | 100 |\n", "| English | en | 100 |\n", "| **Total** | | **900** |\n", "\n", "## Schema\n", "\n", "| Column | Type | Description |\n", "|--------|------|-------------|\n", "| `prompt` | string | Math problem (translated to target language) |\n", "| `chosen` | string | Full step-by-step solution with friendly opener (translated) |\n", "| `rejected` | string | Digits-only stripped version of the original English solution |\n", "| `language` | string | ISO 639-1 language code |\n", "| `prompt_en` | string | Original English GSM8K problem that `prompt` was translated from |\n", "| `chosen_en` | string | Original English GSM8K solution that `chosen` was translated from (without the friendly opener) |\n", "\n", "## Usage\n", "\n", "```python\n", "from datasets import load_dataset\n", "\n", "dataset = load_dataset(\"mzoelfakar/Mini-GSM8K-Multilingual-Alignment\", split=\"train\")\n", "\n", "# Filter by language\n", "arabic_samples = dataset.filter(lambda x: x[\"language\"] == \"ar\")\n", "```\n", "\n", "## Creator\n", "\n", "Created by **[Mohamed Zoelfakar](https://www.linkedin.com/in/mzoelfakar/)** as part of the [Al-Khwarizmi-3B](https://huggingface.co/mzoelfakar/Al-Khwarizmi-3B) project for advancing multilingual mathematical reasoning in small language models.\n", "\"\"\"\n", "\n", "api = HfApi()\n", "api.upload_file(\n", " path_or_fileobj=DATASET_CARD.encode(\"utf-8\"),\n", " path_in_repo=\"README.md\",\n", " repo_id=DATASET_REPO,\n", " repo_type=\"dataset\",\n", ")\n", "print(\"Dataset card pushed.\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 4 }