mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-04 09:28:11 +00:00
19 KiB
19 KiB
In [ ]:
BRANCH = 'v1.0.2'In [ ]:
"""
You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.
Instructions for setting up Colab are as follows:
1. Open a new Python 3 notebook.
2. Import this notebook from GitHub (File -> Upload Notebook -> "GITHUB" tab -> copy/paste GitHub URL)
3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select "GPU" for hardware accelerator)
4. Run this cell to set up dependencies.
"""
# If you're using Google Colab and not running locally, run this cell
# install NeMo
BRANCH = 'v1.0.2'
!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]In [ ]:
import os
import wget
from nemo.collections import nlp as nemo_nlp
from nemo.collections import common as nemo_common
from omegaconf import OmegaConfIn [ ]:
nemo_nlp.modules.get_tokenizer_list()In [ ]:
# instantiate tokenizer wrapper using pretrained model name only
tokenizer1 = nemo_nlp.modules.get_tokenizer(tokenizer_name="bert-base-cased")
# the wrapper has a reference to the original HuggingFace tokenizer
print(tokenizer1.tokenizer)In [ ]:
# check vocabulary (this can be very long)
print(tokenizer1.tokenizer.vocab)In [ ]:
# show all special tokens if it has any
print(tokenizer1.tokenizer.all_special_tokens)In [ ]:
# instantiate tokenizer using custom vocabulary
vocab_file = "myvocab.txt"
vocab = ["he", "llo", "world"]
with open(vocab_file, 'w') as vocab_fp:
vocab_fp.write("\n".join(vocab))In [ ]:
tokenizer2 = nemo_nlp.modules.get_tokenizer(tokenizer_name="bert-base-cased", vocab_file=vocab_file)In [ ]:
# Since we did not overwrite special tokens they should be the same as before
print(tokenizer1.tokenizer.all_special_tokens == tokenizer2.tokenizer.all_special_tokens )In [ ]:
special_tokens_dict = {"unk_token": "<UNK>",
"sep_token": "<SEP>",
"pad_token": "<PAD>",
"bos_token": "<CLS>",
"mask_token": "<MASK>",
"eos_token": "<SEP>",
"cls_token": "<CLS>"}
tokenizer3 = nemo_nlp.modules.get_tokenizer(tokenizer_name="bert-base-cased",
vocab_file=vocab_file,
special_tokens=special_tokens_dict)
# print newly set special tokens
print(tokenizer3.tokenizer.all_special_tokens)
# the special tokens should be different from the previous special tokens
print(tokenizer3.tokenizer.all_special_tokens != tokenizer1.tokenizer.all_special_tokens )In [ ]:
# A safer way to add special tokens is the following:
# define your model
pretrained_model_name = 'bert-base-uncased'
model = nemo_nlp.modules.get_lm_model(pretrained_model_name=pretrained_model_name)
# define pretrained tokenizer
tokenizer_default = nemo_nlp.modules.get_tokenizer(tokenizer_name=pretrained_model_name)In [ ]:
tokenizer_default.text_to_tokens('<MY_NEW_TOKEN> and another word')In [ ]:
special_tokens = {'bos_token': '<BOS>',
'cls_token': '<CSL>',
'additional_special_tokens': ['<MY_NEW_TOKEN>', '<ANOTHER_TOKEN>']}
tokenizer_default.add_special_tokens(special_tokens_dict=special_tokens)
# resize your model so that the embeddings for newly added tokens are updated during training/finetuning
model.resize_token_embeddings(tokenizer_default.vocab_size)
# let's make sure the tokenizer doesn't split our special tokens into subtokens
tokenizer_default.text_to_tokens('<MY_NEW_TOKEN> and another word')In [ ]:
# Megatron tokenizers are instances of the Hugging Face BertTokenizer.
tokenizer4 = nemo_nlp.modules.get_tokenizer(tokenizer_name="megatron-bert-cased")In [ ]:
# download tokenizer script
script_file = "process_asr_text_tokenizer.py"
if not os.path.exists(script_file):
print('Downloading script file...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/tokenizers/process_asr_text_tokenizer.py')
else:
print ('Script already exists')In [ ]:
# Let's prepare some small text data for the tokenizer
data_text = "NeMo is a toolkit for creating Conversational AI applications. \
NeMo toolkit makes it possible for researchers to easily compose complex neural network architectures \
for conversational AI using reusable components - Neural Modules. \
Neural Modules are conceptual blocks of neural networks that take typed inputs and produce typed outputs. \
Such modules typically represent data layers, encoders, decoders, language models, loss functions, or methods of combining activations. \
The toolkit comes with extendable collections of pre-built modules and ready-to-use models for automatic speech recognition (ASR), \
natural language processing (NLP) and text synthesis (TTS). \
Built for speed, NeMo can utilize NVIDIA's Tensor Cores and scale out training to multiple GPUs and multiple nodes."In [ ]:
# Write the text data into a file
data_file="data.txt"
with open(data_file, 'w') as data_fp:
data_fp.write(data_text)In [ ]:
# Some additional parameters for the tokenizer
# To tokenize at unigram, char or word boundary instead of using bpe, change --spe_type accordingly.
# More details see https://github.com/google/sentencepiece#train-sentencepiece-model
tokenizer_spe_type = "bpe" # <-- Can be `bpe`, `unigram`, `word` or `char`
vocab_size = 32In [ ]:
! python process_asr_text_tokenizer.py --data_file=$data_file --data_root=. --vocab_size=$vocab_size --tokenizer=spe --spe_type=$tokenizer_spe_typeIn [ ]:
# See created tokenizer model and vocabulary
spe_model_dir=f"tokenizer_spe_{tokenizer_spe_type}_v{vocab_size}"
! ls $spe_model_dirIn [ ]:
# initialize tokenizer with created tokenizer model, which inherently includes the vocabulary and specify optional special tokens
tokenizer_spe = nemo_nlp.modules.get_tokenizer(tokenizer_name="sentencepiece", tokenizer_model=spe_model_dir+"/tokenizer.model", special_tokens=special_tokens_dict)
# specified special tokens are added to the vocabuary
print(tokenizer_spe.vocab_size)In [ ]:
# If you want to use a simple tokenizer like WordTokenizer without first generating the tokenizer.model first
# we provide the alternative class WordTokenizer or CharTokenizer that takes a user vocabulary as input
# initialize tokenizer with vocabulary and specify optional special tokens
tokenizer_word = nemo_nlp.modules.get_tokenizer(tokenizer_name="word", vocab_file=vocab_file, special_tokens=special_tokens_dict)
# specified special tokens are added to the vocabulary
print(tokenizer_word.vocab_size)In [ ]:
text="hello world"
# create tokens
tokenized = [tokenizer_word.bos_token] + tokenizer_word.text_to_tokens(text) + [tokenizer_word.eos_token]
print(tokenized)
# turn token into input_ids for a neural model, such as BERTModule
print(tokenizer_word.tokens_to_ids(tokenized))