| |
| |
| |
|
|
| |
|
|
| |
|
|
| |
| |
|
|
| import argparse |
| import logging |
| import pprint |
| import sys |
| from os.path import exists, basename |
| from os import makedirs, mkdir |
| from multiprocessing import cpu_count |
| import wandb |
| import datetime |
|
|
| import pandas as pd |
| import torch |
| import torch.utils.data |
| from tqdm import tqdm |
| import warnings |
| warnings.simplefilter(action = "ignore", category = FutureWarning) |
| import x_transformers |
|
|
| from os.path import dirname, realpath |
| import sys |
| sys.path.insert(0, dirname(realpath(__file__))) |
| sys.path.insert(0, dirname(dirname(realpath(__file__)))) |
|
|
| from wrangling.deduplicate import FACETS |
| from dataset import PARTITIONS, MusicDataset |
| from dataset import OUTPUT_DIR as DATASET_OUTPUT_DIR |
| from representation import Indexer, get_encoding, encode_notes |
| import utils |
|
|
| |
|
|
|
|
| |
| |
|
|
| |
| INPUT_DIR = f"{DATASET_OUTPUT_DIR}/{FACETS[0]}" |
| PATHS_TRAIN = f"{INPUT_DIR}/train.txt" |
| PATHS_VALID = f"{INPUT_DIR}/valid.txt" |
| OUTPUT_DIR = INPUT_DIR |
| FINE_TUNING_SUFFIX = "ft" |
|
|
| |
| MAX_SEQ_LEN = 1024 |
| MAX_BEAT = 64 |
| DIM = 512 |
| N_LAYERS = 6 |
| N_HEADS = 8 |
| DROPOUT = 0.2 |
|
|
| |
| N_STEPS = 100000 |
| N_VALID_STEPS = 1000 |
| N_SAVE_STEPS = 5000 |
| EARLY_STOPPING_TOLERANCE = 20 |
| LEARNING_RATE = 0.0005 |
| LEARNING_RATE_WARMUP_STEPS = 5000 |
| LEARNING_RATE_DECAY_STEPS = 100000 |
| LEARNING_RATE_DECAY_MULTIPLIER = 0.1 |
| GRAD_NORM_CLIP = 1.0 |
|
|
| |
| BATCH_SIZE = 12 |
|
|
| |
| RELEVANT_PARTITIONS = list(PARTITIONS.keys())[:-1] |
| LOSS_OUTPUT_COLUMNS = ["step", "partition", "loss"] |
|
|
| |
| PROJECT_NAME = "PDMX" |
| INFER_RUN_NAME_STRING = "-1" |
|
|
| |
|
|
|
|
| |
| |
|
|
| def get_lr_multiplier(step: int, warmup_steps: int, decay_end_steps: int, decay_end_multiplier: float) -> float: |
| """Return the learning rate multiplier with a warmup and decay schedule. |
| |
| The learning rate multiplier starts from 0 and linearly increases to 1 |
| after `warmup_steps`. After that, it linearly decreases to |
| `decay_end_multiplier` until `decay_end_steps` is reached. |
| |
| """ |
| if step < warmup_steps: |
| return (step + 1) / warmup_steps |
| if step > decay_end_steps: |
| return decay_end_multiplier |
| position = (step - warmup_steps) / (decay_end_steps - warmup_steps) |
| return 1 - (1 - decay_end_multiplier) * position |
|
|
| |
|
|
|
|
| |
| |
|
|
| def parse_args(args = None, namespace = None): |
| """Parse command-line arguments.""" |
| parser = argparse.ArgumentParser(prog = "Train", description = "Train a REMI-Style Model.") |
| parser.add_argument("-pt", "--paths_train", default = PATHS_TRAIN, type = str, help = ".txt file with absolute filepaths to training dataset") |
| parser.add_argument("-pv", "--paths_valid", default = PATHS_VALID, type = str, help = ".txt file with absolute filepaths to validation dataset") |
| parser.add_argument("-o", "--output_dir", default = OUTPUT_DIR, type = str, help = "Output directory") |
| parser.add_argument("-ft", "--fine_tune", action = "store_true", help = "Whether this is fine tuning") |
| |
| parser.add_argument("--aug", action = argparse.BooleanOptionalAction, default = True, help = "Whether to use data augmentation") |
| |
| parser.add_argument("--max_seq_len", default = MAX_SEQ_LEN, type = int, help = "Maximum sequence length") |
| parser.add_argument("--max_beat", default = MAX_BEAT, type = int, help = "Maximum beat") |
| parser.add_argument("--dim", default = DIM, type = int, help = "Model dimension") |
| parser.add_argument("-l", "--layers", default = N_LAYERS, type = int, help = "Number of layers") |
| parser.add_argument("--heads", default = N_HEADS, type = int, help = "Number of attention heads") |
| parser.add_argument("--dropout", default = DROPOUT, type = float, help = "Dropout rate") |
| parser.add_argument("--abs_pos_emb", action = argparse.BooleanOptionalAction, default = True, help = "Whether to use absolute positional embedding") |
| parser.add_argument("--rel_pos_emb", action = argparse.BooleanOptionalAction, default = False, help = "Whether to use relative positional embedding") |
| |
| parser.add_argument("--steps", default = N_STEPS, type = int, help = "Number of steps") |
| parser.add_argument("--valid_steps", default = N_VALID_STEPS, type = int, help = "Validation frequency") |
| parser.add_argument("--save_steps", default = N_SAVE_STEPS, type = int, help = "Frequency to save model parameters") |
| parser.add_argument("--early_stopping", action = argparse.BooleanOptionalAction, default = False, help = "Whether to use early stopping") |
| parser.add_argument("--early_stopping_tolerance", default = EARLY_STOPPING_TOLERANCE, type = int, help = "Number of extra validation rounds before early stopping") |
| parser.add_argument("-lr", "--learning_rate", default = LEARNING_RATE, type = float, help = "Learning rate") |
| parser.add_argument("--lr_warmup_steps", default = LEARNING_RATE_WARMUP_STEPS, type = int, help = "Learning rate warmup steps") |
| parser.add_argument("--lr_decay_steps", default = LEARNING_RATE_DECAY_STEPS, type = int, help = "Learning rate decay end steps") |
| parser.add_argument("--lr_decay_multiplier", default = LEARNING_RATE_DECAY_MULTIPLIER, type = float, help = "Learning rate multiplier at the end") |
| parser.add_argument("--grad_norm_clip", default = GRAD_NORM_CLIP, type = float, help = "Gradient norm clipping") |
| |
| parser.add_argument("-g", "--gpu", default = -1, type = int, help = "GPU number") |
| parser.add_argument("-j", "--jobs", default = int(cpu_count() / 4), type = int, help = "Number of workers for data loading") |
| parser.add_argument("-r", "--resume", default = None, type = str, help = "Provide the wandb run name/id to resume a run") |
| return parser.parse_args(args = args, namespace = namespace) |
|
|
| |
|
|
|
|
| |
| |
|
|
| if __name__ == "__main__": |
|
|
| |
| |
|
|
| |
| args = parse_args() |
|
|
| |
| if not exists(args.paths_train): |
| raise ValueError("Invalid --paths_train argument. File does not exist.") |
| if not exists(args.paths_valid): |
| raise ValueError("Invalid --paths_valid argument. File does not exist.") |
| run_name = args.resume |
| args.resume = (run_name != None) |
| |
| |
| device = torch.device(f"cuda:{abs(args.gpu)}" if (torch.cuda.is_available() and args.gpu != -1) else "cpu") |
| print(f"Using device: {device}") |
|
|
| |
| encoding = get_encoding() |
|
|
| |
| indexer = Indexer(data = encoding["event_code_map"]) |
|
|
| |
| print(f"Creating the data loader...") |
| dataset = { |
| "train": MusicDataset(paths = args.paths_train, encoding = encoding, indexer = indexer, encode_fn = encode_notes, max_seq_len = args.max_seq_len, max_beat = args.max_beat, use_augmentation = args.aug), |
| "valid": MusicDataset(paths = args.paths_valid, encoding = encoding, indexer = indexer, encode_fn = encode_notes, max_seq_len = args.max_seq_len, max_beat = args.max_beat, use_augmentation = False) |
| } |
| data_loader = { |
| "train": torch.utils.data.DataLoader(dataset = dataset["train"], batch_size = BATCH_SIZE, shuffle = True, num_workers = args.jobs, collate_fn = dataset["train"].collate), |
| "valid": torch.utils.data.DataLoader(dataset = dataset["valid"], batch_size = BATCH_SIZE, shuffle = False, num_workers = args.jobs, collate_fn = dataset["valid"].collate) |
| } |
|
|
| |
| print(f"Creating model...") |
| model = x_transformers.TransformerWrapper( |
| num_tokens = len(indexer), |
| max_seq_len = args.max_seq_len, |
| attn_layers = x_transformers.Decoder( |
| dim = args.dim, |
| depth = args.layers, |
| heads = args.heads, |
| rotary_pos_emb = args.rel_pos_emb, |
| emb_dropout = args.dropout, |
| attn_dropout = args.dropout, |
| ff_dropout = args.dropout, |
| ), |
| use_abs_pos_emb = args.abs_pos_emb, |
| ).to(device) |
| model = x_transformers.AutoregressiveWrapper(net = model) |
| n_parameters = sum(p.numel() for p in model.parameters()) |
| n_parameters_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) |
|
|
| |
| model_size = int(n_parameters_trainable / 1e+6) |
| output_parent_dir = args.output_dir |
| output_dir_name = f"{model_size}M" |
| output_dir = f"{output_parent_dir}/{output_dir_name}" |
| original_output_dir_name, original_output_dir = output_dir_name, output_dir |
| if not exists(output_dir): |
| if args.fine_tune: |
| raise NotADirectoryError(f"No {output_dir_name} model exists at {output_dir} to fine tune.") |
| else: |
| makedirs(output_dir) |
| elif args.fine_tune: |
| output_dir_name += f"_{FINE_TUNING_SUFFIX}" |
| output_dir = f"{output_parent_dir}/{output_dir_name}" |
| if not exists(output_dir): |
| makedirs(output_dir) |
| checkpoints_dir, original_checkpoints_dir = f"{output_dir}/checkpoints", f"{original_output_dir}/checkpoints" |
| checkpoints_dir_for_model_reloading = original_checkpoints_dir if (args.fine_tune and (not args.resume)) else checkpoints_dir |
| if not exists(checkpoints_dir): |
| mkdir(checkpoints_dir) |
|
|
| |
| group_name = basename(output_parent_dir) |
| if run_name == INFER_RUN_NAME_STRING: |
| run_name = next(filter(lambda name: name.startswith(output_dir_name), (run.name for run in wandb.Api().runs(f"philly/{PROJECT_NAME}", filters = {"group": group_name}))), None) |
| args.resume = (run_name != None) |
| if run_name is None: |
| current_datetime = datetime.datetime.now().strftime("%m%d%y%H%M%S") |
| run_name = f"{output_dir_name}-{current_datetime}" |
| run = wandb.init(config = dict(vars(args), **{"n_parameters": n_parameters, "n_parameters_trainable": n_parameters_trainable}), resume = "allow", project = PROJECT_NAME, group = group_name, name = run_name, id = run_name) |
|
|
| |
| logging_output_filepath = f"{output_dir}/train.log" |
| log_hyperparameters = not (args.resume and exists(logging_output_filepath)) |
| logging.basicConfig(level = logging.INFO, format = "%(message)s", handlers = [logging.FileHandler(filename = logging_output_filepath, mode = "a" if args.resume else "w"), logging.StreamHandler(stream = sys.stdout)]) |
|
|
| |
| if log_hyperparameters: |
| logging.info(f"Running command: python {' '.join(sys.argv)}") |
| logging.info(f"Using arguments:\n{pprint.pformat(vars(args))}") |
| args_output_filepath = f"{output_dir}/train_args.json" |
| logging.info(f"Saved arguments to {args_output_filepath}") |
| utils.save_args(filepath = args_output_filepath, args = args) |
| del args_output_filepath |
| else: |
| with open(logging_output_filepath, "r") as logging_output: |
| print(logging_output.read()) |
|
|
| |
| def log_model_size(): |
| """Log the size of the model.""" |
| logging.info(f"Number of parameters: {n_parameters:,}") |
| logging.info(f"Number of trainable parameters: {n_parameters_trainable:,}") |
| best_model_filepath = {partition: f"{checkpoints_dir_for_model_reloading}/best_model.{partition}.pth" for partition in RELEVANT_PARTITIONS} |
| if args.fine_tune and args.resume and (not all(map(exists, best_model_filepath.values()))): |
| best_model_filepath = {partition: f"{original_checkpoints_dir}/best_model.{partition}.pth" for partition in RELEVANT_PARTITIONS} |
| if args.fine_tune and (not all(map(exists, best_model_filepath.values()))): |
| raise FileNotFoundError(f"Cannot fine tune {original_output_dir_name} model, since relevant state_dict files do not exist.") |
| if (args.resume or args.fine_tune) and all(map(exists, best_model_filepath.values())): |
| model.load_state_dict(torch.load(f = best_model_filepath["valid"], weights_only = True)) |
| if args.fine_tune and log_hyperparameters: |
| log_model_size() |
| else: |
| log_model_size() |
| best_model_filepath = {partition: f"{checkpoints_dir}/best_model.{partition}.pth" for partition in RELEVANT_PARTITIONS} |
| |
| |
| optimizer = torch.optim.Adam(params = model.parameters(), lr = args.learning_rate) |
| best_optimizer_filepath = {partition: f"{checkpoints_dir}/best_optimizer.{partition}.pth" for partition in RELEVANT_PARTITIONS} |
| if args.resume and all(map(exists, best_optimizer_filepath.values())): |
| optimizer.load_state_dict(torch.load(f = best_optimizer_filepath["valid"], weights_only = True)) |
|
|
| |
| scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer = optimizer, lr_lambda = lambda step: get_lr_multiplier(step = step, warmup_steps = args.lr_warmup_steps, decay_end_steps = args.lr_decay_steps, decay_end_multiplier = args.lr_decay_multiplier)) |
| best_scheduler_filepath = {partition: f"{checkpoints_dir}/best_scheduler.{partition}.pth" for partition in RELEVANT_PARTITIONS} |
| if args.resume and all(map(exists, best_scheduler_filepath.values())): |
| scheduler.load_state_dict(torch.load(f = best_scheduler_filepath["valid"], weights_only = True)) |
|
|
| |
|
|
|
|
| |
| |
|
|
| |
| output_filepath = f"{output_dir}/loss.csv" |
| loss_columns_must_be_written = not (exists(output_filepath) and args.resume) |
| if loss_columns_must_be_written: |
| pd.DataFrame(columns = LOSS_OUTPUT_COLUMNS).to_csv(path_or_buf = output_filepath, sep = ",", na_rep = utils.NA_STRING, header = True, index = False, mode = "w") |
|
|
| |
| step = 0 |
| min_loss = {partition: float("inf") for partition in RELEVANT_PARTITIONS} |
| if not loss_columns_must_be_written: |
| previous_loss = pd.read_csv(filepath_or_buffer = output_filepath, sep = ",", na_values = utils.NA_STRING, header = 0, index_col = False) |
| if len(previous_loss) > 0: |
| for partition in RELEVANT_PARTITIONS: |
| min_loss[partition] = float(previous_loss[previous_loss["partition"] == partition]["loss"].min(axis = 0)) |
| step = int(previous_loss["step"].max(axis = 0)) |
| del previous_loss |
| if args.early_stopping: |
| count_early_stopping = 0 |
|
|
| |
| print(f"Current Step: {step:,}") |
|
|
| |
| train_iterator = iter(data_loader["train"]) |
| while step < args.steps: |
|
|
| |
| loss = {partition: 0.0 for partition in RELEVANT_PARTITIONS} |
|
|
| |
| |
|
|
| logging.info(f"Training...") |
|
|
| model.train() |
| count = 0 |
| |
| for batch in (progress_bar := tqdm(iterable = range(args.valid_steps), desc = "Training")): |
|
|
| |
| try: |
| batch = next(train_iterator) |
| except (StopIteration): |
| train_iterator = iter(data_loader["train"]) |
| batch = next(train_iterator) |
|
|
| |
| seq = batch["seq"].to(device) |
| mask = batch["mask"].to(device) |
|
|
| |
| optimizer.zero_grad() |
| loss_batch = model(x = seq, return_outputs = False, mask = mask) |
|
|
| |
| loss_batch.backward() |
| torch.nn.utils.clip_grad_norm_(parameters = model.parameters(), max_norm = args.grad_norm_clip) |
| optimizer.step() |
| scheduler.step() |
|
|
| |
| |
| |
| |
| |
| |
| |
| loss_batch = float(loss_batch) |
| progress_bar.set_postfix(loss = f"{loss_batch:8.4f}") |
|
|
| |
| wandb.log({f"train": loss_batch}, step = step) |
|
|
| |
| count += len(batch) |
|
|
| |
| loss["train"] += loss_batch * len(batch) |
|
|
| |
| step += 1 |
|
|
| |
| del seq, mask, loss_batch |
|
|
| |
| loss["train"] /= count |
| |
| |
| wandb.log({"train": loss["train"]}, step = step) |
|
|
| |
| if (step % args.save_steps) == 0: |
| steps_for_save = int(step / args.valid_steps) |
| torch.save(obj = model.state_dict(), f = f"{checkpoints_dir}/model.{steps_for_save}.pth") |
| torch.save(obj = optimizer.state_dict(), f = f"{checkpoints_dir}/optimizer.{steps_for_save}.pth") |
| torch.save(obj = scheduler.state_dict(), f = f"{checkpoints_dir}/scheduler.{steps_for_save}.pth") |
|
|
| |
|
|
|
|
| |
| |
|
|
| logging.info(f"Validating...") |
|
|
| model.eval() |
| with torch.no_grad(): |
|
|
| count = 0 |
| for batch in tqdm(iterable = data_loader["valid"], desc = "Validating"): |
|
|
| |
| seq = batch["seq"].to(device) |
| mask = batch["mask"].to(device) |
|
|
| |
| loss_batch = model(x = seq, return_outputs = False, mask = mask) |
|
|
| |
| count += len(batch) |
|
|
| |
| loss["valid"] += float(loss_batch) * len(batch) |
| |
| |
| del seq, mask, loss_batch |
|
|
| |
| loss["valid"] /= count |
|
|
| |
| logging.info(f"Validation loss: {loss['valid']:.4f}") |
|
|
| |
| wandb.log({"valid": loss["valid"]}, step = step) |
|
|
| |
|
|
|
|
| |
| |
|
|
| |
| output = pd.DataFrame( |
| data = dict(zip( |
| LOSS_OUTPUT_COLUMNS, |
| (utils.rep(x = step, times = len(RELEVANT_PARTITIONS)), RELEVANT_PARTITIONS, loss.values()))), |
| columns = LOSS_OUTPUT_COLUMNS) |
| output.to_csv(path_or_buf = output_filepath, sep = ",", na_rep = utils.NA_STRING, header = False, index = False, mode = "a") |
|
|
| |
| is_an_improvement = False |
| for partition in RELEVANT_PARTITIONS: |
| partition_loss = loss[partition] |
| if partition_loss < min_loss[partition]: |
| min_loss[partition] = partition_loss |
| logging.info(f"Best {partition}_loss so far!") |
| torch.save(obj = model.state_dict(), f = best_model_filepath[partition]) |
| torch.save(obj = optimizer.state_dict(), f = best_optimizer_filepath[partition]) |
| torch.save(obj = scheduler.state_dict(), f = best_scheduler_filepath[partition]) |
| if args.early_stopping: |
| count_early_stopping = 0 |
| is_an_improvement = True |
| |
| |
| if (not is_an_improvement) and args.early_stopping: |
| count_early_stopping += 1 |
|
|
| |
| if args.early_stopping and (count_early_stopping > args.early_stopping_tolerance): |
| logging.info(f"Stopped the training for no improvements in {args.early_stopping_tolerance} rounds.") |
| break |
|
|
| |
|
|
| |
|
|
| |
| |
| |
|
|
| |
| logging.info(f"Minimum validation loss achieved: {min_loss['valid']}") |
| wandb.log({f"min_valid_loss": min_loss['valid']}) |
|
|
| |
| wandb.finish() |
|
|
| |
| models_output_filepath = f"{output_parent_dir}/models.txt" |
| if exists(models_output_filepath): |
| with open(models_output_filepath, "r") as models_output: |
| models = {model.strip() for model in models_output.readlines()} |
| else: |
| models = set() |
| with open(models_output_filepath, "a") as models_output: |
| if output_dir_name not in models: |
| models_output.write(output_dir_name + "\n") |
|
|
| |
|
|
| |
|
|
|
|