-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer_pygrad.py
executable file
·181 lines (144 loc) · 5.43 KB
/
trainer_pygrad.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
import os
import argparse
from torch import nn
import torch
import pandas as pd
from omegaconf import OmegaConf
from transformers.trainer_utils import get_last_checkpoint
from transformers import (
AutoConfig,
AutoFeatureExtractor,
Wav2Vec2Model
)
from datasets import load_from_disk
from evotorch.neuroevolution.net import count_parameters
import matplotlib.pyplot as plt
from utils.utils import (
preprocess_metadata, get_label_id, DataColletorTrain, CollateWav2vec2, get_feature_vector_attention_mask, preprocess_data, DatasetEVO, predict, CustomSupervisedNE
)
from utils.model import FullyConnectedEvo
import numpy as np
import pygad.torchga
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def main() -> None:
global data_inputs, data_outputs, torch_ga, fc, loss_function
parser = argparse.ArgumentParser()
parser.add_argument(
'-c',
'--config_path',
default='config/default.yaml',
type=str,
help="YAML file with configurations"
)
parser.add_argument(
'--continue_train',
default=False,
action='store_true',
help='If True, continues training using the checkpoint_path parameter'
)
args = parser.parse_args()
cfg = OmegaConf.load(args.config_path)
if os.path.isdir(cfg.train.model_checkpoint):
last_checkpoint = get_last_checkpoint(cfg.train.model_checkpoint)
print("> Resuming Train with checkpoint: ", last_checkpoint)
else:
last_checkpoint = None
train_df = pd.read_csv(cfg.metadata.train_path)
val_df = pd.read_csv(cfg.metadata.dev_path)
train_dataset = preprocess_metadata(cfg=cfg, df=train_df)
val_dataset = preprocess_metadata(cfg=cfg, df=val_df)
label2id, id2label, num_labels = get_label_id(dataset=train_dataset, label_column=cfg.metadata.label_column)
feature_extractor = AutoFeatureExtractor.from_pretrained(cfg.train.model_checkpoint)
config = AutoConfig.from_pretrained(
pretrained_model_name_or_path=last_checkpoint if last_checkpoint else cfg.train.model_checkpoint,
num_labels=num_labels,
label2id=label2id,
id2label=id2label,
)
print(label2id)
model = Wav2Vec2Model(config).to(device)
model.freeze_feature_encoder()
train_data_collator = DataColletorTrain(
batch=train_dataset,
processor=feature_extractor,
apply_augmentation=cfg.data.apply_augmentation,
sampling_rate=cfg.data.target_sampling_rate,
apply_dbfs_norm=cfg.data.apply_dbfs_norm,
target_dbfs=cfg.data.target_dbfs,
label2id=label2id
)
val_data_collator = DataColletorTrain(
batch=val_dataset,
processor=feature_extractor,
apply_augmentation=cfg.data.apply_augmentation,
sampling_rate=cfg.data.target_sampling_rate,
apply_dbfs_norm=cfg.data.apply_dbfs_norm,
target_dbfs=cfg.data.target_dbfs,
label2id=label2id
)
train_loader = torch.utils.data.DataLoader(
train_data_collator,
batch_size=2,
shuffle=True,
drop_last=False,
num_workers=10,
collate_fn=CollateWav2vec2(feature_extractor)
)
val_loader = torch.utils.data.DataLoader(
val_data_collator,
batch_size=2,
shuffle=True,
drop_last=False,
num_workers=10,
collate_fn=CollateWav2vec2(feature_extractor)
)
# preprocess_data(data_loader=val_loader, model=model, out_path="preloaded_data/val")
train_dataset = load_from_disk("preloaded_data/train")
val_dataset = load_from_disk("preloaded_data/train")
# print(val_dataset)
network = FullyConnectedEvo(input_size=1024, num_classes=3)
print(f'Network has {count_parameters(network)} parameters')
train_dataset_final = DatasetEVO(batch=train_dataset)
val_dataset_final = DatasetEVO(batch=val_dataset)
val_loader_final = torch.utils.data.DataLoader(
val_dataset_final,
batch_size=8,
shuffle=True,
drop_last=False,
num_workers=10
)
data_inputs = torch.tensor(train_dataset["hidden_states"])
data_outputs = torch.tensor(train_dataset["label_id"])
loss_function = nn.CrossEntropyLoss()
fc = FullyConnectedEvo(input_size=1024, num_classes=3)
torch_ga = pygad.torchga.TorchGA(model=fc, num_solutions=30)
num_generations = 250
num_parents_mating = 5
initial_population = torch_ga.population_weights
ga_instance = pygad.GA(
num_generations=num_generations,
num_parents_mating=num_parents_mating,
initial_population=initial_population,
fitness_func=fitness_func,
on_generation=callback_generation,
init_range_low=-0.0001,
init_range_high=0.01,
keep_parents=2,
crossover_type="scattered",
crossover_probability=0.2
)
ga_instance.run()
def callback_generation(ga_instance):
print("Generation = {generation}".format(generation=ga_instance.generations_completed))
print("Fitness = {fitness}".format(fitness=ga_instance.best_solution()[1]))
def fitness_func(solution, sol_idx):
predictions = pygad.torchga.predict(
model=fc,
solution=solution,
data=data_inputs
)
print(predictions)
solution_fitness = 1.0 / (loss_function(predictions, data_outputs).detach().numpy() + 0.00000001)
return solution_fitness
if __name__ == '__main__':
main()