mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-06 02:00:46 +00:00
25 KiB
Executable File
25 KiB
Executable File
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 [ ]:
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 [ ]:
In [ ]:
# set the following paths
DATA_DIR = "PATH_TO_DATA"
WORK_DIR = "PATH_TO_CHECKPOINTS_AND_LOGS"In [ ]:
## download get_squad.py script to download and preprocess the SQuAD data
os.makedirs(WORK_DIR, exist_ok=True)
if not os.path.exists(WORK_DIR + '/get_squad.py'):
print('Downloading get_squad.py...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/question_answering/get_squad.py', WORK_DIR)
else:
print ('get_squad.py already exists')In [ ]:
# download and preprocess the data
! python $WORK_DIR/get_squad.py --destDir $DATA_DIRIn [ ]:
! ls -LR {DATA_DIR}/squadIn [ ]:
# This is the model configuration file that we will download, do not change this
MODEL_CONFIG = "question_answering_squad_config.yaml"
# model parameters, play with these
BATCH_SIZE = 12
MAX_SEQ_LENGTH = 384
# specify BERT-like model, you want to use
PRETRAINED_BERT_MODEL = "bert-base-uncased"
TOKENIZER_NAME = "bert-base-uncased" # tokenizer name
# Number of data examples used for training, validation, test and inference
TRAIN_NUM_SAMPLES = VAL_NUM_SAMPLES = TEST_NUM_SAMPLES = 5000
INFER_NUM_SAMPLES = 5
TRAIN_FILE = f"{DATA_DIR}/squad/v1.1/train-v1.1.json"
VAL_FILE = f"{DATA_DIR}/squad/v1.1/dev-v1.1.json"
TEST_FILE = f"{DATA_DIR}/squad/v1.1/dev-v1.1.json"
INFER_FILE = f"{DATA_DIR}/squad/v1.1/dev-v1.1.json"
INFER_PREDICTION_OUTPUT_FILE = "output_prediction.json"
INFER_NBEST_OUTPUT_FILE = "output_nbest.json"
# training parameters
LEARNING_RATE = 0.00003
# number of epochs
MAX_EPOCHS = 1In [ ]:
# download the model's default 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/question_answering/conf/{MODEL_CONFIG}', config_dir)
else:
print ('config file is already exists')In [ ]:
# this line will print the entire default 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 [ ]:
config.model.train_ds.file = TRAIN_FILE
config.model.validation_ds.file = VAL_FILE
config.model.test_ds.file = TEST_FILE
config.model.train_ds.num_samples = TRAIN_NUM_SAMPLES
config.model.validation_ds.num_samples = VAL_NUM_SAMPLES
config.model.test_ds.num_samples = TEST_NUM_SAMPLES
config.model.tokenizer.tokenizer_name = TOKENIZER_NAMEIn [ ]:
# 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
config.trainer.max_epochs = MAX_EPOCHS
# Remove distributed training flags if only running on a single GPU or CPU
config.trainer.accelerator = None
print("Trainer config - \n")
print(OmegaConf.to_yaml(config.trainer))
trainer = pl.Trainer(**config.trainer)In [ ]:
config.exp_manager.exp_dir = WORK_DIR
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)In [ ]:
# list available pretrained models
nemo_nlp.models.QAModel.list_available_models()In [ ]:
# load pretained model
pretrained_model_name="qa_squadv1.1_bertbase"
model = nemo_nlp.models.QAModel.from_pretrained(model_name=pretrained_model_name)In [ ]:
# complete list of supported BERT-like models
nemo_nlp.modules.get_pretrained_lm_models_list()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.test_ds.batch_size = BATCH_SIZE
config.model.optim.lr = LEARNING_RATE
print("Updated model config - \n")
print(OmegaConf.to_yaml(config.model))In [ ]:
# initialize the model
# dataset we'll be prepared for training and evaluation during
model = nemo_nlp.models.QAModel(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 [ ]:
model.setup_test_data(test_data_config=config.model.test_ds)
trainer.test(model)In [ ]:
# # store test prediction under the experiment output folder
output_prediction_file = f"{exp_dir}/{INFER_PREDICTION_OUTPUT_FILE}"
output_nbest_file = f"{exp_dir}/{INFER_NBEST_OUTPUT_FILE}"
all_preds, all_nbests = model.inference(file=INFER_FILE, batch_size=5, num_samples=INFER_NUM_SAMPLES, output_nbest_file=output_nbest_file, output_prediction_file=output_prediction_file)In [ ]:
for _, item in all_preds.items():
print(f"question: {item[0]} answer: {item[1]}")
#The prediction file contains the predicted answer to each question id for the first TEST_NUM_SAMPLES.
! python -m json.tool $exp_dir/$INFER_PREDICTION_OUTPUT_FILE