-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_model.py
191 lines (156 loc) · 5.86 KB
/
train_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import torch
from transformers import (GPTNeoForCausalLM, GPT2Tokenizer, TextDataset,
DataCollatorForLanguageModeling, Trainer,
TrainingArguments, PreTrainedTokenizer)
from torch.utils.data import ConcatDataset
import os
import glob
import random
import numpy as np
import argparse
def load_dataset(file_path: str,
tokenizer: PreTrainedTokenizer) -> TextDataset:
"""
Loads the text data from a file and encodes it using the provided
tokenizer.
Args:
file_path (str): The path to the text file to be loaded.
tokenizer (PreTrainedTokenizer): The tokenizer to be used to
encode the text.
Returns:
TextDataset: The encoded dataset as a `TextDataset` object.
"""
# Load the dataset
dataset = TextDataset(
tokenizer=tokenizer,
file_path=file_path,
block_size=256
)
return dataset
def load_datasets(data_dir: str,
tokenizer: PreTrainedTokenizer) -> TextDataset:
"""
Load all the dataset files and combine them into a single dataset
Args:
data_dir (str): The directory path where the text files are stored.
tokenizer (PreTrainedTokenizer): The tokenizer to use for preprocessing
the text.
Returns:
TextDataset: A concatenated dataset of all the preprocessed text files.
"""
episode_datasets = []
for season_dir in os.listdir(data_dir):
if not os.path.isdir(os.path.join(data_dir, season_dir)):
continue
for episode_file in glob.glob(
os.path.join(data_dir, season_dir, "episode_*.txt")
):
episode_dataset = load_dataset(episode_file, tokenizer)
episode_datasets.append(episode_dataset)
return ConcatDataset(episode_datasets)
def set_seed(seed):
"""
Set the random seed for reproducibility.
Args:
seed (int): The seed value to set.
Returns:
None
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def train_gpt_neo(train_data_dir: str, eval_data_dir: str, model_dir: str,
model_name: str = "EleutherAI/gpt-neo-1.3B",
batch_size: int = 4, epochs: int = 1,
learning_rate: float = 2e-5,
weight_decay: float = 0.01):
"""
Trains a GPT-Neo language model on the provided dataset.
Args:
train_data_dir (str): The directory containing the cleaned input
training data.
eval_data_dir (str): The directory containing the cleaned input
eval data.
model_dir (str): The directory to save the trained model and training
logs.
model_name (str, optional): The name of the pretrained GPT-Neo
model to use.
batch_size (int, optional): The number of training samples per batch.
epochs (int, optional): The number of times to iterate over the
training data.
learning_rate (float, optional): The learning rate for the optimizer.
weight_decay (float, optional): The amount of weight decay to apply
during training.
Returns:
None
"""
set_seed(42)
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
train_tokenized_dataset = load_datasets(train_data_dir, tokenizer)
eval_tokenized_dataset = load_datasets(eval_data_dir, tokenizer)
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False
)
model = GPTNeoForCausalLM.from_pretrained(model_name)
training_args = TrainingArguments(
output_dir=model_dir,
evaluation_strategy="epoch",
learning_rate=learning_rate,
per_device_train_batch_size=batch_size,
num_train_epochs=epochs,
weight_decay=weight_decay,
)
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=train_tokenized_dataset,
eval_dataset=eval_tokenized_dataset
)
trainer.train()
# Evaluate the model
trainer.evaluate()
# Save the model
trainer.save_model(model_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Train a GPT-Neo model on input text data'
)
parser.add_argument(
'train_data_dir', type=str,
help='The directory containing the cleaned input training data.'
)
parser.add_argument(
'eval_data_dir', type=str,
help='The directory containing the cleaned input eval data.'
)
parser.add_argument(
'model_dir', type=str,
help='The directory to save the trained model and training logs.'
)
parser.add_argument(
'--model_name', type=str, default="EleutherAI/gpt-neo-1.3B",
help='The name of the pretrained GPT-Neo model to use.'
)
parser.add_argument(
'--batch_size', type=int, default=4,
help='The number of training samples per batch.'
)
parser.add_argument(
'--epochs', type=int, default=1,
help='The number of times to iterate over the training data.'
)
parser.add_argument(
'--learning_rate', type=float, default=2e-5,
help='The learning rate for the optimizer.'
)
parser.add_argument(
'--weight_decay', type=float, default=0.01,
help='The amount of weight decay to apply during training.'
)
args = parser.parse_args()
train_gpt_neo(args.train_data_dir, args.eval_data_dir,
args.model_dir, args.model_name, args.batch_size,
args.epochs, args.learning_rate, args.weight_decay)