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/05_spot_instances/scripts/train.py
Views: 2546
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)24parser.add_argument("--output_dir", type=str)2526# Data, model, and output directories27parser.add_argument("--output_data_dir", type=str, default=os.environ["SM_OUTPUT_DATA_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# Set up logging35logger = logging.getLogger(__name__)3637logging.basicConfig(38level=logging.getLevelName("INFO"),39handlers=[logging.StreamHandler(sys.stdout)],40format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",41)4243# load datasets44train_dataset = load_from_disk(args.training_dir)45test_dataset = load_from_disk(args.test_dir)4647logger.info(f" loaded train_dataset length is: {len(train_dataset)}")48logger.info(f" loaded test_dataset length is: {len(test_dataset)}")4950metric = load_metric("accuracy")5152def compute_metrics(eval_pred):53predictions, labels = eval_pred54predictions = np.argmax(predictions, axis=1)55return metric.compute(predictions=predictions, references=labels)5657# Prepare model labels - useful in inference API58labels = train_dataset.features["labels"].names59num_labels = len(labels)60label2id, id2label = dict(), dict()61for i, label in enumerate(labels):62label2id[label] = str(i)63id2label[str(i)] = label6465# download model from model hub66model = AutoModelForSequenceClassification.from_pretrained(67args.model_id, num_labels=num_labels, label2id=label2id, id2label=id2label68)69tokenizer = AutoTokenizer.from_pretrained(args.model_id)7071# define training args72training_args = TrainingArguments(73output_dir=args.output_dir,74overwrite_output_dir=True if get_last_checkpoint(args.output_dir) is not None else False,75num_train_epochs=args.epochs,76per_device_train_batch_size=args.train_batch_size,77per_device_eval_batch_size=args.eval_batch_size,78warmup_steps=args.warmup_steps,79fp16=args.fp16,80evaluation_strategy="epoch",81save_strategy="epoch",82save_total_limit=2,83logging_dir=f"{args.output_data_dir}/logs",84learning_rate=float(args.learning_rate),85load_best_model_at_end=True,86metric_for_best_model="accuracy",87)8889# create Trainer instance90trainer = Trainer(91model=model,92args=training_args,93compute_metrics=compute_metrics,94train_dataset=train_dataset,95eval_dataset=test_dataset,96tokenizer=tokenizer,97)9899# train model100if get_last_checkpoint(args.output_dir) is not None:101logger.info("***** continue training *****")102last_checkpoint = get_last_checkpoint(args.output_dir)103trainer.train(resume_from_checkpoint=last_checkpoint)104else:105trainer.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