-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtrain.py
More file actions
282 lines (231 loc) · 11.1 KB
/
train.py
File metadata and controls
282 lines (231 loc) · 11.1 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import argparse
import json
import os
import re
from types import SimpleNamespace
from tqdm import tqdm
from transformers import (
get_cosine_schedule_with_warmup,
get_linear_schedule_with_warmup,
get_constant_schedule_with_warmup,
get_polynomial_decay_schedule_with_warmup,
get_inverse_sqrt_schedule,
)
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.distributed import DistributedSampler
from model import GraphER
from modules.base import load_config_as_namespace
#from modules.run_evaluation import get_for_all_path
def save_top_k_checkpoints(model: GraphER, save_path: str, checkpoint: int, top_k: int = 5):
"""
Save the top-k checkpoints (latest k checkpoints) of a model and tokenizer.
Parameters:
model (GraphER): The model to save.
save_path (str): The directory path to save the checkpoints.
top_k (int): The number of top checkpoints to keep. Defaults to 5.
"""
# Save the current model and tokenizer
if isinstance(model, DDP):
model.module.save_pretrained(os.path.join(save_path, str(checkpoint)))
else:
model.save_pretrained(os.path.join(save_path, str(checkpoint)))
# List all files in the directory
files = os.listdir(save_path)
# Filter files to keep only the model checkpoints
checkpoint_folders = [file for file in files if re.search(r'model_\d+', file)]
# Sort checkpoint files by modification time (latest first)
checkpoint_folders.sort(key=lambda x: os.path.getmtime(os.path.join(save_path, x)), reverse=True)
# Keep only the top-k checkpoints
for checkpoint_folder in checkpoint_folders[top_k:]:
checkpoint_folder = os.path.join(save_path, checkpoint_folder)
checkpoint_files = [os.path.join(checkpoint_folder, f) for f in os.listdir(checkpoint_folder)]
for file in checkpoint_files:
os.remove(file)
os.rmdir(os.path.join(checkpoint_folder))
class Trainer:
def __init__(self, config, allow_distributed, device='cuda'):
self.config = config
self.lr_encoder = float(self.config.lr_encoder)
self.lr_others = float(self.config.lr_others)
self.device = device
if config.prev_path != "none": # fine-tuning mode
self.model_config = SimpleNamespace(
max_types=config.max_types,
max_len=config.max_len,
max_top_k=config.max_top_k,
add_top_k=config.add_top_k,
shuffle_types=config.shuffle_types,
random_drop=config.random_drop,
max_neg_type_ratio=config.max_neg_type_ratio,
max_ent_types=config.fine_tune,
max_rel_types=config.max_rel_types,
)
else:
self.model_config = SimpleNamespace(
model_name=config.model_name,
name=config.name,
max_width=config.max_width,
hidden_size=config.hidden_size,
dropout=config.dropout,
fine_tune=config.fine_tune,
subtoken_pooling=config.subtoken_pooling,
span_mode=config.span_mode,
max_types=config.max_types,
max_len=config.max_len,
num_heads=config.num_heads,
num_transformer_layers=config.num_transformer_layers,
ffn_mul=config.ffn_mul,
scorer=config.scorer,
max_top_k=config.max_top_k,
add_top_k=config.add_top_k,
shuffle_types=config.shuffle_types,
random_drop=config.random_drop,
max_neg_type_ratio=config.max_neg_type_ratio,
max_ent_types=config.fine_tune,
max_rel_types=config.max_rel_types,
)
self.allow_distributed = allow_distributed
def setup_distributed(self, rank, world_size):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '12356'
torch.cuda.set_device(rank)
dist.init_process_group("nccl", rank=rank, world_size=world_size)
def cleanup_distributed(self):
dist.destroy_process_group()
def setup_model_and_optimizer(self, rank=None, device=None):
if device is None:
device = self.device
if self.config.prev_path != "none":
model = GraphER.from_pretrained(self.config.prev_path).to(device)
# some parameters of model.config are not overwritten by the config file
# other than these are overwritten
keep_params = ['model_name', 'name', 'max_width', 'hidden_size', 'dropout', 'subtoken_pooling', 'span_mode',
"fine_tune", "max_types", "max_len", "num_heads", "num_transformer_layers", "ffn_mul",
"scorer"]
for param in keep_params:
original_value = getattr(model.config, param)
setattr(self.model_config, param, original_value)
model.config = self.model_config
else:
model = GraphER(self.model_config).to(device)
if rank is not None:
model = DDP(model, device_ids=[rank], output_device=rank, find_unused_parameters=False)
optimizer = model.module.get_optimizer(self.lr_encoder, self.lr_others, freeze_token_rep=self.config.freeze_token_rep)
else:
optimizer = model.get_optimizer(self.lr_encoder, self.lr_others, freeze_token_rep=self.config.freeze_token_rep)
return model, optimizer
def train_dist(self, rank, world_size, dataset):
# Init distributed process group
self.setup_distributed(rank, world_size)
device = f'cuda:{rank}'
model, optimizer = self.setup_model_and_optimizer(rank, device=device)
sampler = DistributedSampler(dataset, num_replicas=world_size, rank=rank, shuffle=True, drop_last=False)
train_loader = model.module.create_dataloader(dataset, batch_size=self.config.train_batch_size, shuffle=False,
sampler=sampler)
num_steps = self.config.num_steps // world_size
self.train(model=model, optimizer=optimizer, train_loader=train_loader,
num_steps=num_steps, device=device, rank=rank)
self.cleanup_distributed()
def init_scheduler(self, scheduler_type, optimizer, num_warmup_steps, num_steps):
if scheduler_type == "cosine":
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_steps
)
elif scheduler_type == "linear":
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_steps
)
elif scheduler_type == "constant":
scheduler = get_constant_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps,
)
elif scheduler_type == "polynomial":
scheduler = get_polynomial_decay_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_steps
)
elif scheduler_type == "inverse_sqrt":
scheduler = get_inverse_sqrt_schedule(
optimizer,
num_warmup_steps=num_warmup_steps,
)
else:
raise ValueError(
f"Invalid scheduler_type value: '{scheduler_type}' \n Supported scheduler types: 'cosine', 'linear', 'constant', 'polynomial', 'inverse_sqrt'"
)
return scheduler
def train(self, model, optimizer, train_loader, num_steps, device='cuda', rank=None):
model.train()
pbar = tqdm(range(num_steps))
warmup_ratio = self.config.warmup_ratio
eval_every = self.config.eval_every
save_total_limit = self.config.save_total_limit
log_dir = self.config.log_dir
val_data_dir = self.config.val_data_dir
num_warmup_steps = int(num_steps * warmup_ratio) if warmup_ratio < 1 else int(warmup_ratio)
scheduler = self.init_scheduler(self.config.scheduler_type, optimizer, num_warmup_steps, num_steps)
iter_train_loader = iter(train_loader)
scaler = torch.cuda.amp.GradScaler()
for step in pbar:
optimizer.zero_grad()
try:
x = next(iter_train_loader)
except StopIteration:
iter_train_loader = iter(train_loader)
x = next(iter_train_loader)
for k, v in x.items():
if isinstance(v, torch.Tensor):
x[k] = v.to(device)
with torch.cuda.amp.autocast(dtype=torch.float16):
loss = model(x)
if torch.isnan(loss).any():
print("Warning: NaN loss detected")
continue
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
scheduler.step()
description = f"step: {step} | epoch: {step // len(train_loader)} | loss: {loss.item():.2f}"
pbar.set_description(description)
if (step + 1) % eval_every == 0:
if rank is None or rank == 0:
checkpoint = f'model_{step + 1}'
save_top_k_checkpoints(model, log_dir, checkpoint, save_total_limit)
#if val_data_dir != "none":
#get_for_all_path(model, step, log_dir, val_data_dir)
model.train()
def run(self):
with open(self.config.train_data, 'r') as f:
data = json.load(f)
if torch.cuda.device_count() > 1 and self.allow_distributed:
world_size = torch.cuda.device_count()
mp.spawn(self.train_dist, args=(world_size, data), nprocs=world_size, join=True)
else:
model, optimizer = self.setup_model_and_optimizer()
train_loader = model.create_dataloader(data, batch_size=self.config.train_batch_size, shuffle=True)
self.train(model, optimizer, train_loader, num_steps=self.config.num_steps, device=self.device)
def create_parser():
parser = argparse.ArgumentParser(description="grapher")
parser.add_argument("--config", type=str, default="config.yaml", help="Path to config file")
parser.add_argument('--log_dir', type=str, default='logs', help='Path to the log directory')
parser.add_argument('--allow_distributed', type=bool, default=False,
help='Whether to allow distributed training if there are more than one GPU available')
return parser
if __name__ == "__main__":
parser = create_parser()
args = parser.parse_args()
config = load_config_as_namespace(args.config)
config.log_dir = args.log_dir
trainer = Trainer(config, allow_distributed=args.allow_distributed,
device='cuda' if torch.cuda.is_available() else 'cpu')
trainer.run()