From 1d12357027777db137d8068682257e50dfca3a74 Mon Sep 17 00:00:00 2001 From: MaximumEntropy Date: Wed, 25 May 2022 14:08:43 -0700 Subject: [PATCH 1/2] Raise error if bicleaner is not installed Signed-off-by: MaximumEntropy --- ...a_Preprocessing_and_Cleaning_for_NMT.ipynb | 1807 +++++++++-------- 1 file changed, 1007 insertions(+), 800 deletions(-) diff --git a/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb b/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb index 312e284ac30c..f35018234945 100644 --- a/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb +++ b/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb @@ -1,802 +1,1009 @@ { - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "68e3feb7", - "metadata": {}, - "outputs": [], - "source": [ - "\"\"\"\n", - "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n", - "\n", - "Instructions for setting up Colab are as follows:\n", - "1. Open a new Python 3 notebook.\n", - "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n", - "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n", - "4. Run this cell to set up dependencies.\n", - "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n", - "\"\"\"\n", - "## Install dependencies\n", - "!pip install wget\n", - "!apt-get install libboost-all-dev\n", - "!apt-get install gawk\n", - "\n", - "## Install NeMo\n", - "BRANCH = 'r1.9.0'\n", - "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n", - "\n", - "!pip uninstall -y sacrebleu\n", - "!pip install sacrebleu[ja]\n", - "!pip install xxhash\n", - "\n", - "## Install kenlm with 7-gram support\n", - "!mkdir -p data\n", - "!rm -rf data/kenlm\n", - "!git clone https://github.com/kpu/kenlm data/kenlm\n", - "!cd data/kenlm \\\n", - " && pip install . --install-option=\"--max_order 7\" \\\n", - " && mkdir -p build \\\n", - " && cd build \\\n", - " && cmake .. -DKENLM_MAX_ORDER=7 -DCMAKE_INSTALL_PREFIX:PATH=../../kenlm_install \\\n", - " && make -j all install && cd ../../kenlm_install \\\n", - " && export PATH=$PATH:$PWD\n", - "\n", - "# Install bicleaner\n", - "\n", - "!pip install bicleaner" - ] - }, - { - "cell_type": "markdown", - "id": "0075e98c", - "metadata": {}, - "source": [ - "# Data Preprocessing & Cleaning for NMT\n", - "\n", - "This notebook contains a tutorial of data processing and cleaning for NMT (Neural Machine Translation) to train translation models with the [NeMo framework](https://github.com/NVIDIA/NeMo).\n", - "\n", - "A pre-requisite to train supervised neural machine translation systems is the availability of *parallel corpora* of reasonable quality.\n", - "\n", - "A parallel corpus is a collection of sentences or documents that are translations of each other in 2 or more languages.\n", - "\n", - "For example,\n", - "\n", - "| English | Russian |\n", - "| :-: | :-: |\n", - "| To date, a total of 43 participants from 15 countries have completed the training. | К настоящему времени подготовку прошли в общей сложности 43 участника из 15 стран . |\n", - "| M-Sport Bentley writes a new piece of Bentley history at Silverstone | M-Sport Bentley открывает новую страницу в истории Bentley в Сильверстоуне |\n", - "| Information in the application was not true. | Информация в заявлении не была достоверна. |\n", - "\n", - "This notebook will cover the following data pre-processing and data cleaning techniques for such corpora.\n", - "\n", - "## The importance of data cleaning\n", - "\n", - "The presence of noise in the training dataset can adversely affect model quality (https://arxiv.org/abs/1805.12282). Webcrawled and automatically aligned data sources in particular, such as [Paracrawl](https://paracrawl.eu/), [WikiMatrix](https://arxiv.org/abs/1907.05791), [CC-Aligned](https://arxiv.org/abs/1911.06154) and [CC-Matrix](https://arxiv.org/abs/1911.04944) can be extremely noisy.\n", - "\n", - "## Cleaning\n", - "1. Downloading and filtering publicly available datasets based on confidence thresholds (if available). For example, [WikiMatrix](https://arxiv.org/abs/1907.05791) filtering based on [LASER](https://arxiv.org/abs/1812.10464) confidence scores.\n", - "2. Language ID filtering using a pre-trained [fastText classifier](https://fasttext.cc/docs/en/language-identification.html). This step will remove all sentences from the parallel corpus that our classifier predicts as not being in the appropriate language (ex: sentences in the English column that aren't in English or sentences in Russian column that aren't in Russian).\n", - "3. Length and Length-ratio filtering. This steps removes all sentences that are 1) too long 2) too short or 3) have a ratio between their lengths greater than a certain factor (this typically removes partial translations).\n", - "4. [Bicleaner](https://github.com/bitextor/bicleaner) classifier-based cleaning. Bicleaner identifies noisy parallel sentences using a classifier that leverages multiple features such as n-gram language model likelihood scores, word alignment scores and other heuristics.\n", - "\n", - "## Pre-processing\n", - "5. [Moses Punctuation Normalization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/normalize-punctuation.perl). This step standardizes punctuation. For example the less common way to write apostrophes Tiffany`s will be standardized to Tiffany's.\n", - "6. Unicode standardization. There exist some unicode characters that aren't punctuation that need to be standardized for example, this step normalizes the number 4 to 4.\n", - "7. [Moses Tokenization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl) or text segmentation for Chinese/Japanese with [Jieba](https://github.com/fxsjy/jieba) and [mecab](https://github.com/taku910/mecab). For languages like Chinese and Japanese that do not have explicit word segmentation markers (like spaces), we use these tools to introduce spaces into the text that will let us split the string into words. For other languages, we use Moses to separate punctuation markers from words so that they become separate tokens.\n", - "8. Deduplication - This step removes duplicate translation pairs from the corpus.\n", - "9. Shuffling - This step shuffles the order of occurrence of translation pairs.\n", - "\n", - "## Tarred Datasets for Large Corpora\n", - "10. Large datasets with over 50M sentence pairs when batched and pickled can be up to 60GB in size. Loading them entirely into CPU memory when using say 8 or 16 workers with DistributedDataParallel training uses 480-960GB of RAM which is often impractical and inefficient. Instead, we use [Webdataset](https://github.com/webdataset/webdataset) to allow training while keeping datasets on disk and let webddataset handle pre-loading and fetching of data into CPU RAM.\n", - "\n", - "\n", - "## Disclaimer\n", - "\n", - "The data cleaning techniques used in this notebook are only meant to be loose guidelines and are not guaranteed to produced clean parallel corpora at the end of it. Not all of these steps are a necessity for every dataset, " - ] - }, - { - "cell_type": "markdown", - "id": "bb0eb698", - "metadata": {}, - "source": [ - "![NMT Data Pipeline](images/nmt_data_pipeline.png)" - ] - }, - { - "cell_type": "markdown", - "id": "4a9fd8d3", - "metadata": {}, - "source": [ - "# Downloading Publicly Available Data\n", - "\n", - "## WikiMatrix (https://arxiv.org/abs/1907.05791)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "78984523", - "metadata": {}, - "outputs": [], - "source": [ - "!mkdir -p data\n", - "print('Downloading data ...')\n", - "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ru.tsv.gz -O data/WikiMatrix.en-ru.tsv.gz\n", - "print('---------------------')\n", - "print('Unzipping file ...')\n", - "!gunzip -k -f data/WikiMatrix.en-ru.tsv.gz\n", - "print('---------------------')\n", - "print('Peek into the file')\n", - "!head -10 data/WikiMatrix.en-ru.tsv\n", - "print('---------------------')\n", - "print('File length ...')\n", - "!wc -l data/WikiMatrix.en-ru.tsv\n", - "print('---------------------')" - ] - }, - { - "cell_type": "markdown", - "id": "b9a62f9e", - "metadata": {}, - "source": [ - "## Filter Based on LASER Confidence\n", - "\n", - "LASER (https://arxiv.org/abs/1812.10464) is a multi-lingual neural sentence embedding model that is often used for cross-lingual sentence/document retrieval. Similarities in the embedding space are often used as proxies for cross-lingual similarities." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "21608388", - "metadata": {}, - "outputs": [], - "source": [ - "from tqdm import tqdm\n", - "import numpy as np\n", - "\n", - "def num_lines_in_file(fname):\n", - " \"\"\"\n", - " Returns the number of lines in a file.\n", - " \"\"\"\n", - " with open(fname, 'r') as f:\n", - " for i, _ in enumerate(f):\n", - " pass\n", - " return i + 1\n", - "\n", - "def filter_tsv_with_conf(\n", - " input_file, output_file_lang_1, output_file_lang_2,\n", - " confidence_threshold=None, confidence_column=None\n", - "):\n", - " \"\"\"\n", - " Filters a tsv file that has confidence scores associated with each parallel example.\n", - "\n", - " For example:\n", - "\n", - " 1.23 \\t This is a sentence in lang1 \\t This is a sentence in lang2\n", - " \"\"\"\n", - " print()\n", - " print('====================================')\n", - " print('======= TSV Conf Filtering =========')\n", - " print('====================================')\n", - " print()\n", - " num_lines = num_lines_in_file(input_file)\n", - " scores = []\n", - " num_output_lines = 0\n", - " lang_1_col = 0\n", - " lang_2_col = 1\n", - " with open(input_file, 'r') as f, \\\n", - " open(output_file_lang_1, 'w') as f_out_1, \\\n", - " open(output_file_lang_2, 'w') as f_out_2:\n", - " for line in tqdm(f, total=num_lines, desc=f\"Filtering file by confidence {confidence_threshold}\"):\n", - " if line.strip() == '':\n", - " continue\n", - " line = line.strip().split('\\t')\n", - " if len(line) < 2:\n", - " continue\n", - " if confidence_threshold is not None and float(line[confidence_column]) < confidence_threshold:\n", - " continue\n", - " else:\n", - " if confidence_threshold is not None:\n", - " scores.append(float(line[confidence_column]))\n", - " if confidence_column == 0:\n", - " lang_1_col, lang_2_col = 1, 2\n", - " elif confidence_column == 2:\n", - " lang_1_col, lang_2_col = 0, 1\n", - " elif confidence_column == 1:\n", - " lang_1_col, lang_2_col = 0, 2\n", - " else:\n", - " raise ValueError(f\"Invalid Column for confidence {confidence_column}\")\n", - " f_out_1.write(line[lang_1_col] + '\\n')\n", - " f_out_2.write(line[lang_2_col] + '\\n')\n", - " num_output_lines += 1\n", - "\n", - " if confidence_threshold is not None:\n", - " print(f'Confidence score average : {np.mean(scores)}')\n", - " print(f'Confidence score variance : {np.var(scores)}')\n", - " print(f'Kept {num_output_lines} out of {num_lines} after conversion ({(num_output_lines / num_lines) * 100}%)')\n", - " print('====================================')\n", - "\n", - "filter_tsv_with_conf(\n", - " 'data/WikiMatrix.en-ru.tsv',\n", - " 'data/WikiMatrix.en-ru.en', \n", - " 'data/WikiMatrix.en-ru.ru',\n", - " confidence_threshold=1.04, confidence_column=0\n", - ")" - ] - }, - { - "cell_type": "markdown", - "id": "18a171d1", - "metadata": {}, - "source": [ - "## Language ID filtering with fastText\n", - "\n", - "Noisy parallel corpora often contain sentences that are not in the intended language. A classifier that determines the language in which a sentence is written can be used to filter out sentences that aren't in the appropriate language." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d58b7148", - "metadata": {}, - "outputs": [], - "source": [ - "!wget https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin -O data/lid.176.bin\n", - "print()\n", - "print('====================================')\n", - "print('====== Language ID Filtering =======')\n", - "print('====================================')\n", - "print()\n", - "\n", - "\n", - "!wget https://raw.github.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py \\\n", - " -O filter_langs_nmt.py\n", - "\n", - "!python filter_langs_nmt.py \\\n", - " --input-src data/WikiMatrix.en-ru.en \\\n", - " --input-tgt data/WikiMatrix.en-ru.ru \\\n", - " --output-src data/WikiMatrix.en-ru.langidfilter.en \\\n", - " --output-tgt data/WikiMatrix.en-ru.langidfilter.ru \\\n", - " --source-lang en \\\n", - " --target-lang ru \\\n", - " --removed-src data/WikiMatrix.en-ru.langidfilter.removed.en \\\n", - " --removed-tgt data/WikiMatrix.en-ru.langidfilter.removed.ru \\\n", - " --fasttext-model data/lid.176.bin\n", - "\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Number of removed sentences:')\n", - "print('-----------------------------------------')\n", - "print()\n", - "!wc -l data/WikiMatrix.en-ru.langidfilter.removed.ru\n", - "\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Examples of removed sentences')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "!paste -d \"\\t\" \\\n", - " data/WikiMatrix.en-ru.langidfilter.removed.en \\\n", - " data/WikiMatrix.en-ru.langidfilter.removed.ru \\\n", - " | head -10\n", - "print('-----------------------------------------')" - ] - }, - { - "cell_type": "markdown", - "id": "ffb42e92", - "metadata": {}, - "source": [ - "## Length and Ratio Filtering\n", - "\n", - "This step filters out sentences based on their lengths and the ratio between source and target lengths. If (a) src_len / tgt_len or tgt_len / src_len exceed 1.3 or (b) source or target sequence lengths are less than 1 or greater than 250, the sentence pair will be removed." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "52ff172a", - "metadata": {}, - "outputs": [], - "source": [ - "!git clone https://github.com/moses-smt/mosesdecoder data/mosesdecoder\n", - "!cd data/mosesdecoder && git checkout RELEASE-4.0 && cd ../..\n", - "!perl data/mosesdecoder/scripts/training/clean-corpus-n.perl -ratio 1.3 \\\n", - " data/WikiMatrix.en-ru.langidfilter \\\n", - " en ru \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio \\\n", - " 1 250" - ] - }, - { - "cell_type": "markdown", - "id": "01f2b589", - "metadata": {}, - "source": [ - "## Bicleaner Filtering\n", - "\n", - "Bicleaner (https://aclanthology.org/W18-6488/ and https://aclanthology.org/2020.eamt-1.31/) is a tool to identify noisy parallel sentences in translation corpora. It applies 3 different filtering steps:\n", - "\n", - "1. Pre-filtering based on 37 rules.\n", - "2. Language model fluency scores based on n-gram language models trained with kenlm.\n", - "3. Random forest classifier that uses all examples filtered out in steps 1 & 2 as \"negative\" examples." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9be8d4ca", - "metadata": {}, - "outputs": [], - "source": [ - "print('Downloading En-Ru Bicleaner models.')\n", - "!git clone https://github.com/bitextor/bicleaner data/bicleaner\n", - "!cd data/bicleaner && git checkout bicleaner-0.15 && cd ../..\n", - "!data/bicleaner/utils/download-pack.sh en ru\n", - "\n", - "print('Generating Bicleaner scores ...')\n", - "!gawk '{{print \"-\\t-\"}}' \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.en | \\\n", - " paste -d \"\\t\" - data/WikiMatrix.en-ru.langidfilter.lengthratio.en \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.ru | \\\n", - " bicleaner-classify - - en-ru/en-ru.yaml \\\n", - " > data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "43059b8a", - "metadata": {}, - "outputs": [], - "source": [ - "print('Score file ...')\n", - "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores\n", - "\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Filtering based on Bicleaner scores > 0.6 ...')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "print('Filtering out English ...')\n", - "!gawk -F \"\\t\" '{if ($5>0.6) {print $3}}' \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en\n", - "\n", - "print('Filtering out Russian ...')\n", - "!gawk -F \"\\t\" '{if ($5>0.6) {print $4}}' \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru\n", - "\n", - "!paste -d \"\\t\" \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru \\\n", - " | head -10" - ] - }, - { - "cell_type": "markdown", - "id": "0726510c", - "metadata": {}, - "source": [ - "## Normalize Punctuation\n", - "\n", - "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n", - "\n", - "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed." - ] - }, - { - "cell_type": "markdown", - "id": "e73670d6", - "metadata": {}, - "source": [ - "### Sacremoses" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "597e041a", - "metadata": {}, - "outputs": [], - "source": [ - "print('Normalizing English ...')\n", - "!sacremoses -j 4 normalize \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en\n", - "\n", - "print('Normalizing Russian ...')\n", - "!sacremoses -j 4 normalize \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru\n" - ] - }, - { - "cell_type": "markdown", - "id": "240b0a1f", - "metadata": {}, - "source": [ - "## Moses\n", - "\n", - "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n", - "\n", - "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1f5adaa4", - "metadata": {}, - "outputs": [], - "source": [ - "print('Normalizing English ...')\n", - "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l en \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en\n", - "\n", - "print('Normalizing Russian ...')\n", - "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l ru \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru\n" - ] - }, - { - "cell_type": "markdown", - "id": "b8bfad64", - "metadata": {}, - "source": [ - "## Tokenize\n", - "\n", - "Tokenization splits a string into a sequence of tokens. A naive way of doing this would be to simply split the string on spaces (for languages where this is possible). This however, will result in punctuation being \"attached\" to the neighboring word when tokenizing. For example, \n", - "\n", - "\"This is a sentence.\" will be tokenized as [\"This, is, a, sentence.\"].\n", - "\n", - "However, we'd typically like punctuation to be separate tokens for example,\n", - "\n", - "\"This is a sentence.\" will be tokenized my moses or sacremoses as [\", This, is, a, sentence, ., \"]." - ] - }, - { - "cell_type": "markdown", - "id": "06c60b90", - "metadata": {}, - "source": [ - "### Sacremoses" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7bb4c631", - "metadata": {}, - "outputs": [], - "source": [ - "print('Tokenizing English ...')\n", - "!sacremoses -j 4 -l en tokenize -x \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.en\n", - "\n", - "print('Tokenizing Russian ...')\n", - "!sacremoses -j 4 -l ru tokenize -x \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.ru\n" - ] - }, - { - "cell_type": "markdown", - "id": "444bebd7", - "metadata": {}, - "source": [ - "### Moses" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "21333e27", - "metadata": {}, - "outputs": [], - "source": [ - "print('Tokenizing English ...')\n", - "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l en -no-escape -threads 4 \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en\n", - "\n", - "print('Tokenizing Russian ...')\n", - "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l ru -no-escape -threads 4 \\\n", - " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b28df2bb", - "metadata": {}, - "outputs": [], - "source": [ - "print()\n", - "print('-----------------------------------------')\n", - "print('Tokenized Russian Sentences ...')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n", - "\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Tokenized English Sentences ...')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en" - ] - }, - { - "cell_type": "markdown", - "id": "dee5409d", - "metadata": {}, - "source": [ - "## Segmenting Chinese and Japanese\n", - "\n", - "### Jieba segmentation for Chinese" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "41b4cc91", - "metadata": {}, - "outputs": [], - "source": [ - "import jieba\n", - "\n", - "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-zh.tsv.gz -O data/WikiMatrix.en-zh.tsv.gz\n", - "!gunzip -k -f data/WikiMatrix.en-zh.tsv.gz\n", - "\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Chinese text before segmentation ...')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-zh.tsv | head -10\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Segmenting Chinese text ...')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "zh_lines = []\n", - "with open('data/WikiMatrix.en-zh.tsv', 'r') as f:\n", - " for idx, line in enumerate(f):\n", - " line = line.strip().split('\\t')[2]\n", - " zh_lines.append(' '.join(jieba.cut(line)))\n", - " if idx == 100:\n", - " break\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Chinese text after segmentation ...')\n", - "print('\\n'.join(zh_lines[:10]))\n", - "print('-----------------------------------------')\n", - "print()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "489bd915", - "metadata": {}, - "outputs": [], - "source": [ - "import MeCab\n", - "import ipadic\n", - "\n", - "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ja.tsv.gz -O data/WikiMatrix.en-ja.tsv.gz\n", - "!gunzip -k -f data/WikiMatrix.en-ja.tsv.gz\n", - "\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Japanese text before segmentation ...')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-ja.tsv | head -10\n", - "\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Segmenting Japanese text ...')\n", - "print('-----------------------------------------')\n", - "print()\n", - "\n", - "mecab_tokenizer = MeCab.Tagger(ipadic.MECAB_ARGS + \" -Owakati\")\n", - "\n", - "ja_lines = []\n", - "with open('data/WikiMatrix.en-ja.tsv', 'r') as f:\n", - " for idx, line in enumerate(f):\n", - " line = line.strip().split('\\t')[2]\n", - " ja_lines.append(mecab_tokenizer.parse(line))\n", - " if idx == 100:\n", - " break\n", - "print()\n", - "print('-----------------------------------------')\n", - "print('Japanese text after segmentation ...')\n", - "print('\\n'.join(ja_lines[:10]))\n", - "print('-----------------------------------------')\n", - "print()" - ] - }, - { - "cell_type": "markdown", - "id": "4a079efe", - "metadata": {}, - "source": [ - "## Deduplicate" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "55d98bf3", - "metadata": {}, - "outputs": [], - "source": [ - "import xxhash\n", - "\n", - "def dedup_file(input_file_lang_1, input_file_lang_2, output_file_lang_1, output_file_lang_2):\n", - " print()\n", - " print('====================================')\n", - " print('========== De-duplicate ============')\n", - " print('====================================')\n", - " print()\n", - " num_lines = num_lines_in_file(input_file_lang_1)\n", - " hashes = set()\n", - " num_output_lines = 0\n", - " with open(input_file_lang_1, 'r') as f_lang1, \\\n", - " open(input_file_lang_2, 'r') as f_lang2, \\\n", - " open(output_file_lang_1, 'w') as f_out_lang1, \\\n", - " open(output_file_lang_2, 'w') as f_out_lang2:\n", - " for line_1, line_2 in tqdm(zip(f_lang1, f_lang2), total=num_lines, desc=f\"Deduplicating files\"):\n", - " parallel_hash = xxhash.xxh64((line_1.strip() + '\\t' + line_2.strip()).encode('utf-8')).hexdigest()\n", - " if parallel_hash not in hashes:\n", - " hashes.add(parallel_hash)\n", - " f_out_lang1.write(line_1.strip() + '\\n')\n", - " f_out_lang2.write(line_2.strip() + '\\n')\n", - " num_output_lines += 1\n", - "\n", - " print(f\"Kept {num_output_lines} out of {num_lines} after deduplication\")\n", - "\n", - "dedup_file(\n", - " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en',\n", - " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru',\n", - " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en',\n", - " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru'\n", - ")" - ] - }, - { - "cell_type": "markdown", - "id": "da4c181a", - "metadata": {}, - "source": [ - "## Shuffle" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "413734bd", - "metadata": {}, - "outputs": [], - "source": [ - "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en\n", - "\n", - "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru > \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru\n", - "\n", - "!paste -d \"\\t\" \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n", - " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n", - " | head -10" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5f3b3640", - "metadata": {}, - "outputs": [], - "source": [ - "!rm -rf data/tarred_dataset_en_ru_8k_tokens" - ] - }, - { - "cell_type": "markdown", - "id": "844a9f26", - "metadata": {}, - "source": [ - "## Tarred Dataset Creation" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2b045df5", - "metadata": {}, - "outputs": [], - "source": [ - "!wget https://raw.github.com/NVIDIA/NeMo/main/examples/nlp/machine_translation/create_tarred_parallel_dataset.py \\\n", - " -O create_tarred_parallel_dataset.py\n", - "\n", - "!python create_tarred_parallel_dataset.py \\\n", - " --src_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n", - " --tgt_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n", - " --out_dir data/tarred_dataset_en_ru_8k_tokens \\\n", - " --clean \\\n", - " --encoder_tokenizer_name yttm \\\n", - " --encoder_tokenizer_vocab_size 32000 \\\n", - " --encoder_tokenizer_coverage 0.999 \\\n", - " --encoder_tokenizer_bpe_dropout 0.1 \\\n", - " --decoder_tokenizer_name yttm \\\n", - " --decoder_tokenizer_vocab_size 32000 \\\n", - " --decoder_tokenizer_coverage 0.999 \\\n", - " --decoder_tokenizer_bpe_dropout 0.1 \\\n", - " --max_seq_length 512 \\\n", - " --min_seq_length 1 \\\n", - " --tokens_in_batch 8000 \\\n", - " --lines_per_dataset_fragment 100000 \\\n", - " --num_batches_per_tarfile 20\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "990265e5", - "metadata": {}, - "outputs": [], - "source": [ - "!ls data/tarred_dataset_en_ru_8k_tokens" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cc5e123b", - "metadata": {}, - "outputs": [], - "source": [ - "!cat data/tarred_dataset_en_ru_8k_tokens/metadata.tokens.8000.json" - ] - } - ], - "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", - "version": "3.8.8" - } + "cells": [ + { + "cell_type": "markdown", + "id": "fa2a0346", + "metadata": {}, + "source": [ + "Instructions for setting up Colab are as follows:\n", + "1. Open a new Python 3 notebook.\n", + "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n", + "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n", + "4. Run this cell to set up dependencies.\n", + "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect" + ] + }, + { + "cell_type": "markdown", + "id": "0075e98c", + "metadata": {}, + "source": [ + "# Data Preprocessing & Cleaning for NMT\n", + "\n", + "This notebook contains a tutorial of data processing and cleaning for NMT (Neural Machine Translation) to train translation models with the [NeMo framework](https://github.com/NVIDIA/NeMo).\n", + "\n", + "A pre-requisite to train supervised neural machine translation systems is the availability of *parallel corpora* of reasonable quality.\n", + "\n", + "A parallel corpus is a collection of sentences or documents that are translations of each other in 2 or more languages.\n", + "\n", + "For example,\n", + "\n", + "| English | Russian |\n", + "| :-: | :-: |\n", + "| To date, a total of 43 participants from 15 countries have completed the training. | К настоящему времени подготовку прошли в общей сложности 43 участника из 15 стран . |\n", + "| M-Sport Bentley writes a new piece of Bentley history at Silverstone | M-Sport Bentley открывает новую страницу в истории Bentley в Сильверстоуне |\n", + "| Information in the application was not true. | Информация в заявлении не была достоверна. |\n", + "\n", + "This notebook will cover the following data pre-processing and data cleaning techniques for such corpora.\n", + "\n", + "## The importance of data cleaning\n", + "\n", + "The presence of noise in the training dataset can adversely affect model quality (https://arxiv.org/abs/1805.12282). Webcrawled and automatically aligned data sources in particular, such as [Paracrawl](https://paracrawl.eu/), [WikiMatrix](https://arxiv.org/abs/1907.05791), [CC-Aligned](https://arxiv.org/abs/1911.06154) and [CC-Matrix](https://arxiv.org/abs/1911.04944) can be extremely noisy.\n", + "\n", + "## Cleaning\n", + "1. Downloading and filtering publicly available datasets based on confidence thresholds (if available). For example, [WikiMatrix](https://arxiv.org/abs/1907.05791) filtering based on [LASER](https://arxiv.org/abs/1812.10464) confidence scores.\n", + "2. Language ID filtering using a pre-trained [fastText classifier](https://fasttext.cc/docs/en/language-identification.html). This step will remove all sentences from the parallel corpus that our classifier predicts as not being in the appropriate language (ex: sentences in the English column that aren't in English or sentences in Russian column that aren't in Russian).\n", + "3. Length and Length-ratio filtering. This steps removes all sentences that are 1) too long 2) too short or 3) have a ratio between their lengths greater than a certain factor (this typically removes partial translations).\n", + "4. [Bicleaner](https://github.com/bitextor/bicleaner) classifier-based cleaning. Bicleaner identifies noisy parallel sentences using a classifier that leverages multiple features such as n-gram language model likelihood scores, word alignment scores and other heuristics.\n", + "\n", + "## Pre-processing\n", + "5. [Moses Punctuation Normalization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/normalize-punctuation.perl). This step standardizes punctuation. For example the less common way to write apostrophes Tiffany`s will be standardized to Tiffany's.\n", + "6. Unicode standardization. There exist some unicode characters that aren't punctuation that need to be standardized for example, this step normalizes the number 4 to 4.\n", + "7. [Moses Tokenization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl) or text segmentation for Chinese/Japanese with [Jieba](https://github.com/fxsjy/jieba) and [mecab](https://github.com/taku910/mecab). For languages like Chinese and Japanese that do not have explicit word segmentation markers (like spaces), we use these tools to introduce spaces into the text that will let us split the string into words. For other languages, we use Moses to separate punctuation markers from words so that they become separate tokens.\n", + "8. Deduplication - This step removes duplicate translation pairs from the corpus.\n", + "9. Shuffling - This step shuffles the order of occurrence of translation pairs.\n", + "\n", + "## Tarred Datasets for Large Corpora\n", + "10. Large datasets with over 50M sentence pairs when batched and pickled can be up to 60GB in size. Loading them entirely into CPU memory when using say 8 or 16 workers with DistributedDataParallel training uses 480-960GB of RAM which is often impractical and inefficient. Instead, we use [Webdataset](https://github.com/webdataset/webdataset) to allow training while keeping datasets on disk and let webddataset handle pre-loading and fetching of data into CPU RAM.\n", + "\n", + "\n", + "## Disclaimer\n", + "\n", + "The data cleaning techniques used in this notebook are only meant to be loose guidelines and are not guaranteed to produced clean parallel corpora at the end of it. Not all of these steps are a necessity for every dataset, " + ] + }, + { + "cell_type": "markdown", + "id": "bb0eb698", + "metadata": {}, + "source": [ + "![NMT Data Pipeline](images/nmt_data_pipeline.png)" + ] + }, + { + "cell_type": "markdown", + "id": "4a9fd8d3", + "metadata": {}, + "source": [ + "# Downloading Publicly Available Data\n", + "\n", + "## WikiMatrix (https://arxiv.org/abs/1907.05791)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "78984523", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Downloading data ...\n", + "--2022-05-25 21:06:04-- https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ru.tsv.gz\n", + "Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.75.142, 104.22.74.142, 172.67.9.4, ...\n", + "Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.75.142|:443... connected.\n", + "HTTP request sent, awaiting response... 200 OK\n", + "Length: 658252364 (628M) [application/gzip]\n", + "Saving to: ‘data/WikiMatrix.en-ru.tsv.gz’\n", + "\n", + "data/WikiMatrix.en- 100%[===================>] 627.76M 64.0MB/s in 9.9s \n", + "\n", + "2022-05-25 21:06:15 (63.6 MB/s) - ‘data/WikiMatrix.en-ru.tsv.gz’ saved [658252364/658252364]\n", + "\n", + "---------------------\n", + "Unzipping file ...\n", + "---------------------\n", + "Peek into the file\n", + "1.2217877209774821\tThe glory of the Lord has risen upon thee\".\tКакую же из милостей вашего Господа вы считаете ложью?».\n", + "1.2136469670929166\tFear of the Lord is aking to wonder (or awe).\tВоистину, мучений от твоего Господа надлежит остерегаться».\n", + "1.1979604432731699\tI think I washed his body 50 times.\"\tЯ думаю, что я омыла его тело 50 раз.»\n", + "1.1954915649299516\tThere has come to you clear evidence from your Lord.\tК вам пришло ясное знамение от вашего Господа.\n", + "1.1941585356247322\t\"15,000 attend dawn service\".\t15,000 attend dawn service (англ.).\n", + "1.1916203199426767\tAnd in the mountains they suffer a calamity.\tИ в горах их постигла беда.\n", + "1.1913226864413053\tAsk anybody, particularly the critics.\"\tСпросите кого угодно, в особенности критиков.»\n", + "1.1881032124947857\t\"Wiranto – survivor with iron will\".\t«Wiranto — survivor with iron will».\n", + "1.1865469635358286\t\"They Saved Lisa's Brain\".\t«They Saved Lisa’s Brain» (рус.\n", + "1.1863071915494687\tHowever, patients liked banknotes or coins of the Japan Bank.\tОднако пациенты предпочитали банкноты или монеты Банка Японии.\n", + "---------------------\n", + "File length ...\n", + "5203872 data/WikiMatrix.en-ru.tsv\n", + "---------------------\n" + ] + } + ], + "source": [ + "!mkdir -p data\n", + "print('Downloading data ...')\n", + "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ru.tsv.gz -O data/WikiMatrix.en-ru.tsv.gz\n", + "print('---------------------')\n", + "print('Unzipping file ...')\n", + "!gunzip -k -f data/WikiMatrix.en-ru.tsv.gz\n", + "print('---------------------')\n", + "print('Peek into the file')\n", + "!head -10 data/WikiMatrix.en-ru.tsv\n", + "print('---------------------')\n", + "print('File length ...')\n", + "!wc -l data/WikiMatrix.en-ru.tsv\n", + "print('---------------------')" + ] + }, + { + "cell_type": "markdown", + "id": "b9a62f9e", + "metadata": {}, + "source": [ + "## Filter Based on LASER Confidence\n", + "\n", + "LASER (https://arxiv.org/abs/1812.10464) is a multi-lingual neural sentence embedding model that is often used for cross-lingual sentence/document retrieval. Similarities in the embedding space are often used as proxies for cross-lingual similarities." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "21608388", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "====================================\n", + "======= TSV Conf Filtering =========\n", + "====================================\n", + "\n" + ] }, - "nbformat": 4, - "nbformat_minor": 5 -} \ No newline at end of file + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Filtering file by confidence 1.04: 100%|████████████████████████| 5203872/5203872 [00:11<00:00, 452287.46it/s]\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Confidence score average : 1.0628594097124588\n", + "Confidence score variance : 0.0003311031014927841\n", + "Kept 1661908 out of 5203872 after conversion (31.935989201886596%)\n", + "====================================\n" + ] + } + ], + "source": [ + "from tqdm import tqdm\n", + "import numpy as np\n", + "\n", + "def num_lines_in_file(fname):\n", + " \"\"\"\n", + " Returns the number of lines in a file.\n", + " \"\"\"\n", + " with open(fname, 'r') as f:\n", + " for i, _ in enumerate(f):\n", + " pass\n", + " return i + 1\n", + "\n", + "def filter_tsv_with_conf(\n", + " input_file, output_file_lang_1, output_file_lang_2,\n", + " confidence_threshold=None, confidence_column=None\n", + "):\n", + " \"\"\"\n", + " Filters a tsv file that has confidence scores associated with each parallel example.\n", + "\n", + " For example:\n", + "\n", + " 1.23 \\t This is a sentence in lang1 \\t This is a sentence in lang2\n", + " \"\"\"\n", + " print()\n", + " print('====================================')\n", + " print('======= TSV Conf Filtering =========')\n", + " print('====================================')\n", + " print()\n", + " num_lines = num_lines_in_file(input_file)\n", + " scores = []\n", + " num_output_lines = 0\n", + " lang_1_col = 0\n", + " lang_2_col = 1\n", + " with open(input_file, 'r') as f, \\\n", + " open(output_file_lang_1, 'w') as f_out_1, \\\n", + " open(output_file_lang_2, 'w') as f_out_2:\n", + " for line in tqdm(f, total=num_lines, desc=f\"Filtering file by confidence {confidence_threshold}\"):\n", + " if line.strip() == '':\n", + " continue\n", + " line = line.strip().split('\\t')\n", + " if len(line) < 2:\n", + " continue\n", + " if confidence_threshold is not None and float(line[confidence_column]) < confidence_threshold:\n", + " continue\n", + " else:\n", + " if confidence_threshold is not None:\n", + " scores.append(float(line[confidence_column]))\n", + " if confidence_column == 0:\n", + " lang_1_col, lang_2_col = 1, 2\n", + " elif confidence_column == 2:\n", + " lang_1_col, lang_2_col = 0, 1\n", + " elif confidence_column == 1:\n", + " lang_1_col, lang_2_col = 0, 2\n", + " else:\n", + " raise ValueError(f\"Invalid Column for confidence {confidence_column}\")\n", + " f_out_1.write(line[lang_1_col] + '\\n')\n", + " f_out_2.write(line[lang_2_col] + '\\n')\n", + " num_output_lines += 1\n", + "\n", + " if confidence_threshold is not None:\n", + " print(f'Confidence score average : {np.mean(scores)}')\n", + " print(f'Confidence score variance : {np.var(scores)}')\n", + " print(f'Kept {num_output_lines} out of {num_lines} after conversion ({(num_output_lines / num_lines) * 100}%)')\n", + " print('====================================')\n", + "\n", + "filter_tsv_with_conf(\n", + " 'data/WikiMatrix.en-ru.tsv',\n", + " 'data/WikiMatrix.en-ru.en', \n", + " 'data/WikiMatrix.en-ru.ru',\n", + " confidence_threshold=1.04, confidence_column=0\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "18a171d1", + "metadata": {}, + "source": [ + "## Language ID filtering with fastText\n", + "\n", + "Noisy parallel corpora often contain sentences that are not in the intended language. A classifier that determines the language in which a sentence is written can be used to filter out sentences that aren't in the appropriate language." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "d58b7148", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "--2022-05-25 21:06:40-- https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin\n", + "Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.74.142, 172.67.9.4, 104.22.75.142, ...\n", + "Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.74.142|:443... connected.\n", + "HTTP request sent, awaiting response... 200 OK\n", + "Length: 131266198 (125M) [application/octet-stream]\n", + "Saving to: ‘data/lid.176.bin’\n", + "\n", + "data/lid.176.bin 100%[===================>] 125.18M 51.7MB/s in 2.4s \n", + "\n", + "2022-05-25 21:06:43 (51.7 MB/s) - ‘data/lid.176.bin’ saved [131266198/131266198]\n", + "\n", + "\n", + "====================================\n", + "====== Language ID Filtering =======\n", + "====================================\n", + "\n", + "--2022-05-25 21:06:43-- https://raw.github.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py\n", + "Resolving raw.github.com (raw.github.com)... 185.199.109.133, 185.199.108.133, 185.199.111.133, ...\n", + "Connecting to raw.github.com (raw.github.com)|185.199.109.133|:443... connected.\n", + "HTTP request sent, awaiting response... 301 Moved Permanently\n", + "Location: https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py [following]\n", + "--2022-05-25 21:06:43-- https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py\n", + "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.111.133, 185.199.109.133, ...\n", + "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected.\n", + "HTTP request sent, awaiting response... 200 OK\n", + "Length: 14739 (14K) [text/plain]\n", + "Saving to: ‘filter_langs_nmt.py’\n", + "\n", + "filter_langs_nmt.py 100%[===================>] 14.39K --.-KB/s in 0.001s \n", + "\n", + "2022-05-25 21:06:44 (26.0 MB/s) - ‘filter_langs_nmt.py’ saved [14739/14739]\n", + "\n", + "processed lines / total number of lines: 100%|▉| 1658588/1661908 [00:11<00:00, 1\n", + "\n", + "-----------------------------------------\n", + "Number of removed sentences:\n", + "-----------------------------------------\n", + "\n", + "33671 data/WikiMatrix.en-ru.langidfilter.removed.ru\n", + "\n", + "-----------------------------------------\n", + "Examples of removed sentences\n", + "-----------------------------------------\n", + "\n", + "Ask Sylvia!\tСпроси Сильвию!\n", + "Любовь Шутова: Теперь ответственности больше.\tЛюбовь Шутова: теперь ответственности больше.\n", + "\"Александр Митта: Нужно понимать, как управлять вниманием зрителя\" .\tАлександр Митта: Нужно понимать, как управлять вниманием зрителя.\n", + "Пышка, я тебя знаю: вкус советского детства.\tПышка, я тебя знаю: вкус советского детства.\n", + "Ethnologue (\tEthnologue  (англ.)\n", + "\"Почему «Доброе утро» лишилось двух ведущих\".\tПочему «Доброе утро» лишилось двух ведущих? (неопр.).\n", + "Time Masters Vol.\tTime Masters Vol.\n", + "1999 – Which pronunciation do you prefer?.\t1999 — Which pronunciation do you prefer?.\n", + "1980 – The brogue that isn't.\t1980 — The brogue that isn’t.\n", + "\"Формы новые нужны, драмы всякие важны.\tФормы новые нужны, драмы всякие важны.\n", + "paste: write error: Broken pipe\n", + "paste: write error\n", + "-----------------------------------------\n" + ] + } + ], + "source": [ + "!wget https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin -O data/lid.176.bin\n", + "print()\n", + "print('====================================')\n", + "print('====== Language ID Filtering =======')\n", + "print('====================================')\n", + "print()\n", + "\n", + "\n", + "!wget https://raw.github.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py \\\n", + " -O filter_langs_nmt.py\n", + "\n", + "!python filter_langs_nmt.py \\\n", + " --input-src data/WikiMatrix.en-ru.en \\\n", + " --input-tgt data/WikiMatrix.en-ru.ru \\\n", + " --output-src data/WikiMatrix.en-ru.langidfilter.en \\\n", + " --output-tgt data/WikiMatrix.en-ru.langidfilter.ru \\\n", + " --source-lang en \\\n", + " --target-lang ru \\\n", + " --removed-src data/WikiMatrix.en-ru.langidfilter.removed.en \\\n", + " --removed-tgt data/WikiMatrix.en-ru.langidfilter.removed.ru \\\n", + " --fasttext-model data/lid.176.bin\n", + "\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Number of removed sentences:')\n", + "print('-----------------------------------------')\n", + "print()\n", + "!wc -l data/WikiMatrix.en-ru.langidfilter.removed.ru\n", + "\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Examples of removed sentences')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "!paste -d \"\\t\" \\\n", + " data/WikiMatrix.en-ru.langidfilter.removed.en \\\n", + " data/WikiMatrix.en-ru.langidfilter.removed.ru \\\n", + " | head -10\n", + "print('-----------------------------------------')" + ] + }, + { + "cell_type": "markdown", + "id": "ffb42e92", + "metadata": {}, + "source": [ + "## Length and Ratio Filtering\n", + "\n", + "This step filters out sentences based on their lengths and the ratio between source and target lengths. If (a) src_len / tgt_len or tgt_len / src_len exceed 1.3 or (b) source or target sequence lengths are less than 1 or greater than 250, the sentence pair will be removed." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "52ff172a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Cloning into 'data/mosesdecoder'...\n", + "remote: Enumerating objects: 148097, done.\u001b[K\n", + "remote: Counting objects: 100% (525/525), done.\u001b[K\n", + "remote: Compressing objects: 100% (229/229), done.\u001b[K\n", + "remote: Total 148097 (delta 323), reused 441 (delta 292), pack-reused 147572\u001b[K\n", + "Receiving objects: 100% (148097/148097), 129.88 MiB | 26.55 MiB/s, done.\n", + "Resolving deltas: 100% (114349/114349), done.\n", + "Note: switching to 'RELEASE-4.0'.\n", + "\n", + "You are in 'detached HEAD' state. You can look around, make experimental\n", + "changes and commit them, and you can discard any commits you make in this\n", + "state without impacting any branches by switching back to a branch.\n", + "\n", + "If you want to create a new branch to retain commits you create, you may\n", + "do so (now or later) by using -c with the switch command. Example:\n", + "\n", + " git switch -c \n", + "\n", + "Or undo this operation with:\n", + "\n", + " git switch -\n", + "\n", + "Turn off this advice by setting config variable advice.detachedHead to false\n", + "\n", + "HEAD is now at 65c75ff07 use std::unordered_set instead of boost::unordered_set for all instances in moses2. To avoid confusion\n", + "clean-corpus.perl: processing data/WikiMatrix.en-ru.langidfilter.en & .ru to data/WikiMatrix.en-ru.langidfilter.lengthratio, cutoff 1-250, ratio 1.3\n", + "..........(100000)..........(200000)..........(300000)..........(400000)..........(500000)..........(600000)..........(700000)..........(800000)..........(900000)..........(1000000)..........(1100000)..........(1200000)..........(1300000)..........(1400000)..........(1500000)..........(1600000)..\n", + "Input sentences: 1628237 Output sentences: 1138638\n" + ] + } + ], + "source": [ + "!git clone https://github.com/moses-smt/mosesdecoder data/mosesdecoder\n", + "!cd data/mosesdecoder && git checkout RELEASE-4.0 && cd ../..\n", + "!perl data/mosesdecoder/scripts/training/clean-corpus-n.perl -ratio 1.3 \\\n", + " data/WikiMatrix.en-ru.langidfilter \\\n", + " en ru \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio \\\n", + " 1 250" + ] + }, + { + "cell_type": "markdown", + "id": "8214daca", + "metadata": {}, + "source": [ + "THE FOLLOWING CELLS REQUIRE THE INSTALLATION OF BICLEANER, WHICH REQUIRES COMPILING PACKAGES FROM SOURCE AND IS TRICKY TO GET WORKING INSIDE THIS CONTAINER. PLEASE INSTALL BICLEANER FROM THE REPOSITORY - https://github.com/bitextor/bicleaner OR FOLLOW INSTRUCTIONS BELOW. CELLS FOLLOWING THIS WILL NOT RUN IF BICLEANER IS NOT INSTALLED." + ] + }, + { + "cell_type": "markdown", + "id": "950d1380", + "metadata": {}, + "source": [ + "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n", + "\n", + "## Install dependencies\n", + "\n", + "!pip install wget\n", + "!apt-get install libboost-all-dev\n", + "!apt-get install gawk\n", + "\n", + "## Install NeMo\n", + "\n", + "BRANCH = 'r1.9.0'\n", + "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n", + "\n", + "!pip uninstall -y sacrebleu\n", + "!pip install sacrebleu[ja]\n", + "!pip install xxhash\n", + "\n", + "## Install kenlm with 7-gram support\n", + "!mkdir -p data\n", + "!rm -rf data/kenlm\n", + "!git clone https://github.com/kpu/kenlm data/kenlm\n", + "!cd data/kenlm \\\n", + " && pip install . --install-option=\"--max_order 7\" \\\n", + " && mkdir -p build \\\n", + " && cd build \\\n", + " && cmake .. -DKENLM_MAX_ORDER=7 -DCMAKE_INSTALL_PREFIX:PATH=../../kenlm_install \\\n", + " && make -j all install && cd ../../kenlm_install \\\n", + " && export PATH=$PATH:$PWD\n", + "\n", + "# Install bicleaner\n", + "\n", + "!pip install bicleaner" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "ab796da4", + "metadata": {}, + "outputs": [ + { + "ename": "ImportError", + "evalue": "You need to install Bicleaner to proceed. Could not import the bicleaner package.", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", + "Input \u001b[0;32mIn [6]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mbicleaner\u001b[39;00m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n", + "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'bicleaner'", + "\nDuring handling of the above exception, another exception occurred:\n", + "\u001b[0;31mImportError\u001b[0m Traceback (most recent call last)", + "Input \u001b[0;32mIn [6]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mbicleaner\u001b[39;00m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n\u001b[0;32m----> 4\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mYou need to install Bicleaner to proceed. Could not import the bicleaner package.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", + "\u001b[0;31mImportError\u001b[0m: You need to install Bicleaner to proceed. Could not import the bicleaner package." + ] + } + ], + "source": [ + "try:\n", + " import bicleaner\n", + "except ImportError:\n", + " raise ImportError(f\"You need to install Bicleaner to proceed. Could not import the bicleaner package.\")" + ] + }, + { + "cell_type": "markdown", + "id": "01f2b589", + "metadata": {}, + "source": [ + "## Bicleaner Filtering\n", + "\n", + "Bicleaner (https://aclanthology.org/W18-6488/ and https://aclanthology.org/2020.eamt-1.31/) is a tool to identify noisy parallel sentences in translation corpora. It applies 3 different filtering steps:\n", + "\n", + "1. Pre-filtering based on 37 rules.\n", + "2. Language model fluency scores based on n-gram language models trained with kenlm.\n", + "3. Random forest classifier that uses all examples filtered out in steps 1 & 2 as \"negative\" examples." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9be8d4ca", + "metadata": {}, + "outputs": [], + "source": [ + "print('Downloading En-Ru Bicleaner models.')\n", + "!git clone https://github.com/bitextor/bicleaner data/bicleaner\n", + "!cd data/bicleaner && git checkout bicleaner-0.15 && cd ../..\n", + "!data/bicleaner/utils/download-pack.sh en ru\n", + "\n", + "print('Generating Bicleaner scores ...')\n", + "!gawk '{{print \"-\\t-\"}}' \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.en | \\\n", + " paste -d \"\\t\" - data/WikiMatrix.en-ru.langidfilter.lengthratio.en \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.ru | \\\n", + " bicleaner-classify - - en-ru/en-ru.yaml \\\n", + " > data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43059b8a", + "metadata": {}, + "outputs": [], + "source": [ + "print('Score file ...')\n", + "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores\n", + "\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Filtering based on Bicleaner scores > 0.6 ...')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "print('Filtering out English ...')\n", + "!gawk -F \"\\t\" '{if ($5>0.6) {print $3}}' \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en\n", + "\n", + "print('Filtering out Russian ...')\n", + "!gawk -F \"\\t\" '{if ($5>0.6) {print $4}}' \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru\n", + "\n", + "!paste -d \"\\t\" \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru \\\n", + " | head -10" + ] + }, + { + "cell_type": "markdown", + "id": "0726510c", + "metadata": {}, + "source": [ + "## Normalize Punctuation\n", + "\n", + "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n", + "\n", + "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed." + ] + }, + { + "cell_type": "markdown", + "id": "e73670d6", + "metadata": {}, + "source": [ + "### Sacremoses" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "597e041a", + "metadata": {}, + "outputs": [], + "source": [ + "print('Normalizing English ...')\n", + "!sacremoses -j 4 normalize \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en\n", + "\n", + "print('Normalizing Russian ...')\n", + "!sacremoses -j 4 normalize \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru\n" + ] + }, + { + "cell_type": "markdown", + "id": "240b0a1f", + "metadata": {}, + "source": [ + "## Moses\n", + "\n", + "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n", + "\n", + "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1f5adaa4", + "metadata": {}, + "outputs": [], + "source": [ + "print('Normalizing English ...')\n", + "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l en \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en\n", + "\n", + "print('Normalizing Russian ...')\n", + "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l ru \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru\n" + ] + }, + { + "cell_type": "markdown", + "id": "b8bfad64", + "metadata": {}, + "source": [ + "## Tokenize\n", + "\n", + "Tokenization splits a string into a sequence of tokens. A naive way of doing this would be to simply split the string on spaces (for languages where this is possible). This however, will result in punctuation being \"attached\" to the neighboring word when tokenizing. For example, \n", + "\n", + "\"This is a sentence.\" will be tokenized as [\"This, is, a, sentence.\"].\n", + "\n", + "However, we'd typically like punctuation to be separate tokens for example,\n", + "\n", + "\"This is a sentence.\" will be tokenized my moses or sacremoses as [\", This, is, a, sentence, ., \"]." + ] + }, + { + "cell_type": "markdown", + "id": "06c60b90", + "metadata": {}, + "source": [ + "### Sacremoses" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7bb4c631", + "metadata": {}, + "outputs": [], + "source": [ + "print('Tokenizing English ...')\n", + "!sacremoses -j 4 -l en tokenize -x \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.en\n", + "\n", + "print('Tokenizing Russian ...')\n", + "!sacremoses -j 4 -l ru tokenize -x \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.ru\n" + ] + }, + { + "cell_type": "markdown", + "id": "444bebd7", + "metadata": {}, + "source": [ + "### Moses" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "21333e27", + "metadata": {}, + "outputs": [], + "source": [ + "print('Tokenizing English ...')\n", + "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l en -no-escape -threads 4 \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en\n", + "\n", + "print('Tokenizing Russian ...')\n", + "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l ru -no-escape -threads 4 \\\n", + " < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b28df2bb", + "metadata": {}, + "outputs": [], + "source": [ + "print()\n", + "print('-----------------------------------------')\n", + "print('Tokenized Russian Sentences ...')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n", + "\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Tokenized English Sentences ...')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en" + ] + }, + { + "cell_type": "markdown", + "id": "dee5409d", + "metadata": {}, + "source": [ + "## Segmenting Chinese and Japanese\n", + "\n", + "### Jieba segmentation for Chinese" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "41b4cc91", + "metadata": {}, + "outputs": [], + "source": [ + "import jieba\n", + "\n", + "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-zh.tsv.gz -O data/WikiMatrix.en-zh.tsv.gz\n", + "!gunzip -k -f data/WikiMatrix.en-zh.tsv.gz\n", + "\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Chinese text before segmentation ...')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-zh.tsv | head -10\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Segmenting Chinese text ...')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "zh_lines = []\n", + "with open('data/WikiMatrix.en-zh.tsv', 'r') as f:\n", + " for idx, line in enumerate(f):\n", + " line = line.strip().split('\\t')[2]\n", + " zh_lines.append(' '.join(jieba.cut(line)))\n", + " if idx == 100:\n", + " break\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Chinese text after segmentation ...')\n", + "print('\\n'.join(zh_lines[:10]))\n", + "print('-----------------------------------------')\n", + "print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "489bd915", + "metadata": {}, + "outputs": [], + "source": [ + "import MeCab\n", + "import ipadic\n", + "\n", + "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ja.tsv.gz -O data/WikiMatrix.en-ja.tsv.gz\n", + "!gunzip -k -f data/WikiMatrix.en-ja.tsv.gz\n", + "\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Japanese text before segmentation ...')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-ja.tsv | head -10\n", + "\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Segmenting Japanese text ...')\n", + "print('-----------------------------------------')\n", + "print()\n", + "\n", + "mecab_tokenizer = MeCab.Tagger(ipadic.MECAB_ARGS + \" -Owakati\")\n", + "\n", + "ja_lines = []\n", + "with open('data/WikiMatrix.en-ja.tsv', 'r') as f:\n", + " for idx, line in enumerate(f):\n", + " line = line.strip().split('\\t')[2]\n", + " ja_lines.append(mecab_tokenizer.parse(line))\n", + " if idx == 100:\n", + " break\n", + "print()\n", + "print('-----------------------------------------')\n", + "print('Japanese text after segmentation ...')\n", + "print('\\n'.join(ja_lines[:10]))\n", + "print('-----------------------------------------')\n", + "print()" + ] + }, + { + "cell_type": "markdown", + "id": "4a079efe", + "metadata": {}, + "source": [ + "## Deduplicate" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "55d98bf3", + "metadata": {}, + "outputs": [], + "source": [ + "import xxhash\n", + "\n", + "def dedup_file(input_file_lang_1, input_file_lang_2, output_file_lang_1, output_file_lang_2):\n", + " print()\n", + " print('====================================')\n", + " print('========== De-duplicate ============')\n", + " print('====================================')\n", + " print()\n", + " num_lines = num_lines_in_file(input_file_lang_1)\n", + " hashes = set()\n", + " num_output_lines = 0\n", + " with open(input_file_lang_1, 'r') as f_lang1, \\\n", + " open(input_file_lang_2, 'r') as f_lang2, \\\n", + " open(output_file_lang_1, 'w') as f_out_lang1, \\\n", + " open(output_file_lang_2, 'w') as f_out_lang2:\n", + " for line_1, line_2 in tqdm(zip(f_lang1, f_lang2), total=num_lines, desc=f\"Deduplicating files\"):\n", + " parallel_hash = xxhash.xxh64((line_1.strip() + '\\t' + line_2.strip()).encode('utf-8')).hexdigest()\n", + " if parallel_hash not in hashes:\n", + " hashes.add(parallel_hash)\n", + " f_out_lang1.write(line_1.strip() + '\\n')\n", + " f_out_lang2.write(line_2.strip() + '\\n')\n", + " num_output_lines += 1\n", + "\n", + " print(f\"Kept {num_output_lines} out of {num_lines} after deduplication\")\n", + "\n", + "dedup_file(\n", + " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en',\n", + " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru',\n", + " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en',\n", + " 'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru'\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "da4c181a", + "metadata": {}, + "source": [ + "## Shuffle" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "413734bd", + "metadata": {}, + "outputs": [], + "source": [ + "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en\n", + "\n", + "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru > \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru\n", + "\n", + "!paste -d \"\\t\" \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n", + " data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n", + " | head -10" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f3b3640", + "metadata": {}, + "outputs": [], + "source": [ + "!rm -rf data/tarred_dataset_en_ru_8k_tokens" + ] + }, + { + "cell_type": "markdown", + "id": "844a9f26", + "metadata": {}, + "source": [ + "## Tarred Dataset Creation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2b045df5", + "metadata": {}, + "outputs": [], + "source": [ + "!wget https://raw.github.com/NVIDIA/NeMo/main/examples/nlp/machine_translation/create_tarred_parallel_dataset.py \\\n", + " -O create_tarred_parallel_dataset.py\n", + "\n", + "!python create_tarred_parallel_dataset.py \\\n", + " --src_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n", + " --tgt_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n", + " --out_dir data/tarred_dataset_en_ru_8k_tokens \\\n", + " --clean \\\n", + " --encoder_tokenizer_name yttm \\\n", + " --encoder_tokenizer_vocab_size 32000 \\\n", + " --encoder_tokenizer_coverage 0.999 \\\n", + " --encoder_tokenizer_bpe_dropout 0.1 \\\n", + " --decoder_tokenizer_name yttm \\\n", + " --decoder_tokenizer_vocab_size 32000 \\\n", + " --decoder_tokenizer_coverage 0.999 \\\n", + " --decoder_tokenizer_bpe_dropout 0.1 \\\n", + " --max_seq_length 512 \\\n", + " --min_seq_length 1 \\\n", + " --tokens_in_batch 8000 \\\n", + " --lines_per_dataset_fragment 100000 \\\n", + " --num_batches_per_tarfile 20\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "990265e5", + "metadata": {}, + "outputs": [], + "source": [ + "!ls data/tarred_dataset_en_ru_8k_tokens" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cc5e123b", + "metadata": {}, + "outputs": [], + "source": [ + "!cat data/tarred_dataset_en_ru_8k_tokens/metadata.tokens.8000.json" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.8.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 4cde0d27748f8d4d91baf05112dede1de9f35c61 Mon Sep 17 00:00:00 2001 From: MaximumEntropy Date: Wed, 25 May 2022 14:10:27 -0700 Subject: [PATCH 2/2] Clear cells Signed-off-by: MaximumEntropy --- ...a_Preprocessing_and_Cleaning_for_NMT.ipynb | 211 ++---------------- 1 file changed, 15 insertions(+), 196 deletions(-) diff --git a/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb b/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb index f35018234945..74bda451f297 100644 --- a/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb +++ b/tutorials/nlp/Data_Preprocessing_and_Cleaning_for_NMT.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "fa2a0346", + "id": "bd9c257a", "metadata": {}, "source": [ "Instructions for setting up Colab are as follows:\n", @@ -82,47 +82,10 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": null, "id": "78984523", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Downloading data ...\n", - "--2022-05-25 21:06:04-- https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ru.tsv.gz\n", - "Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.75.142, 104.22.74.142, 172.67.9.4, ...\n", - "Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.75.142|:443... connected.\n", - "HTTP request sent, awaiting response... 200 OK\n", - "Length: 658252364 (628M) [application/gzip]\n", - "Saving to: ‘data/WikiMatrix.en-ru.tsv.gz’\n", - "\n", - "data/WikiMatrix.en- 100%[===================>] 627.76M 64.0MB/s in 9.9s \n", - "\n", - "2022-05-25 21:06:15 (63.6 MB/s) - ‘data/WikiMatrix.en-ru.tsv.gz’ saved [658252364/658252364]\n", - "\n", - "---------------------\n", - "Unzipping file ...\n", - "---------------------\n", - "Peek into the file\n", - "1.2217877209774821\tThe glory of the Lord has risen upon thee\".\tКакую же из милостей вашего Господа вы считаете ложью?».\n", - "1.2136469670929166\tFear of the Lord is aking to wonder (or awe).\tВоистину, мучений от твоего Господа надлежит остерегаться».\n", - "1.1979604432731699\tI think I washed his body 50 times.\"\tЯ думаю, что я омыла его тело 50 раз.»\n", - "1.1954915649299516\tThere has come to you clear evidence from your Lord.\tК вам пришло ясное знамение от вашего Господа.\n", - "1.1941585356247322\t\"15,000 attend dawn service\".\t15,000 attend dawn service (англ.).\n", - "1.1916203199426767\tAnd in the mountains they suffer a calamity.\tИ в горах их постигла беда.\n", - "1.1913226864413053\tAsk anybody, particularly the critics.\"\tСпросите кого угодно, в особенности критиков.»\n", - "1.1881032124947857\t\"Wiranto – survivor with iron will\".\t«Wiranto — survivor with iron will».\n", - "1.1865469635358286\t\"They Saved Lisa's Brain\".\t«They Saved Lisa’s Brain» (рус.\n", - "1.1863071915494687\tHowever, patients liked banknotes or coins of the Japan Bank.\tОднако пациенты предпочитали банкноты или монеты Банка Японии.\n", - "---------------------\n", - "File length ...\n", - "5203872 data/WikiMatrix.en-ru.tsv\n", - "---------------------\n" - ] - } - ], + "outputs": [], "source": [ "!mkdir -p data\n", "print('Downloading data ...')\n", @@ -151,39 +114,10 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "id": "21608388", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "====================================\n", - "======= TSV Conf Filtering =========\n", - "====================================\n", - "\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "Filtering file by confidence 1.04: 100%|████████████████████████| 5203872/5203872 [00:11<00:00, 452287.46it/s]\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Confidence score average : 1.0628594097124588\n", - "Confidence score variance : 0.0003311031014927841\n", - "Kept 1661908 out of 5203872 after conversion (31.935989201886596%)\n", - "====================================\n" - ] - } - ], + "outputs": [], "source": [ "from tqdm import tqdm\n", "import numpy as np\n", @@ -270,74 +204,10 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": null, "id": "d58b7148", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "--2022-05-25 21:06:40-- https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin\n", - "Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.74.142, 172.67.9.4, 104.22.75.142, ...\n", - "Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.74.142|:443... connected.\n", - "HTTP request sent, awaiting response... 200 OK\n", - "Length: 131266198 (125M) [application/octet-stream]\n", - "Saving to: ‘data/lid.176.bin’\n", - "\n", - "data/lid.176.bin 100%[===================>] 125.18M 51.7MB/s in 2.4s \n", - "\n", - "2022-05-25 21:06:43 (51.7 MB/s) - ‘data/lid.176.bin’ saved [131266198/131266198]\n", - "\n", - "\n", - "====================================\n", - "====== Language ID Filtering =======\n", - "====================================\n", - "\n", - "--2022-05-25 21:06:43-- https://raw.github.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py\n", - "Resolving raw.github.com (raw.github.com)... 185.199.109.133, 185.199.108.133, 185.199.111.133, ...\n", - "Connecting to raw.github.com (raw.github.com)|185.199.109.133|:443... connected.\n", - "HTTP request sent, awaiting response... 301 Moved Permanently\n", - "Location: https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py [following]\n", - "--2022-05-25 21:06:43-- https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py\n", - "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.111.133, 185.199.109.133, ...\n", - "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected.\n", - "HTTP request sent, awaiting response... 200 OK\n", - "Length: 14739 (14K) [text/plain]\n", - "Saving to: ‘filter_langs_nmt.py’\n", - "\n", - "filter_langs_nmt.py 100%[===================>] 14.39K --.-KB/s in 0.001s \n", - "\n", - "2022-05-25 21:06:44 (26.0 MB/s) - ‘filter_langs_nmt.py’ saved [14739/14739]\n", - "\n", - "processed lines / total number of lines: 100%|▉| 1658588/1661908 [00:11<00:00, 1\n", - "\n", - "-----------------------------------------\n", - "Number of removed sentences:\n", - "-----------------------------------------\n", - "\n", - "33671 data/WikiMatrix.en-ru.langidfilter.removed.ru\n", - "\n", - "-----------------------------------------\n", - "Examples of removed sentences\n", - "-----------------------------------------\n", - "\n", - "Ask Sylvia!\tСпроси Сильвию!\n", - "Любовь Шутова: Теперь ответственности больше.\tЛюбовь Шутова: теперь ответственности больше.\n", - "\"Александр Митта: Нужно понимать, как управлять вниманием зрителя\" .\tАлександр Митта: Нужно понимать, как управлять вниманием зрителя.\n", - "Пышка, я тебя знаю: вкус советского детства.\tПышка, я тебя знаю: вкус советского детства.\n", - "Ethnologue (\tEthnologue  (англ.)\n", - "\"Почему «Доброе утро» лишилось двух ведущих\".\tПочему «Доброе утро» лишилось двух ведущих? (неопр.).\n", - "Time Masters Vol.\tTime Masters Vol.\n", - "1999 – Which pronunciation do you prefer?.\t1999 — Which pronunciation do you prefer?.\n", - "1980 – The brogue that isn't.\t1980 — The brogue that isn’t.\n", - "\"Формы новые нужны, драмы всякие важны.\tФормы новые нужны, драмы всякие важны.\n", - "paste: write error: Broken pipe\n", - "paste: write error\n", - "-----------------------------------------\n" - ] - } - ], + "outputs": [], "source": [ "!wget https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin -O data/lid.176.bin\n", "print()\n", @@ -393,45 +263,10 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": null, "id": "52ff172a", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Cloning into 'data/mosesdecoder'...\n", - "remote: Enumerating objects: 148097, done.\u001b[K\n", - "remote: Counting objects: 100% (525/525), done.\u001b[K\n", - "remote: Compressing objects: 100% (229/229), done.\u001b[K\n", - "remote: Total 148097 (delta 323), reused 441 (delta 292), pack-reused 147572\u001b[K\n", - "Receiving objects: 100% (148097/148097), 129.88 MiB | 26.55 MiB/s, done.\n", - "Resolving deltas: 100% (114349/114349), done.\n", - "Note: switching to 'RELEASE-4.0'.\n", - "\n", - "You are in 'detached HEAD' state. You can look around, make experimental\n", - "changes and commit them, and you can discard any commits you make in this\n", - "state without impacting any branches by switching back to a branch.\n", - "\n", - "If you want to create a new branch to retain commits you create, you may\n", - "do so (now or later) by using -c with the switch command. Example:\n", - "\n", - " git switch -c \n", - "\n", - "Or undo this operation with:\n", - "\n", - " git switch -\n", - "\n", - "Turn off this advice by setting config variable advice.detachedHead to false\n", - "\n", - "HEAD is now at 65c75ff07 use std::unordered_set instead of boost::unordered_set for all instances in moses2. To avoid confusion\n", - "clean-corpus.perl: processing data/WikiMatrix.en-ru.langidfilter.en & .ru to data/WikiMatrix.en-ru.langidfilter.lengthratio, cutoff 1-250, ratio 1.3\n", - "..........(100000)..........(200000)..........(300000)..........(400000)..........(500000)..........(600000)..........(700000)..........(800000)..........(900000)..........(1000000)..........(1100000)..........(1200000)..........(1300000)..........(1400000)..........(1500000)..........(1600000)..\n", - "Input sentences: 1628237 Output sentences: 1138638\n" - ] - } - ], + "outputs": [], "source": [ "!git clone https://github.com/moses-smt/mosesdecoder data/mosesdecoder\n", "!cd data/mosesdecoder && git checkout RELEASE-4.0 && cd ../..\n", @@ -444,7 +279,7 @@ }, { "cell_type": "markdown", - "id": "8214daca", + "id": "28de44eb", "metadata": {}, "source": [ "THE FOLLOWING CELLS REQUIRE THE INSTALLATION OF BICLEANER, WHICH REQUIRES COMPILING PACKAGES FROM SOURCE AND IS TRICKY TO GET WORKING INSIDE THIS CONTAINER. PLEASE INSTALL BICLEANER FROM THE REPOSITORY - https://github.com/bitextor/bicleaner OR FOLLOW INSTRUCTIONS BELOW. CELLS FOLLOWING THIS WILL NOT RUN IF BICLEANER IS NOT INSTALLED." @@ -452,7 +287,7 @@ }, { "cell_type": "markdown", - "id": "950d1380", + "id": "4ea62d2c", "metadata": {}, "source": [ "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n", @@ -491,26 +326,10 @@ }, { "cell_type": "code", - "execution_count": 6, - "id": "ab796da4", - "metadata": {}, - "outputs": [ - { - "ename": "ImportError", - "evalue": "You need to install Bicleaner to proceed. Could not import the bicleaner package.", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", - "Input \u001b[0;32mIn [6]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mbicleaner\u001b[39;00m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n", - "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'bicleaner'", - "\nDuring handling of the above exception, another exception occurred:\n", - "\u001b[0;31mImportError\u001b[0m Traceback (most recent call last)", - "Input \u001b[0;32mIn [6]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mbicleaner\u001b[39;00m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n\u001b[0;32m----> 4\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mYou need to install Bicleaner to proceed. Could not import the bicleaner package.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", - "\u001b[0;31mImportError\u001b[0m: You need to install Bicleaner to proceed. Could not import the bicleaner package." - ] - } - ], + "execution_count": null, + "id": "f3c0cf69", + "metadata": {}, + "outputs": [], "source": [ "try:\n", " import bicleaner\n",