-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin_main.py
More file actions
executable file
·1432 lines (1232 loc) · 58 KB
/
bin_main.py
File metadata and controls
executable file
·1432 lines (1232 loc) · 58 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
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
#!/usr/bin/env python3
# coding: utf-8
print("Importing modules.")
from beartype.typing import *
import collections
import graphlib
import itertools
import logging
import math
from pathlib import Path
import random
import re
import time
from beartype import beartype
import h5py # type: ignore[import]
import fire # type: ignore[import]
import json # type: ignore[import]
import jsonlines as jsonl # type: ignore
import more_itertools
import numpy as np
import os
import pytorch_lightning as pl
import rich
import torch
from tqdm import tqdm # type: ignore
import transformers
import wandb
import pretty_traceback # type: ignore
pretty_traceback.install()
import bart_modified
import data_collator
import data_datasets
import data_tokenizer
import data_generation_arithmetic
import general_shared_constants
import general_utils
import our_metrics
import script_data_subset_selection
import script_convert_h5
print("Done loading modules.\n")
SCRIPT_DIR = Path(__file__).absolute().parent
LOGGER = logging.getLogger(__name__)
DEBUG = os.environ.get("DEBUG", "False") == "True"
class ValidModes:
per_batch = "per_batch"
per_sample = "per_sample"
valid_modes = {per_batch, per_sample}
#########################################################################################################
ACTIVE_MODES = {ValidModes.per_batch}
NUM_SAMPLES_VALID = 20000
EVAL_EVERY_N_EPOCHS = 1
DETERMINISTIC = True
LEARNING_RATE = 0.001
WEIGHT_DECAY = 0
GRADIENT_CLIP_VAL = 0.1
GENERATION_KWARGS = dict(
num_beams=1,
use_cache=True,
# Should never hange:
min_length=0,
constraints=None,
do_sample=False,
tgt_array_indices=None
)
# Stuff that should never change
NUM_GPUS = 1
WANDB_ENTITY = "julesgm"
WANDB_PROJECT = "self_learned_explanations"
PRECISION = 16
DATA_PATH = SCRIPT_DIR / "data"
def generate(model: transformers.PreTrainedModel, **kwargs):
assert isinstance(model, bart_modified.ModifiedBartForConditionalGeneration), "only type currently supported"
for k in GENERATION_KWARGS.keys():
assert GENERATION_KWARGS[k] == kwargs[k], f"{k} mismatch"
assert "max_length" in kwargs, "max_length not in kwargs"
return model.generate(**kwargs)
GEN_FUNCTION = generate
#########################################################################################################
CONC_MODE = "top_sort"
#########################################################################################################
def clean_sample_for_logging(tokens, tokenizer):
"""
Only removes -100 tokens values.
"""
tokens_list = tokens.cpu().numpy().tolist()
as_string = tokenizer.decode(tokens_list, ignore_special_symbols=False)
pale_map = {
"<-100>": "[bright_cyan]#[/bright_cyan]",
"<pad>": "[bright_cyan]^[/bright_cyan]",
}
for token, new_v in pale_map.items():
as_string = re.sub(
r"(?<="
+ re.escape(token)
+ r")"
+ r"\s+"
+ r"(?="
+ re.escape(token)
+ r")",
"",
as_string,
)
as_string = as_string.replace(token, new_v)
return as_string
def prep_return_data(output, decoder_input_ids, tokenizer):
assert len(output.shape) == 1, output.shape
list_output = output.tolist()
list_output_filtered = list_output[len(decoder_input_ids) :]
good_output = tokenizer.decode(list_output_filtered, ignore_special_symbols=True)
if good_output and good_output[-1] == ")":
good_output = good_output[:-1]
return good_output.replace("<eos>", "").strip()
def color_matching(seq_a, seq_b):
output_a = [
f"[green]{a}" if a == b else f"[red]{a}"
for a, b in itertools.zip_longest(seq_a, seq_b, fillvalue="")
if a
]
output_b = [
f"[green]{b}" if a == b else f"[red]{b}"
for a, b in itertools.zip_longest(seq_a, seq_b, fillvalue="")
if b
]
return output_a, output_b
class RenewableGenerator:
def __init__(self, fn, len):
self.fn = fn
self.iter = None
self.len = len
def __len__(self):
return self.len
def __iter__(self):
self.iter = self.fn()
return self
def __next__(self):
features = next(self.iter)
for k, v in features.items():
if isinstance(v, torch.Tensor):
features[k] = v.pin_memory()
return features
def top_sort_build_tree(
dep_dict: dict,
visited_datagen: data_generation_arithmetic.Node
):
if visited_datagen.get_children():
dep_dict[visited_datagen] = []
for child in visited_datagen.get_children():
if child.get_children():
dep_dict[visited_datagen].append(child)
top_sort_build_tree(dep_dict, child)
def actual_prediction(
batch: dict[str, torch.Tensor],
collator: transformers.data.data_collator.DataCollatorMixin,
model: transformers.PreTrainedModel,
generation_kwargs: dict[str, Any],
gen_function: Callable,
):
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Use the Data Collator on the data
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
batch = collator(batch)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Cudify everything
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for k, v in batch.items():
batch[k] = v.cuda()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Create the decoder_attention_mask
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if "decoder_attention_mask" in batch:
batch["decoder_attention_mask"] = batch["decoder_attention_mask_for_gen"]
del batch["decoder_attention_mask_for_gen"]
bound_length = min(
model.config.max_length - 6, batch["decoder_input_ids_for_gen"].shape[1] - 1
)
batch["decoder_input_ids"] = batch["decoder_input_ids_for_gen"][:, :bound_length]
rich.print("[red bold]FIX DECODER LENGTH STUFF AND DECODER HEAD")
del batch["decoder_input_ids_for_gen"]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Generate
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
start = time.perf_counter()
output = gen_function(
model=model,
**batch,
**generation_kwargs,
)
delta = time.perf_counter() - start
print(f"Generation took {delta:.5f} seconds, {delta / output.shape[0]}s per item.")
return output
def json_dumper_default(obj: Any) -> list[Union[int, float]]:
if isinstance(obj, (torch.Tensor, np.ndarray)):
return obj.tolist()
raise TypeError("Type not serializable")
class _PLBart(pl.LightningModule):
def __init__(
self,
*,
model: transformers.PreTrainedModel,
tokenizer: data_tokenizer.ArithmeticTokenizer,
train_ds,
eval_ds,
train_batch_size: int,
eval_batch_size: int,
generation_kwargs: dict[str, Any],
learning_rate: float,
is_adamw: bool,
weight_decay: Optional[float],
# scheduler_type,
# scheduler_kwargs,
# do_allen_nlp_predictions: bool,
freeform_options: set[bool],
max_total_length_gen: int,
max_answer_gen: int,
max_depth: int,
do_log_results: bool,
path_log_results: Path,
extra_info_file: Path,
):
super().__init__()
self._model: transformers.PreTrainedModel = model
self._tokenizer: Final = tokenizer
self._batch_size: Final[int] = train_batch_size
self._eval_batch_size: Final[int] = eval_batch_size
self._generation_kwargs: Final[dict[str, Any]] = generation_kwargs
self._logging_conf: Final[dict[str, bool]] = dict(
prog_bar=True, on_step=True, on_epoch=True, logger=True
)
self._freeform_options: Final[set[bool]] = freeform_options
self._extra_info_file: Final[Path] = extra_info_file
################################################################################
# Related to datasets
################################################################################
# These things are defined in the dataset
self._mask_intermediate_labels = isinstance(
train_ds, data_datasets.SelfLearnedBasicDataset
)
self._max_depth: Final[int] = max_depth
self._max_answer_gen: Final[int] = max_answer_gen
self._max_total_length_gen: Final[int] = max_total_length_gen
self._shuffle_train: Final[bool] = True
self._shuffle_val: Final[bool] = False
assert train_ds is not eval_ds, "train_ds and eval_ds must be different objects"
self._train_ds: Final = train_ds
self._eval_ds: Final = eval_ds
################################################################################
# Rel. to logging results for answer overlap estim.
################################################################################
self._do_log_results: Final[bool] = do_log_results
self._path_log_results: Final[Optional[Path]] = path_log_results
self._results_to_log: Optional[dict[str, dict[bool, dict[str, torch.Tensor]]]] = {}
self._labels_to_log: dict[str, str] = {}
################################################################################
# Specific to the optimizer, its scheduler
################################################################################
self._learning_rate: Final[float] = learning_rate
self._is_adamw: Final[bool] = is_adamw
self._weight_decay: Final[Optional[float]] = weight_decay
# Related to the scheduler:
# self.scheduler_type = scheduler_type
# self.scheduler_kwargs = scheduler_kwargs
assert (
"max_length" not in self._generation_kwargs
), "the max length is computed dynamically"
def on_train_epoch_start(self):
if isinstance(self._train_ds, data_datasets.CurriculumSelfLearned):
self._train_ds.mix(
{
0: 1.0,
1: 1.0,
2: 1.0,
}
)
def on_validation_start(self) -> None:
if isinstance(self._eval_ds, data_datasets.CurriculumSelfLearned):
self._eval_ds.mix(
{
0: 1.0,
1: 1.0,
2: 1.0,
}
)
def on_train_epoch_end(self) -> None:
with self._extra_info_file.open("w") as f:
json.dump(dict( # type: ignore[call-arg]
torch_rng_state=torch.random.get_rng_state(),
numpy_rng_state=np.random.get_state(),
python_rng_state=random.getstate(),
wandb_run_id=wandb.run.id,
), f, default=json_dumper_default)
def forward(self, **kwargs):
if "decoder_input_ids_for_gen" in kwargs:
kwargs_filtered = {
k: w
for k, w in kwargs.items()
if k != "decoder_input_ids_for_gen"
and k != "decoder_attention_mask_for_gen"
}
else:
kwargs_filtered = kwargs
assert "decoder_input_ids" in kwargs_filtered, "'decoder_input_ids' is required"
assert self._model.config.bos_token_id not in kwargs_filtered["labels"]
assert torch.all(
kwargs_filtered["decoder_input_ids"][:, 0]
== self._model.config.decoder_start_token_id
)
if "decoder_position_ids" not in kwargs_filtered:
kwargs_filtered["decoder_position_ids"] = None
if "tgt_array_indices" not in kwargs_filtered:
kwargs_filtered["tgt_array_indices"] = None
return self._model(
**kwargs_filtered
)
def training_step(self, batch, batch_idx):
outputs = self(**batch)
self.log("train_loss", outputs.loss, **self._logging_conf)
return outputs.loss
def validation_step(self, batch: Dict[str, Union[torch.Tensor, list[str]]], batch_idx): # type: ignore[override]
idents = cast(list[str], batch.pop("idents"))
loss: torch.Tensor = self(**batch).loss
things_to_log = dict(eval_loss=loss)
per_batch_preds = None
per_batch_labels = None
self._model: transformers.PreTrainedModel = self._model.eval() # type: ignore[no-redef]
#######################################################################
# Print every N batches
#######################################################################
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Batch mode inference
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ValidModes.per_batch in ACTIVE_MODES:
per_batch_preds = {}
for is_freeform in self._freeform_options:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Prep the argumetns.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# We copy the dict because we will modify it.
generation_kwargs = dict(**self._generation_kwargs)
# Freeform mode doesn't need `decode_input_ids_for_gen`, & basic mode
# only has a freeform mode.
if not is_freeform:
assert (
"decoder_input_ids_for_gen" in batch
or not self._eval_ds.has_decoder_input_ids_for_gen
)
if self._eval_ds.has_decoder_input_ids_for_gen:
# We truncate the decoder_input_ids to the max length.
generation_kwargs["decoder_input_ids"] = cast(torch.Tensor, batch[
"decoder_input_ids_for_gen"
])[:, :self._max_total_length_gen]
# Freeform always potentially generates all the way.
# In othercases, we either generate MAX_ANSWER_GEN more tokens or
# stop at the end of the max total length.
if is_freeform or not self._eval_ds.has_decoder_input_ids_for_gen:
max_length = self._max_total_length_gen
else:
max_length = min(
generation_kwargs["decoder_input_ids"].shape[1]
+ self._max_answer_gen,
self._max_total_length_gen,
)
# Run inference.
per_batch_preds[is_freeform] = GEN_FUNCTION(
self._model,
input_ids=batch["input_ids"],
attention_mask=batch["attention_mask"],
max_length=max_length,
**generation_kwargs,
)
# Initialize metrics
em = {
mode: {
k: {"all": our_metrics.EM()} | {level: our_metrics.EM() for level in range(1, self._max_depth + 1)}
for k in self._freeform_options
if not (mode == ValidModes.per_sample and k)
}
for mode in ACTIVE_MODES
}
###################################################################
# Examine the samples and predictions one by one.
# In per_sample mode, also do predictions.
###################################################################
big_counter = []
preds: DefaultDict[str, dict[bool, dict[str, torch.Tensor]]] = collections.defaultdict(dict)
for i, pack in enumerate(
tqdm(general_utils.zip_dicts(batch), desc="Validating", total=len(batch["input_ids"]))
):
do_print = i < 5
if do_print:
print("#" * 80)
for is_freeform in self._freeform_options:
# TODO: wtf is this
per_batch_pred = None
if ValidModes.per_batch in ACTIVE_MODES:
sample = pack
per_batch_pred = per_batch_preds[is_freeform][i]
per_sample_pred = None
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Freeform mode doesn't neeed to be done in per sample mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
not_necessary = is_freeform and ValidModes.per_batch in ACTIVE_MODES
if ValidModes.per_sample in ACTIVE_MODES and not not_necessary:
sample = pack
generation_kwargs = dict(**self._generation_kwargs)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Prep decoder input ids
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if self._eval_ds.has_decoder_input_ids_for_gen and not is_freeform:
took_out_pad_tokens = [
x
for x in sample["decoder_input_ids_for_gen"]
if x != self._tokenizer.pad_token_id
]
generation_kwargs["decoder_input_ids"] = torch.stack(
took_out_pad_tokens
).reshape(1, -1)[:, :self._max_total_length_gen]
assert sample["input_ids"] is not None
assert sample["attention_mask"] is not None
if is_freeform or not self._eval_ds.has_decoder_input_ids_for_gen:
max_length = self._max_total_length_gen
else:
max_length = min(
generation_kwargs["decoder_input_ids"].shape[1]
+ self._max_answer_gen,
self._max_total_length_gen,
)
per_sample_pred = GEN_FUNCTION(
self._model,
input_ids=sample["input_ids"].reshape(1, -1),
attention_mask=sample["attention_mask"].reshape(1, -1),
max_length=max_length,
**generation_kwargs,
)
assert len(per_sample_pred) == 1, per_sample_pred.shape
assert len(per_sample_pred.shape) == 2, per_sample_pred.shape
per_sample_pred = per_sample_pred[0]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# File the predictions per mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pred_per_mode = {}
if ValidModes.per_sample in ACTIVE_MODES and not not_necessary:
pred_per_mode[ValidModes.per_sample] = per_sample_pred
if ValidModes.per_batch in ACTIVE_MODES:
pred_per_mode[ValidModes.per_batch] = per_batch_pred
preds[idents[i]][is_freeform] = pred_per_mode
assert ValidModes.per_batch in ACTIVE_MODES
for mode, pred in pred_per_mode.items():
cleaned = our_metrics.OurMetric.prepare(
self._tokenizer, pred, sample["labels"], do_print=False
)
clean_pred = cleaned["cleaned_preds"]
clean_label = cleaned["cleaned_labels"]
if self._eval_ds.has_decoder_input_ids_for_gen and not is_freeform:
clean_pred = clean_pred[
general_utils.find_last(clean_pred, self._tokenizer.token_to_idx["="]) :
]
clean_label = clean_label[
general_utils.find_last(clean_label, self._tokenizer.token_to_idx["="]) :
]
if do_print:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Prep per-sample outputs
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# rich.print("Raw `input_ids`:\n", sample["input_ids"])
# if (
# not is_freeform
# and self.eval_ds.has_decoder_input_ids_for_gen
# ):
# rich.print(
# "Raw `decoder_input_ids_for_gen`:\n",
# sample["decoder_input_ids_for_gen"],
# )
# rich.print("Raw Pred:\n", pred)
# rich.print("Raw `labels`:\n", sample["labels"])
# print_cleaned_inputs = clean_sample_for_logging(
# sample["input_ids"], self._tokenizer
# )
# print_cleaned_labels = clean_sample_for_logging(
# sample["labels"], self._tokenizer
# )
# print_cleaned_gen = clean_sample_for_logging(pred, self._tokenizer)
# print_cleaned_decoder_input_ids = None
if "decoder_input_ids" in generation_kwargs:
if mode == ValidModes.per_sample:
assert (
len(generation_kwargs["decoder_input_ids"].shape)
== 2
), generation_kwargs["decoder_input_ids"].shape
assert (
generation_kwargs["decoder_input_ids"].shape[0] == 1
), generation_kwargs["decoder_input_ids"].shape
print_cleaned_decoder_input_ids = clean_sample_for_logging(
generation_kwargs["decoder_input_ids"][0],
self._tokenizer,
)
elif ValidModes.per_batch:
print_cleaned_decoder_input_ids = clean_sample_for_logging(
sample["decoder_input_ids_for_gen"], self._tokenizer
)
else:
raise ValueError(f"Unknown mode {mode}")
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Print them
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# rich.print(f"[black bold]{mode} {'Freeform' if is_freeform else 'Not-Freeform'}:")
# rich.print(f'Inputs:\n[bright_cyan]"{print_cleaned_inputs}"')
#
# if cleaned_decoder_input_ids:
# rich.print(
# f'Decoder Inputs:\n[bright_cyan]"{cleaned_decoder_input_ids}"'
# )
#
# rich.print(f'Gen:\n[bright_cyan]"{print_cleaned_gen}"')
# rich.print(f'Label:\n[bright_cyan] "{print_cleaned_labels}"')
#
# idx_colored_a, idx_colored_b = color_matching(
# clean_pred, clean_label
# )
# rich.print(f"clean_pred: ", clean_pred)
# rich.print(f"clean_label: ", clean_label)
# rich.print(f"(EM) Answer: " + ", ".join(idx_colored_a))
# rich.print(f"(EM) Label: " + ", ".join(idx_colored_b))
# print("~" * 80)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Update Metrics
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if not (mode == ValidModes.per_sample and is_freeform):
# TODO: This is slow but it is precise.
level = data_generation_arithmetic.tree_depth_from_ids(
sample["input_ids"], self._tokenizer)
big_counter.append(level)
assert level > 0, level
assert level <= self._max_depth, level
em[mode][is_freeform][level].add(
clean_pred,
clean_label,
do_print=False,
descr=None,
)
em[mode][is_freeform]["all"].add(
clean_pred,
clean_label,
do_print=False,
descr=None,
)
###############################################################
# Compute and print per batch metrics
###############################################################
for is_freeform in self._freeform_options:
for mode in ACTIVE_MODES:
if is_freeform and mode == ValidModes.per_sample:
continue
# Make sure that the totals make sense
if DEBUG:
sum_sub_totals = sum([
level_metric.total for name, level_metric in
em[mode][is_freeform].items() if isinstance(name, int)
])
assert em[mode][is_freeform]["all"].total == sum_sub_totals, (
em[mode][is_freeform]["all"].total, sum_sub_totals
)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Per level or all ...
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
freeform_str_maybe = (
"freeform_"
if (is_freeform and not mode == ValidModes.per_sample)
else ""
)
for em_level in em[mode][is_freeform]:
em_obj = em[mode][is_freeform][em_level]
header = f"{freeform_str_maybe}{em_level}_{mode}"
if em_obj.total:
em_acc_val = em_obj.compute()
ratio = em_obj.correct / em_obj.total
text_ratio = f"{em_obj.correct}/{em_obj.total}"
things_to_log_key = f"EM_{header}"
assert things_to_log_key not in things_to_log
things_to_log[things_to_log_key] = em_acc_val
rich.print(
f"GOT {header} {text_ratio} = {ratio:.2%}\n"
)
else:
rich.print(
f"GOT {header} -/0 = -\n"
)
if self._do_log_results:
# Add the results of the batch to the accumulated results of the epoch
if DEBUG:
joint_idents = preds.keys() & self._results_to_log.keys()
assert not joint_idents, joint_idents
self._results_to_log.update(preds)
self.log_dict(things_to_log, **self._logging_conf) # type: ignore[arg-type]
self._model = self._model.train() # type: ignore[no-redef]
def on_validation_epoch_end(self) -> None:
# with h5py.File(self._path_log_results.parent / "main_h5_predictions.h5", "a") as f:
# none_of_them = (
# script_convert_h5.H5_INPUT_IDS_KEY not in f and
# script_convert_h5.H5_PREDICTIONS_KEY not in f and
# script_convert_h5.H5_LABEL_IDS_KEY not in f
# )
# all_of_them = (
# script_convert_h5.H5_INPUT_IDS_KEY in f and
# script_convert_h5.H5_PREDICTIONS_KEY in f and
# script_convert_h5.H5_LABEL_IDS_KEY in f
# )
# assert none_of_them or all_of_them, list(f.keys())
# sorted_keys = np.array(sorted(self._results_to_log), dtype=np.int64)
# tokenized_inputs = np.array([self._tokenizer(x) for x in sorted_keys], dtype=np.int64)
# tokenized_preds = self._results_to_log[True][sorted_keys]
# if none_of_them:
# f.create_dataset(
# script_convert_h5.H5_INPUT_IDS_KEY,
# data=self._results_to_log[script_convert_h5.H5_INPUT_IDS_KEY][True],
# max_shape=(None, ),
# )
# f.create_dataset(
# script_convert_h5.H5_PREDICTIONS_KEY,
# data=self._results_to_log[script_convert_h5.H5_PREDICTIONS_KEY][True],
# max_shape=(None, ),
# )
# f.create_dataset(
# script_convert_h5.H5_LABEL_IDS_KEY,
# data=None,
# max_shape=(None, ),
# )
# else:
# pass
with jsonl.open(
self._path_log_results,
"a",
dumps=lambda x: json.dumps(x, default=json_dumper_default)
) as f: # type: ignore[call-arg]
f.write(dict(
epoch=self.current_epoch,
results=self._results_to_log,
))
self._results_to_log = {}
def configure_optimizers(self):
"""
See ref
https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.core.lightning.html#pytorch_lightning.core.lightning.LightningModule.configure_optimizers
"""
if self._is_adamw:
optimizer_class = torch.optim.AdamW
else:
optimizer_class = torch.optim.Adam
optimizer = optimizer_class(
self.parameters(),
lr=self._learning_rate,
weight_decay=self._weight_decay,
capturable=True,
)
output = dict(optimizer=optimizer)
# if SCHEDULER_TYPES[self.scheduler_type]:
# output["lr_scheduler"] = {}
# output["lr_scheduler"]["scheduler"] = SCHEDULER_TYPES[self.scheduler_type](
# optimizer=optimizer, **self.scheduler_kwargs
# )
# output["lr_scheduler"]["interval"] = "epoch"
# output["frequency"] = 1
return output
def _make_dataloader(self, ds, batch_size, shuffle, dl_name):
assert False, "Not tested in a while"
collator = our_data_collator.DataCollatorWithDecoderInputIds(
self._tokenizer,
model=self._model,
max_length=self._tokenizer.max_length,
mask_intermediate_labels=self._mask_intermediate_labels,
)
if shuffle:
indices = np.random.permutation(len(ds))
else:
indices = np.arange(len(ds))
if CONC_MODE == "yield":
for i in tqdm(range(0, len(ds), batch_size), desc=f"progress in {dl_name}"):
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
batch_indices = indices[i : i + batch_size]
pred_logger = datagen.PredLogger()
iterators = [iter(ds.get(i, pred_logger)) for i in batch_indices]
send_values = [None] * len(iterators)
final_values = [None] * len(iterators)
prediction_batch = []
prediction_batch_iterator_idx = []
at_least_one = True
iteration_no = 0
while at_least_one:
iteration_no += 1
at_least_one = False
for idx, iterator in enumerate(iterators):
# print(f"{iteration_no = } - working on iterator #{idx}")
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Ignore this iterator if it is done
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if final_values[idx] is not None:
continue
try:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Get the next value from the iterator, no state if first iteration.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if send_values[idx] is None:
query = next(iterator)
else:
query = iterator.send(send_values[idx])
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Add to the batch pile, with meta info
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
prediction_batch.append(
dict(
input_data=datagen.prep_input_data(
tokenizer=self._tokenizer,
input_str=query["input_str"],
pseudo_without_head=query[
"pseudo_without_head"
],
),
logging_info=query["logging_info"],
)
)
# Meta info
prediction_batch_iterator_idx.append(idx)
at_least_one = True
except StopIteration as err:
final_value = err.value
final_values[idx] = final_value
if prediction_batch:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Prep the inputs
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
without_logging_info = [
dict(
input_ids=x["input_data"][0],
decoder_input_ids_for_gen=x["input_data"][1],
)
for x in prediction_batch
]
assert isinstance(without_logging_info[0], dict), type(
without_logging_info[0]
)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Do the prediction
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# rich.print(f"[redbold]{len(without_logging_info) = } / {batch_size}")
outputs = actual_prediction(
batch_arg=without_logging_info,
collator=collator,
model=self._model,
generation_kwargs=self._generation_kwargs,
gen_function=GEN_FUNCTION,
max_answer_gen=self._max_answer_gen,
max_total_gen_length=self._max_total_length_gen,
)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Prep the outputs
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for idx, output, input_data in zip(
prediction_batch_iterator_idx, outputs, without_logging_info
):
send_values[idx] = prep_return_data(
output,
decoder_input_ids=input_data[
"decoder_input_ids_for_gen"
],
tokenizer=self._tokenizer,
)
prediction_batch = []
prediction_batch_iterator_idx = []
num_nones = sum(x is None for x in final_values)
assert num_nones == 0, f"{num_nones}/{len(final_values)} were None"
if ds is self._eval_ds:
pred_logger.log()
yield collator(final_values)
if CONC_MODE == "top_sort":
assert self._train_ds._mask_intermediate_labels
for i in tqdm(range(0, len(ds), batch_size), desc=f"progress in {dl_name}"):
batch_indices = indices[i : i + batch_size]
root_nodes = [ds.get_top_sort(i) for i in batch_indices]
sorters = [] # 1 to 1 with root nodes, ok
node_to_sorter = {}
for root_node in root_nodes:
tree = {}
top_sort_build_tree(tree, root_node)
sorter = graphlib.TopologicalSorter(tree)
sorter.prepare()
sorters.append(sorter)
node_to_sorter[root_node] = sorter
at_least_one = True
while at_least_one:
at_least_one = False
node_batch: List[datagen.Node] = []
nodes_to_sorters = {}
for sorter in sorters:
if sorter.is_active():
nodes = sorter.get_ready()
for node in nodes:
nodes_to_sorters[node] = sorter
node_batch.extend(nodes)
# Heuristic: do the deepest nodes first, they are likely the ones blocking
# the most nodes.
node_batch.sort(
key=lambda x: x.get_root_complexity_level() - x.get_complexity_level(),
reverse=True
)
node_batch = node_batch[:batch_size]
input_ids = [
self._tokenizer(node.get_input_str()) for node in node_batch
]
decoder_input_ids = [
self._tokenizer(
node.get_pseudo_topsort_query(),
return_tensors=None,
no_eos=False,
strip_special_symbols=True,
)
for node in node_batch
]
labels = [
len(decoder_ii) * [-100] + self._tokenizer(node.get_value(), None, no_eos=False)
for decoder_ii, node in zip(decoder_input_ids, node_batch)
]
batch = dict(
input_ids=input_ids,
decoder_input_ids=decoder_input_ids,
labels=labels,
)
outputs = actual_prediction(
batch_arg=batch,
collator=collator,
model=self._model,
generation_kwargs=self._generation_kwargs,
gen_function=GEN_FUNCTION,
max_answer_gen=self._max_answer_gen,
max_total_gen_length=self._max_total_length_gen,
)
for node, output in zip(sorters, node_batch, outputs):
text = self._tokenizer.decode(
output.tolist()
)
node.set_pseudo_value(text.split("=")[-1])
node_to_sorter[node].done(node)
for sorter in sorters:
if sorter.is_active():
at_least_one = True
break
pre_collate_batch = []
for node in nodes:
encoder_ii = self._tokenizer(
node.get_input_str(), return_tensors="pt", no_eos=False
)
# Like this the special sybol stripping is OK
decoder_body = self._tokenizer(
node.get_pseudo_topsort_query(),
return_tensors=None,
no_eos=True,