-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassifier.py
1806 lines (1532 loc) · 89.3 KB
/
classifier.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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
from torch.utils.data import DataLoader
import torch.distributed as dist
from torch.utils.data.distributed import DistributedSampler
from torch.nn.parallel import DistributedDataParallel as DDP
from torch_model_base import TorchModelBase
import torch.optim as optim
from torch.distributed.optim import ZeroRedundancyOptimizer
from sklearn.model_selection import train_test_split
from transformers import ElectraConfig, AutoTokenizer
from transformers import ElectraPreTrainedModel, ElectraModel
import os
import time
import utils
import sys
import select
from tqdm import tqdm
from multiprocessing import Value
from colors import *
from utils import (format_time, print_state_summary, format_tolerance, get_nic_color, get_score_colors,
print_rank_memory_summary, convert_labels_to_tensor, convert_numeric_to_labels, tensor_to_numpy,
get_scheduler, SwishGLU)
import wandb
import torch.onnx
import io
import warnings
# Ignore some warnings related to ONNX conversion
warnings.filterwarnings("ignore", message="Converting a tensor to a Python boolean")
warnings.filterwarnings("ignore", message="Converting a tensor to a Python number")
warnings.filterwarnings("ignore", message="Converting a tensor to a Python list")
class SentimentDataset(torch.utils.data.Dataset):
def __init__(self, sentences, labels, tokenizer, label_dict=None, max_length=512, device='cpu'):
self.sentences = sentences
self.tokenizer = tokenizer
self.max_length = max_length
self.device = device
if labels is not None:
self.labels = convert_labels_to_tensor(labels, label_dict, device)
else:
self.labels = None
def __len__(self):
return len(self.sentences)
def __getitem__(self, idx):
sentence = self.sentences[idx]
encoding = self.tokenizer(
sentence,
add_special_tokens=True,
max_length=self.max_length,
padding='max_length',
truncation=True,
return_tensors='pt',
)
item = {key: val.squeeze(0) for key, val in encoding.items()}
if self.labels is not None:
item['labels'] = self.labels[idx]
return item
class BERTClassifier(nn.Module):
def __init__(self, bert_model, pooling, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate, finetune_layers=1, rank=0):
super().__init__()
self.bert = bert_model
# Remove BERT's original pooler
self.bert.pooler = None
# Add our custom pooling layer
self.custom_pooling = PoolingLayer(pooling)
self.classifier = Classifier(bert_model.config.hidden_size, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate)
# Get the total number of layers in the BERT model
total_bert_layers = len(self.bert.encoder.layer)
# Freeze all layers except the specified number of final layers
if finetune_layers == 0:
# Freeze all BERT parameters
for param in self.bert.parameters():
param.requires_grad = False
elif finetune_layers < total_bert_layers:
modules_to_freeze = [self.bert.embeddings, *self.bert.encoder.layer[:-finetune_layers]]
for module in modules_to_freeze:
for param in module.parameters():
param.requires_grad = False
# Count trainable and non-trainable parameters
bert_trainable_params = sum(p.numel() for p in self.bert.parameters() if p.requires_grad)
bert_non_trainable_params = sum(p.numel() for p in self.bert.parameters() if not p.requires_grad)
# Count layers requiring gradients
layers_requiring_grad = sum(any(p.requires_grad for p in layer.parameters()) for layer in self.bert.encoder.layer)
if rank == 0:
print(f"BERT's original pooler removed. Using custom pooling type: {pooling}")
print(f"BERT has {bert_trainable_params:,} trainable parameters and {bert_non_trainable_params:,} non-trainable parameters")
print(f"Number of BERT layers requiring gradients: {layers_requiring_grad} out of {total_bert_layers}")
if finetune_layers == 0:
print("All BERT layers are frozen")
else:
print(f"Fine-tuning the last {finetune_layers} out of {total_bert_layers} BERT layers")
def forward(self, input_ids, attention_mask):
# Get the last hidden states from BERT
bert_outputs = self.bert(input_ids, attention_mask=attention_mask)
# Apply our custom pooling
pooled_output = self.custom_pooling(bert_outputs.last_hidden_state, attention_mask)
# Pass the pooled output to the classifier
return self.classifier(pooled_output)
class TransformerClassifier(nn.Module):
def __init__(self, transformer_model, pooling, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate, finetune_layers=1, rank=0):
super().__init__()
self.transformer = transformer_model
# Remove the model's original pooler if it exists
if hasattr(self.transformer, 'pooler'):
self.transformer.pooler = None
# Add our custom pooling layer
self.custom_pooling = PoolingLayer(pooling)
self.classifier = Classifier(self.transformer.config.hidden_size, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate)
# Get the total number of layers in the transformer model
if hasattr(self.transformer, 'encoder'):
total_layers = len(self.transformer.encoder.layer)
elif hasattr(self.transformer, 'layers'):
total_layers = len(self.transformer.layers)
else:
total_layers = 12 # default for most models, adjust if necessary
# Freeze all layers except the specified number of final layers
if finetune_layers == 0:
for param in self.transformer.parameters():
param.requires_grad = False
elif finetune_layers < total_layers:
modules_to_freeze = self.transformer.embeddings
if hasattr(self.transformer, 'encoder'):
modules_to_freeze = [modules_to_freeze, *self.transformer.encoder.layer[:-finetune_layers]]
elif hasattr(self.transformer, 'layers'):
modules_to_freeze = [modules_to_freeze, *self.transformer.layers[:-finetune_layers]]
for module in modules_to_freeze:
for param in module.parameters():
param.requires_grad = False
# Count trainable and non-trainable parameters
trainable_params = sum(p.numel() for p in self.transformer.parameters() if p.requires_grad)
non_trainable_params = sum(p.numel() for p in self.transformer.parameters() if not p.requires_grad)
if rank == 0:
print(f"Transformer's original pooler removed. Using custom pooling type: {pooling}")
print(f"Transformer has {trainable_params:,} trainable parameters and {non_trainable_params:,} non-trainable parameters")
print(f"Fine-tuning the last {finetune_layers} out of {total_layers} Transformer layers")
def forward(self, **inputs):
outputs = self.transformer(**inputs)
pooled_output = self.custom_pooling(outputs.last_hidden_state, inputs['attention_mask'])
return self.classifier(pooled_output)
class Classifier(nn.Module):
def __init__(self, input_dim, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate=0.0):
super().__init__()
layers = []
layers.append(nn.Linear(input_dim, hidden_dim))
layers.append(hidden_activation)
if dropout_rate > 0:
layers.append(nn.Dropout(dropout_rate))
for _ in range(num_layers - 1):
layers.append(nn.Linear(hidden_dim, hidden_dim))
layers.append(hidden_activation)
if dropout_rate > 0:
layers.append(nn.Dropout(dropout_rate))
layers.append(nn.Linear(hidden_dim, n_classes))
self.layers = nn.Sequential(*layers)
def forward(self, x):
return self.layers(x)
class PoolingLayer(nn.Module):
def __init__(self, pooling_type='cls'):
super().__init__()
self.pooling_type = pooling_type
def forward(self, last_hidden_state, attention_mask):
if self.pooling_type == 'cls':
return last_hidden_state[:, 0, :]
elif self.pooling_type == 'mean':
return (last_hidden_state * attention_mask.unsqueeze(-1)).sum(1) / attention_mask.sum(-1).unsqueeze(-1)
elif self.pooling_type == 'max':
return torch.max(last_hidden_state * attention_mask.unsqueeze(-1), dim=1)[0]
else:
raise ValueError(f"Unknown pooling method: {self.pooling_type}")
class CustomElectraClassifier(ElectraPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.electra = ElectraModel(config)
# Remove the original pooler if it exists
if hasattr(self.electra, 'pooler'):
self.electra.pooler = None
# Add your custom pooling layer
self.pooling = PoolingLayer(pooling_type=config.pooling)
# Handle custom activation functions
activation_name = config.hidden_activation
if activation_name == 'SwishGLU':
hidden_activation = SwishGLU(input_dim=config.hidden_dim, output_dim=config.hidden_dim)
else:
activation_class = getattr(nn, activation_name)
hidden_activation = activation_class()
self.classifier = Classifier(
input_dim=config.hidden_size,
hidden_dim=config.hidden_dim,
hidden_activation=hidden_activation,
num_layers=config.num_layers,
n_classes=config.num_labels,
dropout_rate=config.dropout_rate
)
self.init_weights()
def forward(self, input_ids=None, attention_mask=None, **kwargs):
outputs = self.electra(input_ids, attention_mask=attention_mask, **kwargs)
pooled_output = self.pooling(outputs.last_hidden_state, attention_mask)
logits = self.classifier(pooled_output)
return logits
class TorchDDPNeuralClassifier(TorchModelBase):
def __init__(self,
bert_model,
bert_tokenizer,
finetune_bert,
finetune_layers,
label_dict=None,
numeric_dict=None,
pooling='cls',
hidden_dim=300,
hidden_activation=nn.Tanh(),
num_layers=1,
batch_size=1028,
max_iter=1000,
eta=0.001,
optimizer_class=torch.optim.Adam,
use_zero=True,
scheduler_class=None,
l2_strength=0,
gradient_accumulation_steps=1,
max_grad_norm=None,
warm_start=False,
early_stopping=None,
validation_fraction=0.1,
n_iter_no_change=10,
tol=1e-5,
device=None,
rank=None,
world_size=None,
debug=False,
checkpoint_dir=None,
checkpoint_interval=None,
resume_from_checkpoint=False,
target_score=None,
interactive=False,
response_pipe=None,
freeze_bert=False,
dropout_rate=0.0,
show_progress=False,
advance_epochs=1,
wandb_run = None,
random_seed=42,
lr_decay=1.0,
optimizer_kwargs={},
scheduler_kwargs={}):
"""
A flexible neural network classifier with Distributed Data Parallel (DDP) support.
This classifier allows for a variable number of hidden layers and supports
distributed training across multiple GPUs using PyTorch's DistributedDataParallel.
Parameters
----------
hidden_dim : int, optional (default=300)
The dimensionality of each hidden layer.
hidden_activation : torch.nn.Module, optional (default=nn.Tanh())
The activation function used for the hidden layers.
num_layers : int, optional (default=1)
The number of hidden layers in the network.
n_iter_no_change : int, optional (default=10)
Number of iterations with no improvement to wait before early stopping.
early_stopping : bool, optional (default=True)
Whether to use early stopping to terminate training when validation scores
stop improving.
tol : float, optional (default=1e-5)
Tolerance for improvement in early stopping.
rank : int or None, optional (default=None)
The rank of the current process in distributed training.
debug : bool, optional (default=False)
If True, print additional debug information during training.
**base_kwargs
Additional keyword arguments to be passed to the TorchModelBase constructor.
Attributes
----------
model : torch.nn.Module
The PyTorch model representing the neural network.
loss : torch.nn.CrossEntropyLoss
The loss function used for training.
classes_ : list
The list of class labels known to the classifier.
n_classes_ : int
The number of classes.
input_dim : int
The dimensionality of the input features.
Methods
-------
fit(X, y, rank, world_size, device, debug=False)
Fit the model to the training data using distributed training.
predict(X, device=None)
Predict class labels for samples in X.
predict_proba(X, device=None)
Predict class probabilities for samples in X.
score(X, y, device=None)
Return the mean accuracy on the given test data and labels.
to(device)
Move the model to the specified device.
Notes
-----
This classifier is designed to be used in a distributed setting with multiple
GPUs. It uses PyTorch's DistributedDataParallel for efficient parallel training.
The fit method requires additional parameters (rank, world_size, device) to
support distributed training.
Examples
--------
>>> import torch
>>> from torch.nn.parallel import DistributedDataParallel as DDP
>>> model = TorchDDPFlexibleNeuralClassifier(hidden_dim=100, num_layers=2)
>>> # Assuming X_train and y_train are your training data
>>> model.fit(X_train, y_train, rank=0, world_size=1, device=torch.device('cuda:0'))
>>> predictions = model.predict(X_test)
"""
# Call the superclass constructor
super().__init__(
batch_size=batch_size,
max_iter=max_iter,
eta=eta,
optimizer_class=optimizer_class,
l2_strength=l2_strength,
gradient_accumulation_steps=gradient_accumulation_steps,
max_grad_norm=max_grad_norm,
warm_start=warm_start,
early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change,
tol=tol,
device=device,
**optimizer_kwargs
)
# Set additional attributes
self.bert_model = bert_model
self.bert_tokenizer = bert_tokenizer
self.finetune_bert = finetune_bert
self.finetune_layers = finetune_layers
self.label_dict = label_dict
self.numeric_dict = numeric_dict
self.pooling = pooling
self.hidden_dim = hidden_dim
self.hidden_activation = hidden_activation
self.num_layers = num_layers
self.rank = rank
self.world_size = world_size
self.debug = debug
self.checkpoint_dir = checkpoint_dir
self.checkpoint_interval = checkpoint_interval
self.resume_from_checkpoint = resume_from_checkpoint
self.target_score = target_score
self.interactive = interactive
self.response_pipe = response_pipe
self.freeze_bert = freeze_bert
self.dropout_rate = dropout_rate
self.show_progress = show_progress
self.advance_epochs = advance_epochs
self.use_zero = use_zero
self.scheduler_class = scheduler_class
self.scheduler = None
self.scheduler_kwargs = scheduler_kwargs or {}
self.wandb_run = wandb_run
self.random_seed = random_seed
self.lr_decay = lr_decay
self.loss = nn.CrossEntropyLoss(reduction="mean")
# Extend self.params with the new parameters
self.params.extend([
'finetune_bert', 'pooling', 'hidden_dim', 'hidden_activation',
'num_layers', 'checkpoint_interval', 'target_score', 'interactive',
'freeze_bert', 'dropout_rate', 'show_progress', 'advance_epochs',
'use_zero', 'scheduler_class'
])
# Handle optimizer_kwargs
for k, v in optimizer_kwargs.items():
setattr(self, k, v)
if k not in self.params:
self.params.append(k)
def build_graph(self):
if not hasattr(self, 'n_classes_') or self.n_classes_ is None:
raise ValueError(f"{red}n_classes_ is not set. Make sure fit() is called before building the graph.{reset}")
if self.finetune_bert:
model = BERTClassifier(
self.bert_model,
self.pooling,
self.hidden_dim,
self.hidden_activation,
self.num_layers,
self.n_classes_,
self.dropout_rate,
self.finetune_layers,
self.rank
)
if self.freeze_bert:
for param in model.bert.parameters():
param.requires_grad = False
else:
model = Classifier(
self.input_dim,
self.hidden_dim,
self.hidden_activation,
self.num_layers,
self.n_classes_,
self.dropout_rate
)
if self.rank == 0:
print(f"\n{sky_blue}Model Architecture Summary:{reset}")
print(model)
total_params = 0
trainable_params = 0
total_layers = 0
trainable_layers = 0
print(f"\n{sky_blue}Model Parameters:{reset}")
for name, module in model.named_modules():
if isinstance(module, (nn.Linear, nn.Embedding, nn.LayerNorm)):
total_layers += 1
layer_params = sum(p.numel() for p in module.parameters())
total_params += layer_params
if any(p.requires_grad for p in module.parameters()):
trainable_layers += 1
trainable_params += layer_params
print(f" {name}: {layer_params:,} (trainable)")
else:
print(f" {name}: {layer_params:,} (frozen)")
print(f"\nTotal layers: {total_layers}")
print(f"Trainable layers: {trainable_layers}")
print(f"Total parameters: {total_params:,}")
print(f"Trainable parameters: {trainable_params:,}")
print(f"Percentage of trainable parameters: {trainable_params/total_params*100:.2f}%")
return model
def build_optimizer(self):
# Group parameters by layer depth with different learning rates
lr_decay = getattr(self, 'lr_decay', 1.0) # Default to 1.0 if not set
if self.finetune_bert: # Only do layer-wise decay if we're fine-tuning BERT
if hasattr(self.model, 'module'):
bert = self.model.module.bert
else:
bert = self.model.bert
# Create parameter groups with decaying learning rates
optimizer_grouped_parameters = []
# Classifier (highest learning rate)
classifier_params = [p for n, p in self.model.named_parameters() if 'classifier' in n and p.requires_grad]
if classifier_params:
optimizer_grouped_parameters.append({
'params': classifier_params,
'lr': self.eta,
'weight_decay': self.l2_strength
})
# BERT layers
num_layers = len(bert.encoder.layer)
for layer_num in range(num_layers):
layer = bert.encoder.layer[-(layer_num + 1)] # Start from last layer
layer_params = [p for p in layer.parameters() if p.requires_grad]
if layer_params:
layer_lr = self.eta * (lr_decay ** layer_num)
optimizer_grouped_parameters.append({
'params': layer_params,
'lr': layer_lr,
'weight_decay': self.l2_strength
})
# Embeddings (lowest learning rate)
embedding_params = [p for p in bert.embeddings.parameters() if p.requires_grad]
if embedding_params:
embeddings_lr = self.eta * (lr_decay ** num_layers)
optimizer_grouped_parameters.append({
'params': embedding_params,
'lr': embeddings_lr,
'weight_decay': self.l2_strength
})
else:
# Standard parameter groups without layer-wise decay
trainable_params = [p for p in self.model.parameters() if p.requires_grad]
if not trainable_params:
raise ValueError("No trainable parameters found in the model!")
optimizer_grouped_parameters = [{
'params': trainable_params,
'lr': self.eta,
'weight_decay': self.l2_strength
}]
if self.use_zero:
# Make parameters contiguous
for group in optimizer_grouped_parameters:
for param in group['params']:
if param.requires_grad:
param.data = param.data.contiguous()
optimizer = ZeroRedundancyOptimizer(
optimizer_grouped_parameters,
optimizer_class=self.optimizer_class,
**self.optimizer_kwargs
)
else:
optimizer = self.optimizer_class(
optimizer_grouped_parameters,
**self.optimizer_kwargs
)
if self.rank == 0:
print(f"Using optimizer: {self.optimizer_class.__name__}, Use Zero: {self.use_zero}, Base Learning Rate: {self.eta}, L2 strength: {self.l2_strength}")
if self.finetune_bert and lr_decay != 1.0:
print(f"Layer-wise decay factor: {lr_decay}")
if self.optimizer_kwargs:
print("Optimizer arguments:")
for key, value in self.optimizer_kwargs.items():
print(f"- {key}: {value}")
if self.scheduler_class is not None:
# Set default values based on scheduler type
if self.scheduler_class == optim.lr_scheduler.CosineAnnealingLR:
if 'T_max' not in self.scheduler_kwargs:
self.scheduler_kwargs['T_max'] = self.max_iter
elif self.scheduler_class == optim.lr_scheduler.CosineAnnealingWarmRestarts:
if 'T_0' not in self.scheduler_kwargs:
self.scheduler_kwargs['T_0'] = self.max_iter // 10 # Restart every 1/10th of total epochs
elif self.scheduler_class == optim.lr_scheduler.StepLR:
if 'step_size' not in self.scheduler_kwargs:
self.scheduler_kwargs['step_size'] = self.max_iter // 3 # Step every 1/3 of total epochs
elif self.scheduler_class == optim.lr_scheduler.MultiStepLR:
if 'milestones' not in self.scheduler_kwargs:
self.scheduler_kwargs['milestones'] = [self.max_iter // 2, self.max_iter * 3 // 4] # Steps at 1/2 and 3/4 of total epochs
elif self.scheduler_class == optim.lr_scheduler.CyclicLR:
if 'base_lr' not in self.scheduler_kwargs:
self.scheduler_kwargs['base_lr'] = self.eta / 10
if 'max_lr' not in self.scheduler_kwargs:
self.scheduler_kwargs['max_lr'] = self.eta
if 'step_size_up' not in self.scheduler_kwargs:
self.scheduler_kwargs['step_size_up'] = self.max_iter // 20 # 1/20th of total epochs
scheduler = self.scheduler_class(optimizer, **self.scheduler_kwargs)
if self.rank == 0:
print(f"Using scheduler: {self.scheduler_class.__name__}")
if self.scheduler_kwargs:
print("Scheduler arguments:")
for key, value in self.scheduler_kwargs.items():
print(f"- {key}: {value}")
else:
scheduler = None
self.scheduler = scheduler
return optimizer
def build_dataset(self, X, y=None):
X = tensor_to_numpy(X)
self.input_dim = X.shape[1]
X = torch.FloatTensor(X)
if y is None:
dataset = torch.utils.data.TensorDataset(X)
else:
self.classes_ = sorted(set(y))
self.n_classes_ = len(self.classes_)
print(f"Classes: {self.classes_}, Number of classes: {self.n_classes_}") if self.rank == 0 else None
class2index = dict(zip(self.classes_, range(self.n_classes_)))
y = torch.tensor([class2index[label] for label in y], dtype=torch.long)
if self.debug:
print(f"Rank {self.rank}: X shape: {X.shape}, y shape: {y.shape}")
dataset = torch.utils.data.TensorDataset(X, y)
return dataset
@staticmethod
def _build_validation_split(*args, validation_fraction=0.2, random_seed=42):
"""
Split `*args` into train and dev portions for early stopping.
We use `train_test_split`. For args of length N, then delivers
N*2 objects, arranged as
X1_train, X1_test, X2_train, X2_test, ..., y_train, y_test
Parameters
----------
*args: List of objects to split.
validation_fraction: float
Percentage of the examples to use for the dev portion. In
`fit`, this is determined by `self.validation_fraction`.
We give it as an argument here to facilitate unit testing.
Returns
-------
Pair of tuples `train` and `dev`
"""
if validation_fraction == 1.0:
return args, args
results = train_test_split(*args, test_size=validation_fraction,
random_state=random_seed,
shuffle=True,
stratify=args[-1] if isinstance(args[-1], np.ndarray) else None)
train = results[::2]
dev = results[1::2]
return train, dev
def _update_no_improvement_count_early_stopping(self, X, y, epoch, debug):
current_score = self.score(X, y)
if self.best_score is None or current_score > self.best_score + self.tol:
self.best_score = current_score
self.no_improvement_count = 0
else:
self.no_improvement_count += 1
if debug and self.rank == 0:
print(f"Current Score: {current_score:.6f}, Best Score: {self.best_score:.6f}, Tolerance: {self.tol}, No Improvement Count: {self.no_improvement_count}")
return current_score
def _update_no_improvement_count_errors(self, epoch_loss, epoch, debug):
if self.best_error is None or epoch_loss < self.best_error - self.tol:
self.best_error = epoch_loss
self.no_improvement_count = 0
else:
self.no_improvement_count += 1
if debug and self.rank == 0:
print(f"Current Loss: {epoch_loss:.6f}, Best Loss: {self.best_error:.6f}, Tolerance {self.tol}, No Improvement Count: {self.no_improvement_count}")
return epoch_loss
def save_model(self, directory='saves', epoch=None, optimizer=None, is_final=False, save_pickle=False, save_hf=False, weights_name='bert-base-uncased'):
if not os.path.exists(directory):
os.makedirs(directory)
# Prepare saveable parameters
saveable_params = {param: getattr(self, param) for param in self.params
if param not in ['rank', 'response_pipe', 'bert_model', 'bert_tokenizer']}
# Prepare model state dictionary
state = {
'epoch': epoch,
'model_state_dict': self.model.module.state_dict() if hasattr(self.model, 'module') else self.model.state_dict(),
'params': saveable_params
}
if optimizer:
state['optimizer_state_dict'] = optimizer.state_dict()
# Save as a PyTorch checkpoint
timestamp = time.strftime("%Y%m%d-%H%M%S")
filename = f'final_model_{timestamp}' if is_final else f'checkpoint_epoch_{epoch}_{timestamp}'
torch.save(state, os.path.join(directory, filename + '.pth'))
print(f"Saved model state: {os.path.join(directory, filename + '.pth')}")
# Optionally save as a pickle file if specified
if is_final and save_pickle:
self.to_pickle(os.path.join(directory, filename + '.pkl'))
print(f"Saved model pickle: {os.path.join(directory, filename + '.pkl')}")
self.model.to(self.device)
# Optionally save in Hugging Face format
if save_hf:
hf_save_dir = os.path.join(directory, f"{filename}_huggingface")
os.makedirs(hf_save_dir, exist_ok=True)
# Create a config object with your custom parameters
config = ElectraConfig.from_pretrained(weights_name)
config.num_labels = self.n_classes_
config.hidden_dim = self.hidden_dim
# Adjust config.hidden_activation
if isinstance(self.hidden_activation, nn.Module):
config.hidden_activation = self.hidden_activation.__class__.__name__
else:
config.hidden_activation = self.hidden_activation
config.num_layers = self.num_layers
config.dropout_rate = self.dropout_rate
config.pooling = self.pooling # Ensure pooling_type is included
# Create an instance of your custom model
model = CustomElectraClassifier(config)
# Adjust the state dict keys
adjusted_state_dict = {}
for k, v in state['model_state_dict'].items():
if k.startswith('bert.'):
new_key = k.replace('bert.', 'electra.')
else:
new_key = k
adjusted_state_dict[new_key] = v
# Load the adjusted state dict
model.load_state_dict(adjusted_state_dict)
# Save the model and tokenizer
model.save_pretrained(hf_save_dir)
model.save_pretrained(hf_save_dir, safe_serialization=False)
self.bert_tokenizer.save_pretrained(hf_save_dir)
print(f"Model also saved in Hugging Face format to {hf_save_dir}")
# Debugging information if enabled
if self.debug and self.rank == 0:
print("Params saved:")
print_state_summary(saveable_params)
def load_model(self, directory='checkpoints', filename=None, pattern='checkpoint_epoch', use_saved_params=True, rank=0, debug=False):
if not os.path.exists(directory):
raise ValueError(f"Directory {directory} does not exist")
if filename is not None:
latest_checkpoint = os.path.join(directory, filename)
else:
# Find the latest file if no specific file is given
matching_files = [os.path.join(directory, d) for d in os.listdir(directory) if pattern in d]
if not matching_files:
raise ValueError(f"No files matching the pattern '{pattern}' found in directory: {directory}")
latest_checkpoint = max(matching_files, key=os.path.getctime)
checkpoint = torch.load(latest_checkpoint, map_location=self.device)
print(f"Loaded checkpoint: {latest_checkpoint}") if rank == 0 else None
# Get the model state dict if it exists
model_state_dict = checkpoint.get('model_state_dict')
if model_state_dict:
# Remove 'module.' prefix if exists
model_state_dict = {k.replace("module.", ""): v for k, v in model_state_dict.items()}
print(f"Retrieved model state dictionary.") if rank == 0 else None
if debug:
print_state_summary(model_state_dict)
else:
print(f"No model state dictionary found in checkpoint.") if rank == 0 else None
# Get the optimizer state dict if it exists
optimizer_state_dict = checkpoint.get('optimizer_state_dict')
if optimizer_state_dict:
print(f"Retrieved optimizer state dictionary.") if rank == 0 else None
if debug:
print_state_summary(optimizer_state_dict)
else:
print(f"No optimizer state dictionary found in checkpoint.") if rank == 0 else None
# Optionally update model parameters with the saved parameters
if use_saved_params and 'params' in checkpoint:
saved_params = checkpoint['params']
if debug and rank == 0:
print(f"BEFORE updating model parameters:")
print_state_summary(self.__dict__)
# Update the parameters
for key, value in saved_params.items():
if hasattr(self, key):
setattr(self, key, value)
if debug and rank == 0:
print(f"AFTER updating model parameters:")
print_state_summary(self.__dict__)
start_epoch = checkpoint.get('epoch', 0) + 1
return start_epoch, model_state_dict, optimizer_state_dict
def send_stop_signal(self):
if self.response_pipe:
try:
self.response_pipe.send('stop')
print(f"Rank {self.rank} sent stop signal") if self.debug else None
except Exception as e:
print(f"Rank {self.rank} failed to send stop signal: {e}") if self.debug else None
else:
print(f"Rank {self.rank} has no response_pipe to send stop signal") if self.debug else None
def set_advance_epochs(self, value):
self.advance_epochs = value
if self.response_pipe:
try:
self.response_pipe.send(f'advance_epochs:{value}')
print(f"Rank {self.rank} set advance_epochs to {value}") if self.debug else None
except Exception as e:
print(f"Rank {self.rank} failed to set advance_epochs: {e}") if self.debug else None
else:
print(f"Rank {self.rank} has no response_pipe to set advance_epochs") if self.debug else None
def compute_accuracy(self, y_true, y_pred):
return (y_true == y_pred).mean()
def compute_train_metrics(self, X, y, epoch, debug=False, device=None):
if device is None:
device = self.device
# Temporarily set to eval mode
self.model.eval()
with torch.no_grad():
all_preds = []
all_labels = []
if self.finetune_bert:
dataset = SentimentDataset(X, y, self.bert_tokenizer, self.label_dict, device=device)
sampler = torch.utils.data.distributed.DistributedSampler(
dataset, num_replicas=self.world_size, rank=self.rank, shuffle=False
)
dataloader = DataLoader(dataset, batch_size=self.batch_size, sampler=sampler)
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = self.model(input_ids, attention_mask=attention_mask)
all_preds.append(outputs.argmax(dim=1))
all_labels.append(labels)
else:
X = tensor_to_numpy(X)
y = np.array(y)
if y.dtype == object:
y = np.array([self.label_dict[label] for label in y])
dataset = torch.utils.data.TensorDataset(torch.FloatTensor(X), torch.LongTensor(y))
sampler = torch.utils.data.distributed.DistributedSampler(
dataset, num_replicas=self.world_size, rank=self.rank, shuffle=False
)
dataloader = DataLoader(dataset, batch_size=self.batch_size, sampler=sampler)
for X_batch, y_batch in dataloader:
X_batch = X_batch.to(device)
y_batch = y_batch.to(device)
outputs = self.model(X_batch)
all_preds.append(outputs.argmax(dim=1))
all_labels.append(y_batch)
# Concatenate predictions and labels
all_preds = torch.cat(all_preds)
all_labels = torch.cat(all_labels)
# Gather sizes from all ranks
local_size = torch.tensor([all_preds.size(0)], device=device)
sizes_list = [torch.zeros(1, device=device, dtype=torch.int64) for _ in range(self.world_size)]
torch.distributed.all_gather(sizes_list, local_size)
sizes = [int(size.item()) for size in sizes_list]
max_size = max(sizes)
# Pad tensors to the maximum size
pad_size = max_size - all_preds.size(0)
if pad_size > 0:
all_preds = torch.cat([
all_preds,
torch.zeros(pad_size, dtype=all_preds.dtype, device=device)
])
all_labels = torch.cat([
all_labels,
torch.zeros(pad_size, dtype=all_labels.dtype, device=device)
])
# Prepare lists for gathering tensors
gathered_preds = [torch.zeros(max_size, dtype=all_preds.dtype, device=device) for _ in range(self.world_size)]
gathered_labels = [torch.zeros(max_size, dtype=all_labels.dtype, device=device) for _ in range(self.world_size)]
# Gather predictions and labels from all ranks
torch.distributed.all_gather(gathered_preds, all_preds)
torch.distributed.all_gather(gathered_labels, all_labels)
# Remove padding and concatenate
all_preds = torch.cat([preds[:sizes[i]] for i, preds in enumerate(gathered_preds)])
all_labels = torch.cat([labels[:sizes[i]] for i, labels in enumerate(gathered_labels)])
# Move tensors to CPU for metric computation
all_preds = all_preds.cpu().numpy()
all_labels = all_labels.cpu().numpy()
# Compute training metrics
train_score = utils.safe_macro_f1(all_labels, all_preds)
train_accuracy = self.compute_accuracy(all_labels, all_preds)
# Debug statements
if debug and self.rank == 0:
print(f"Train Score at epoch {epoch}: F1 = {train_score:.6f}, Accuracy = {train_accuracy:.6f}")
self.model.train()
return train_score, train_accuracy
def compute_validation_metrics(self, X, y, epoch, debug=False, device=None):
if device is None:
device = self.device
self.model.eval()
# Initialize tensors for loss and sample count
val_loss = torch.tensor(0.0, device=device)
total_samples = torch.tensor(0, device=device)
all_preds = []
all_labels = []
with torch.no_grad():
if self.finetune_bert:
# Create dataset and DistributedSampler
dataset = SentimentDataset(X, y, self.bert_tokenizer, self.label_dict, device=device)
sampler = torch.utils.data.distributed.DistributedSampler(
dataset, num_replicas=self.world_size, rank=self.rank, shuffle=False
)
dataloader = DataLoader(dataset, batch_size=self.batch_size, sampler=sampler)
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = self.model(input_ids, attention_mask=attention_mask)
loss = self.loss(outputs, labels)
# Accumulate loss and sample count
val_loss += loss * labels.size(0)
total_samples += labels.size(0)
# Collect predictions and labels
all_preds.append(outputs.argmax(dim=1))
all_labels.append(labels)
else:
X = tensor_to_numpy(X)
y = np.array(y)
if y.dtype == object:
y = np.array([self.label_dict[label] for label in y])
dataset = torch.utils.data.TensorDataset(torch.FloatTensor(X), torch.LongTensor(y))
sampler = torch.utils.data.distributed.DistributedSampler(
dataset, num_replicas=self.world_size, rank=self.rank, shuffle=False
)
dataloader = DataLoader(dataset, batch_size=self.batch_size, sampler=sampler)