Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/sagemaker/15_training_compiler/scripts/train.py
Views: 2555
import argparse1import logging2import os3import random4import sys56import numpy as np7import torch8from datasets import load_from_disk, load_metric9from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments10from transformers.trainer_utils import get_last_checkpoint1112if __name__ == "__main__":1314parser = argparse.ArgumentParser()1516# hyperparameters sent by the client are passed as command-line arguments to the script.17parser.add_argument("--epochs", type=int, default=3)18parser.add_argument("--train_batch_size", type=int, default=32)19parser.add_argument("--eval_batch_size", type=int, default=64)20parser.add_argument("--warmup_steps", type=int, default=500)21parser.add_argument("--model_id", type=str)22parser.add_argument("--learning_rate", type=str, default=5e-5)23parser.add_argument("--fp16", type=bool, default=True)2425# Data, model, and output directories26parser.add_argument("--output_data_dir", type=str, default=os.environ["SM_OUTPUT_DATA_DIR"])27parser.add_argument("--output_dir", type=str, default=os.environ["SM_MODEL_DIR"])28parser.add_argument("--n_gpus", type=str, default=os.environ["SM_NUM_GPUS"])29parser.add_argument("--training_dir", type=str, default=os.environ["SM_CHANNEL_TRAIN"])30parser.add_argument("--test_dir", type=str, default=os.environ["SM_CHANNEL_TEST"])3132args, _ = parser.parse_known_args()3334# is needed for Amazon SageMaker Training Compiler35os.environ["GPU_NUM_DEVICES"] = args.n_gpus3637# Set up logging38logger = logging.getLogger(__name__)3940logging.basicConfig(41level=logging.getLevelName("INFO"),42handlers=[logging.StreamHandler(sys.stdout)],43format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",44)4546# load datasets47train_dataset = load_from_disk(args.training_dir)48test_dataset = load_from_disk(args.test_dir)4950logger.info(f" loaded train_dataset length is: {len(train_dataset)}")51logger.info(f" loaded test_dataset length is: {len(test_dataset)}")5253# define metrics and metrics function54metric = load_metric("accuracy")5556def compute_metrics(eval_pred):57predictions, labels = eval_pred58predictions = np.argmax(predictions, axis=1)59return metric.compute(predictions=predictions, references=labels)6061# Prepare model labels - useful in inference API62labels = train_dataset.features["labels"].names63num_labels = len(labels)64label2id, id2label = dict(), dict()65for i, label in enumerate(labels):66label2id[label] = str(i)67id2label[str(i)] = label6869# download model from model hub70model = AutoModelForSequenceClassification.from_pretrained(71args.model_id, num_labels=num_labels, label2id=label2id, id2label=id2label72)73tokenizer = AutoTokenizer.from_pretrained(args.model_id)7475# define training args76training_args = TrainingArguments(77output_dir=args.output_dir,78overwrite_output_dir=True if get_last_checkpoint(args.output_dir) is not None else False,79num_train_epochs=args.epochs,80per_device_train_batch_size=args.train_batch_size,81per_device_eval_batch_size=args.eval_batch_size,82warmup_steps=args.warmup_steps,83fp16=args.fp16,84evaluation_strategy="epoch",85save_strategy="epoch",86save_total_limit=2,87logging_dir=f"{args.output_data_dir}/logs",88learning_rate=float(args.learning_rate),89load_best_model_at_end=True,90metric_for_best_model="accuracy",91disable_tqdm=True,92)9394# create Trainer instance95trainer = Trainer(96model=model,97args=training_args,98compute_metrics=compute_metrics,99train_dataset=train_dataset,100eval_dataset=test_dataset,101tokenizer=tokenizer,102)103104# train model105trainer.train()106107# evaluate model108eval_result = trainer.evaluate(eval_dataset=test_dataset)109110# writes eval result to file which can be accessed later in s3 ouput111with open(os.path.join(args.output_data_dir, "eval_results.txt"), "w") as writer:112print(f"***** Eval results *****")113for key, value in sorted(eval_result.items()):114writer.write(f"{key} = {value}\n")115print(f"{key} = {value}\n")116117# Saves the model to s3 uses os.environ["SM_MODEL_DIR"] to make sure checkpointing works118trainer.save_model(os.environ["SM_MODEL_DIR"])119120121