-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathkd_lib.py
More file actions
2021 lines (1805 loc) · 91.6 KB
/
kd_lib.py
File metadata and controls
2021 lines (1805 loc) · 91.6 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
from __future__ import annotations
import logging
import os
import sys
import time
from collections import deque
from math import ceil, cos, pi
from pathlib import Path
from types import SimpleNamespace
TRAIN_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(TRAIN_DIR)
if TRAIN_DIR in sys.path:
sys.path.remove(TRAIN_DIR)
if PROJECT_ROOT not in sys.path:
sys.path.insert(0, PROJECT_ROOT)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import torch
import torch.nn.functional as F
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import DistributedType, set_seed
from omegaconf import OmegaConf
from torch.optim import AdamW
from nemo_automodel.components.config.loader import _resolve_target
from nemo_automodel.components.distillation.teacher_rpc import AsyncTeacherClient
from nemo_automodel.components.distillation.vlm_kd import collect_generation_kd_indices
from nemo_automodel.components.distillation.vlm_on_policy import (
build_prompt_batch,
build_teacher_batch_from_gold_response,
build_teacher_batch_from_on_policy_response,
sample_on_policy_responses,
)
from nemo_automodel.components.loss.topk_kd_loss import TopKKDLoss
from train.utils import flatten_omega_conf, get_config
logger = get_logger(__name__, log_level="INFO")
def to_device(data, device):
if isinstance(data, dict):
return type(data)({k: to_device(v, device) for k, v in data.items()})
if isinstance(data, (list, tuple)):
return type(data)(to_device(v, device) for v in data)
if isinstance(data, torch.Tensor):
return data.to(device, non_blocking=True)
return data
def to_cpu(data):
if isinstance(data, dict):
return type(data)({k: to_cpu(v) for k, v in data.items()})
if isinstance(data, (list, tuple)):
return type(data)(to_cpu(v) for v in data)
if isinstance(data, torch.Tensor):
return data.detach().cpu()
return data
def instantiate_config(cfg, **extra_kwargs):
if cfg is None:
return None
container = OmegaConf.to_container(cfg, resolve=True)
if not isinstance(container, dict) or "_target_" not in container:
raise ValueError(f"Config must be a mapping with `_target_`, got: {container}")
target = container.pop("_target_")
container.update(extra_kwargs)
fn = _resolve_target(target)
return fn(**container)
def build_components(config):
from transformers import AutoProcessor
processor = instantiate_config(config.get("processor", None))
if processor is None:
processor = AutoProcessor.from_pretrained(
config.model.pretrained_model_name_or_path,
trust_remote_code=True,
)
dataset_kwargs = {k: v for k, v in OmegaConf.to_container(config.dataset, resolve=True).items() if k != "_target_"}
dataset = instantiate_config(config.dataset, **dataset_kwargs)
collate_fn = None
if config.dataloader.get("collate_fn", None) is not None:
collate_target = str(config.dataloader.collate_fn.get("_target_", ""))
collate_extra_kwargs = {}
diffusion_cfg = config.get("diffusion_kd", None)
if diffusion_cfg is not None and collate_target.endswith("qwen_vl_block_collate_fn"):
collate_extra_kwargs["min_mask_rate"] = float(diffusion_cfg.get("min_mask_rate", 0.001))
collate_extra_kwargs["max_mask_rate"] = float(diffusion_cfg.get("max_mask_rate", 1.0))
collate_fn = instantiate_config(
config.dataloader.collate_fn,
processor=processor,
max_len=config.dataset.max_len,
**collate_extra_kwargs,
)
dataloader_kwargs = {
k: v
for k, v in OmegaConf.to_container(config.dataloader, resolve=True).items()
if k not in ("_target_", "collate_fn")
}
dataloader = instantiate_config(
config.dataloader,
dataset=dataset,
collate_fn=collate_fn,
batch_size=int(config.training.per_device_train_batch_size),
**dataloader_kwargs,
)
student = instantiate_config(config.model)
return dataloader, student, processor
def save_checkpoint(accelerator, model, processor, output_dir: str, step: int):
if not accelerator.is_main_process:
return
save_dir = Path(output_dir) / f"step-{step}"
save_dir.mkdir(parents=True, exist_ok=True)
unwrapped = accelerator.unwrap_model(model)
if hasattr(unwrapped, "save_pretrained"):
unwrapped.save_pretrained(save_dir)
if processor is not None and hasattr(processor, "save_pretrained"):
processor.save_pretrained(save_dir)
else:
torch.save(unwrapped.state_dict(), save_dir / "model.pt")
def build_generation_config(config) -> SimpleNamespace:
return SimpleNamespace(**OmegaConf.to_container(config.on_policy, resolve=True))
def build_lr_schedule(config) -> SimpleNamespace:
scheduler_cfg = config.get("lr_scheduler", None)
warmup_steps = int(scheduler_cfg.get("warmup_steps", 0)) if scheduler_cfg is not None else 0
min_lr_ratio = float(scheduler_cfg.get("min_lr_ratio", 0.1)) if scheduler_cfg is not None else 0.1
warmup_start_ratio = float(scheduler_cfg.get("warmup_start_ratio", 0.1)) if scheduler_cfg is not None else 0.1
min_lr_ratio = max(0.0, min(1.0, min_lr_ratio))
warmup_start_ratio = max(0.0, min(1.0, warmup_start_ratio))
grad_accum_steps = max(int(config.training.gradient_accumulation_steps), 1)
total_train_steps = max(int(config.training.max_steps), 1)
total_optimizer_steps = max(ceil(total_train_steps / grad_accum_steps), 1)
warmup_steps = min(max(warmup_steps, 0), total_optimizer_steps)
base_lr = float(config.optimizer.lr)
return SimpleNamespace(
base_lr=base_lr,
warmup_steps=warmup_steps,
min_lr_ratio=min_lr_ratio,
warmup_start_ratio=warmup_start_ratio,
total_optimizer_steps=total_optimizer_steps,
)
def build_epoch_lr_schedule(config, total_train_steps: int) -> SimpleNamespace:
scheduler_cfg = config.get("lr_scheduler", None)
warmup_steps = int(scheduler_cfg.get("warmup_steps", 0)) if scheduler_cfg is not None else 0
min_lr_ratio = float(scheduler_cfg.get("min_lr_ratio", 0.1)) if scheduler_cfg is not None else 0.1
warmup_start_ratio = float(scheduler_cfg.get("warmup_start_ratio", 0.1)) if scheduler_cfg is not None else 0.1
min_lr_ratio = max(0.0, min(1.0, min_lr_ratio))
warmup_start_ratio = max(0.0, min(1.0, warmup_start_ratio))
total_train_steps = max(int(total_train_steps), 1)
warmup_steps = min(max(warmup_steps, 0), total_train_steps)
base_lr = float(config.optimizer.lr)
return SimpleNamespace(
base_lr=base_lr,
warmup_steps=warmup_steps,
min_lr_ratio=min_lr_ratio,
warmup_start_ratio=warmup_start_ratio,
total_train_steps=total_train_steps,
)
def resolve_training_schedule(config, dataloader) -> SimpleNamespace:
if "num_epochs" not in config.training:
raise ValueError("training.num_epochs is required to derive max_steps from epochs")
num_epochs = int(config.training.num_epochs)
if num_epochs <= 0:
raise ValueError(f"training.num_epochs must be greater than 0, got {num_epochs}")
try:
epoch_steps = int(len(dataloader))
except TypeError as exc:
raise ValueError("Epoch-based training requires a dataloader with a defined length") from exc
if epoch_steps <= 0:
raise ValueError(f"Dataloader length must be greater than 0, got {epoch_steps}")
grad_accum_steps = max(int(config.training.gradient_accumulation_steps), 1)
optimizer_steps_per_epoch = max(ceil(epoch_steps / grad_accum_steps), 1)
total_micro_steps = epoch_steps * num_epochs
total_train_steps = optimizer_steps_per_epoch * num_epochs
return SimpleNamespace(
num_epochs=num_epochs,
epoch_steps=epoch_steps,
optimizer_steps_per_epoch=optimizer_steps_per_epoch,
total_micro_steps=total_micro_steps,
total_train_steps=total_train_steps,
)
def get_lr_for_optimizer_step(schedule: SimpleNamespace, optimizer_step: int) -> float:
if optimizer_step <= 0:
return schedule.base_lr * schedule.warmup_start_ratio
if schedule.warmup_steps > 0 and optimizer_step <= schedule.warmup_steps:
warmup_progress = float(optimizer_step - 1) / float(max(schedule.warmup_steps - 1, 1))
lr_ratio = schedule.warmup_start_ratio + (1.0 - schedule.warmup_start_ratio) * warmup_progress
return schedule.base_lr * lr_ratio
if schedule.total_optimizer_steps <= schedule.warmup_steps:
return schedule.base_lr * schedule.min_lr_ratio
progress = float(optimizer_step - schedule.warmup_steps) / float(
schedule.total_optimizer_steps - schedule.warmup_steps
)
progress = max(0.0, min(1.0, progress))
cosine_decay = 0.5 * (1.0 + cos(pi * progress))
return schedule.base_lr * (schedule.min_lr_ratio + (1.0 - schedule.min_lr_ratio) * cosine_decay)
def get_lr_for_global_step(schedule: SimpleNamespace, global_step: int) -> float:
if global_step <= 0:
return schedule.base_lr * schedule.warmup_start_ratio
if schedule.warmup_steps > 0 and global_step <= schedule.warmup_steps:
warmup_progress = float(global_step - 1) / float(max(schedule.warmup_steps - 1, 1))
lr_ratio = schedule.warmup_start_ratio + (1.0 - schedule.warmup_start_ratio) * warmup_progress
return schedule.base_lr * lr_ratio
if schedule.total_train_steps <= schedule.warmup_steps:
return schedule.base_lr * schedule.min_lr_ratio
progress = float(global_step - schedule.warmup_steps) / float(
schedule.total_train_steps - schedule.warmup_steps
)
progress = max(0.0, min(1.0, progress))
cosine_decay = 0.5 * (1.0 + cos(pi * progress))
return schedule.base_lr * (schedule.min_lr_ratio + (1.0 - schedule.min_lr_ratio) * cosine_decay)
def set_optimizer_lr(optimizer, lr: float):
for param_group in optimizer.param_groups:
param_group["lr"] = lr
def _count_parameters(model):
total_params = sum(parameter.numel() for parameter in model.parameters())
trainable_params = sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad)
return total_params, trainable_params
def log_student_model_info(model):
total_params, trainable_params = _count_parameters(model)
ratio = (100.0 * trainable_params / total_params) if total_params > 0 else 0.0
first_param = next(model.parameters(), None)
logger.info(
"student model | class=%s | dtype=%s | total_params=%d | trainable_params=%d | trainable_ratio=%.4f%%",
model.__class__.__name__,
str(first_param.dtype) if first_param is not None else "n/a",
total_params,
trainable_params,
ratio,
)
def build_debug_config(config) -> SimpleNamespace:
debug_cfg = config.get("debug", None)
if debug_cfg is None:
return SimpleNamespace(
enabled=False,
log_generated_text=False,
log_topk_overlap=False,
generated_text_every_steps=1,
generated_text_num_samples=1,
generated_text_skip_special_tokens=True,
log_prompt_text=True,
topk_overlap_every_steps=1,
topk_overlap_k=10,
topk_overlap_num_samples=2,
)
return SimpleNamespace(
enabled=bool(debug_cfg.get("enabled", False)),
log_generated_text=bool(debug_cfg.get("log_generated_text", False)),
log_topk_overlap=bool(debug_cfg.get("log_topk_overlap", False)),
generated_text_every_steps=int(debug_cfg.get("generated_text_every_steps", 1)),
generated_text_num_samples=int(debug_cfg.get("generated_text_num_samples", 1)),
generated_text_skip_special_tokens=bool(debug_cfg.get("generated_text_skip_special_tokens", True)),
log_prompt_text=bool(debug_cfg.get("log_prompt_text", True)),
topk_overlap_every_steps=int(debug_cfg.get("topk_overlap_every_steps", 1)),
topk_overlap_k=int(debug_cfg.get("topk_overlap_k", 10)),
topk_overlap_num_samples=int(debug_cfg.get("topk_overlap_num_samples", 2)),
)
def build_stability_config(config) -> SimpleNamespace:
stability_cfg = config.get("stability", None)
if stability_cfg is None:
return SimpleNamespace(
log_timing=True,
log_timing_every_steps=1,
warn_on_max_len_hit=True,
drop_rollout_if_hits_max_len=False,
)
return SimpleNamespace(
log_timing=bool(stability_cfg.get("log_timing", True)),
log_timing_every_steps=int(stability_cfg.get("log_timing_every_steps", 1)),
warn_on_max_len_hit=bool(stability_cfg.get("warn_on_max_len_hit", True)),
drop_rollout_if_hits_max_len=bool(stability_cfg.get("drop_rollout_if_hits_max_len", False)),
)
def _get_decoder(processor):
if processor is None:
return None
if hasattr(processor, "batch_decode"):
return processor.batch_decode
tokenizer = getattr(processor, "tokenizer", None)
if tokenizer is not None and hasattr(tokenizer, "batch_decode"):
return tokenizer.batch_decode
return None
def _decode_sequences(processor, sequences: torch.Tensor, skip_special_tokens: bool) -> list[str]:
decoder = _get_decoder(processor)
if decoder is None:
return []
return decoder(
sequences.detach().cpu(),
skip_special_tokens=skip_special_tokens,
clean_up_tokenization_spaces=False,
)
def _decode_token_ids(processor, token_ids: torch.Tensor, skip_special_tokens: bool) -> list[str]:
if token_ids.numel() == 0:
return []
sequences = token_ids.detach().cpu().view(-1, 1)
return _decode_sequences(processor, sequences, skip_special_tokens=skip_special_tokens)
def _format_token_debug(token_id: int, token_text: str | None) -> str:
if token_text is None:
return str(token_id)
sanitized = (
token_text.replace("\\", "\\\\")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
)
return f"{token_id}:{sanitized}"
def infer_effective_response_lens(
sampled_responses: torch.Tensor,
response_lens: torch.Tensor,
eos_token_id: int,
mask_token_id: int,
) -> torch.Tensor:
if sampled_responses.ndim != 2:
raise ValueError(
f"`sampled_responses` must be 2D to infer effective lengths, got shape={tuple(sampled_responses.shape)}"
)
effective_lens = response_lens.clone()
max_generated_width = int(sampled_responses.shape[1])
if max_generated_width <= 0:
return torch.zeros_like(response_lens)
for batch_idx in range(sampled_responses.shape[0]):
upper_bound = min(int(response_lens[batch_idx].item()), max_generated_width)
if upper_bound <= 0:
effective_lens[batch_idx] = 0
continue
current = sampled_responses[batch_idx, :upper_bound]
eos_positions = torch.nonzero(current == eos_token_id, as_tuple=False).flatten()
if eos_positions.numel() > 0:
effective_lens[batch_idx] = int(eos_positions[0].item()) + 1
continue
mask_positions = torch.nonzero(current == mask_token_id, as_tuple=False).flatten()
if mask_positions.numel() > 0:
effective_lens[batch_idx] = int(mask_positions[0].item())
continue
effective_lens[batch_idx] = upper_bound
return effective_lens
def estimate_tensor_payload_nbytes(data) -> int:
if isinstance(data, dict):
return sum(estimate_tensor_payload_nbytes(value) for value in data.values())
if isinstance(data, (list, tuple)):
return sum(estimate_tensor_payload_nbytes(value) for value in data)
if isinstance(data, torch.Tensor):
return int(data.numel() * data.element_size())
return 0
def count_grid_tokens(grid_thw: torch.Tensor | None) -> int:
if grid_thw is None or grid_thw.numel() == 0:
return 0
return int(torch.prod(grid_thw.long(), dim=-1).sum().item())
def build_rollout_request_lens(
original_response_lens: torch.Tensor,
configured_max_response_len: int,
) -> torch.Tensor:
if configured_max_response_len > 0:
return torch.clamp(original_response_lens, max=configured_max_response_len)
return original_response_lens.clone()
def analyze_rollout_stop_reasons(
sampled_responses: torch.Tensor,
request_response_lens: torch.Tensor,
effective_response_lens: torch.Tensor,
eos_token_id: int,
mask_token_id: int,
configured_max_response_len: int,
) -> dict[str, int]:
upper_bounds = torch.clamp(request_response_lens, max=int(sampled_responses.shape[1]))
eos_stop_samples = 0
mask_trunc_samples = 0
max_len_stop_samples = 0
request_cap_stop_samples = 0
for batch_idx in range(sampled_responses.shape[0]):
upper_bound = int(upper_bounds[batch_idx].item())
if upper_bound <= 0:
continue
current = sampled_responses[batch_idx, :upper_bound]
eos_positions = torch.nonzero(current == eos_token_id, as_tuple=False).flatten()
if eos_positions.numel() > 0:
eos_stop_samples += 1
continue
mask_positions = torch.nonzero(current == mask_token_id, as_tuple=False).flatten()
if mask_positions.numel() > 0:
mask_trunc_samples += 1
continue
effective_len = int(effective_response_lens[batch_idx].item())
if configured_max_response_len > 0 and effective_len >= configured_max_response_len:
max_len_stop_samples += 1
else:
request_cap_stop_samples += 1
return {
"request_response_len_max": int(request_response_lens.max().item()) if request_response_lens.numel() > 0 else 0,
"effective_response_len_max": int(effective_response_lens.max().item()) if effective_response_lens.numel() > 0 else 0,
"eos_stop_samples": eos_stop_samples,
"mask_trunc_samples": mask_trunc_samples,
"max_len_stop_samples": max_len_stop_samples,
"request_cap_stop_samples": request_cap_stop_samples,
}
def create_attention_mask(
prefix_len: int,
response_len: int,
block_size: int,
max_len: int,
device: torch.device,
) -> torch.Tensor:
seq_len = min(prefix_len + 2 * response_len, max_len)
mask = torch.zeros((max_len, max_len), dtype=torch.bool, device=device)
if seq_len <= 0:
return mask.unsqueeze(0).unsqueeze(0)
block_ids = torch.empty((seq_len,), dtype=torch.long, device=device)
token_types = torch.empty((seq_len,), dtype=torch.int8, device=device)
clean_start = min(prefix_len, seq_len)
clean_end = min(prefix_len + response_len, seq_len)
noisy_start = clean_end
block_ids[:clean_start] = torch.arange(clean_start, device=device) // block_size
token_types[:clean_start] = 0
if clean_end > clean_start:
num_prefix_blocks = (prefix_len + block_size - 1) // block_size
clean_len = clean_end - clean_start
clean_rel_positions = torch.arange(clean_len, device=device)
clean_blocks = num_prefix_blocks + clean_rel_positions // block_size
block_ids[clean_start:clean_end] = clean_blocks
token_types[clean_start:clean_end] = 1
if noisy_start < seq_len:
num_prefix_blocks = (prefix_len + block_size - 1) // block_size
noisy_len = seq_len - noisy_start
noisy_rel_positions = torch.arange(noisy_len, device=device)
noisy_blocks = num_prefix_blocks + noisy_rel_positions // block_size
block_ids[noisy_start:seq_len] = noisy_blocks
token_types[noisy_start:seq_len] = 2
q_blocks = block_ids.view(-1, 1)
k_blocks = block_ids.view(1, -1)
q_types = token_types.view(-1, 1)
k_types = token_types.view(1, -1)
base_mask = q_blocks >= k_blocks
noisy_query_mask = q_types == 2
noisy_visibility = (k_types == 0) | ((k_types == 1) & (k_blocks < q_blocks)) | ((k_types == 2) & (k_blocks == q_blocks))
local_mask = torch.where(noisy_query_mask, noisy_visibility, base_mask)
mask[:seq_len, :seq_len] = local_mask
return mask.unsqueeze(0).unsqueeze(0)
def slice_sample_position_ids(position_ids: torch.Tensor, batch_idx: int, length: int) -> torch.Tensor:
if position_ids.ndim == 3:
return position_ids[:, batch_idx : batch_idx + 1, :length]
return position_ids[batch_idx : batch_idx + 1, :length]
def build_gold_ce_batch(
batch: dict[str, torch.Tensor],
prompt_lens: torch.Tensor,
response_lens: torch.Tensor,
pad_token_id: int,
mask_token_id: int | None = None,
max_response_len: int = 0,
) -> tuple[dict[str, torch.Tensor], torch.Tensor, int]:
if mask_token_id is not None:
return build_masked_gold_ce_batch(
batch=batch,
prompt_lens=prompt_lens,
response_lens=response_lens,
pad_token_id=pad_token_id,
mask_token_id=mask_token_id,
max_response_len=max_response_len,
)
batch_size = batch["input_ids"].shape[0]
device = batch["input_ids"].device
capped_response_lens = response_lens.clone()
if max_response_len > 0:
capped_response_lens = torch.clamp(capped_response_lens, max=max_response_len)
max_len = int((prompt_lens + capped_response_lens).max().item()) if batch_size > 0 else 0
packed_input_ids = torch.full(
(batch_size, max_len),
fill_value=pad_token_id,
dtype=batch["input_ids"].dtype,
device=device,
)
labels = torch.full((batch_size, max_len), fill_value=-100, dtype=batch["input_ids"].dtype, device=device)
masked_indices = torch.zeros((batch_size, max_len), dtype=torch.bool, device=device)
target_tokens = []
for batch_idx in range(batch_size):
prompt_len = int(prompt_lens[batch_idx].item())
response_len = int(capped_response_lens[batch_idx].item())
total_len = prompt_len + response_len
packed_input_ids[batch_idx, :prompt_len] = batch["input_ids"][batch_idx, :prompt_len]
if response_len > 0:
gold_response = batch["labels"][batch_idx, prompt_len : prompt_len + response_len]
packed_input_ids[batch_idx, prompt_len:total_len] = gold_response
labels[batch_idx, prompt_len:total_len] = gold_response
masked_indices[batch_idx, prompt_len:total_len] = True
target_tokens.append(gold_response)
result = {
"input_ids": packed_input_ids,
"labels": labels,
"masked_indices": masked_indices,
}
if "position_ids" in batch:
result["position_ids"] = batch["position_ids"][..., :max_len]
for key in ("pixel_values", "pixel_values_videos", "image_grid_thw", "video_grid_thw"):
if key in batch:
result[key] = batch[key]
return (
result,
torch.cat(target_tokens, dim=0) if target_tokens else packed_input_ids.new_empty((0,)),
int(capped_response_lens.sum().item()) if capped_response_lens.numel() > 0 else 0,
)
def build_masked_gold_ce_batch(
batch: dict[str, torch.Tensor],
prompt_lens: torch.Tensor,
response_lens: torch.Tensor,
pad_token_id: int,
mask_token_id: int,
max_response_len: int = 0,
) -> tuple[dict[str, torch.Tensor], torch.Tensor, int]:
batch_size = batch["input_ids"].shape[0]
device = batch["input_ids"].device
block_size = int(batch.get("block_size", 4))
capped_response_lens = response_lens.clone()
if max_response_len > 0:
capped_response_lens = torch.clamp(capped_response_lens, max=max_response_len)
max_len = int((prompt_lens + 2 * capped_response_lens).max().item()) if batch_size > 0 else 0
packed_input_ids = torch.full(
(batch_size, max_len),
fill_value=pad_token_id,
dtype=batch["input_ids"].dtype,
device=device,
)
labels = torch.full((batch_size, max_len), fill_value=-100, dtype=batch["input_ids"].dtype, device=device)
masked_indices = torch.zeros((batch_size, max_len), dtype=torch.bool, device=device)
attention_masks = []
target_tokens = []
packed_position_ids = None
if "position_ids" in batch:
batch_position_ids = batch["position_ids"]
if batch_position_ids.ndim == 3:
packed_position_ids = torch.zeros(
(batch_position_ids.shape[0], batch_size, max_len),
dtype=batch_position_ids.dtype,
device=device,
)
else:
packed_position_ids = torch.zeros(
(batch_size, max_len),
dtype=batch_position_ids.dtype,
device=device,
)
for batch_idx in range(batch_size):
prompt_len = int(prompt_lens[batch_idx].item())
response_len = int(capped_response_lens[batch_idx].item())
clean_start = prompt_len
clean_end = prompt_len + response_len
noisy_start = clean_end
total_len = prompt_len + 2 * response_len
packed_input_ids[batch_idx, :prompt_len] = batch["input_ids"][batch_idx, :prompt_len]
if response_len > 0:
gold_response = batch["labels"][batch_idx, prompt_len : prompt_len + response_len]
packed_input_ids[batch_idx, clean_start:clean_end] = gold_response
packed_input_ids[batch_idx, noisy_start:total_len] = mask_token_id
labels[batch_idx, noisy_start:total_len] = gold_response
masked_indices[batch_idx, noisy_start:total_len] = True
target_tokens.append(gold_response)
if packed_position_ids is not None:
sample_position_ids = slice_sample_position_ids(batch["position_ids"], batch_idx, prompt_len + response_len)
prompt_position_ids = sample_position_ids[..., :prompt_len]
clean_position_ids = sample_position_ids[..., prompt_len : prompt_len + response_len]
if packed_position_ids.ndim == 3:
packed_position_ids[:, batch_idx : batch_idx + 1, :prompt_len] = prompt_position_ids
packed_position_ids[:, batch_idx : batch_idx + 1, clean_start:clean_end] = clean_position_ids
packed_position_ids[:, batch_idx : batch_idx + 1, noisy_start:total_len] = clean_position_ids
else:
packed_position_ids[batch_idx : batch_idx + 1, :prompt_len] = prompt_position_ids
packed_position_ids[batch_idx : batch_idx + 1, clean_start:clean_end] = clean_position_ids
packed_position_ids[batch_idx : batch_idx + 1, noisy_start:total_len] = clean_position_ids
elif packed_position_ids is not None and prompt_len > 0:
sample_position_ids = slice_sample_position_ids(batch["position_ids"], batch_idx, prompt_len)
if packed_position_ids.ndim == 3:
packed_position_ids[:, batch_idx : batch_idx + 1, :prompt_len] = sample_position_ids
else:
packed_position_ids[batch_idx : batch_idx + 1, :prompt_len] = sample_position_ids
attention_masks.append(
create_attention_mask(
prefix_len=prompt_len,
response_len=response_len,
block_size=block_size,
max_len=max_len,
device=device,
)
)
result = {
"input_ids": packed_input_ids,
"labels": labels,
"masked_indices": masked_indices,
"attention_mask": torch.cat(attention_masks, dim=0),
"logits_to_keep": masked_indices,
}
if packed_position_ids is not None:
result["position_ids"] = packed_position_ids
for key in ("pixel_values", "pixel_values_videos", "image_grid_thw", "video_grid_thw"):
if key in batch:
result[key] = batch[key]
return (
result,
torch.cat(target_tokens, dim=0) if target_tokens else packed_input_ids.new_empty((0,)),
int(capped_response_lens.sum().item()) if capped_response_lens.numel() > 0 else 0,
)
def collect_gold_kd_indices(
prompt_lens: torch.Tensor,
response_lens: torch.Tensor,
) -> tuple[torch.Tensor | None, torch.Tensor | None, int]:
batch_indices = []
teacher_positions = []
total_tokens = 0
for batch_idx in range(prompt_lens.shape[0]):
prompt_len = int(prompt_lens[batch_idx].item())
response_len = int(response_lens[batch_idx].item())
if response_len <= 0:
continue
current_positions = torch.arange(
prompt_len - 1,
prompt_len + response_len - 1,
dtype=torch.long,
device=prompt_lens.device,
)
valid = current_positions >= 0
if not torch.any(valid):
continue
current_positions = current_positions[valid]
batch_indices.append(
torch.full(
(int(current_positions.shape[0]),),
fill_value=batch_idx,
dtype=torch.long,
device=prompt_lens.device,
)
)
teacher_positions.append(current_positions)
total_tokens += int(current_positions.shape[0])
if not batch_indices:
return None, None, 0
return torch.cat(batch_indices, dim=0), torch.cat(teacher_positions, dim=0), total_tokens
def compute_gold_losses(
student_model,
gold_ce_batch: dict | None,
gold_target_tokens: torch.Tensor | None,
gold_teacher_reply: dict | None = None,
topk_kd_loss: TopKKDLoss | None = None,
):
if gold_ce_batch is None or gold_target_tokens is None or gold_target_tokens.numel() == 0:
zero_source = gold_target_tokens
if zero_source is None:
first_param = next(student_model.parameters(), None)
if first_param is not None:
zero_source = first_param
else:
zero_source = torch.tensor(0.0)
zero = zero_source.new_tensor(0.0)
return zero, zero, 0
if "attention_mask" not in gold_ce_batch or "logits_to_keep" not in gold_ce_batch:
gold_ce_loss, gold_tokens = compute_gold_ce_loss(student_model, gold_ce_batch, gold_target_tokens)
zero = gold_ce_loss.new_tensor(0.0)
if gold_teacher_reply is not None:
raise ValueError("Gold KD requires a masked gold CE batch exposing `attention_mask` and `logits_to_keep`.")
return gold_ce_loss, zero, gold_tokens
base_model = student_model
while hasattr(base_model, "module"):
base_model = base_model.module
if not hasattr(base_model, "model") or not hasattr(base_model, "lm_head"):
raise AttributeError(
f"`compute_gold_losses` expects an unwrapped model exposing `.model` and `.lm_head`, got {type(base_model)}"
)
outputs = base_model.model(
input_ids=gold_ce_batch["input_ids"],
attention_mask=gold_ce_batch["attention_mask"],
position_ids=gold_ce_batch.get("position_ids", None),
pixel_values=gold_ce_batch.get("pixel_values", None),
pixel_values_videos=gold_ce_batch.get("pixel_values_videos", None),
image_grid_thw=gold_ce_batch.get("image_grid_thw", None),
video_grid_thw=gold_ce_batch.get("video_grid_thw", None),
use_cache=False,
)
hidden_states = outputs[0]
logits = base_model.lm_head(hidden_states[gold_ce_batch["logits_to_keep"]].contiguous())
target_tokens = gold_target_tokens.to(logits.device)
gold_ce_loss = F.cross_entropy(logits.float(), target_tokens.long())
gold_kd_loss = logits.new_tensor(0.0)
if gold_teacher_reply is not None:
if topk_kd_loss is None:
raise ValueError("`topk_kd_loss` is required when `gold_teacher_reply` is provided.")
teacher_topk_indices = gold_teacher_reply["teacher_topk_indices"].to(logits.device)
teacher_topk_logits = gold_teacher_reply["teacher_topk_logits"].to(logits.device)
if teacher_topk_indices.shape[0] != logits.shape[0]:
raise ValueError(
f"Gold KD token mismatch: student={int(logits.shape[0])}, teacher={int(teacher_topk_indices.shape[0])}."
)
gold_kd_loss = topk_kd_loss(
logits,
teacher_topk_indices=teacher_topk_indices,
teacher_topk_logits=teacher_topk_logits,
num_batch_labels=logits.shape[0],
)
return gold_ce_loss, gold_kd_loss, int(target_tokens.numel())
def compute_gold_ce_loss(student_model, gold_ce_batch: dict | None, gold_target_tokens: torch.Tensor | None):
if gold_ce_batch is None or gold_target_tokens is None or gold_target_tokens.numel() == 0:
zero_source = gold_target_tokens
if zero_source is None:
first_param = next(student_model.parameters(), None)
if first_param is not None:
zero_source = first_param
else:
zero_source = torch.tensor(0.0)
zero = zero_source.new_tensor(0.0)
return zero, 0
if "attention_mask" in gold_ce_batch and "logits_to_keep" in gold_ce_batch:
gold_ce_loss, _, gold_tokens = compute_gold_losses(
student_model=student_model,
gold_ce_batch=gold_ce_batch,
gold_target_tokens=gold_target_tokens,
)
return gold_ce_loss, gold_tokens
outputs = student_model(
input_ids=gold_ce_batch["input_ids"],
position_ids=gold_ce_batch.get("position_ids", None),
labels=gold_ce_batch["labels"],
masked_indices=gold_ce_batch["masked_indices"],
return_logits=True,
pixel_values=gold_ce_batch.get("pixel_values", None),
pixel_values_videos=gold_ce_batch.get("pixel_values_videos", None),
image_grid_thw=gold_ce_batch.get("image_grid_thw", None),
video_grid_thw=gold_ce_batch.get("video_grid_thw", None),
)
logits = outputs.logits
target_tokens = gold_target_tokens.to(logits.device)
gold_ce_loss = F.cross_entropy(logits.float(), target_tokens.long())
return gold_ce_loss, int(target_tokens.numel())
def log_rank0_generated_text(processor, item: dict, global_step: int, debug_config: SimpleNamespace):
if not debug_config.enabled or not debug_config.log_generated_text:
return
if global_step % max(debug_config.generated_text_every_steps, 1) != 0:
return
if "debug_prompt_input_ids" not in item or "debug_sampled_responses" not in item:
return
num_samples = min(
int(debug_config.generated_text_num_samples),
int(item["debug_sampled_responses"].shape[0]),
)
if num_samples <= 0:
return
sampled_responses = item["debug_sampled_responses"][:num_samples]
prompt_input_ids = item["debug_prompt_input_ids"][:num_samples]
prompt_lens = item["debug_prompt_lens"][:num_samples].tolist()
response_lens = item.get("debug_response_lens", None)
if response_lens is not None:
response_lens = response_lens[:num_samples].tolist()
trimmed_responses = []
for idx in range(num_samples):
current_response_len = int(sampled_responses.shape[1]) if response_lens is None else int(response_lens[idx])
trimmed_responses.append(sampled_responses[idx, :current_response_len])
max_response_len = max((response.shape[0] for response in trimmed_responses), default=0)
padded_responses = torch.full(
(num_samples, max_response_len),
fill_value=0,
dtype=sampled_responses.dtype,
)
for idx, response in enumerate(trimmed_responses):
if response.numel() > 0:
padded_responses[idx, : response.shape[0]] = response.cpu()
generated_texts = _decode_sequences(
processor,
padded_responses,
skip_special_tokens=debug_config.generated_text_skip_special_tokens,
)
if not generated_texts:
logger.info("step %s | debug text decode skipped because processor has no batch_decode()", global_step)
return
prompt_texts = []
if debug_config.log_prompt_text:
trimmed_prompts = [prompt_input_ids[idx, : int(prompt_lens[idx])] for idx in range(num_samples)]
max_prompt_len = max((prompt.shape[0] for prompt in trimmed_prompts), default=0)
padded_prompts = torch.full(
(num_samples, max_prompt_len),
fill_value=0,
dtype=prompt_input_ids.dtype,
)
for idx, prompt in enumerate(trimmed_prompts):
if prompt.numel() > 0:
padded_prompts[idx, : prompt.shape[0]] = prompt.cpu()
prompt_texts = _decode_sequences(
processor,
padded_prompts,
skip_special_tokens=debug_config.generated_text_skip_special_tokens,
)
for idx in range(num_samples):
if prompt_texts:
logger.info("step %s | rank0 sample %s | prompt: %s", global_step, idx, prompt_texts[idx])
logger.info("step %s | rank0 sample %s | generated: %s", global_step, idx, generated_texts[idx])
def build_topk_overlap_debug(
processor,
selected_student_logits: torch.Tensor,
teacher_topk_indices: torch.Tensor,
debug_config: SimpleNamespace,
target_tokens: torch.Tensor | None = None,
prompt_lengths: torch.Tensor | None = None,
response_positions: torch.Tensor | None = None,
teacher_positions: torch.Tensor | None = None,
):
if teacher_topk_indices.numel() == 0:
return None
overlap_k = min(
max(int(debug_config.topk_overlap_k), 1),
int(teacher_topk_indices.shape[-1]),
int(selected_student_logits.shape[-1]),
)
student_top_indices = torch.topk(selected_student_logits.float(), k=overlap_k, dim=-1).indices
teacher_top_indices = teacher_topk_indices[:, :overlap_k]
overlap_matrix = (student_top_indices.unsqueeze(-1) == teacher_top_indices.unsqueeze(-2)).any(dim=-1)
overlap_counts = overlap_matrix.sum(dim=-1)
overlap_ratio = overlap_counts.float() / float(overlap_k)
diagnostics = {
"topk_overlap_k": overlap_k,
"topk_overlap_mean": float(overlap_ratio.mean().item()),
}
sample_count = min(
max(int(debug_config.topk_overlap_num_samples), 0),
int(student_top_indices.shape[0]),
)
if sample_count <= 0:
return diagnostics
total_positions = int(student_top_indices.shape[0])
if sample_count >= total_positions:
sampled_indices = torch.arange(total_positions, device=student_top_indices.device)
else:
sampled_indices = torch.randperm(total_positions, device=student_top_indices.device)[:sample_count]
decode_enabled = bool(debug_config.generated_text_skip_special_tokens)
sample_entries = []
for sampled_idx in sampled_indices.tolist():
current_student = student_top_indices[sampled_idx]
current_teacher = teacher_top_indices[sampled_idx]
current_overlap = int(overlap_counts[sampled_idx].item())
student_decoded = _decode_token_ids(processor, current_student, skip_special_tokens=decode_enabled)
teacher_decoded = _decode_token_ids(processor, current_teacher, skip_special_tokens=decode_enabled)
student_items = [
_format_token_debug(
int(current_student[idx].item()),
student_decoded[idx] if idx < len(student_decoded) else None,
)
for idx in range(current_student.shape[0])
]
teacher_items = [
_format_token_debug(
int(current_teacher[idx].item()),
teacher_decoded[idx] if idx < len(teacher_decoded) else None,
)
for idx in range(current_teacher.shape[0])
]
sample_entries.append(
{
"sample_idx": sampled_idx,
"overlap_count": current_overlap,
"response_position": None
if response_positions is None
else int(response_positions[sampled_idx].item()),
"prompt_length": None
if prompt_lengths is None
else int(prompt_lengths[sampled_idx].item()),
"teacher_position": None
if teacher_positions is None
else int(teacher_positions[sampled_idx].item()),
"target_token": None if target_tokens is None else _format_token_debug(
int(target_tokens[sampled_idx].item()),
_decode_token_ids(
processor,