{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Fine-Tuning a Sango Language Model\n", "\n", "First language model for **Sango**, the national language of the Central African Republic (5M+ speakers).\n", "\n", "Uses **LoRA** to fine-tune [TinyLlama-1.1B](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0) on the [MEYNG/sango-vocabulary](https://huggingface.co/datasets/MEYNG/sango-vocabulary) dataset from Hugging Face.\n", "\n", "**Requirements:** Free Google Colab T4 GPU (~25 min total training time).\n", "\n", "By [MEYNG](https://meyng.com) | [SangoAI](https://sangoai.sbs) | [GitHub](https://github.com/meyng-hub/sangoai)" ] }, { "cell_type": "code", "metadata": {}, "source": [ "# Cell 1: Install dependencies\n", "!pip install -q transformers>=4.38.0 peft>=0.9.0 datasets>=2.17.0 bitsandbytes>=0.42.0 accelerate>=0.27.0 sentencepiece protobuf huggingface_hub" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": "# Cell 2: Download dataset from Hugging Face\nfrom datasets import load_dataset\n\n# Load both configs (vocabulary + training_pairs)\nvocab_dataset = load_dataset(\"MEYNG/sango-vocabulary\", \"vocabulary\")\npairs_dataset = load_dataset(\"MEYNG/sango-vocabulary\", \"training_pairs\")\n\nprint(f\"Vocabulary entries: {len(vocab_dataset['train'])}\")\nprint(f\"Training pairs: {len(pairs_dataset['train'])}\")\nprint(f\"\\nVocab columns: {vocab_dataset['train'].column_names}\")\nprint(f\"\\nSample vocab entry:\")\nvocab_dataset[\"train\"][0]", "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": "# Cell 3: Prepare training data\n# Convert vocabulary entries into instruction-tuning pairs (forward + reverse translations)\n\nimport json\nimport random\n\ndef generate_vocab_pairs(entries):\n \"\"\"Generate instruction-output pairs from vocabulary entries.\"\"\"\n pairs = []\n for entry in entries:\n sango = (entry.get(\"sango\") or \"\").strip()\n french = (entry.get(\"french\") or \"\").strip()\n english = (entry.get(\"english\") or \"\").strip()\n pronunciation = (entry.get(\"pronunciation\") or \"\").strip()\n category = (entry.get(\"category\") or \"\").strip()\n ex_sg = (entry.get(\"example_sango\") or \"\").strip()\n ex_fr = (entry.get(\"example_french\") or \"\").strip()\n ex_en = (entry.get(\"example_english\") or \"\").strip()\n\n if not sango:\n continue\n\n # English <-> Sango\n if english:\n pairs.append({\"instruction\": f\"Translate to Sango: {english}\", \"output\": sango})\n pairs.append({\"instruction\": f\"Translate to English: {sango}\", \"output\": english})\n pairs.append({\"instruction\": f\"What does '{sango}' mean in English?\", \"output\": english})\n\n # French <-> Sango\n if french:\n pairs.append({\"instruction\": f\"Traduire en sango : {french}\", \"output\": sango})\n pairs.append({\"instruction\": f\"Traduire en fran\\u00e7ais : {sango}\", \"output\": french})\n pairs.append({\"instruction\": f\"Que signifie '{sango}' en fran\\u00e7ais ?\", \"output\": french})\n\n # Pronunciation\n if pronunciation:\n pairs.append({\"instruction\": f\"How do you pronounce '{sango}' in Sango?\",\n \"output\": f\"'{sango}' is pronounced: {pronunciation}\"})\n\n # Category\n if category and english:\n pairs.append({\"instruction\": f\"Give me a Sango word in the category '{category}'.\",\n \"output\": f\"{sango} ({english})\"})\n\n # Example sentences\n if ex_sg and ex_en:\n pairs.append({\"instruction\": f\"Translate this Sango sentence to English: {ex_sg}\", \"output\": ex_en})\n pairs.append({\"instruction\": f\"Translate to Sango: {ex_en}\", \"output\": ex_sg})\n if ex_sg and ex_fr:\n pairs.append({\"instruction\": f\"Traduire cette phrase sango en fran\\u00e7ais : {ex_sg}\", \"output\": ex_fr})\n pairs.append({\"instruction\": f\"Traduire en sango : {ex_fr}\", \"output\": ex_sg})\n\n return pairs\n\n\ndef generate_sentence_pairs(entries):\n \"\"\"Convert parallel Sango<->French text pairs into instruction format.\"\"\"\n pairs = []\n for entry in entries:\n source = (entry.get(\"source\") or \"\").strip()\n target = (entry.get(\"target\") or \"\").strip()\n if len(source) < 5 or len(target) < 5:\n continue\n if source.isupper() and len(source.split()) <= 5:\n continue\n pairs.append({\"instruction\": f\"Traduire du sango en fran\\u00e7ais : {source}\", \"output\": target})\n pairs.append({\"instruction\": f\"Traduire en sango : {target}\", \"output\": source})\n return pairs\n\n\n# Generate pairs from vocabulary\nvocab_entries = [dict(row) for row in vocab_dataset[\"train\"]]\nall_pairs = generate_vocab_pairs(vocab_entries)\n\n# Generate pairs from training pairs\ntp_entries = [dict(row) for row in pairs_dataset[\"train\"]]\nall_pairs += generate_sentence_pairs(tp_entries)\n\n# Deduplicate\nseen = set()\nunique = []\nfor p in all_pairs:\n key = (p[\"instruction\"], p[\"output\"])\n if key not in seen:\n seen.add(key)\n unique.append(p)\n\n# Shuffle and split 90/10\nrandom.seed(42)\nrandom.shuffle(unique)\nsplit_idx = int(len(unique) * 0.9)\ntrain_data = unique[:split_idx]\neval_data = unique[split_idx:]\n\nprint(f\"Total unique pairs: {len(unique)}\")\nprint(f\"Train: {len(train_data)} | Eval: {len(eval_data)}\")\nprint(f\"\\nSample training examples:\")\nfor ex in train_data[:3]:\n print(f\" Q: {ex['instruction']}\")\n print(f\" A: {ex['output']}\\n\")", "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# Cell 4: Load base model with 4-bit quantization\n", "\n", "import torch\n", "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n", "from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training\n", "from datasets import Dataset\n", "\n", "MODEL_NAME = \"TinyLlama/TinyLlama-1.1B-Chat-v1.0\"\n", "TEMPLATE = \"<|user|>\\n{instruction}\\n<|assistant|>\\n{output}\"\n", "MAX_LEN = 256\n", "\n", "# Check GPU\n", "if torch.cuda.is_available():\n", " gpu = torch.cuda.get_device_name(0)\n", " mem = torch.cuda.get_device_properties(0).total_mem / (1024**3)\n", " print(f\"GPU: {gpu} ({mem:.1f} GB)\")\n", "else:\n", " print(\"WARNING: No GPU detected! Go to Runtime > Change runtime type > T4 GPU\")\n", "\n", "# Load tokenizer\n", "print(\"\\nLoading tokenizer ...\")\n", "tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)\n", "if tokenizer.pad_token is None:\n", " tokenizer.pad_token = tokenizer.eos_token\n", " tokenizer.pad_token_id = tokenizer.eos_token_id\n", "\n", "# Tokenize datasets\n", "print(\"Tokenizing ...\")\n", "def tokenize(examples, template):\n", " texts = [template.format(instruction=ex[\"instruction\"], output=ex[\"output\"]) for ex in examples]\n", " enc = tokenizer(texts, truncation=True, max_length=MAX_LEN, padding=\"max_length\", return_tensors=\"pt\")\n", " labels = enc[\"input_ids\"].clone()\n", " labels[labels == tokenizer.pad_token_id] = -100\n", " return Dataset.from_dict({\"input_ids\": enc[\"input_ids\"], \"attention_mask\": enc[\"attention_mask\"], \"labels\": labels})\n", "\n", "train_dataset = tokenize(train_data, TEMPLATE)\n", "eval_dataset = tokenize(eval_data, TEMPLATE)\n", "print(f\"Train: {len(train_dataset)} | Eval: {len(eval_dataset)} sequences\")\n", "\n", "# Load model with 4-bit quantization (NF4)\n", "print(f\"\\nLoading {MODEL_NAME} (4-bit quantized) ...\")\n", "bnb_config = BitsAndBytesConfig(\n", " load_in_4bit=True,\n", " bnb_4bit_quant_type=\"nf4\",\n", " bnb_4bit_compute_dtype=torch.float16,\n", " bnb_4bit_use_double_quant=True,\n", ")\n", "model = AutoModelForCausalLM.from_pretrained(\n", " MODEL_NAME,\n", " quantization_config=bnb_config,\n", " device_map=\"auto\",\n", " trust_remote_code=True,\n", ")\n", "model = prepare_model_for_kbit_training(model)\n", "print(\"Model loaded!\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# Cell 5: Configure LoRA and train\n", "\n", "from transformers import TrainingArguments, Trainer, DataCollatorForSeq2Seq\n", "\n", "OUTPUT_DIR = \"/content/sango-lora-adapter\"\n", "\n", "# LoRA configuration\n", "lora_config = LoraConfig(\n", " task_type=TaskType.CAUSAL_LM,\n", " r=16,\n", " lora_alpha=32,\n", " lora_dropout=0.05,\n", " target_modules=[\"q_proj\", \"v_proj\", \"k_proj\", \"o_proj\"],\n", " bias=\"none\",\n", ")\n", "model = get_peft_model(model, lora_config)\n", "trainable, total = model.get_nb_trainable_parameters()\n", "print(f\"Parameters: {total:,} total, {trainable:,} trainable ({100*trainable/total:.2f}%)\")\n", "\n", "# Training arguments\n", "training_args = TrainingArguments(\n", " output_dir=OUTPUT_DIR,\n", " num_train_epochs=3,\n", " per_device_train_batch_size=4,\n", " per_device_eval_batch_size=4,\n", " gradient_accumulation_steps=4,\n", " learning_rate=2e-4,\n", " weight_decay=0.01,\n", " warmup_ratio=0.03,\n", " lr_scheduler_type=\"cosine\",\n", " logging_steps=10,\n", " save_strategy=\"epoch\",\n", " eval_strategy=\"epoch\",\n", " save_total_limit=2,\n", " fp16=True,\n", " report_to=\"none\",\n", " remove_unused_columns=False,\n", " dataloader_pin_memory=True,\n", " seed=42,\n", ")\n", "\n", "# Train\n", "print(\"\\nTraining started ... (3 epochs, ~25 min on T4)\")\n", "trainer = Trainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=train_dataset,\n", " eval_dataset=eval_dataset,\n", " data_collator=DataCollatorForSeq2Seq(tokenizer, pad_to_multiple_of=8, return_tensors=\"pt\", padding=True),\n", ")\n", "trainer.train()\n", "\n", "# Save adapter + metadata\n", "print(f\"\\nSaving adapter to {OUTPUT_DIR} ...\")\n", "model.save_pretrained(OUTPUT_DIR)\n", "tokenizer.save_pretrained(OUTPUT_DIR)\n", "\n", "import json, os\n", "metadata = {\n", " \"base_model\": MODEL_NAME,\n", " \"lora_r\": 16, \"lora_alpha\": 32, \"lora_dropout\": 0.05,\n", " \"target_modules\": [\"q_proj\", \"v_proj\", \"k_proj\", \"o_proj\"],\n", " \"epochs\": 3, \"learning_rate\": 2e-4, \"batch_size\": 4, \"grad_accum\": 4,\n", " \"max_length\": MAX_LEN,\n", " \"train_examples\": len(train_data), \"eval_examples\": len(eval_data),\n", " \"quantized\": True,\n", " \"prompt_template\": TEMPLATE,\n", "}\n", "with open(os.path.join(OUTPUT_DIR, \"training_metadata.json\"), \"w\") as f:\n", " json.dump(metadata, f, indent=2)\n", "\n", "print(\"Training complete!\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# Cell 6: Test the model with sample translations\n", "\n", "import time\n", "from peft import PeftModel\n", "\n", "# Reload for clean inference\n", "del model\n", "torch.cuda.empty_cache()\n", "\n", "base_model = AutoModelForCausalLM.from_pretrained(\n", " MODEL_NAME,\n", " quantization_config=bnb_config,\n", " device_map=\"auto\",\n", " trust_remote_code=True,\n", ")\n", "model = PeftModel.from_pretrained(base_model, OUTPUT_DIR)\n", "model.eval()\n", "\n", "def generate_answer(instruction, max_new_tokens=64):\n", " prompt = f\"<|user|>\\n{instruction}\\n<|assistant|>\\n\"\n", " inputs = tokenizer(prompt, return_tensors=\"pt\", truncation=True, max_length=256)\n", " inputs = {k: v.cuda() for k, v in inputs.items()}\n", " with torch.no_grad():\n", " out = model.generate(\n", " **inputs, max_new_tokens=max_new_tokens,\n", " do_sample=False, repetition_penalty=1.2,\n", " pad_token_id=tokenizer.pad_token_id,\n", " eos_token_id=tokenizer.eos_token_id,\n", " )\n", " gen = out[0][inputs[\"input_ids\"].shape[1]:]\n", " text = tokenizer.decode(gen, skip_special_tokens=True).strip()\n", " if \"\\n\" in text:\n", " text = text.split(\"\\n\")[0].strip()\n", " return text\n", "\n", "# Test queries\n", "test_queries = [\n", " \"Translate to Sango: hello\",\n", " \"Translate to Sango: thank you\",\n", " \"Translate to English: Bara ala\",\n", " \"Traduire en fran\\u00e7ais : Singuila\",\n", " \"What does 'nzoni' mean in English?\",\n", " \"Translate to Sango: How are you?\",\n", " \"Traduire en sango : Bonjour\",\n", " \"How do you pronounce 'Bara ala' in Sango?\",\n", "]\n", "\n", "print(\"Model test results:\\n\")\n", "for q in test_queries:\n", " start = time.time()\n", " ans = generate_answer(q)\n", " t = time.time() - start\n", " print(f\" Q: {q}\")\n", " print(f\" A: {ans} ({t:.2f}s)\\n\")\n", "\n", "# Benchmark on eval set (first 100 examples for speed)\n", "print(\"=\" * 50)\n", "print(\"Benchmarking on eval set (first 100 examples) ...\")\n", "print(\"=\" * 50)\n", "exact = 0\n", "partial = 0\n", "n_eval = min(100, len(eval_data))\n", "for i, ex in enumerate(eval_data[:n_eval]):\n", " pred = generate_answer(ex[\"instruction\"])\n", " exp = ex[\"output\"]\n", " if pred.lower().strip() == exp.lower().strip():\n", " exact += 1\n", " if exp.lower() in pred.lower() or pred.lower() in exp.lower():\n", " partial += 1\n", " if (i + 1) % 25 == 0:\n", " print(f\" [{i+1}/{n_eval}] exact={exact} partial={partial}\")\n", "\n", "print(f\"\\nResults ({n_eval} examples):\")\n", "print(f\" Exact match: {exact}/{n_eval} ({100*exact/n_eval:.1f}%)\")\n", "print(f\" Partial match: {partial}/{n_eval} ({100*partial/n_eval:.1f}%)\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# Cell 7: Upload to Hugging Face (optional)\n", "# Uncomment and run to upload your trained adapter\n", "\n", "# from huggingface_hub import login\n", "# login() # Paste your HF token from https://huggingface.co/settings/tokens\n", "\n", "# model.push_to_hub(\"MEYNG/sango-tinyllama-lora\")\n", "# tokenizer.push_to_hub(\"MEYNG/sango-tinyllama-lora\")\n", "# print(\"Uploaded to https://huggingface.co/MEYNG/sango-tinyllama-lora\")\n", "\n", "# --- OR save to Google Drive before Colab session expires ---\n", "# from google.colab import drive\n", "# drive.mount(\"/content/drive\")\n", "# !cp -r /content/sango-lora-adapter /content/drive/MyDrive/sango-lora-adapter\n", "# print(\"Saved to Google Drive!\")\n", "\n", "print(\"To upload: uncomment the lines above and run this cell.\")\n", "print(f\"Adapter location: {OUTPUT_DIR}\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Next Steps\n", "\n", "**What you just built:** A LoRA adapter that teaches TinyLlama-1.1B to translate between Sango, French, and English.\n", "\n", "**To improve the model:**\n", "- Add more parallel text data (books, news articles, conversations in Sango)\n", "- Increase training epochs (5-10) for better memorization\n", "- Try a larger base model (Phi-2, Mistral-7B) if you have more VRAM\n", "- Fine-tune on conversational data for a Sango chatbot\n", "\n", "**Links:**\n", "- Dataset: [MEYNG/sango-vocabulary](https://huggingface.co/datasets/MEYNG/sango-vocabulary)\n", "- Model: [MEYNG/sango-tinyllama-lora](https://huggingface.co/MEYNG/sango-tinyllama-lora)\n", "- Platform: [sangoai.sbs](https://sangoai.sbs)\n", "- GitHub: [meyng-hub/sangoai](https://github.com/meyng-hub/sangoai)\n", "- Organization: [meyng.com](https://meyng.com)" ] } ] }