{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "W030Ll_cpF_H" }, "source": [ "#Luganda Language Model\n", "\n", "[Git Notebook: Reference](https://github.com/SunbirdAI/salt/blob/main/notebooks/Train%20Multilingual%20Model.ipynb)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "oLLGScuuP0VX" }, "outputs": [], "source": [ "# from IPython import display\n", "# !pip install transformers[torch]\n", "# !pip install sacrebleu\n", "# !pip install sacremoses\n", "# !pip install datasets\n", "# !pip install wandb\n", "# !pip install sentencepiece\n", "# display.clear_output()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3sVCeJ5ERnr2" }, "outputs": [], "source": [ "import datasets\n", "from IPython import display\n", "import numpy as np\n", "import os\n", "import pandas as pd\n", "import random\n", "import sentencepiece\n", "import sacrebleu\n", "import sacremoses\n", "import tqdm\n", "import transformers\n", "import torch\n", "import wandb" ] }, { "cell_type": "markdown", "metadata": { "id": "JpUFWhV3ab0e" }, "source": [ "#Dataset\n", "\n", "Let's start with step 1: loading and preprocessing the data. We'll define a function to load the sentences from the data files and create a tokenized dataset. This involves converting the sentences into sequences of numerical tokens that the model can work with. We'll use the AutoTokenizer class from the transformers library to do this. We'll also truncate or pad the sequences to a fixed length so that they can be batched together. The fixed length is a hyperparameter that you can adjust as needed." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "5cg3u77KQVY3" }, "outputs": [], "source": [ "from transformers import AutoTokenizer\n", "from torch.utils.data import Dataset\n", "from typing import List\n", "import torch\n", "\n", "class TranslationDataset(Dataset):\n", " def __init__(self, source_sentences: List[str], target_sentences: List[str], tokenizer, max_length=32):\n", " self.source_sentences = source_sentences\n", " self.target_sentences = target_sentences\n", " self.tokenizer = tokenizer\n", " self.max_length = max_length\n", "\n", " def __len__(self):\n", " return len(self.source_sentences)\n", "\n", " def __getitem__(self, idx):\n", " source_sentence = self.source_sentences[idx]\n", " target_sentence = self.target_sentences[idx]\n", "\n", " tokenized_source = self.tokenizer(source_sentence, truncation=True, padding='max_length', max_length=self.max_length, return_tensors=\"pt\")\n", " tokenized_target = self.tokenizer(target_sentence, truncation=True, padding='max_length', max_length=self.max_length, return_tensors=\"pt\")\n", "\n", " return tokenized_source, tokenized_target\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "F9S8nBSmQ6xF" }, "outputs": [], "source": [ "# Next, let's define a function to load the sentences from the data files\n", "def load_sentences(file_path):\n", " with open(file_path, \"r\") as f:\n", " sentences = f.read().split(\"\\n\")\n", " # Remove any empty sentences\n", " sentences = [sentence for sentence in sentences if sentence]\n", " return sentences\n" ] }, { "cell_type": "markdown", "metadata": { "id": "7icyFvbVasv8" }, "source": [ "Here we're using the `Helsinki-NLP/opus-mt-lg-en` model as the base for our tokenizer. This model has been pre-trained on a large corpus of Luganda and English text, so it should be a good starting point for our task." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "zvZGxxGfRN_2" }, "outputs": [], "source": [ "# Initialize the tokenizer\n", "tokenizer = AutoTokenizer.from_pretrained(\"Helsinki-NLP/opus-mt-lg-en\")\n", "\n", "# Load sentences\n", "source_sentences = load_sentences(\"train_comb.lug\")\n", "target_sentences = load_sentences(\"train_comb.en\")\n", "\n", "# Create the dataset\n", "dataset = TranslationDataset(source_sentences, target_sentences, tokenizer)\n", "\n", "# Similarly, you can create validation and test datasets\n", "\n", "valid_source_sentences = load_sentences(\"val.lug\")\n", "valid_target_sentences = load_sentences(\"val.en\")\n", "\n", "vadi_dataset = TranslationDataset(valid_source_sentences, valid_target_sentences, tokenizer)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "g98kVGKKSQhK" }, "outputs": [], "source": [ "from transformers import AutoModelForSeq2SeqLM\n", "\n", "# Initialize the model\n", "model = AutoModelForSeq2SeqLM.from_pretrained(\"Helsinki-NLP/opus-mt-lg-en\")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "IICfLDein5TM" }, "outputs": [], "source": [ "# def train_model(model, dataloader, val_dataloader, optimizer, num_epochs=10, save_path=\"Models/model.bin\", early_stop=3):\n", "# # Set initial validation loss to positive infinity\n", "# best_val_loss = float(\"inf\")\n", "# # Initialize early stopping counter\n", "# early_stop_counter = 0\n", "\n", "# # Training loop\n", "# for epoch in range(num_epochs):\n", "# # Training\n", "# model.train()\n", "# for batch in dataloader:\n", "# optimizer.zero_grad()\n", "# input_ids = batch[0][\"input_ids\"].squeeze().to(\"cuda\")\n", "# attention_mask = batch[0][\"attention_mask\"].squeeze().to(\"cuda\")\n", "# labels = batch[1][\"input_ids\"].squeeze().to(\"cuda\")\n", "# outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)\n", "# loss = outputs.loss\n", "# loss.backward()\n", "# optimizer.step()\n", "\n", "# # Validation\n", "# model.eval()\n", "# total_val_loss = 0\n", "# with torch.no_grad():\n", "# for batch in val_dataloader:\n", "# input_ids = batch[0][\"input_ids\"].squeeze().to(\"cuda\")\n", "# attention_mask = batch[0][\"attention_mask\"].squeeze().to(\"cuda\")\n", "# labels = batch[1][\"input_ids\"].squeeze().to(\"cuda\")\n", "# outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)\n", "# loss = outputs.loss\n", "# total_val_loss += loss.item()\n", "# avg_val_loss = total_val_loss / len(val_dataloader)\n", "# print(f\"Validation loss at epoch {epoch}: {avg_val_loss}\")\n", "\n", "# # If validation loss improved, save the model and reset early stopping counter\n", "# if avg_val_loss < best_val_loss:\n", "# best_val_loss = avg_val_loss\n", "# torch.save(model.state_dict(), save_path)\n", "# early_stop_counter = 0\n", "# # If validation loss did not improve, increment early stopping counter\n", "# else:\n", "# early_stop_counter += 1\n", "\n", "# # If early stopping counter reached limit, stop training early\n", "# if early_stop_counter >= early_stop:\n", "# print(\"Early stopping triggered\")\n", "# break\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "vcBedpk3SgSI", "outputId": "f52fd995-397e-4836-aa44-1d9e0fc94e35" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.10/dist-packages/transformers/optimization.py:411: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning\n", " warnings.warn(\n" ] } ], "source": [ "from torch.utils.data import DataLoader\n", "from transformers import AdamW\n", "import torch.nn.functional as F\n", "\n", "# Create the DataLoader\n", "dataloader = DataLoader(dataset, batch_size=32, shuffle=True)\n", "val_dataloader = DataLoader(vadi_dataset, batch_size=32, shuffle=True)\n", "\n", "# Initialize the optimizer\n", "optimizer = AdamW(model.parameters(), lr=1e-5)\n", "\n", "# Move the model to the GPU\n", "model = model.to(\"cuda\")\n", "\n", "def train_model(model, dataloader, val_dataloader, optimizer, num_epochs=100, save_path=\"Models/model.bin\", early_stop=15):\n", " # Set initial validation loss to positive infinity\n", " best_val_loss = float(\"inf\")\n", " # Initialize early stopping counter\n", " early_stop_counter = 0\n", "\n", " # Training loop\n", " for epoch in range(num_epochs):\n", " # Training\n", " model.train()\n", " for batch in dataloader:\n", " optimizer.zero_grad()\n", " input_ids = batch[0][\"input_ids\"].squeeze().to(\"cuda\")\n", " attention_mask = batch[0][\"attention_mask\"].squeeze().to(\"cuda\")\n", " labels = batch[1][\"input_ids\"].squeeze().to(\"cuda\")\n", " outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)\n", " loss = outputs.loss\n", " loss.backward()\n", " optimizer.step()\n", "\n", " # Validation\n", " model.eval()\n", " total_val_loss = 0\n", " with torch.no_grad():\n", " for batch in val_dataloader:\n", " input_ids = batch[0][\"input_ids\"].squeeze().to(\"cuda\")\n", " attention_mask = batch[0][\"attention_mask\"].squeeze().to(\"cuda\")\n", " labels = batch[1][\"input_ids\"].squeeze().to(\"cuda\")\n", " outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)\n", " loss = outputs.loss\n", " total_val_loss += loss.item()\n", " avg_val_loss = total_val_loss / len(val_dataloader)\n", " print(f\"Validation loss at epoch {epoch}: {avg_val_loss}\")\n", "\n", " # If validation loss improved, save the model and reset early stopping counter\n", " if avg_val_loss < best_val_loss:\n", " best_val_loss = avg_val_loss\n", " torch.save(model.state_dict(), save_path)\n", " early_stop_counter = 0\n", " # If validation loss did not improve, increment early stopping counter\n", " else:\n", " early_stop_counter += 1\n", "\n", " # If early stopping counter reached limit, stop training early\n", " if early_stop_counter >= early_stop:\n", " print(\"Early stopping triggered\")\n", " break\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SGLDovijVFgI", "outputId": "80431766-2367-453d-b644-970f0a277c6b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Validation loss at epoch 0: 1.7545462523319924\n", "Validation loss at epoch 1: 1.754554176515387\n", "Validation loss at epoch 2: 1.7544680806093438\n", "Validation loss at epoch 3: 1.7546287728834522\n", "Validation loss at epoch 4: 1.7545841932296753\n", "Validation loss at epoch 5: 1.754523749499358\n", "Validation loss at epoch 6: 1.7545043581215911\n", "Validation loss at epoch 7: 1.754460991815079\n", "Validation loss at epoch 8: 1.7544717650080837\n", "Validation loss at epoch 9: 1.754521275675574\n", "Validation loss at epoch 10: 1.7546228022538415\n", "Validation loss at epoch 11: 1.7545199015343835\n", "Validation loss at epoch 12: 1.7544237670972365\n", "Validation loss at epoch 13: 1.7543645856916443\n", "Validation loss at epoch 14: 1.7545291823010112\n", "Validation loss at epoch 15: 1.7544125946917275\n", "Validation loss at epoch 16: 1.7545219927795173\n", "Validation loss at epoch 17: 1.7544939120610554\n", "Validation loss at epoch 18: 1.7546383881753729\n", "Validation loss at epoch 19: 1.7544449724892313\n", "Validation loss at epoch 20: 1.7543920389441556\n", "Validation loss at epoch 21: 1.754468938176946\n", "Validation loss at epoch 22: 1.7544591380644214\n", "Validation loss at epoch 23: 1.7544086173523303\n", "Validation loss at epoch 24: 1.7543756333432456\n", "Validation loss at epoch 25: 1.7544627235841381\n", "Validation loss at epoch 26: 1.7545039237931717\n", "Validation loss at epoch 27: 1.7544716698254725\n", "Validation loss at epoch 28: 1.7545381793680117\n", "Validation loss at epoch 29: 1.7545897045800851\n", "Validation loss at epoch 30: 1.7545358460078868\n", "Validation loss at epoch 31: 1.7544444235720376\n", "Validation loss at epoch 32: 1.754581522571948\n", "Validation loss at epoch 33: 1.7545249785563743\n", "Validation loss at epoch 34: 1.754526928413746\n", "Validation loss at epoch 35: 1.7544997089592986\n", "Validation loss at epoch 36: 1.754356905471447\n", "Validation loss at epoch 37: 1.7544961908991024\n", "Validation loss at epoch 38: 1.7544016745663429\n", "Validation loss at epoch 39: 1.7544285225313763\n", "Validation loss at epoch 40: 1.7543853114741716\n", "Validation loss at epoch 41: 1.7544597156288089\n", "Validation loss at epoch 42: 1.7544455519018247\n", "Validation loss at epoch 43: 1.7545130761094796\n", "Validation loss at epoch 44: 1.7544649515965187\n", "Validation loss at epoch 45: 1.7544141277786374\n", "Validation loss at epoch 46: 1.7543530149977336\n", "Validation loss at epoch 47: 1.754479126412739\n", "Validation loss at epoch 48: 1.754434443259424\n", "Validation loss at epoch 49: 1.7545662998229035\n", "Validation loss at epoch 50: 1.7544944332551586\n", "Validation loss at epoch 51: 1.7544685287993083\n", "Validation loss at epoch 52: 1.754468088002168\n", "Validation loss at epoch 53: 1.754519222318664\n", "Validation loss at epoch 54: 1.7544778945834139\n", "Validation loss at epoch 55: 1.754462572031243\n", "Validation loss at epoch 56: 1.7544783483179964\n", "Validation loss at epoch 57: 1.75440527856812\n", "Validation loss at epoch 58: 1.7543795145759287\n", "Validation loss at epoch 59: 1.7547633232072342\n", "Validation loss at epoch 60: 1.7543582971705947\n", "Validation loss at epoch 61: 1.7546772864437843\n", "Validation loss at epoch 62: 1.75445248175037\n", "Validation loss at epoch 63: 1.7546141766762549\n", "Validation loss at epoch 64: 1.7545681397120159\n", "Validation loss at epoch 65: 1.7544179286143577\n", "Validation loss at epoch 66: 1.7545378984406936\n", "Validation loss at epoch 67: 1.7545608402222626\n", "Validation loss at epoch 68: 1.7545665456343067\n", "Validation loss at epoch 69: 1.7544571272162504\n", "Validation loss at epoch 70: 1.75438537523728\n", "Validation loss at epoch 71: 1.754475281220074\n", "Validation loss at epoch 72: 1.7544309556946274\n", "Validation loss at epoch 73: 1.7544244287549988\n", "Validation loss at epoch 74: 1.754499077796936\n", "Validation loss at epoch 75: 1.7544040023818497\n", "Validation loss at epoch 76: 1.7544351991756941\n", "Validation loss at epoch 77: 1.754511554111806\n", "Validation loss at epoch 78: 1.7543873029161794\n", "Validation loss at epoch 79: 1.7544674688531448\n", "Validation loss at epoch 80: 1.7544794553934142\n", "Validation loss at epoch 81: 1.7544126473655997\n", "Validation loss at epoch 82: 1.7543944314468738\n", "Validation loss at epoch 83: 1.7545764122822487\n", "Validation loss at epoch 84: 1.754630867824998\n", "Validation loss at epoch 85: 1.754439910252889\n", "Validation loss at epoch 86: 1.7544531914614891\n", "Validation loss at epoch 87: 1.754458603008773\n", "Validation loss at epoch 88: 1.7545876179554665\n", "Validation loss at epoch 89: 1.7544927439948386\n", "Validation loss at epoch 90: 1.7544405303260153\n", "Validation loss at epoch 91: 1.7544977942178415\n", "Validation loss at epoch 92: 1.7545225269110627\n", "Validation loss at epoch 93: 1.7544962186221928\n", "Validation loss at epoch 94: 1.7546170672705008\n", "Validation loss at epoch 95: 1.7544567150663035\n", "Validation loss at epoch 96: 1.7544416161470635\n", "Validation loss at epoch 97: 1.7545978921328405\n", "Validation loss at epoch 98: 1.7546191123104835\n", "Validation loss at epoch 99: 1.7544194071791892\n" ] } ], "source": [ "# Train the model\n", "train_model(model, dataloader, val_dataloader, optimizer)" ] }, { "cell_type": "markdown", "metadata": { "id": "P-3KwjtCZ0C2" }, "source": [ "# BLUE Score\n", "The Bilingual Evaluation Understudy (BLEU) score is a metric used to measure the quality of machine-generated translations. It compares the machine-generated translations to one or more reference translations. The BLEU score is a number between 0 and 100.\n", "\n", "1. A score of 0 means that the machine-generated translations do not match the reference translations at all.\n", "2. A score of 100 means that the machine-generated translations perfectly match the reference translations.\n", "\n", "The BLEU score takes into account the precision of n-grams in the machine-generated translations. It also includes a brevity penalty for translations that are too short, as these may not fully capture the meaning of the reference translations.\n", "\n", "Here are some general guidelines for interpreting BLEU scores:\n", "\n", "- A BLEU score in the range of 10-19 is considered to be equivalent to a translation done by a human with elementary proficiency in the target language, with some fluency errors.\n", "- A score in the range of 20-29 is roughly equivalent to a translation done by a human with intermediate proficiency in the target language, with minimal fluency errors.\n", "- A score in the range of 30-40 is equivalent to a translation done by a human with advanced proficiency in the target language, with few to no fluency errors.\n", "- A score in the range of 40-50 is equivalent to a translation done by a professional human translator.\n", "- A score above 50 is typically considered to be equivalent to a high-quality, professional human translation.\n", "\n", "It's important to note that while the BLEU score is a useful metric, it does not capture all aspects of translation quality. For example, it does not measure the grammatical correctness of the translations, and it may not accurately reflect the quality of translations for languages with complex grammar or sentence structure. Therefore, it's a good idea to use other evaluation methods in addition to the BLEU score when assessing the quality of machine translations." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "gpiRWBrmVcGK", "outputId": "bdb3fe7c-7659-462a-95e0-da74f63f64f6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "BLEU score: 62.538661494402014\n" ] } ], "source": [ "from transformers import AutoTokenizer\n", "from torch.utils.data import DataLoader\n", "from sacrebleu import corpus_bleu\n", "\n", "# Create the test dataset and DataLoader\n", "test_source_sentences = load_sentences(\"test.lug\")\n", "test_target_sentences = load_sentences(\"test.en\")\n", "test_dataset = TranslationDataset(test_source_sentences, test_target_sentences, tokenizer)\n", "test_dataloader = DataLoader(test_dataset, batch_size=32)\n", "\n", "# Evaluate the model\n", "model.eval()\n", "model.to(\"cuda\")\n", "\n", "predictions = []\n", "actuals = []\n", "\n", "with torch.no_grad():\n", " for batch in test_dataloader:\n", " input_ids = batch[0][\"input_ids\"].squeeze().to(\"cuda\")\n", " attention_mask = batch[0][\"attention_mask\"].squeeze().to(\"cuda\")\n", " labels = batch[1][\"input_ids\"].squeeze().to(\"cuda\")\n", " outputs = model.generate(input_ids=input_ids, attention_mask=attention_mask)\n", "\n", " # Convert output tokens to sentences\n", " pred_sentences = [tokenizer.decode(tokens) for tokens in outputs]\n", " actual_sentences = [tokenizer.decode(tokens) for tokens in labels]\n", " predictions.extend(pred_sentences)\n", " actuals.extend(actual_sentences)\n", "\n", "# Compute BLEU score\n", "bleu_score = corpus_bleu(predictions, [actuals]).score\n", "print(f\"BLEU score: {bleu_score}\")\n" ] }, { "cell_type": "markdown", "metadata": { "id": "iIWT_hi8dRNU" }, "source": [ "Load the saved model: You can load the saved model using the load_state_dict method. You'll need to initialize the model architecture first, and then load the saved parameters into it." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "FeoE1M2mdQwD" }, "outputs": [], "source": [ "model = AutoModelForSeq2SeqLM.from_pretrained(\"Helsinki-NLP/opus-mt-lg-en\")\n", "model.load_state_dict(torch.load(\"Models/model.bin\"))\n", "model = model.to(\"cuda\") # if you're using a GPU\n" ] }, { "cell_type": "markdown", "metadata": { "id": "uadyysKRdYrw" }, "source": [ "# Translate a new sentence:\n", "\n", "To translate a new sentence, you'll need to tokenize the sentence, feed it to the model, and then decode the model's output back into a sentence." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ma7Lcd6ndVIo", "outputId": "ec311303-ebc0-4c15-e9b5-a3e29d8665fc" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " How do you know?\n" ] } ], "source": [ "sentence = \"Oli otya?\"\n", "# Tokenize the sentence\n", "tokenized_sentence = tokenizer(sentence, return_tensors=\"pt\")\n", "tokenized_sentence = tokenized_sentence.to(\"cuda\") # if you're using a GPU\n", "# Generate the translation\n", "translated_tokens = model.generate(**tokenized_sentence)\n", "# Decode the translation\n", "translation = tokenizer.decode(translated_tokens[0])\n", "print(translation)\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }