From 5b07e0cfeb0d3cb8ffbef6e510bcec68e623bbc5 Mon Sep 17 00:00:00 2001 From: Alp Date: Fri, 29 Nov 2019 17:34:16 +0100 Subject: [PATCH] commands to patch the empty lines problem #2 --- starter_notebook.ipynb | 1406 ++++++++++++++++++++-------------------- 1 file changed, 707 insertions(+), 699 deletions(-) diff --git a/starter_notebook.ipynb b/starter_notebook.ipynb index d2ba9416..269fa56a 100644 --- a/starter_notebook.ipynb +++ b/starter_notebook.ipynb @@ -1,701 +1,709 @@ { - "nbformat": 4, - "nbformat_minor": 0, - "metadata": { - "accelerator": "GPU", - "colab": { - "name": "starter_notebook.ipynb", - "provenance": [], - "collapsed_sections": [], - "toc_visible": true - }, - "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", - "version": "3.5.6" - } + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Igc5itf-xMGj" + }, + "source": [ + "# Masakhane - Machine Translation for African Languages (Using JoeyNMT)" + ] }, - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "Igc5itf-xMGj" - }, - "source": [ - "# Masakhane - Machine Translation for African Languages (Using JoeyNMT)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "x4fXCKCf36IK" - }, - "source": [ - "## Note before beginning:\n", - "### - The idea is that you should be able to make minimal changes to this in order to get SOME result for your own translation corpus. \n", - "\n", - "### - The tl;dr: Go to the **\"TODO\"** comments which will tell you what to update to get up and running\n", - "\n", - "### - If you actually want to have a clue what you're doing, read the text and peek at the links\n", - "\n", - "### - With 100 epochs, it should take around 7 hours to run in Google Colab\n", - "\n", - "### - Once you've gotten a result for your language, please attach and email your notebook that generated it to masakhanetranslation@gmail.com\n", - "\n", - "### - If you care enough and get a chance, doing a brief background on your language would be amazing. See examples in [(Martinus, 2019)](https://arxiv.org/abs/1906.05685)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "l929HimrxS0a" - }, - "source": [ - "## Retrieve your data & make a parallel corpus\n", - "\n", - "If you are wanting to use the JW300 data referenced on the Masakhane website or in our GitHub repo, you can use `opus-tools` to convert the data into a convenient format. `opus_read` from that package provides a convenient tool for reading the native aligned XML files and to convert them to TMX format. The tool can also be used to fetch relevant files from OPUS on the fly and to filter the data as necessary. [Read the documentation](https://pypi.org/project/opustools-pkg/) for more details.\n", - "\n", - "Once you have your corpus files in TMX format (an xml structure which will include the sentences in your target language and your source language in a single file), we recommend reading them into a pandas dataframe. Thankfully, Jade wrote a silly `tmx2dataframe` package which converts your tmx file to a pandas dataframe. " - ] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "oGRmDELn7Az0", - "colab": {} - }, - "source": [ - "from google.colab import drive\n", - "drive.mount('/content/drive')" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "Cn3tgQLzUxwn", - "colab": {} - }, - "source": [ - "# TODO: Set your source and target languages. Keep in mind, these traditionally use language codes as found here:\n", - "# These will also become the suffix's of all vocab and corpus files used throughout\n", - "import os\n", - "source_language = \"en\"\n", - "target_language = \"xh\" \n", - "lc = False # If True, lowercase the data.\n", - "seed = 42 # Random seed for shuffling.\n", - "tag = \"baseline\" # Give a unique name to your folder - this is to ensure you don't rewrite any models you've already submitted\n", - "\n", - "os.environ[\"src\"] = source_language # Sets them in bash as well, since we often use bash scripts\n", - "os.environ[\"tgt\"] = target_language\n", - "os.environ[\"tag\"] = tag\n", - "\n", - "# This will save it to a folder in our gdrive instead!\n", - "!mkdir -p \"/content/drive/My Drive/masakhane/$src-$tgt-$tag\"\n", - "os.environ[\"gdrive_path\"] = \"/content/drive/My Drive/masakhane/%s-%s-%s\" % (source_language, target_language, tag)" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "kBSgJHEw7Nvx", - "colab": {} - }, - "source": [ - "!echo $gdrive_path" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "gA75Fs9ys8Y9", - "colab": {} - }, - "source": [ - "# Install opus-tools\n", - "! pip install opustools-pkg" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "xq-tDZVks7ZD", - "colab": {} - }, - "source": [ - "# Downloading our corpus\n", - "! opus_read -d JW300 -s $src -t $tgt -wm moses -w jw300.$src jw300.$tgt -q\n", - "\n", - "# extract the corpus file\n", - "! gunzip JW300_latest_xml_$src-$tgt.xml.gz" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "id": "n48GDRnP8y2G", - "colab_type": "code", - "colab": {} - }, - "source": [ - "# Download the global test set.\n", - "! wget https://raw.githubusercontent.com/juliakreutzer/masakhane/master/jw300_utils/test/test.en-any.en\n", - " \n", - "# And the specific test set for this language pair.\n", - "os.environ[\"trg\"] = target_language \n", - "os.environ[\"src\"] = source_language \n", - "\n", - "! wget https://raw.githubusercontent.com/juliakreutzer/masakhane/master/jw300_utils/test/test.en-$trg.en \n", - "! mv test.en-$trg.en test.en\n", - "! wget https://raw.githubusercontent.com/juliakreutzer/masakhane/master/jw300_utils/test/test.en-$trg.$trg \n", - "! mv test.en-$trg.$trg test.$trg" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "id": "NqDG-CI28y2L", - "colab_type": "code", - "colab": {} - }, - "source": [ - "# Read the test data to filter from train and dev splits.\n", - "# Store english portion in set for quick filtering checks.\n", - "en_test_sents = set()\n", - "filter_test_sents = \"test.en-any.en\"\n", - "j = 0\n", - "with open(filter_test_sents) as f:\n", - " for line in f:\n", - " en_test_sents.add(line.strip())\n", - " j += 1\n", - "print('Loaded {} global test sentences to filter from the training/dev data.'.format(j))" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "3CNdwLBCfSIl", - "colab": {} - }, - "source": [ - "import pandas as pd\n", - "\n", - "# TMX file to dataframe\n", - "source_file = 'jw300.' + source_language\n", - "target_file = 'jw300.' + target_language\n", - "\n", - "source = []\n", - "target = []\n", - "skip_lines = [] # Collect the line numbers of the source portion to skip the same lines for the target portion.\n", - "with open(source_file) as f:\n", - " for i, line in enumerate(f):\n", - " # Skip sentences that are contained in the test set.\n", - " if line.strip() not in en_test_sents:\n", - " source.append(line.strip())\n", - " else:\n", - " skip_lines.append(i) \n", - "with open(target_file) as f:\n", - " for j, line in enumerate(f):\n", - " # Only add to corpus if corresponding source was not skipped.\n", - " if j not in skip_lines:\n", - " target.append(line.strip())\n", - " \n", - "print('Loaded data and skipped {}/{} lines since contained in test set.'.format(len(skip_lines), i))\n", - " \n", - "df = pd.DataFrame(zip(source, target), columns=['source_sentence', 'target_sentence'])\n", - "# if you get TypeError: data argument can't be an iterator is because of your zip version run this below\n", - "#df = pd.DataFrame(list(zip(source, target)), columns=['source_sentence', 'target_sentence'])\n", - "df.head(3)" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "YkuK3B4p2AkN" - }, - "source": [ - "## Pre-processing and export\n", - "\n", - "It is generally a good idea to remove duplicate translations and conflicting translations from the corpus. In practice, these public corpora include some number of these that need to be cleaned.\n", - "\n", - "In addition we will split our data into dev/test/train and export to the filesystem." - ] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "M_2ouEOH1_1q", - "colab": {} - }, - "source": [ - "# drop duplicate translations\n", - "df_pp = df.drop_duplicates()\n", - "\n", - "# drop conflicting translations\n", - "# (this is optional and something that you might want to comment out \n", - "# depending on the size of your corpus)\n", - "df_pp.drop_duplicates(subset='source_sentence', inplace=True)\n", - "df_pp.drop_duplicates(subset='target_sentence', inplace=True)\n", - "\n", - "# Shuffle the data to remove bias in dev set selection.\n", - "df_pp = df_pp.sample(frac=1, random_state=seed).reset_index(drop=True)" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "id": "Z_1BwAApEtMk", - "colab_type": "code", - "colab": {} - }, - "source": [ - "# Install fuzzy wuzzy to remove \"almost duplicate\" sentences in the\n", - "# test and training sets.\n", - "! pip install fuzzywuzzy\n", - "! pip install python-Levenshtein\n", - "import time\n", - "from fuzzywuzzy import process\n", - "import numpy as np\n", - "\n", - "# reset the index of the training set after previous filtering\n", - "df_pp.reset_index(drop=False, inplace=True)\n", - "\n", - "# Remove samples from the training data set if they \"almost overlap\" with the\n", - "# samples in the test set.\n", - "\n", - "# Filtering function. Adjust pad to narrow down the candidate matches to\n", - "# within a certain length of characters of the given sample.\n", - "def fuzzfilter(sample, candidates, pad):\n", - " candidates = [x for x in candidates if len(x) <= len(sample)+pad and len(x) >= len(sample)-pad] \n", - " if len(candidates) > 0:\n", - " return process.extractOne(sample, candidates)[1]\n", - " else:\n", - " return np.nan\n", - "\n", - "# NOTE - This might run slow depending on the size of your training set. We are\n", - "# printing some information to help you track how long it would take. \n", - "scores = []\n", - "start_time = time.time()\n", - "for idx, row in df_pp.iterrows():\n", - " scores.append(fuzzfilter(row['source_sentence'], list(en_test_sents), 5))\n", - " if idx % 1000 == 0:\n", - " hours, rem = divmod(time.time() - start_time, 3600)\n", - " minutes, seconds = divmod(rem, 60)\n", - " print(\"{:0>2}:{:0>2}:{:05.2f}\".format(int(hours),int(minutes),seconds), \"%0.2f percent complete\" % (100.0*float(idx)/float(len(df_pp))))\n", - "\n", - "# Filter out \"almost overlapping samples\"\n", - "df_pp['scores'] = scores\n", - "df_pp = df_pp[df_pp['scores'] < 95]" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "hxxBOCA-xXhy", - "colab": {} - }, - "source": [ - "# This section does the split between train/dev for the parallel corpora then saves them as separate files\n", - "# We use 1000 dev test and the given test set.\n", - "import csv\n", - "\n", - "# Do the split between dev/train and create parallel corpora\n", - "num_dev_patterns = 1000\n", - "\n", - "# Optional: lower case the corpora - this will make it easier to generalize, but without proper casing.\n", - "if lc: # Julia: making lowercasing optional\n", - " df_pp[\"source_sentence\"] = df_pp[\"source_sentence\"].str.lower()\n", - " df_pp[\"target_sentence\"] = df_pp[\"target_sentence\"].str.lower()\n", - "\n", - "# Julia: test sets are already generated\n", - "dev = df_pp.tail(num_dev_patterns) # Herman: Error in original\n", - "stripped = df_pp.drop(df_pp.tail(num_dev_patterns).index)\n", - "\n", - "with open(\"train.\"+source_language, \"w\") as src_file, open(\"train.\"+target_language, \"w\") as trg_file:\n", - " for index, row in stripped.iterrows():\n", - " src_file.write(row[\"source_sentence\"]+\"\\n\")\n", - " trg_file.write(row[\"target_sentence\"]+\"\\n\")\n", - " \n", - "with open(\"dev.\"+source_language, \"w\") as src_file, open(\"dev.\"+target_language, \"w\") as trg_file:\n", - " for index, row in dev.iterrows():\n", - " src_file.write(row[\"source_sentence\"]+\"\\n\")\n", - " trg_file.write(row[\"target_sentence\"]+\"\\n\")\n", - "\n", - "#stripped[[\"source_sentence\"]].to_csv(\"train.\"+source_language, header=False, index=False) # Herman: Added `header=False` everywhere\n", - "#stripped[[\"target_sentence\"]].to_csv(\"train.\"+target_language, header=False, index=False) # Julia: Problematic handling of quotation marks.\n", - "\n", - "#dev[[\"source_sentence\"]].to_csv(\"dev.\"+source_language, header=False, index=False)\n", - "#dev[[\"target_sentence\"]].to_csv(\"dev.\"+target_language, header=False, index=False)\n", - "\n", - "# Doublecheck the format below. There should be no extra quotation marks or weird characters.\n", - "! head train.*\n", - "! head dev.*" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "epeCydmCyS8X" - }, - "source": [ - "\n", - "\n", - "---\n", - "\n", - "\n", - "## Installation of JoeyNMT\n", - "\n", - "JoeyNMT is a simple, minimalist NMT package which is useful for learning and teaching. Check out the documentation for JoeyNMT [here](https://joeynmt.readthedocs.io) " - ] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "iBRMm4kMxZ8L", - "colab": {} - }, - "source": [ - "# Install JoeyNMT\n", - "! git clone https://github.com/joeynmt/joeynmt.git\n", - "! cd joeynmt; pip3 install ." - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "AaE77Tcppex9" - }, - "source": [ - "# Preprocessing the Data into Subword BPE Tokens\n", - "\n", - "- One of the most powerful improvements for agglutinative languages (a feature of most Bantu languages) is using BPE tokenization [ (Sennrich, 2015) ](https://arxiv.org/abs/1508.07909).\n", - "\n", - "- It was also shown that by optimizing the umber of BPE codes we significantly improve results for low-resourced languages [(Sennrich, 2019)](https://www.aclweb.org/anthology/P19-1021) [(Martinus, 2019)](https://arxiv.org/abs/1906.05685)\n", - "\n", - "- Below we have the scripts for doing BPE tokenization of our data. We use 4000 tokens as recommended by [(Sennrich, 2019)](https://www.aclweb.org/anthology/P19-1021). You do not need to change anything. Simply running the below will be suitable. " - ] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "H-TyjtmXB1mL", - "colab": {} - }, - "source": [ - "# One of the huge boosts in NMT performance was to use a different method of tokenizing. \n", - "# Usually, NMT would tokenize by words. However, using a method called BPE gave amazing boosts to performance\n", - "\n", - "# Do subword NMT\n", - "from os import path\n", - "os.environ[\"src\"] = source_language # Sets them in bash as well, since we often use bash scripts\n", - "os.environ[\"tgt\"] = target_language\n", - "\n", - "# Learn BPEs on the training data.\n", - "os.environ[\"data_path\"] = path.join(\"joeynmt\", \"data\", source_language + target_language) # Herman! \n", - "! subword-nmt learn-joint-bpe-and-vocab --input train.$src train.$tgt -s 4000 -o bpe.codes.4000 --write-vocabulary vocab.$src vocab.$tgt\n", - "\n", - "# Apply BPE splits to the development and test data.\n", - "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$src < train.$src > train.bpe.$src\n", - "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$tgt < train.$tgt > train.bpe.$tgt\n", - "\n", - "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$src < dev.$src > dev.bpe.$src\n", - "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$tgt < dev.$tgt > dev.bpe.$tgt\n", - "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$src < test.$src > test.bpe.$src\n", - "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$tgt < test.$tgt > test.bpe.$tgt\n", - "\n", - "# Create directory, move everyone we care about to the correct location\n", - "! mkdir -p $data_path\n", - "! cp train.* $data_path\n", - "! cp test.* $data_path\n", - "! cp dev.* $data_path\n", - "! cp bpe.codes.4000 $data_path\n", - "! ls $data_path\n", - "\n", - "# Also move everything we care about to a mounted location in google drive (relevant if running in colab) at gdrive_path\n", - "! cp train.* \"$gdrive_path\"\n", - "! cp test.* \"$gdrive_path\"\n", - "! cp dev.* \"$gdrive_path\"\n", - "! cp bpe.codes.4000 \"$gdrive_path\"\n", - "! ls \"$gdrive_path\"\n", - "\n", - "# Create that vocab using build_vocab\n", - "! sudo chmod 777 joeynmt/scripts/build_vocab.py\n", - "! joeynmt/scripts/build_vocab.py joeynmt/data/$src$tgt/train.bpe.$src joeynmt/data/$src$tgt/train.bpe.$tgt --output_path joeynmt/data/$src$tgt/vocab.txt\n", - "\n", - "# Some output\n", - "! echo \"BPE Xhosa Sentences\"\n", - "! tail -n 5 test.bpe.$tgt\n", - "! echo \"Combined BPE Vocab\"\n", - "! tail -n 10 joeynmt/data/$src$tgt/vocab.txt # Herman" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "IlMitUHR8Qy-", - "colab": {} - }, - "source": [ - "# Also move everything we care about to a mounted location in google drive (relevant if running in colab) at gdrive_path\n", - "! cp train.* \"$gdrive_path\"\n", - "! cp test.* \"$gdrive_path\"\n", - "! cp dev.* \"$gdrive_path\"\n", - "! cp bpe.codes.4000 \"$gdrive_path\"\n", - "! ls \"$gdrive_path\"" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "Ixmzi60WsUZ8" - }, - "source": [ - "# Creating the JoeyNMT Config\n", - "\n", - "JoeyNMT requires a yaml config. We provide a template below. We've also set a number of defaults with it, that you may play with!\n", - "\n", - "- We used Transformer architecture \n", - "- We set our dropout to reasonably high: 0.3 (recommended in [(Sennrich, 2019)](https://www.aclweb.org/anthology/P19-1021))\n", - "\n", - "Things worth playing with:\n", - "- The batch size (also recommended to change for low-resourced languages)\n", - "- The number of epochs (we've set it at 30 just so it runs in about an hour, for testing purposes)\n", - "- The decoder options (beam_size, alpha)\n", - "- Evaluation metrics (BLEU versus Crhf4)" - ] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "PIs1lY2hxMsl", - "colab": {} - }, - "source": [ - "# This creates the config file for our JoeyNMT system. It might seem overwhelming so we've provided a couple of useful parameters you'll need to update\n", - "# (You can of course play with all the parameters if you'd like!)\n", - "\n", - "name = '%s%s' % (source_language, target_language)\n", - "gdrive_path = os.environ[\"gdrive_path\"]\n", - "\n", - "# Create the config\n", - "config = \"\"\"\n", - "name: \"{name}_transformer\"\n", - "\n", - "data:\n", - " src: \"{source_language}\"\n", - " trg: \"{target_language}\"\n", - " train: \"data/{name}/train.bpe\"\n", - " dev: \"data/{name}/dev.bpe\"\n", - " test: \"data/{name}/test.bpe\"\n", - " level: \"bpe\"\n", - " lowercase: False\n", - " max_sent_length: 100\n", - " src_vocab: \"data/{name}/vocab.txt\"\n", - " trg_vocab: \"data/{name}/vocab.txt\"\n", - "\n", - "testing:\n", - " beam_size: 5\n", - " alpha: 1.0\n", - "\n", - "training:\n", - " #load_model: \"{gdrive_path}/models/{name}_transformer/1.ckpt\" # if uncommented, load a pre-trained model from this checkpoint\n", - " random_seed: 42\n", - " optimizer: \"adam\"\n", - " normalization: \"tokens\"\n", - " adam_betas: [0.9, 0.999] \n", - " scheduling: \"plateau\" # TODO: try switching from plateau to Noam scheduling\n", - " patience: 5 # For plateau: decrease learning rate by decrease_factor if validation score has not improved for this many validation rounds.\n", - " learning_rate_factor: 0.5 # factor for Noam scheduler (used with Transformer)\n", - " learning_rate_warmup: 1000 # warmup steps for Noam scheduler (used with Transformer)\n", - " decrease_factor: 0.7\n", - " loss: \"crossentropy\"\n", - " learning_rate: 0.0003\n", - " learning_rate_min: 0.00000001\n", - " weight_decay: 0.0\n", - " label_smoothing: 0.1\n", - " batch_size: 4096\n", - " batch_type: \"token\"\n", - " eval_batch_size: 3600\n", - " eval_batch_type: \"token\"\n", - " batch_multiplier: 1\n", - " early_stopping_metric: \"ppl\"\n", - " epochs: 30 # TODO: Decrease for when playing around and checking of working. Around 30 is sufficient to check if its working at all\n", - " validation_freq: 1000 # TODO: Set to at least once per epoch.\n", - " logging_freq: 100\n", - " eval_metric: \"bleu\"\n", - " model_dir: \"models/{name}_transformer\"\n", - " overwrite: False # TODO: Set to True if you want to overwrite possibly existing models. \n", - " shuffle: True\n", - " use_cuda: True\n", - " max_output_length: 100\n", - " print_valid_sents: [0, 1, 2, 3]\n", - " keep_last_ckpts: 3\n", - "\n", - "model:\n", - " initializer: \"xavier\"\n", - " bias_initializer: \"zeros\"\n", - " init_gain: 1.0\n", - " embed_initializer: \"xavier\"\n", - " embed_init_gain: 1.0\n", - " tied_embeddings: True\n", - " tied_softmax: True\n", - " encoder:\n", - " type: \"transformer\"\n", - " num_layers: 6\n", - " num_heads: 4 # TODO: Increase to 8 for larger data.\n", - " embeddings:\n", - " embedding_dim: 256 # TODO: Increase to 512 for larger data.\n", - " scale: True\n", - " dropout: 0.2\n", - " # typically ff_size = 4 x hidden_size\n", - " hidden_size: 256 # TODO: Increase to 512 for larger data.\n", - " ff_size: 1024 # TODO: Increase to 2048 for larger data.\n", - " dropout: 0.3\n", - " decoder:\n", - " type: \"transformer\"\n", - " num_layers: 6\n", - " num_heads: 4 # TODO: Increase to 8 for larger data.\n", - " embeddings:\n", - " embedding_dim: 256 # TODO: Increase to 512 for larger data.\n", - " scale: True\n", - " dropout: 0.2\n", - " # typically ff_size = 4 x hidden_size\n", - " hidden_size: 256 # TODO: Increase to 512 for larger data.\n", - " ff_size: 1024 # TODO: Increase to 2048 for larger data.\n", - " dropout: 0.3\n", - "\"\"\".format(name=name, gdrive_path=os.environ[\"gdrive_path\"], source_language=source_language, target_language=target_language)\n", - "with open(\"joeynmt/configs/transformer_{name}.yaml\".format(name=name),'w') as f:\n", - " f.write(config)" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "pIifxE3Qzuvs" - }, - "source": [ - "# Train the Model\n", - "\n", - "This single line of joeynmt runs the training using the config we made above" - ] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "6ZBPFwT94WpI", - "colab": {} - }, - "source": [ - "# Train the model\n", - "# You can press Ctrl-C to stop. And then run the next cell to save your checkpoints! \n", - "!cd joeynmt; python3 -m joeynmt train configs/transformer_$src$tgt.yaml" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "MBoDS09JM807", - "colab": {} - }, - "source": [ - "# Copy the created models from the notebook storage to google drive for persistant storage \n", - "!cp -r joeynmt/models/${src}${tgt}_transformer/* \"$gdrive_path/models/${src}${tgt}_transformer/\"" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "n94wlrCjVc17", - "colab": {} - }, - "source": [ - "# Output our validation accuracy\n", - "! cat \"$gdrive_path/models/${src}${tgt}_transformer/validations.txt\"" - ], - "execution_count": 0, - "outputs": [] - }, - { - "cell_type": "code", - "metadata": { - "colab_type": "code", - "id": "66WhRE9lIhoD", - "colab": {} - }, - "source": [ - "# Test our model\n", - "! cd joeynmt; python3 -m joeynmt test \"$gdrive_path/models/${src}${tgt}_transformer/config.yaml\"" - ], - "execution_count": 0, - "outputs": [] - } - ] -} \ No newline at end of file + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "x4fXCKCf36IK" + }, + "source": [ + "## Note before beginning:\n", + "### - The idea is that you should be able to make minimal changes to this in order to get SOME result for your own translation corpus. \n", + "\n", + "### - The tl;dr: Go to the **\"TODO\"** comments which will tell you what to update to get up and running\n", + "\n", + "### - If you actually want to have a clue what you're doing, read the text and peek at the links\n", + "\n", + "### - With 100 epochs, it should take around 7 hours to run in Google Colab\n", + "\n", + "### - Once you've gotten a result for your language, please attach and email your notebook that generated it to masakhanetranslation@gmail.com\n", + "\n", + "### - If you care enough and get a chance, doing a brief background on your language would be amazing. See examples in [(Martinus, 2019)](https://arxiv.org/abs/1906.05685)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "l929HimrxS0a" + }, + "source": [ + "## Retrieve your data & make a parallel corpus\n", + "\n", + "If you are wanting to use the JW300 data referenced on the Masakhane website or in our GitHub repo, you can use `opus-tools` to convert the data into a convenient format. `opus_read` from that package provides a convenient tool for reading the native aligned XML files and to convert them to TMX format. The tool can also be used to fetch relevant files from OPUS on the fly and to filter the data as necessary. [Read the documentation](https://pypi.org/project/opustools-pkg/) for more details.\n", + "\n", + "Once you have your corpus files in TMX format (an xml structure which will include the sentences in your target language and your source language in a single file), we recommend reading them into a pandas dataframe. Thankfully, Jade wrote a silly `tmx2dataframe` package which converts your tmx file to a pandas dataframe. " + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "oGRmDELn7Az0" + }, + "outputs": [], + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "Cn3tgQLzUxwn" + }, + "outputs": [], + "source": [ + "# TODO: Set your source and target languages. Keep in mind, these traditionally use language codes as found here:\n", + "# These will also become the suffix's of all vocab and corpus files used throughout\n", + "import os\n", + "source_language = \"en\"\n", + "target_language = \"xh\" \n", + "lc = False # If True, lowercase the data.\n", + "seed = 42 # Random seed for shuffling.\n", + "tag = \"baseline\" # Give a unique name to your folder - this is to ensure you don't rewrite any models you've already submitted\n", + "\n", + "os.environ[\"src\"] = source_language # Sets them in bash as well, since we often use bash scripts\n", + "os.environ[\"tgt\"] = target_language\n", + "os.environ[\"tag\"] = tag\n", + "\n", + "# This will save it to a folder in our gdrive instead!\n", + "!mkdir -p \"/content/drive/My Drive/masakhane/$src-$tgt-$tag\"\n", + "os.environ[\"gdrive_path\"] = \"/content/drive/My Drive/masakhane/%s-%s-%s\" % (source_language, target_language, tag)" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "kBSgJHEw7Nvx" + }, + "outputs": [], + "source": [ + "!echo $gdrive_path" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "gA75Fs9ys8Y9" + }, + "outputs": [], + "source": [ + "# Install opus-tools\n", + "! pip install opustools-pkg" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "xq-tDZVks7ZD" + }, + "outputs": [], + "source": [ + "# Downloading our corpus\n", + "! opus_read -d JW300 -s $src -t $tgt -wm moses -w jw300.$src jw300.$tgt -q\n", + "\n", + "# extract the corpus file\n", + "! gunzip JW300_latest_xml_$src-$tgt.xml.gz" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "n48GDRnP8y2G" + }, + "outputs": [], + "source": [ + "# Download the global test set.\n", + "! wget https://raw.githubusercontent.com/juliakreutzer/masakhane/master/jw300_utils/test/test.en-any.en\n", + " \n", + "# And the specific test set for this language pair.\n", + "os.environ[\"trg\"] = target_language \n", + "os.environ[\"src\"] = source_language \n", + "\n", + "! wget https://raw.githubusercontent.com/juliakreutzer/masakhane/master/jw300_utils/test/test.en-$trg.en \n", + "! mv test.en-$trg.en test.en\n", + "! wget https://raw.githubusercontent.com/juliakreutzer/masakhane/master/jw300_utils/test/test.en-$trg.$trg \n", + "! mv test.en-$trg.$trg test.$trg" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "NqDG-CI28y2L" + }, + "outputs": [], + "source": [ + "# Read the test data to filter from train and dev splits.\n", + "# Store english portion in set for quick filtering checks.\n", + "en_test_sents = set()\n", + "filter_test_sents = \"test.en-any.en\"\n", + "j = 0\n", + "with open(filter_test_sents) as f:\n", + " for line in f:\n", + " en_test_sents.add(line.strip())\n", + " j += 1\n", + "print('Loaded {} global test sentences to filter from the training/dev data.'.format(j))" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "3CNdwLBCfSIl" + }, + "outputs": [], + "source": [ + "import pandas as pd\n", + "\n", + "# TMX file to dataframe\n", + "source_file = 'jw300.' + source_language\n", + "target_file = 'jw300.' + target_language\n", + "\n", + "source = []\n", + "target = []\n", + "skip_lines = [] # Collect the line numbers of the source portion to skip the same lines for the target portion.\n", + "with open(source_file) as f:\n", + " for i, line in enumerate(f):\n", + " # Skip sentences that are contained in the test set.\n", + " if line.strip() not in en_test_sents:\n", + " source.append(line.strip())\n", + " else:\n", + " skip_lines.append(i) \n", + "with open(target_file) as f:\n", + " for j, line in enumerate(f):\n", + " # Only add to corpus if corresponding source was not skipped.\n", + " if j not in skip_lines:\n", + " target.append(line.strip())\n", + " \n", + "print('Loaded data and skipped {}/{} lines since contained in test set.'.format(len(skip_lines), i))\n", + " \n", + "df = pd.DataFrame(zip(source, target), columns=['source_sentence', 'target_sentence'])\n", + "# if you get TypeError: data argument can't be an iterator is because of your zip version run this below\n", + "#df = pd.DataFrame(list(zip(source, target)), columns=['source_sentence', 'target_sentence'])\n", + "df.head(3)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "YkuK3B4p2AkN" + }, + "source": [ + "## Pre-processing and export\n", + "\n", + "It is generally a good idea to remove duplicate translations and conflicting translations from the corpus. In practice, these public corpora include some number of these that need to be cleaned.\n", + "\n", + "In addition we will split our data into dev/test/train and export to the filesystem." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "M_2ouEOH1_1q" + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "# drop duplicate translations\n", + "df_pp = df.drop_duplicates()\n", + "\n", + "#drop empty lines (alp)\n", + "df_pp['source_sentence'].replace('', np.nan, inplace=True)\n", + "df_pp['target_sentence'].replace('', np.nan, inplace=True)\n", + "df_pp.dropna(subset=['source_sentence'], inplace=True)\n", + "df_pp.dropna(subset=['target_sentence'], inplace=True)\n", + "\n", + "# drop conflicting translations\n", + "# (this is optional and something that you might want to comment out \n", + "# depending on the size of your corpus)\n", + "df_pp.drop_duplicates(subset='source_sentence', inplace=True)\n", + "df_pp.drop_duplicates(subset='target_sentence', inplace=True)\n", + "\n", + "# Shuffle the data to remove bias in dev set selection.\n", + "df_pp = df_pp.sample(frac=1, random_state=seed).reset_index(drop=True)" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "Z_1BwAApEtMk" + }, + "outputs": [], + "source": [ + "# Install fuzzy wuzzy to remove \"almost duplicate\" sentences in the\n", + "# test and training sets.\n", + "! pip install fuzzywuzzy\n", + "! pip install python-Levenshtein\n", + "import time\n", + "from fuzzywuzzy import process\n", + "import numpy as np\n", + "\n", + "# reset the index of the training set after previous filtering\n", + "df_pp.reset_index(drop=False, inplace=True)\n", + "\n", + "# Remove samples from the training data set if they \"almost overlap\" with the\n", + "# samples in the test set.\n", + "\n", + "# Filtering function. Adjust pad to narrow down the candidate matches to\n", + "# within a certain length of characters of the given sample.\n", + "def fuzzfilter(sample, candidates, pad):\n", + " candidates = [x for x in candidates if len(x) <= len(sample)+pad and len(x) >= len(sample)-pad] \n", + " if len(candidates) > 0:\n", + " return process.extractOne(sample, candidates)[1]\n", + " else:\n", + " return np.nan\n", + "\n", + "# NOTE - This might run slow depending on the size of your training set. We are\n", + "# printing some information to help you track how long it would take. \n", + "scores = []\n", + "start_time = time.time()\n", + "for idx, row in df_pp.iterrows():\n", + " scores.append(fuzzfilter(row['source_sentence'], list(en_test_sents), 5))\n", + " if idx % 1000 == 0:\n", + " hours, rem = divmod(time.time() - start_time, 3600)\n", + " minutes, seconds = divmod(rem, 60)\n", + " print(\"{:0>2}:{:0>2}:{:05.2f}\".format(int(hours),int(minutes),seconds), \"%0.2f percent complete\" % (100.0*float(idx)/float(len(df_pp))))\n", + "\n", + "# Filter out \"almost overlapping samples\"\n", + "df_pp['scores'] = scores\n", + "df_pp = df_pp[df_pp['scores'] < 95]" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "hxxBOCA-xXhy" + }, + "outputs": [], + "source": [ + "# This section does the split between train/dev for the parallel corpora then saves them as separate files\n", + "# We use 1000 dev test and the given test set.\n", + "import csv\n", + "\n", + "# Do the split between dev/train and create parallel corpora\n", + "num_dev_patterns = 1000\n", + "\n", + "# Optional: lower case the corpora - this will make it easier to generalize, but without proper casing.\n", + "if lc: # Julia: making lowercasing optional\n", + " df_pp[\"source_sentence\"] = df_pp[\"source_sentence\"].str.lower()\n", + " df_pp[\"target_sentence\"] = df_pp[\"target_sentence\"].str.lower()\n", + "\n", + "# Julia: test sets are already generated\n", + "dev = df_pp.tail(num_dev_patterns) # Herman: Error in original\n", + "stripped = df_pp.drop(df_pp.tail(num_dev_patterns).index)\n", + "\n", + "with open(\"train.\"+source_language, \"w\") as src_file, open(\"train.\"+target_language, \"w\") as trg_file:\n", + " for index, row in stripped.iterrows():\n", + " src_file.write(row[\"source_sentence\"]+\"\\n\")\n", + " trg_file.write(row[\"target_sentence\"]+\"\\n\")\n", + " \n", + "with open(\"dev.\"+source_language, \"w\") as src_file, open(\"dev.\"+target_language, \"w\") as trg_file:\n", + " for index, row in dev.iterrows():\n", + " src_file.write(row[\"source_sentence\"]+\"\\n\")\n", + " trg_file.write(row[\"target_sentence\"]+\"\\n\")\n", + "\n", + "#stripped[[\"source_sentence\"]].to_csv(\"train.\"+source_language, header=False, index=False) # Herman: Added `header=False` everywhere\n", + "#stripped[[\"target_sentence\"]].to_csv(\"train.\"+target_language, header=False, index=False) # Julia: Problematic handling of quotation marks.\n", + "\n", + "#dev[[\"source_sentence\"]].to_csv(\"dev.\"+source_language, header=False, index=False)\n", + "#dev[[\"target_sentence\"]].to_csv(\"dev.\"+target_language, header=False, index=False)\n", + "\n", + "# Doublecheck the format below. There should be no extra quotation marks or weird characters.\n", + "! head train.*\n", + "! head dev.*" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "epeCydmCyS8X" + }, + "source": [ + "\n", + "\n", + "---\n", + "\n", + "\n", + "## Installation of JoeyNMT\n", + "\n", + "JoeyNMT is a simple, minimalist NMT package which is useful for learning and teaching. Check out the documentation for JoeyNMT [here](https://joeynmt.readthedocs.io) " + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "iBRMm4kMxZ8L" + }, + "outputs": [], + "source": [ + "# Install JoeyNMT\n", + "! git clone https://github.com/joeynmt/joeynmt.git\n", + "! cd joeynmt; pip3 install ." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "AaE77Tcppex9" + }, + "source": [ + "# Preprocessing the Data into Subword BPE Tokens\n", + "\n", + "- One of the most powerful improvements for agglutinative languages (a feature of most Bantu languages) is using BPE tokenization [ (Sennrich, 2015) ](https://arxiv.org/abs/1508.07909).\n", + "\n", + "- It was also shown that by optimizing the umber of BPE codes we significantly improve results for low-resourced languages [(Sennrich, 2019)](https://www.aclweb.org/anthology/P19-1021) [(Martinus, 2019)](https://arxiv.org/abs/1906.05685)\n", + "\n", + "- Below we have the scripts for doing BPE tokenization of our data. We use 4000 tokens as recommended by [(Sennrich, 2019)](https://www.aclweb.org/anthology/P19-1021). You do not need to change anything. Simply running the below will be suitable. " + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "H-TyjtmXB1mL" + }, + "outputs": [], + "source": [ + "# One of the huge boosts in NMT performance was to use a different method of tokenizing. \n", + "# Usually, NMT would tokenize by words. However, using a method called BPE gave amazing boosts to performance\n", + "\n", + "# Do subword NMT\n", + "from os import path\n", + "os.environ[\"src\"] = source_language # Sets them in bash as well, since we often use bash scripts\n", + "os.environ[\"tgt\"] = target_language\n", + "\n", + "# Learn BPEs on the training data.\n", + "os.environ[\"data_path\"] = path.join(\"joeynmt\", \"data\", source_language + target_language) # Herman! \n", + "! subword-nmt learn-joint-bpe-and-vocab --input train.$src train.$tgt -s 4000 -o bpe.codes.4000 --write-vocabulary vocab.$src vocab.$tgt\n", + "\n", + "# Apply BPE splits to the development and test data.\n", + "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$src < train.$src > train.bpe.$src\n", + "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$tgt < train.$tgt > train.bpe.$tgt\n", + "\n", + "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$src < dev.$src > dev.bpe.$src\n", + "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$tgt < dev.$tgt > dev.bpe.$tgt\n", + "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$src < test.$src > test.bpe.$src\n", + "! subword-nmt apply-bpe -c bpe.codes.4000 --vocabulary vocab.$tgt < test.$tgt > test.bpe.$tgt\n", + "\n", + "# Create directory, move everyone we care about to the correct location\n", + "! mkdir -p $data_path\n", + "! cp train.* $data_path\n", + "! cp test.* $data_path\n", + "! cp dev.* $data_path\n", + "! cp bpe.codes.4000 $data_path\n", + "! ls $data_path\n", + "\n", + "# Also move everything we care about to a mounted location in google drive (relevant if running in colab) at gdrive_path\n", + "! cp train.* \"$gdrive_path\"\n", + "! cp test.* \"$gdrive_path\"\n", + "! cp dev.* \"$gdrive_path\"\n", + "! cp bpe.codes.4000 \"$gdrive_path\"\n", + "! ls \"$gdrive_path\"\n", + "\n", + "# Create that vocab using build_vocab\n", + "! sudo chmod 777 joeynmt/scripts/build_vocab.py\n", + "! joeynmt/scripts/build_vocab.py joeynmt/data/$src$tgt/train.bpe.$src joeynmt/data/$src$tgt/train.bpe.$tgt --output_path joeynmt/data/$src$tgt/vocab.txt\n", + "\n", + "# Some output\n", + "! echo \"BPE Xhosa Sentences\"\n", + "! tail -n 5 test.bpe.$tgt\n", + "! echo \"Combined BPE Vocab\"\n", + "! tail -n 10 joeynmt/data/$src$tgt/vocab.txt # Herman" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "IlMitUHR8Qy-" + }, + "outputs": [], + "source": [ + "# Also move everything we care about to a mounted location in google drive (relevant if running in colab) at gdrive_path\n", + "! cp train.* \"$gdrive_path\"\n", + "! cp test.* \"$gdrive_path\"\n", + "! cp dev.* \"$gdrive_path\"\n", + "! cp bpe.codes.4000 \"$gdrive_path\"\n", + "! ls \"$gdrive_path\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Ixmzi60WsUZ8" + }, + "source": [ + "# Creating the JoeyNMT Config\n", + "\n", + "JoeyNMT requires a yaml config. We provide a template below. We've also set a number of defaults with it, that you may play with!\n", + "\n", + "- We used Transformer architecture \n", + "- We set our dropout to reasonably high: 0.3 (recommended in [(Sennrich, 2019)](https://www.aclweb.org/anthology/P19-1021))\n", + "\n", + "Things worth playing with:\n", + "- The batch size (also recommended to change for low-resourced languages)\n", + "- The number of epochs (we've set it at 30 just so it runs in about an hour, for testing purposes)\n", + "- The decoder options (beam_size, alpha)\n", + "- Evaluation metrics (BLEU versus Crhf4)" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "PIs1lY2hxMsl" + }, + "outputs": [], + "source": [ + "# This creates the config file for our JoeyNMT system. It might seem overwhelming so we've provided a couple of useful parameters you'll need to update\n", + "# (You can of course play with all the parameters if you'd like!)\n", + "\n", + "name = '%s%s' % (source_language, target_language)\n", + "gdrive_path = os.environ[\"gdrive_path\"]\n", + "\n", + "# Create the config\n", + "config = \"\"\"\n", + "name: \"{name}_transformer\"\n", + "\n", + "data:\n", + " src: \"{source_language}\"\n", + " trg: \"{target_language}\"\n", + " train: \"data/{name}/train.bpe\"\n", + " dev: \"data/{name}/dev.bpe\"\n", + " test: \"data/{name}/test.bpe\"\n", + " level: \"bpe\"\n", + " lowercase: False\n", + " max_sent_length: 100\n", + " src_vocab: \"data/{name}/vocab.txt\"\n", + " trg_vocab: \"data/{name}/vocab.txt\"\n", + "\n", + "testing:\n", + " beam_size: 5\n", + " alpha: 1.0\n", + "\n", + "training:\n", + " #load_model: \"{gdrive_path}/models/{name}_transformer/1.ckpt\" # if uncommented, load a pre-trained model from this checkpoint\n", + " random_seed: 42\n", + " optimizer: \"adam\"\n", + " normalization: \"tokens\"\n", + " adam_betas: [0.9, 0.999] \n", + " scheduling: \"plateau\" # TODO: try switching from plateau to Noam scheduling\n", + " patience: 5 # For plateau: decrease learning rate by decrease_factor if validation score has not improved for this many validation rounds.\n", + " learning_rate_factor: 0.5 # factor for Noam scheduler (used with Transformer)\n", + " learning_rate_warmup: 1000 # warmup steps for Noam scheduler (used with Transformer)\n", + " decrease_factor: 0.7\n", + " loss: \"crossentropy\"\n", + " learning_rate: 0.0003\n", + " learning_rate_min: 0.00000001\n", + " weight_decay: 0.0\n", + " label_smoothing: 0.1\n", + " batch_size: 4096\n", + " batch_type: \"token\"\n", + " eval_batch_size: 3600\n", + " eval_batch_type: \"token\"\n", + " batch_multiplier: 1\n", + " early_stopping_metric: \"ppl\"\n", + " epochs: 30 # TODO: Decrease for when playing around and checking of working. Around 30 is sufficient to check if its working at all\n", + " validation_freq: 1000 # TODO: Set to at least once per epoch.\n", + " logging_freq: 100\n", + " eval_metric: \"bleu\"\n", + " model_dir: \"models/{name}_transformer\"\n", + " overwrite: False # TODO: Set to True if you want to overwrite possibly existing models. \n", + " shuffle: True\n", + " use_cuda: True\n", + " max_output_length: 100\n", + " print_valid_sents: [0, 1, 2, 3]\n", + " keep_last_ckpts: 3\n", + "\n", + "model:\n", + " initializer: \"xavier\"\n", + " bias_initializer: \"zeros\"\n", + " init_gain: 1.0\n", + " embed_initializer: \"xavier\"\n", + " embed_init_gain: 1.0\n", + " tied_embeddings: True\n", + " tied_softmax: True\n", + " encoder:\n", + " type: \"transformer\"\n", + " num_layers: 6\n", + " num_heads: 4 # TODO: Increase to 8 for larger data.\n", + " embeddings:\n", + " embedding_dim: 256 # TODO: Increase to 512 for larger data.\n", + " scale: True\n", + " dropout: 0.2\n", + " # typically ff_size = 4 x hidden_size\n", + " hidden_size: 256 # TODO: Increase to 512 for larger data.\n", + " ff_size: 1024 # TODO: Increase to 2048 for larger data.\n", + " dropout: 0.3\n", + " decoder:\n", + " type: \"transformer\"\n", + " num_layers: 6\n", + " num_heads: 4 # TODO: Increase to 8 for larger data.\n", + " embeddings:\n", + " embedding_dim: 256 # TODO: Increase to 512 for larger data.\n", + " scale: True\n", + " dropout: 0.2\n", + " # typically ff_size = 4 x hidden_size\n", + " hidden_size: 256 # TODO: Increase to 512 for larger data.\n", + " ff_size: 1024 # TODO: Increase to 2048 for larger data.\n", + " dropout: 0.3\n", + "\"\"\".format(name=name, gdrive_path=os.environ[\"gdrive_path\"], source_language=source_language, target_language=target_language)\n", + "with open(\"joeynmt/configs/transformer_{name}.yaml\".format(name=name),'w') as f:\n", + " f.write(config)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "pIifxE3Qzuvs" + }, + "source": [ + "# Train the Model\n", + "\n", + "This single line of joeynmt runs the training using the config we made above" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "6ZBPFwT94WpI" + }, + "outputs": [], + "source": [ + "# Train the model\n", + "# You can press Ctrl-C to stop. And then run the next cell to save your checkpoints! \n", + "!cd joeynmt; python3 -m joeynmt train configs/transformer_$src$tgt.yaml" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "MBoDS09JM807" + }, + "outputs": [], + "source": [ + "# Copy the created models from the notebook storage to google drive for persistant storage \n", + "!cp -r joeynmt/models/${src}${tgt}_transformer/* \"$gdrive_path/models/${src}${tgt}_transformer/\"" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "n94wlrCjVc17" + }, + "outputs": [], + "source": [ + "# Output our validation accuracy\n", + "! cat \"$gdrive_path/models/${src}${tgt}_transformer/validations.txt\"" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "66WhRE9lIhoD" + }, + "outputs": [], + "source": [ + "# Test our model\n", + "! cd joeynmt; python3 -m joeynmt test \"$gdrive_path/models/${src}${tgt}_transformer/config.yaml\"" + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "collapsed_sections": [], + "name": "starter_notebook.ipynb", + "provenance": [], + "toc_visible": true + }, + "kernelspec": { + "display_name": "Python 3.7", + "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", + "version": "3.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +}