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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
#!/usr/bin/env python3
"""
Simple Trainer script for the twin two-hop dataset.

It expects the dataset format produced by data_preparation.py:
- train.json: list of {"input_text", "target_text", ...}
- valid.json: optional list (can be empty)

We train a causal LM to predict target_text; input_text is ignored because
target_text already concatenates the input plus the answer token.
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Dict, List
from datetime import datetime
import inspect

import torch
import numpy as np
from torch.utils.data import Dataset
from transformers import (
    AutoConfig,
    AutoModelForCausalLM,
    AutoTokenizer,
    GPT2Config,
    PreTrainedTokenizerFast,
    Trainer,
    TrainingArguments,
    DataCollatorForLanguageModeling,
    TrainerCallback,
    default_data_collator,
)
from torch.utils.data import Subset


def normalize_text(value):
    if isinstance(value, list):
        return "".join(value)
    return value


class SmallTokenDictionaryTokenizer:
    def __init__(self, vocab_list: List[str], base_tokenizer):
        self.unk_token = base_tokenizer.unk_token or "<unk>"
        self.eos_token = base_tokenizer.eos_token or "<eos>"
        self.pad_token = base_tokenizer.pad_token or self.eos_token
        self.bos_token = base_tokenizer.bos_token
        special_tokens = []
        for tok in base_tokenizer.all_special_tokens:
            if tok not in special_tokens:
                special_tokens.append(tok)
        for tok in [self.unk_token, self.eos_token, self.pad_token, self.bos_token]:
            if tok and tok not in special_tokens:
                special_tokens.append(tok)

        tokens = []
        for tok in special_tokens + vocab_list:
            if tok not in tokens:
                tokens.append(tok)

        self.small_tokens = tokens
        self.all_special_tokens = special_tokens
        self.token_to_id = {tok: i for i, tok in enumerate(tokens)}
        self.id_to_token = {i: tok for tok, i in self.token_to_id.items()}
        self.unk_token_id = self.token_to_id[self.unk_token]
        self.eos_token_id = self.token_to_id[self.eos_token]
        self.pad_token_id = self.token_to_id[self.pad_token]
        self.bos_token_id = self.token_to_id[self.bos_token] if self.bos_token in self.token_to_id else None
        self.padding_side = "right"
        self.is_small_tokenizer = True

    def __len__(self):
        return len(self.small_tokens)

    def _split_angle_tokens(self, text: str) -> List[str]:
        if not text:
            return []
        if text.startswith("<") and text.endswith(">") and "><" in text:
            parts = text[1:-1].split("><")
            return [f"<{part}>" for part in parts]
        if text.startswith("<") and text.endswith(">"):
            return [text]
        return text.split()

    def _to_tokens(self, value, is_split_into_words: bool) -> List[str]:
        if isinstance(value, list):
            return value
        if is_split_into_words:
            return self._split_angle_tokens(str(value))
        return self._split_angle_tokens(str(value))

    def convert_tokens_to_ids(self, token: str) -> int:
        return self.token_to_id.get(token, self.unk_token_id)

    def encode_tokens(self, tokens: List[str], add_special_tokens: bool) -> List[int]:
        ids = [self.convert_tokens_to_ids(tok) for tok in tokens]
        if add_special_tokens:
            if self.bos_token_id is not None:
                ids = [self.bos_token_id] + ids
            if self.eos_token_id is not None:
                ids = ids + [self.eos_token_id]
        return ids

    def __call__(
        self,
        inputs,
        is_split_into_words: bool = False,
        truncation: bool = False,
        max_length: int | None = None,
        padding: bool | str = False,
        return_tensors: str | None = None,
        add_special_tokens: bool = False,
    ):
        if isinstance(inputs, list):
            if is_split_into_words and inputs and all(isinstance(x, str) for x in inputs):
                inputs = [inputs]
        else:
            inputs = [inputs]
        sequences = []
        for item in inputs:
            tokens = self._to_tokens(item, is_split_into_words=is_split_into_words)
            ids = self.encode_tokens(tokens, add_special_tokens=add_special_tokens)
            if truncation and max_length is not None:
                ids = ids[:max_length]
            sequences.append(ids)

        if padding:
            if padding == "max_length":
                pad_len = max_length if max_length is not None else max(len(s) for s in sequences) if sequences else 0
            else:
                pad_len = max(len(s) for s in sequences) if sequences else 0
        else:
            pad_len = None

        input_ids = []
        attention_mask = []
        for seq in sequences:
            if pad_len is not None:
                pad_needed = pad_len - len(seq)
                if pad_needed > 0:
                    seq = seq + [self.pad_token_id] * pad_needed
                elif pad_needed < 0:
                    seq = seq[:pad_len]
            input_ids.append(seq)
            attention_mask.append([1 if tok != self.pad_token_id else 0 for tok in seq])

        if return_tensors == "pt":
            input_ids = torch.tensor(input_ids, dtype=torch.long)
            attention_mask = torch.tensor(attention_mask, dtype=torch.long)
        return {"input_ids": input_ids, "attention_mask": attention_mask}

    def decode(self, ids: List[int], skip_special_tokens: bool = False) -> str:
        tokens = []
        for idx in ids:
            tok = self.id_to_token.get(int(idx), self.unk_token)
            if skip_special_tokens and tok in self.all_special_tokens:
                continue
            tokens.append(tok)
        return "".join(tokens)

    def save_pretrained(self, output_dir: str | Path):
        out = Path(output_dir)
        out.mkdir(parents=True, exist_ok=True)
        with (out / "vocab.json").open("w", encoding="utf-8") as f:
            json.dump(self.small_tokens, f)
        with (out / "special_tokens_map.json").open("w", encoding="utf-8") as f:
            json.dump(
                {
                    "unk_token": self.unk_token,
                    "eos_token": self.eos_token,
                    "pad_token": self.pad_token,
                    "bos_token": self.bos_token,
                },
                f,
            )
        return (str(out / "vocab.json"),)


def build_small_tokenizer(base_tokenizer, vocab_list: List[str]):
    return SmallTokenDictionaryTokenizer(vocab_list, base_tokenizer)


def reinit_small_embeddings(model):
    input_embed = model.get_input_embeddings()
    output_embed = model.get_output_embeddings()
    if input_embed is not None:
        model._init_weights(input_embed)
    if output_embed is not None and output_embed is not input_embed:
        model._init_weights(output_embed)
    if hasattr(model, "tie_weights"):
        model.tie_weights()


def ensure_token_list(value):
    if isinstance(value, list):
        return value
    if not value:
        return []
    if isinstance(value, str) and value.startswith("<") and value.endswith(">"):
        if "><" in value:
            parts = value[1:-1].split("><")
            return [f"<{part}>" for part in parts]
        return [value]
    if isinstance(value, str):
        return value.split()
    return [str(value)]


def to_text(value):
    return "".join(ensure_token_list(value))


def encode_values(tokenizer, values, max_length, padding, truncation, use_small):
    if use_small:
        token_lists = [ensure_token_list(v) for v in values]
        return tokenizer(
            token_lists,
            is_split_into_words=True,
            truncation=truncation,
            max_length=max_length,
            padding=padding,
            return_tensors="pt",
        )
    texts = [to_text(v) for v in values]
    return tokenizer(
        texts,
        truncation=truncation,
        max_length=max_length,
        padding=padding,
        return_tensors="pt",
    )


def log_tokenizer_test(tokenizer, sample_text: str):
    print("Tokenizer test input:", sample_text)
    raw = tokenizer(sample_text, add_special_tokens=False)
    raw_ids = raw["input_ids"]
    if raw_ids and isinstance(raw_ids[0], list):
        raw_ids = raw_ids[0]
    print("Tokenizer raw ids:", raw_ids)
    print("Tokenizer raw decoded:", tokenizer.decode(raw_ids, skip_special_tokens=False))
    if getattr(tokenizer, "is_small_tokenizer", False):
        tokens = ensure_token_list(sample_text)
        split = tokenizer(tokens, is_split_into_words=True, add_special_tokens=False)
        split_ids = split["input_ids"]
        if split_ids and isinstance(split_ids[0], list):
            split_ids = split_ids[0]
        print("Tokenizer split tokens:", tokens)
        print("Tokenizer split ids:", split_ids)
        print("Tokenizer split decoded:", tokenizer.decode(split_ids, skip_special_tokens=False))


class LayerDropWrapper(torch.nn.Module):
    def __init__(self, block: torch.nn.Module):
        super().__init__()
        self.block = block
        self.skip = False
        sig = inspect.signature(self.block.forward)
        params = sig.parameters
        if "layer_past" in params:
            self.order = "gpt2"
        elif "past_key_value" in params:
            self.order = "llama"
        else:
            self.order = "generic"
        self._sig = sig

    def forward(self, hidden_states, *args, **kwargs):
        if not self.skip:
            return self.block(hidden_states, *args, **kwargs)
        # Build a minimal output tuple that matches expected order.
        bound = self._sig.bind_partial(hidden_states, *args, **kwargs)
        use_cache = bound.arguments.get("use_cache", False)
        output_attentions = bound.arguments.get("output_attentions", False)
        outputs = (hidden_states,)
        if self.order == "gpt2":
            if use_cache:
                outputs += (None,)
            if output_attentions:
                outputs += (None,)
        elif self.order == "llama":
            if output_attentions:
                outputs += (None,)
            if use_cache:
                outputs += (None,)
        else:
            if output_attentions:
                outputs += (None,)
            if use_cache:
                outputs += (None,)
        return outputs


class BlockDropoutController:
    def __init__(self, blocks: List[LayerDropWrapper], block_size: int, p: float, seed: int):
        self.blocks = blocks
        self.block_size = block_size
        self.p = p
        self.rng = np.random.default_rng(seed)

    def clear(self):
        for block in self.blocks:
            block.skip = False

    def sample_and_apply(self):
        self.clear()
        if self.p <= 0 or self.block_size <= 0:
            return
        num_layers = len(self.blocks)
        num_blocks = (num_layers + self.block_size - 1) // self.block_size
        #pass at least one block
        passed = False
        for b in range(num_blocks):
            if self.rng.uniform() < self.p:
                start = b * self.block_size
                end = min(start + self.block_size, num_layers)
                #print(f"Dropping block {b} (layers {start} to {end-1})")
                for i in range(start, end):
                    self.blocks[i].skip = True
            else:
                #print(f"Passing block {b} ")
                passed = True
        if not passed:
            #pass the last block if all were dropped
            #print(f"All blocks were dropped; passing last block {num_blocks -1}")
            start = (num_blocks - 1) * self.block_size
            end = min(start + self.block_size, num_layers)
            for i in range(start, end):
                self.blocks[i].skip = False
        #print("*"*20)
        #input("Press Enter to continue...")


def apply_block_dropout(model: torch.nn.Module, block_size: int, p: float, seed: int):
    if p <= 0 or block_size <= 0:
        return None
    blocks = None
    if hasattr(model, "transformer") and hasattr(model.transformer, "h"):
        blocks = model.transformer.h
    elif hasattr(model, "model") and hasattr(model.model, "layers"):
        blocks = model.model.layers
    if blocks is None:
        raise ValueError("Unsupported model architecture for block dropout.")

    wrapped = []
    for i, block in enumerate(blocks):
        wrapper = LayerDropWrapper(block)
        blocks[i] = wrapper
        wrapped.append(wrapper)

    controller = BlockDropoutController(wrapped, block_size, p, seed)
    orig_forward = model.forward

    def forward_with_drop(*args, **kwargs):
        if model.training:
            controller.sample_and_apply()
        else:
            controller.clear()
        # orig_forward is already bound to model; do not pass self explicitly.
        if len(args) > 0 and args[0] is model:
            args = args[1:]
        return orig_forward(*args, **kwargs)

    model.forward = forward_with_drop
    return controller


class JsonTextDataset(Dataset):
    def __init__(self, data: List[Dict], tokenizer, max_length: int, loss_compute_method: str):
        self.data = data
        self.tokenizer = tokenizer
        self.max_length = max_length
        self.loss_compute_method = loss_compute_method

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        target_value = self.data[idx]["target_text"]
        input_value = self.data[idx].get("input_text", "")
        use_small = getattr(self.tokenizer, "is_small_tokenizer", False)
        target_tokens = ensure_token_list(target_value)
        input_tokens = ensure_token_list(input_value)
        target_text = "".join(target_tokens)
        input_text = "".join(input_tokens)

        if use_small:
            enc = self.tokenizer(
                target_tokens,
                is_split_into_words=True,
                truncation=True,
                max_length=self.max_length,
                return_tensors="pt",
                padding="max_length",
            )
        else:
            enc = self.tokenizer(
                target_text,
                truncation=True,
                max_length=self.max_length,
                return_tensors="pt",
                padding="max_length",
            )
        item = {k: v.squeeze(0) for k, v in enc.items()}
        labels = item["input_ids"].clone()

        # Always compute prefix length so accuracy can be answer-only.
        if use_small:
            enc_input = self.tokenizer(
                input_tokens,
                is_split_into_words=True,
                truncation=True,
                max_length=self.max_length,
                return_tensors="pt",
                padding=False,
            )
        else:
            enc_input = self.tokenizer(
                input_text,
                truncation=True,
                max_length=self.max_length,
                return_tensors="pt",
                padding=False,
            )
        input_len = enc_input["input_ids"].shape[1]
        item["input_len"] = torch.tensor(input_len, dtype=torch.long)

        if self.loss_compute_method == "answer" and input_len > 0:
            labels[:input_len] = -100

        # Always ignore padding in loss.
        labels[item["attention_mask"] == 0] = -100
        item["labels"] = labels
        return item


class EpochEvalCallback(TrainerCallback):
    def __init__(
        self,
        test_dataset: Dataset,
        train_dataset: Dataset,
        evaluate_epoch: int,
        train_eval_samples: int,
        train_eval_seed: int,
        tokenizer,
        log_eval_samples: int,
        log_eval_seed: int,
    ):
        self.test_dataset = test_dataset
        self.train_dataset = train_dataset
        self.evaluate_epoch = evaluate_epoch
        self.trainer = None
        self.train_eval_samples = train_eval_samples
        self.train_eval_seed = train_eval_seed
        self._train_subset = None
        self.tokenizer = tokenizer
        self.log_eval_samples = log_eval_samples
        self.log_eval_seed = log_eval_seed
        self.best_test_seq_acc = None

    def _get_train_subset(self):
        if self._train_subset is not None:
            return self._train_subset
        if not self.train_dataset or self.train_eval_samples <= 0:
            return None
        rng = np.random.default_rng(self.train_eval_seed)
        total = len(self.train_dataset)
        count = min(self.train_eval_samples, total)
        indices = rng.choice(total, size=count, replace=False).tolist()
        self._train_subset = Subset(self.train_dataset, indices)
        return self._train_subset

    def _sequence_accuracy(self, trainer: Trainer, dataset: Dataset) -> Dict[str, float]:
        if dataset is None:
            return {}
        base, indices = self._resolve_dataset(dataset)
        total = 0
        correct = 0
        token_total = 0
        token_correct = 0
        device = trainer.args.device
        batch_size = trainer.args.per_device_eval_batch_size or trainer.args.per_device_train_batch_size or 8
        max_len = getattr(base, "max_length", None)
        use_small = getattr(self.tokenizer, "is_small_tokenizer", False)

        for chunk in self._chunked(indices, batch_size):
            input_values = [base.data[i].get("input_text", "") for i in chunk]
            target_values = [base.data[i]["target_text"] for i in chunk]

            enc_tgt = encode_values(
                self.tokenizer,
                target_values,
                max_len,
                padding="max_length" if max_len else True,
                truncation=True,
                use_small=use_small,
            )
            enc_inp = encode_values(
                self.tokenizer,
                input_values,
                max_len,
                padding="max_length" if max_len else True,
                truncation=True,
                use_small=use_small,
            )
            enc_tgt = {k: v.to(device) for k, v in enc_tgt.items()}
            enc_inp = {k: v.to(device) for k, v in enc_inp.items()}

            with torch.no_grad():
                logits = trainer.model(**enc_tgt).logits
            preds = torch.argmax(logits, dim=-1).cpu()
            attn_tgt = enc_tgt.get("attention_mask", torch.ones_like(enc_tgt["input_ids"])).cpu()
            attn_inp = enc_inp.get("attention_mask", torch.ones_like(enc_inp["input_ids"])).cpu()
            tgt_ids = enc_tgt["input_ids"].cpu()
            pred_shift = preds[:, :-1]
            tgt_shift = tgt_ids[:, 1:]

            for j in range(len(chunk)):
                length = int(attn_tgt[j].sum().item())
                input_len = int(attn_inp[j].sum().item())
                input_len = min(input_len, length)
                if length <= input_len or length <= 1:
                    continue
                ans_start = max(input_len - 1, 0)
                ans_end = max(length - 1, 0)
                if ans_end <= ans_start:
                    continue
                pred_slice = pred_shift[j][ans_start:ans_end]
                tgt_slice = tgt_shift[j][ans_start:ans_end]
                token_correct += (pred_slice == tgt_slice).sum().item()
                token_total += (ans_end - ans_start)
                correct += int(torch.all(pred_slice == tgt_slice).item())
                total += 1

        seq_acc = correct / total if total else 0.0
        tok_acc = token_correct / token_total if token_total else 0.0
        return {"seq_acc": seq_acc, "token_acc": tok_acc}

    @staticmethod
    def _resolve_dataset(dataset: Dataset):
        if isinstance(dataset, Subset):
            base = dataset.dataset
            indices = list(dataset.indices)
        else:
            base = dataset
            indices = list(range(len(dataset)))
        return base, indices

    @staticmethod
    def _chunked(items: List[int], chunk_size: int):
        for i in range(0, len(items), chunk_size):
            yield items[i : i + chunk_size]

    def _collect_output_rows(self, trainer: Trainer, dataset: Dataset, split_name: str):
        if self.log_eval_samples <= 0 or dataset is None:
            return []
        base, indices = self._resolve_dataset(dataset)
        total = len(indices)
        if total == 0:
            return []
        n = min(self.log_eval_samples, total)
        rng = np.random.default_rng(self.log_eval_seed)
        chosen = rng.choice(total, size=n, replace=False).tolist() if n < total else list(range(total))
        raw_indices = [indices[i] for i in chosen]

        rows = []
        device = trainer.args.device
        batch_size = trainer.args.per_device_eval_batch_size or trainer.args.per_device_train_batch_size or 8
        max_len = getattr(base, "max_length", None)

        use_small = getattr(self.tokenizer, "is_small_tokenizer", False)
        for chunk in self._chunked(raw_indices, batch_size):
            target_texts_raw = [base.data[i]["target_text"] for i in chunk]
            input_texts_raw = [base.data[i].get("input_text", "") for i in chunk]

            enc = encode_values(
                self.tokenizer,
                target_texts_raw,
                max_len,
                padding="max_length" if max_len else True,
                truncation=True,
                use_small=use_small,
            )
            enc = {k: v.to(device) for k, v in enc.items()}

            input_len_list = [int(base[i]["input_len"]) for i in chunk]

            with torch.no_grad():
                logits = trainer.model(**enc).logits
            preds = torch.argmax(logits, dim=-1).cpu()
            attn = enc.get("attention_mask", torch.ones_like(enc["input_ids"])).cpu()
            pred_shift = preds[:, :-1]

            for j in range(len(chunk)):
                length = int(attn[j].sum().item())
                tgt_ids = enc["input_ids"][j][:length].cpu().tolist()
                pred_ids = preds[j][:length].tolist()
                pred_text = self.tokenizer.decode(pred_ids, skip_special_tokens=False)
                input_len = min(input_len_list[j], length)
                answer_ids = tgt_ids[input_len:length]
                if length > 1:
                    ans_start = max(input_len - 1, 0)
                    ans_end = max(length - 1, 0)
                    model_answer_ids = pred_shift[j][ans_start:ans_end].tolist() if ans_end > ans_start else []
                else:
                    model_answer_ids = []
                correct = bool(answer_ids == model_answer_ids) if answer_ids else False
                # Extract answer tokens from target/pred slices.
                answer_text = self.tokenizer.decode(answer_ids, skip_special_tokens=False) if answer_ids else ""
                model_answer_text = self.tokenizer.decode(model_answer_ids, skip_special_tokens=False) if model_answer_ids else ""
                rows.append(
                    {
                        "split": split_name,
                        "input_text": input_texts_raw[j],
                        "target_text": target_texts_raw[j],
                        "model_output": pred_text,
                        "target_answer": answer_text,
                        "model_answer": model_answer_text,
                        "correct": correct,
                    }
                )

        if not rows and len(indices) > 0:
            idx = indices[0]
            item = base.data[idx]
            rows.append(
                {
                    "split": split_name,
                    "input_text": item.get("input_text", ""),
                    "target_text": item["target_text"],
                    "model_output": "",
                    "target_answer": "",
                    "model_answer": "",
                    "correct": False,
                }
            )
        return rows

    def _log_outputs_table(self, trainer: Trainer, rows: List[Dict], split_name: str):
        if not rows:
            return
        if "wandb" not in trainer.args.report_to:
            return
        if not trainer.is_world_process_zero():
            return
        try:
            import wandb
        except ImportError:
            return

        table = wandb.Table(
            columns=[
                "split",
                "input_text",
                "target_text",
                "model_output",
                "target_answer",
                "model_answer",
                "correct",
            ]
        )
        for row in rows:
            table.add_data(
                str(row["split"]),
                str(row["input_text"]),
                str(row["target_text"]),
                str(row["model_output"]),
                str(row.get("target_answer", "")),
                str(row.get("model_answer", "")),
                bool(row["correct"]),
            )
        wandb.log(
            {
                f"{split_name}_samples": table,
                f"{split_name}_samples_count": len(rows),
            },
            step=trainer.state.global_step,
        )

    @staticmethod
    def _append_epoch_log(trainer: Trainer, payload: Dict):
        if not trainer.is_world_process_zero():
            return
        out_path = Path(trainer.args.output_dir) / "log_epochs.json"
        if out_path.exists():
            try:
                data = json.loads(out_path.read_text())
            except json.JSONDecodeError:
                data = []
        else:
            data = []
        data.append(payload)
        out_path.write_text(json.dumps(data, indent=2))

    def _save_best_checkpoint(self, trainer: Trainer, metrics: Dict, current_epoch: int):
        if not trainer.is_world_process_zero():
            return
        output_dir = Path(trainer.args.output_dir) / "best_twohop_test"
        output_dir.mkdir(parents=True, exist_ok=True)
        trainer.model.save_pretrained(output_dir)
        self.tokenizer.save_pretrained(output_dir)
        payload = {
            "epoch": current_epoch,
            "global_step": trainer.state.global_step,
            "metrics": metrics,
        }
        (output_dir / "best_metrics.json").write_text(json.dumps(payload, indent=2))

    def on_epoch_end(self, args, state, control, **kwargs):
        if not self.test_dataset:
            return control
        if self.evaluate_epoch <= 0:
            return control
        if state.epoch is None:
            return control
        current_epoch = int(state.epoch)
        if current_epoch > 0 and current_epoch % self.evaluate_epoch == 0:
            trainer = self.trainer or kwargs.get("trainer")
            if trainer is None:
                return control
            # Test loss + accuracy on full test set.
            metrics = trainer.evaluate(self.test_dataset, metric_key_prefix="test")
            test_acc = self._sequence_accuracy(trainer, self.test_dataset)
            metrics.update({f"test_{k}": v for k, v in test_acc.items()})

            # Accuracy on a fixed-size subset of training set.
            train_subset = self._get_train_subset()
            train_acc = self._sequence_accuracy(trainer, train_subset)
            metrics.update({f"train_subset_{k}": v for k, v in train_acc.items()})

            test_seq_acc = metrics.get("test_seq_acc")
            if test_seq_acc is not None:
                if self.best_test_seq_acc is None or test_seq_acc > self.best_test_seq_acc:
                    self.best_test_seq_acc = test_seq_acc
                    self._save_best_checkpoint(trainer, metrics, current_epoch)
            if self.best_test_seq_acc is not None:
                metrics["best_test_seq_acc"] = self.best_test_seq_acc

            trainer.log(metrics)
            test_rows = self._collect_output_rows(trainer, self.test_dataset, "test")
            train_rows = self._collect_output_rows(trainer, train_subset, "train_subset") if train_subset is not None else []
            self._log_outputs_table(trainer, test_rows, "test")
            if train_rows:
                self._log_outputs_table(trainer, train_rows, "train_subset")

            # Save offline log
            payload = {
                "epoch": current_epoch,
                "global_step": trainer.state.global_step,
                "metrics": metrics,
                "test_samples": test_rows,
                "train_subset_samples": train_rows,
            }
            self._append_epoch_log(trainer, payload)
        return control


def load_json(path: Path):
    with path.open() as f:
        return json.load(f)


def parse_args():
    ap = argparse.ArgumentParser(description="Train a GPT-2 LM on the twin two-hop dataset.")
    ap.add_argument("--data-dir", type=Path, required=True, help="Path to dataset directory (with train.json/valid.json).")
    ap.add_argument("--output-dir", type=Path, required=True, help="Where to save checkpoints.")
    ap.add_argument("--model-name", type=str, default="gpt2", help="HF model name or local path to initialize from.")
    ap.add_argument("--from-scratch", action="store_true", help="If set, initialize a fresh model with the same architecture as --model-name but randomized weights.")
    ap.add_argument("--trust-remote-code", action="store_true", help="Allow custom model/tokenizer code (needed for some Qwen checkpoints).")
    ap.add_argument("--create-special-token", action="store_true", help="Add all dataset tokens to the tokenizer so each entity/relation is a unique token.")
    ap.add_argument("--use-small-tokenizer", action="store_true", help="Use a tokenizer with only dataset tokens + special tokens.")
    ap.add_argument("--max-length", type=int, default=64, help="Max sequence length.")
    ap.add_argument("--batch-size", type=int, default=16, help="Per-device batch size.")
    ap.add_argument("--epochs", type=int, default=3, help="Training epochs.")
    ap.add_argument(
        "--loss-compute-method",
        choices=["full", "answer"],
        default="answer",
        help="Loss on full sequence or only answer tokens.",
    )
    ap.add_argument("--block-dropout-p", type=float, default=0.0, help="Probability to drop each block (training only).")
    ap.add_argument("--block-dropout-block-size", type=int, default=0, help="Number of layers per block.")
    ap.add_argument("--block-dropout-seed", type=int, default=7, help="Seed for block dropout.")
    ap.add_argument("--lr", type=float, default=1e-4, help="Learning rate.")
    ap.add_argument("--weight-decay", type=float, default=0.0, help="Weight decay for AdamW.")
    ap.add_argument("--warmup-steps", type=int, default=2000, help="Warmup steps.")
    ap.add_argument("--logging-steps", type=int, default=10, help="Log every n steps.")
    ap.add_argument("--save-steps", type=int, default=1000, help="Save every n steps.")
    ap.add_argument("--eval-steps", type=int, default=None, help="Evaluate every n steps if valid set exists.")
    ap.add_argument("--evaluate-epoch", type=int, default=10, help="Run test-set eval every N epochs (<=0 disables).")
    ap.add_argument("--train-eval-samples", type=int, default=256, help="Number of train samples for periodic accuracy.")
    ap.add_argument("--train-eval-seed", type=int, default=7, help="Seed for selecting train-eval subset.")
    ap.add_argument("--log-eval-samples", type=int, default=20, help="Number of samples to log to W&B tables.")
    ap.add_argument("--log-eval-seed", type=int, default=7, help="Seed for sampling logged examples.")
    ap.add_argument("--wandb-project", type=str, default=None, help="Optional W&B project name for logging.")
    return ap.parse_args()


def build_run_name(args) -> str:
    model_name = (args.model_name or "model").split("/")[-1]
    data_name = Path(args.data_dir).name
    flags = []
    if args.from_scratch:
        flags.append("scratch")
    if args.create_special_token:
        flags.append("specialtok")
    if args.use_small_tokenizer:
        flags.append("smalltok")
    if args.trust_remote_code:
        flags.append("remote")
    ts = datetime.now().strftime("%Y%m%d-%H%M%S")
    flag_str = "-".join(flags) if flags else "base"
    return f"{model_name}_{data_name}_{flag_str}_{ts}_lr{args.lr}_wd{args.weight_decay}_bdp{args.block_dropout_p}_bds{args.block_dropout_block_size}_bs{args.batch_size}_ep{args.epochs}"


def main():
    args = parse_args()
    run_name = build_run_name(args)
    train_path = args.data_dir / "train.json"
    valid_path = args.data_dir / "valid.json"
    test_path = args.data_dir / "test.json"
    if not train_path.exists():
        raise FileNotFoundError(f"Missing train.json at {train_path}")

    train_data = load_json(train_path)
    valid_data = load_json(valid_path) if valid_path.exists() else []
    test_data = load_json(test_path) if test_path.exists() else []

    base_tokenizer = AutoTokenizer.from_pretrained(
        args.model_name if not args.from_scratch else "gpt2",
        trust_remote_code=args.trust_remote_code,
    )
    if base_tokenizer.pad_token is None:
        base_tokenizer.pad_token = base_tokenizer.eos_token
    base_tokenizer.padding_side = "right"

    if args.use_small_tokenizer:
        vocab_path = args.data_dir / "vocab.json"
        if not vocab_path.exists():
            raise FileNotFoundError(f"--use-small-tokenizer was set, but {vocab_path} is missing")
        with vocab_path.open() as f:
            vocab_list = json.load(f)
        tokenizer = build_small_tokenizer(base_tokenizer, vocab_list)
    else:
        tokenizer = base_tokenizer
        # Optionally add all dataset tokens so each entity/relation is a single token.
        if args.create_special_token:
            vocab_path = args.data_dir / "vocab.json"
            if not vocab_path.exists():
                raise FileNotFoundError(f"--create-special-token was set, but {vocab_path} is missing")
            with vocab_path.open() as f:
                vocab_list = json.load(f)
            tokenizer.add_tokens(vocab_list, special_tokens=True)

    if args.from_scratch:
        # Build a fresh model with the same architecture as the base model.
        base_name = args.model_name or "gpt2"
        if base_name == "gpt2" and not args.trust_remote_code:
            # Keep a simple default if user wants GPT-2 from scratch without remote code.
            config = GPT2Config(
                vocab_size=len(tokenizer),
                n_layer=8,
                n_head=12,
                n_embd=768,
            )
        else:
            config = AutoConfig.from_pretrained(base_name, trust_remote_code=args.trust_remote_code)
            # Ensure vocab matches tokenizer (especially if we added dataset tokens).
            config.vocab_size = len(tokenizer)
        try:
            model = AutoModelForCausalLM.from_config(config, trust_remote_code=args.trust_remote_code)
        except TypeError:
            model = AutoModelForCausalLM.from_config(config)
    else:
        model = AutoModelForCausalLM.from_pretrained(
            args.model_name,
            trust_remote_code=args.trust_remote_code,
        )
        model.resize_token_embeddings(len(tokenizer))
        if args.use_small_tokenizer:
            reinit_small_embeddings(model)
    if tokenizer.pad_token_id is not None:
        model.config.pad_token_id = tokenizer.pad_token_id

    if args.use_small_tokenizer:
        tokens = getattr(tokenizer, "small_tokens", None)
        if tokens is not None:
            print("Small tokenizer tokens:", tokens)
            print("Small tokenizer size:", len(tokens))
        emb = model.get_input_embeddings().weight.detach().cpu()
        print("Embedding shape:", tuple(emb.shape))
        print("Embedding sample:", emb[:2])

    log_tokenizer_test(tokenizer, "<a_e_1><r_2><a_e_3>")

    # Optional block-wise layer dropout during training.
    if args.block_dropout_p > 0 and args.block_dropout_block_size > 0:
        apply_block_dropout(model, args.block_dropout_block_size, args.block_dropout_p, args.block_dropout_seed)

    train_ds = JsonTextDataset(train_data, tokenizer, args.max_length, args.loss_compute_method)
    valid_ds = JsonTextDataset(valid_data, tokenizer, args.max_length, args.loss_compute_method) if valid_data else None
    print("train_ds samples:", len(train_ds), "sample item:", train_ds[0],"tokenized:", tokenizer.decode(train_ds[0]['input_ids']))
    test_ds = JsonTextDataset(test_data, tokenizer, args.max_length, args.loss_compute_method) if test_data else None
    print("test_ds samples:", len(test_ds), "sample item:", test_ds[0],"tokenized:", tokenizer.decode(test_ds[0]['input_ids']) if test_ds else "N/A")

    data_collator = default_data_collator

    eval_strategy = "steps" if valid_ds else "no"
    eval_steps = args.eval_steps if args.eval_steps is not None else args.logging_steps

    # Older transformers may not accept evaluation_strategy/ev al_steps.
    try:
        training_args = TrainingArguments(
            output_dir=str(args.output_dir),
            per_device_train_batch_size=args.batch_size,
            per_device_eval_batch_size=args.batch_size,
            num_train_epochs=args.epochs,
            learning_rate=args.lr,
            weight_decay=args.weight_decay,
            warmup_steps=args.warmup_steps,
            logging_steps=args.logging_steps,
            save_steps=args.save_steps,
            evaluation_strategy=eval_strategy,
            eval_steps=eval_steps,
            report_to=["wandb"] if args.wandb_project else [],
            run_name=run_name,
            save_total_limit=3,
            gradient_checkpointing=False,
            lr_scheduler_type="cosine",
            remove_unused_columns=False,
        )
    except TypeError:
        training_args = TrainingArguments(
            output_dir=str(args.output_dir),
            per_device_train_batch_size=args.batch_size,
            per_device_eval_batch_size=args.batch_size,
            num_train_epochs=args.epochs,
            learning_rate=args.lr,
            weight_decay=args.weight_decay,
            warmup_steps=args.warmup_steps,
            logging_steps=args.logging_steps,
            save_steps=args.save_steps,
            report_to=["wandb"] if args.wandb_project else [],
            run_name=run_name,
            save_total_limit=3,
            gradient_checkpointing=False,
            lr_scheduler_type="cosine",
            remove_unused_columns=False,
        )

    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_ds,
        eval_dataset=valid_ds,
        data_collator=data_collator,
    )

    if test_ds and args.evaluate_epoch > 0:
        callback = EpochEvalCallback(
            test_ds,
            train_ds,
            args.evaluate_epoch,
            args.train_eval_samples,
            args.train_eval_seed,
            tokenizer,
            args.log_eval_samples,
            args.log_eval_seed,
        )
        callback.trainer = trainer
        trainer.add_callback(callback)

    if args.wandb_project:
        import wandb

        wandb.init(project=args.wandb_project, name=run_name)

    trainer.train()
    trainer.save_model(args.output_dir)
    tokenizer.save_pretrained(args.output_dir)


if __name__ == "__main__":
    main()