CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
huggingface

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: huggingface/notebooks
Path: blob/main/sagemaker/15_training_compiler/scripts/train.py
Views: 2548
1
import argparse
2
import logging
3
import os
4
import random
5
import sys
6
7
import numpy as np
8
import torch
9
from datasets import load_from_disk, load_metric
10
from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments
11
from transformers.trainer_utils import get_last_checkpoint
12
13
if __name__ == "__main__":
14
15
parser = argparse.ArgumentParser()
16
17
# hyperparameters sent by the client are passed as command-line arguments to the script.
18
parser.add_argument("--epochs", type=int, default=3)
19
parser.add_argument("--train_batch_size", type=int, default=32)
20
parser.add_argument("--eval_batch_size", type=int, default=64)
21
parser.add_argument("--warmup_steps", type=int, default=500)
22
parser.add_argument("--model_id", type=str)
23
parser.add_argument("--learning_rate", type=str, default=5e-5)
24
parser.add_argument("--fp16", type=bool, default=True)
25
26
# Data, model, and output directories
27
parser.add_argument("--output_data_dir", type=str, default=os.environ["SM_OUTPUT_DATA_DIR"])
28
parser.add_argument("--output_dir", type=str, default=os.environ["SM_MODEL_DIR"])
29
parser.add_argument("--n_gpus", type=str, default=os.environ["SM_NUM_GPUS"])
30
parser.add_argument("--training_dir", type=str, default=os.environ["SM_CHANNEL_TRAIN"])
31
parser.add_argument("--test_dir", type=str, default=os.environ["SM_CHANNEL_TEST"])
32
33
args, _ = parser.parse_known_args()
34
35
# is needed for Amazon SageMaker Training Compiler
36
os.environ["GPU_NUM_DEVICES"] = args.n_gpus
37
38
# Set up logging
39
logger = logging.getLogger(__name__)
40
41
logging.basicConfig(
42
level=logging.getLevelName("INFO"),
43
handlers=[logging.StreamHandler(sys.stdout)],
44
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
45
)
46
47
# load datasets
48
train_dataset = load_from_disk(args.training_dir)
49
test_dataset = load_from_disk(args.test_dir)
50
51
logger.info(f" loaded train_dataset length is: {len(train_dataset)}")
52
logger.info(f" loaded test_dataset length is: {len(test_dataset)}")
53
54
# define metrics and metrics function
55
metric = load_metric("accuracy")
56
57
def compute_metrics(eval_pred):
58
predictions, labels = eval_pred
59
predictions = np.argmax(predictions, axis=1)
60
return metric.compute(predictions=predictions, references=labels)
61
62
# Prepare model labels - useful in inference API
63
labels = train_dataset.features["labels"].names
64
num_labels = len(labels)
65
label2id, id2label = dict(), dict()
66
for i, label in enumerate(labels):
67
label2id[label] = str(i)
68
id2label[str(i)] = label
69
70
# download model from model hub
71
model = AutoModelForSequenceClassification.from_pretrained(
72
args.model_id, num_labels=num_labels, label2id=label2id, id2label=id2label
73
)
74
tokenizer = AutoTokenizer.from_pretrained(args.model_id)
75
76
# define training args
77
training_args = TrainingArguments(
78
output_dir=args.output_dir,
79
overwrite_output_dir=True if get_last_checkpoint(args.output_dir) is not None else False,
80
num_train_epochs=args.epochs,
81
per_device_train_batch_size=args.train_batch_size,
82
per_device_eval_batch_size=args.eval_batch_size,
83
warmup_steps=args.warmup_steps,
84
fp16=args.fp16,
85
evaluation_strategy="epoch",
86
save_strategy="epoch",
87
save_total_limit=2,
88
logging_dir=f"{args.output_data_dir}/logs",
89
learning_rate=float(args.learning_rate),
90
load_best_model_at_end=True,
91
metric_for_best_model="accuracy",
92
disable_tqdm=True,
93
)
94
95
# create Trainer instance
96
trainer = Trainer(
97
model=model,
98
args=training_args,
99
compute_metrics=compute_metrics,
100
train_dataset=train_dataset,
101
eval_dataset=test_dataset,
102
tokenizer=tokenizer,
103
)
104
105
# train model
106
trainer.train()
107
108
# evaluate model
109
eval_result = trainer.evaluate(eval_dataset=test_dataset)
110
111
# writes eval result to file which can be accessed later in s3 ouput
112
with open(os.path.join(args.output_data_dir, "eval_results.txt"), "w") as writer:
113
print(f"***** Eval results *****")
114
for key, value in sorted(eval_result.items()):
115
writer.write(f"{key} = {value}\n")
116
print(f"{key} = {value}\n")
117
118
# Saves the model to s3 uses os.environ["SM_MODEL_DIR"] to make sure checkpointing works
119
trainer.save_model(os.environ["SM_MODEL_DIR"])
120
121