-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathtrain.py
479 lines (442 loc) · 17.9 KB
/
train.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
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
import argparse
import os
import random
from pathlib import Path
from typing import Union
import lightning as pl
import numpy as np
import torch
import torch.nn.functional as F
from lightning import Trainer
from lightning.fabric.utilities import rank_zero_only
from lightning.pytorch.callbacks import ModelCheckpoint
from peft import LoraConfig, TaskType
from safetensors.torch import save_file as safe_save_file
from torch import optim
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import Dataset, DataLoader
import MIDI
from midi_model import MIDIModel, MIDIModelConfig, config_name_list
from midi_tokenizer import MIDITokenizerV1, MIDITokenizerV2
EXTENSION = [".mid", ".midi"]
def file_ext(fname):
return os.path.splitext(fname)[1].lower()
class MidiDataset(Dataset):
def __init__(self, midi_list, tokenizer: Union[MIDITokenizerV1, MIDITokenizerV2], max_len=2048, min_file_size=3000,
max_file_size=384000,
aug=True, check_quality=False, rand_start=True):
self.tokenizer = tokenizer
self.midi_list = midi_list
self.max_len = max_len
self.min_file_size = min_file_size
self.max_file_size = max_file_size
self.aug = aug
self.check_quality = check_quality
self.rand_start = rand_start
def __len__(self):
return len(self.midi_list)
def load_midi(self, index):
path = self.midi_list[index]
try:
with open(path, 'rb') as f:
datas = f.read()
if len(datas) > self.max_file_size: # large midi file will spend too much time to load
raise ValueError("file too large")
elif len(datas) < self.min_file_size:
raise ValueError("file too small")
mid = MIDI.midi2score(datas)
if max([0] + [len(track) for track in mid[1:]]) == 0:
raise ValueError("empty track")
mid = self.tokenizer.tokenize(mid)
if self.check_quality and not self.tokenizer.check_quality(mid)[0]:
raise ValueError("bad quality")
if self.aug:
mid = self.tokenizer.augment(mid)
except Exception:
mid = self.load_midi(random.randint(0, self.__len__() - 1))
return mid
def __getitem__(self, index):
mid = self.load_midi(index)
mid = np.asarray(mid, dtype=np.int16)
# if mid.shape[0] < self.max_len:
# mid = np.pad(mid, ((0, self.max_len - mid.shape[0]), (0, 0)),
# mode="constant", constant_values=self.tokenizer.pad_id)
if self.rand_start:
start_idx = random.randrange(0, max(1, mid.shape[0] - self.max_len))
start_idx = random.choice([0, start_idx])
else:
max_start = max(1, mid.shape[0] - self.max_len)
start_idx = (index * (max_start // 8)) % max_start
mid = mid[start_idx: start_idx + self.max_len]
mid = mid.astype(np.int64)
mid = torch.from_numpy(mid)
return mid
def collate_fn(self, batch):
max_len = max([len(mid) for mid in batch])
batch = [F.pad(mid, (0, 0, 0, max_len - mid.shape[0]), mode="constant", value=self.tokenizer.pad_id) for mid in batch]
batch = torch.stack(batch)
return batch
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
""" Create a schedule with a learning rate that decreases linearly after
linearly increasing during a warmup period.
"""
def lr_lambda(current_step):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps))
return max(0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)))
return LambdaLR(optimizer, lr_lambda, last_epoch)
class TrainMIDIModel(MIDIModel, pl.LightningModule):
def __init__(self, config: MIDIModelConfig,
lr=2e-4, weight_decay=0.01, warmup=1e3, max_step=1e6, sample_seq=False,
gen_example_interval=1, example_batch=8):
super(TrainMIDIModel, self).__init__(config)
self.lr = lr
self.weight_decay = weight_decay
self.warmup = warmup
self.max_step = max_step
self.sample_seq = sample_seq
self.gen_example_interval = gen_example_interval
self.example_batch = example_batch
self.last_save_step = 0
self.gen_example_count = 0
def configure_optimizers(self):
param_optimizer = list(self.named_parameters())
no_decay = ['bias', 'norm'] # no decay for bias and Norm
optimizer_grouped_parameters = [
{
'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay': self.weight_decay},
{
'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
'weight_decay': 0.0
}
]
optimizer = optim.AdamW(
optimizer_grouped_parameters,
lr=self.lr,
betas=(0.9, 0.99),
eps=1e-08,
)
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=self.warmup,
num_training_steps=self.max_step,
)
return {
"optimizer": optimizer,
"lr_scheduler": {
"scheduler": lr_scheduler,
"interval": "step",
"frequency": 1
}
}
def compute_accuracy(self, logits, labels):
out = torch.argmax(logits, dim=-1)
out = out.flatten()
labels = labels.flatten()
mask = (labels != self.tokenizer.pad_id)
out = out[mask]
labels = labels[mask]
num_right = (out == labels)
num_right = torch.sum(num_right).type(torch.float32)
acc = num_right / len(labels)
return acc
def training_step(self, batch, batch_idx):
x = batch[:, :-1].contiguous() # (batch_size, midi_sequence_length, token_sequence_length)
y = batch[:, 1:].contiguous()
hidden = self.forward(x)
if self.sample_seq: # to reduce vram
rand_idx = [-1] + random.sample(list(range(y.shape[1] - 2)), min(127, (y.shape[1] - 2) // 2))
hidden = hidden[:, rand_idx]
y = y[:, rand_idx]
hidden = hidden.reshape(-1, hidden.shape[-1])
y = y.reshape(-1, y.shape[-1]) # (batch_size*midi_sequence_length, token_sequence_length)
x = y[:, :-1]
logits = self.forward_token(hidden, x)
loss = F.cross_entropy(
logits.view(-1, self.tokenizer.vocab_size),
y.view(-1),
reduction="mean",
ignore_index=self.tokenizer.pad_id
)
self.log("train/loss", loss)
self.log("train/lr", self.lr_schedulers().get_last_lr()[0])
return loss
def validation_step(self, batch, batch_idx):
x = batch[:, :-1].contiguous() # (batch_size, midi_sequence_length, token_sequence_length)
y = batch[:, 1:].contiguous()
hidden = self.forward(x)
hidden = hidden.reshape(-1, hidden.shape[-1])
y = y.reshape(-1, y.shape[-1]) # (batch_size*midi_sequence_length, token_sequence_length)
x = y[:, :-1]
logits = self.forward_token(hidden, x)
loss = F.cross_entropy(
logits.view(-1, self.tokenizer.vocab_size),
y.view(-1),
reduction="mean",
ignore_index=self.tokenizer.pad_id
)
acc = self.compute_accuracy(logits, y)
self.log_dict({"val/loss": loss, "val/acc": acc}, sync_dist=True)
return loss
@rank_zero_only
def gen_example(self, save_dir):
base_dir = f"{save_dir}/sample/{self.global_step}"
if not os.path.exists(base_dir):
Path(base_dir).mkdir(parents=True)
midis = self.generate(batch_size=self.example_batch)
midis = [self.tokenizer.detokenize(midi) for midi in midis]
imgs = [self.tokenizer.midi2img(midi) for midi in midis]
for i, (img, midi) in enumerate(zip(imgs, midis)):
img.save(f"{base_dir}/0_{i}.png")
with open(f"{base_dir}/0_{i}.mid", 'wb') as f:
f.write(MIDI.score2midi(midi))
prompt = val_dataset.load_midi(random.randint(0, len(val_dataset) - 1))
prompt = np.asarray(prompt, dtype=np.int16)
ori = prompt[:512]
img = self.tokenizer.midi2img(self.tokenizer.detokenize(ori))
img.save(f"{base_dir}/1_ori.png")
prompt = prompt[:256].astype(np.int64)
midis = self.generate(prompt, batch_size=self.example_batch)
midis = [self.tokenizer.detokenize(midi) for midi in midis]
imgs = [self.tokenizer.midi2img(midi) for midi in midis]
for i, (img, midi) in enumerate(zip(imgs, midis)):
img.save(f"{base_dir}/1_{i}.png")
with open(f"{base_dir}/1_{i}.mid", 'wb') as f:
f.write(MIDI.score2midi(midi))
@rank_zero_only
def save_peft(self, save_dir):
adapter_name = self.active_adapters()[0]
adapter_config = self.peft_config[adapter_name]
if not os.path.exists(save_dir):
os.makedirs(save_dir, exist_ok=True)
adapter_config.save_pretrained(save_dir)
adapter_state_dict = self.get_adapter_state_dict(adapter_name)
safe_save_file(adapter_state_dict,
os.path.join(save_dir, "adapter_model.safetensors"),
metadata={"format": "pt"})
def on_save_checkpoint(self, checkpoint):
if self.global_step == self.last_save_step:
return
self.last_save_step = self.global_step
trainer = self.trainer
if len(trainer.loggers) > 0:
if trainer.loggers[0].save_dir is not None:
save_dir = trainer.loggers[0].save_dir
else:
save_dir = trainer.default_root_dir
name = trainer.loggers[0].name
version = trainer.loggers[0].version
version = version if isinstance(version, str) else f"version_{version}"
save_dir = os.path.join(save_dir, str(name), version)
else:
save_dir = trainer.default_root_dir
self.config.save_pretrained(os.path.join(save_dir, "checkpoints"))
if self._hf_peft_config_loaded:
self.save_peft(os.path.join(save_dir, "lora"))
self.gen_example_count += 1
if self.gen_example_interval>0 and self.gen_example_count % self.gen_example_interval == 0:
try:
self.gen_example(save_dir)
except Exception as e:
print(e)
def get_midi_list(path):
all_files = {
os.path.join(root, fname)
for root, _dirs, files in os.walk(path)
for fname in files
}
all_midis = sorted(
fname for fname in all_files if file_ext(fname) in EXTENSION
)
return all_midis
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# model args
parser.add_argument(
"--resume", type=str, default="", help="resume training from ckpt"
)
parser.add_argument(
"--ckpt", type=str, default="", help="load ckpt"
)
parser.add_argument(
"--config", type=str, default="tv2o-medium", help="model config name or file"
)
parser.add_argument(
"--task", type=str, default="train", choices=["train", "lora"], help="Full train or lora"
)
# dataset args
parser.add_argument(
"--data", type=str, default="data", help="dataset path"
)
parser.add_argument(
"--data-val-split",
type=int,
default=128,
help="the number of midi files divided into the validation set",
)
parser.add_argument(
"--max-len",
type=int,
default=2048,
help="max seq length for training",
)
parser.add_argument(
"--quality", action="store_true", default=False, help="check dataset quality"
)
# training args
parser.add_argument("--seed", type=int, default=0, help="seed")
parser.add_argument("--lr", type=float, default=1e-4, help="learning rate")
parser.add_argument("--weight-decay", type=float, default=0.01, help="weight decay")
parser.add_argument("--warmup-step", type=int, default=1e2, help="warmup step")
parser.add_argument("--max-step", type=int, default=1e6, help="max training step")
parser.add_argument("--grad-clip", type=float, default=1.0, help="gradient clip val")
parser.add_argument(
"--sample-seq", action="store_true", default=False, help="sample midi seq to reduce vram"
)
parser.add_argument(
"--gen-example-interval", type=int, default=1, help="generate example interval. set 0 to disable"
)
parser.add_argument(
"--batch-size-train", type=int, default=2, help="batch size for training"
)
parser.add_argument(
"--batch-size-val", type=int, default=2, help="batch size for val"
)
parser.add_argument(
"--batch-size-gen-example", type=int, default=8, help="batch size for generate example"
)
parser.add_argument(
"--workers-train",
type=int,
default=4,
help="workers num for training dataloader",
)
parser.add_argument(
"--workers-val",
type=int,
default=4,
help="workers num for validation dataloader",
)
parser.add_argument(
"--acc-grad", type=int, default=2, help="gradient accumulation"
)
parser.add_argument(
"--accelerator",
type=str,
default="gpu",
choices=["cpu", "gpu", "tpu", "ipu", "hpu", "auto"],
help="accelerator",
)
parser.add_argument(
"--precision",
type=str,
default="bf16-true",
choices=["16-true", "16-mixed", "bf16-true", "bf16-mixed", "32-true", "64-true", "64", "32", "16", "bf16"],
help="precision",
)
parser.add_argument("--devices", type=int, default=-1, help="devices num")
parser.add_argument("--nodes", type=int, default=1, help="nodes num")
parser.add_argument(
"--disable-benchmark", action="store_true", default=False, help="disable cudnn benchmark"
)
parser.add_argument(
"--log-step", type=int, default=1, help="log training loss every n steps"
)
parser.add_argument(
"--val-step", type=int, default=1600, help="valid and save every n steps, set 0 to valid and save every epoch"
)
opt = parser.parse_args()
print(opt)
if not os.path.exists("lightning_logs"):
os.mkdir("lightning_logs")
if not os.path.exists("sample"):
os.mkdir("sample")
pl.seed_everything(opt.seed)
print("---load dataset---")
if opt.config in config_name_list:
config = MIDIModelConfig.from_name(opt.config)
else:
config = MIDIModelConfig.from_json_file(opt.config)
tokenizer = config.tokenizer
midi_list = get_midi_list(opt.data)
random.shuffle(midi_list)
full_dataset_len = len(midi_list)
train_dataset_len = full_dataset_len - opt.data_val_split
train_midi_list = midi_list[:train_dataset_len]
val_midi_list = midi_list[train_dataset_len:]
train_dataset = MidiDataset(train_midi_list, tokenizer, max_len=opt.max_len, aug=True, check_quality=opt.quality,
rand_start=True)
val_dataset = MidiDataset(val_midi_list, tokenizer, max_len=opt.max_len, aug=False, check_quality=opt.quality,
rand_start=False)
train_dataloader = DataLoader(
train_dataset,
batch_size=opt.batch_size_train,
shuffle=True,
persistent_workers=True,
num_workers=opt.workers_train,
pin_memory=True,
collate_fn=train_dataset.collate_fn
)
val_dataloader = DataLoader(
val_dataset,
batch_size=opt.batch_size_val,
shuffle=False,
persistent_workers=True,
num_workers=opt.workers_val,
pin_memory=True,
collate_fn=val_dataset.collate_fn
)
print(f"train: {len(train_dataset)} val: {len(val_dataset)}")
torch.backends.cuda.enable_mem_efficient_sdp(True)
torch.backends.cuda.enable_flash_sdp(True)
model = TrainMIDIModel(config, lr=opt.lr, weight_decay=opt.weight_decay,
warmup=opt.warmup_step, max_step=opt.max_step,
sample_seq=opt.sample_seq, gen_example_interval=opt.gen_example_interval,
example_batch=opt.batch_size_gen_example)
if opt.ckpt:
ckpt = torch.load(opt.ckpt, map_location="cpu")
state_dict = ckpt.get("state_dict", ckpt)
model.load_state_dict(state_dict, strict=False)
elif opt.task == "lora":
raise ValueError("--ckpt must be set to train lora")
if opt.task == "lora":
model.requires_grad_(False)
lora_config = LoraConfig(
r=64,
target_modules=["q_proj", "o_proj", "k_proj", "v_proj", "gate_proj", "up_proj", "down_proj"],
task_type=TaskType.CAUSAL_LM,
bias="none",
lora_alpha=128,
lora_dropout=0
)
model.add_adapter(lora_config)
print("---start train---")
checkpoint_callback = ModelCheckpoint(
monitor="val/loss",
mode="min",
save_top_k=1,
save_last=True,
auto_insert_metric_name=False,
filename="epoch={epoch},loss={val/loss:.4f}",
)
callbacks = [checkpoint_callback]
trainer = Trainer(
precision=opt.precision,
accumulate_grad_batches=opt.acc_grad,
gradient_clip_val=opt.grad_clip,
accelerator=opt.accelerator,
devices=opt.devices,
num_nodes=opt.nodes,
max_steps=opt.max_step,
benchmark=not opt.disable_benchmark,
val_check_interval=opt.val_step or None,
log_every_n_steps=1,
strategy="auto",
callbacks=callbacks,
)
ckpt_path = opt.resume
if ckpt_path == "":
ckpt_path = None
print("---start train---")
trainer.fit(model, train_dataloader, val_dataloader, ckpt_path=ckpt_path)