mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-04 17:38:10 +00:00
21 KiB
21 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
!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]
In [ ]:
# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:
# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'
! pip install ipywidgets
! jupyter nbextension enable --py widgetsnbextension
# Please restart the kernel after running this cellIn [ ]:
from nemo.utils.exp_manager import exp_manager
from nemo.collections import nlp as nemo_nlp
import os
import wget
import torch
import pytorch_lightning as pl
from omegaconf import OmegaConfIn [ ]:
DATA_DIR = "PATH_TO_DATA"
WORK_DIR = "PATH_TO_CHECKPOINTS_AND_LOGS"
MODEL_CONFIG = "punctuation_capitalization_config.yaml"
# model parameters
BATCH_SIZE = 128
MAX_SEQ_LENGTH = 64
LEARNING_RATE = 0.00002
NUM_SAMPLES = 10000In [ ]:
## download get_tatoeba_data.py script to download and preprocess the Tatoeba data
os.makedirs(WORK_DIR, exist_ok=True)
if not os.path.exists(WORK_DIR + '/get_tatoeba_data.py'):
print('Downloading get_tatoeba_data.py...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/data/get_tatoeba_data.py', WORK_DIR)
else:
print ('get_tatoeba_data.py is already exists')In [ ]:
# download and preprocess the data
# --clean_dir flag deletes raw Tataoeba data, remove the flag to avoid multiple data downloads if you want to experiment with the dataset size
! python $WORK_DIR/get_tatoeba_data.py --data_dir $DATA_DIR --num_sample $NUM_SAMPLES --clean_dirIn [ ]:
! ls -l {DATA_DIR}In [ ]:
# let's take a look at the data
print('Text:')
! head -n 5 {DATA_DIR}/text_train.txt
print('\nLabels:')
! head -n 5 {DATA_DIR}/labels_train.txtIn [ ]:
# download the model's configuration file
config_dir = WORK_DIR + '/configs/'
os.makedirs(config_dir, exist_ok=True)
if not os.path.exists(config_dir + MODEL_CONFIG):
print('Downloading config file...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG, config_dir)
else:
print ('config file is already exists')In [ ]:
# this line will print the entire config of the model
config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'
print(config_path)
config = OmegaConf.load(config_path)
print(OmegaConf.to_yaml(config))In [ ]:
# in this tutorial train and dev data is located in the same folder, so it is enought to add the path of the data directory to our config
config.model.dataset.data_dir = DATA_DIRIn [ ]:
print("Trainer config - \n")
print(OmegaConf.to_yaml(config.trainer))In [ ]:
# lets modify some trainer configs
# checks if we have GPU available and uses it
cuda = 1 if torch.cuda.is_available() else 0
config.trainer.gpus = cuda
config.trainer.precision = 16 if torch.cuda.is_available() else 32
# For mixed precision training, use precision=16 and amp_level=O1
# Reduces maximum number of epochs to 1 for a quick training
config.trainer.max_epochs = 1
# Remove distributed training flags
config.trainer.accelerator = None
trainer = pl.Trainer(**config.trainer)In [ ]:
exp_dir = exp_manager(trainer, config.get("exp_manager", None))
# the exp_dir provides a path to the current experiment for easy access
exp_dir = str(exp_dir)
exp_dirIn [ ]:
# complete list of supported BERT-like models
nemo_nlp.modules.get_pretrained_lm_models_list()
PRETRAINED_BERT_MODEL = "bert-base-uncased"In [ ]:
# add the specified above model parameters to the config
config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL
config.model.train_ds.batch_size = BATCH_SIZE
config.model.validation_ds.batch_size = BATCH_SIZE
config.model.optim.lr = LEARNING_RATE
config.model.train_ds.num_samples = NUM_SAMPLES
config.model.validation_ds.num_samples = NUM_SAMPLES
In [ ]:
# initialize the model
# during this stage, the dataset and data loaders we'll be prepared for training and evaluation
config.trainer.max_epochs = 3
model = nemo_nlp.models.PunctuationCapitalizationModel(cfg=config.model, trainer=trainer)In [ ]:
try:
from google import colab
COLAB_ENV = True
except (ImportError, ModuleNotFoundError):
COLAB_ENV = False
# Load the TensorBoard notebook extension
if COLAB_ENV:
%load_ext tensorboard
%tensorboard --logdir {exp_dir}
else:
print("To use tensorboard, please use this notebook in a Google Colab environment.")In [ ]:
# start the training
trainer.fit(model)In [ ]:
# define the list of queiries for inference
queries = [
'we bought four shirts and one mug from the nvidia gear store in santa clara',
'what can i do for you today',
'how are you',
'how is the weather in',
]
inference_results = model.add_punctuation_capitalization(queries)
print()
for query, result in zip(queries, inference_results):
print(f'Query : {query}')
print(f'Combined: {result.strip()}\n')In [ ]:
# let's reload our pretrained model
pretrained_model = nemo_nlp.models.PunctuationCapitalizationModel.from_pretrained('punctuation_en_distilbert')
# setup train and validation Pytorch DataLoaders
pretrained_model.update_data_dir(DATA_DIR)
pretrained_model.setup_training_data()
pretrained_model.setup_validation_data()
# and now we can create a PyTorch Lightning trainer and call `fit` again
# for this tutorial we are setting fast_dev_run to True, and the trainer will run 1 training batch and 1 validation batch
# for actual model training, disable the flag
fast_dev_run = True
trainer = pl.Trainer(gpus=1, fast_dev_run=fast_dev_run)
trainer.fit(pretrained_model)In [ ]: