File size: 31,020 Bytes
e3cb0cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
# Disable parallelism in HuggingFace tokenizers to avoid fork-related warnings/deadlocks
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
import shutil
from functools import partial
import torch
from monet_qwen3_model.modeling_qwen3_vl_monet import Qwen3VLMonetForConditionalGeneration
from transformers import Qwen3VLConfig, AutoTokenizer, AutoProcessor
from PIL import Image
Image.MAX_IMAGE_PIXELS = None  # Raw dataset images can exceed PIL's decompression-bomb threshold.
import warnings
warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)
import logging
from tqdm import tqdm
from trl import SFTTrainer, SFTConfig
from qwen_vl_utils import process_vision_info
import torch.distributed as dist
from src.utils import *
from src.task import *
from src.trainer import *
import random
import wandb
from time import time
import pdb
seed_everything(seed=42)
args=get_args()

# Optional: enable anomaly detection when debugging in-place grad issues
if os.environ.get("TORCH_ANOMALY", "0") == "1":
    try:
        torch.autograd.set_detect_anomaly(True)
        logging.info("Enabled torch.autograd anomaly detection (TORCH_ANOMALY=1)")
    except Exception:
        pass

# DDP-friendly logging: only rank0 writes file
_rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", "0")))
_handlers = [logging.StreamHandler()]
if _rank == 0 and getattr(args, 'log_file', None):
    _handlers.insert(0, logging.FileHandler(args.log_file, mode='a', encoding='utf-8'))
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    handlers=_handlers,
)

logging.info('=='*20)
logging.info(args)
logging.info('=='*20)

# Load the model and processor

patch=14 # processor.image_processor.patch_size
# Use slow processor to avoid fast-processor info spam and behavioral drift
processor = AutoProcessor.from_pretrained(args.load_model_path, use_fast=True, trust_remote_code=True)

if _rank == 0:
    # Rewrite deprecated preprocessor.json into video_preprocessor.json by re-saving once
    try:
        processor.save_pretrained(args.load_model_path)
        if args.wandb_name is not None:
            wandb.init(project='Latent-Think',entity="Latent-Think",name=args.wandb_name,config={"ce_emphasize_factor":args.ce_emphasize_factor,"sft_analysis_ratio":args.sft_analysis_ratio})
    except Exception as _e:
        logging.debug(f"Processor save_pretrained skip: {_e}")

processor.tokenizer.add_tokens("<abs_vis_token_pad>", special_tokens=True)
processor.tokenizer.add_tokens("<abs_vis_token>", special_tokens=True)
processor.tokenizer.add_tokens("</abs_vis_token>", special_tokens=True)
processor.tokenizer.add_tokens("<observation>", special_tokens=True)
processor.tokenizer.add_tokens("</observation>", special_tokens=True)

config = Qwen3VLConfig.from_pretrained(args.load_model_path)

config.stage = args.stage
# Avoid `use_cache=True` with gradient checkpointing warnings; training doesn't need cache
config.use_cache = False
# The Stage-3 custom 4D attention mask (latent masking + the input-image curriculum mask)
# is only honored by sdpa/eager attention; flash_attention_2 ignores arbitrary 4D additive
# masks, which would silently disable the mask. Force sdpa so the mask takes effect (and so
# the flash-attn-less `monet` env loads cleanly).
config._attn_implementation = "sdpa"
# Some Qwen configs carry an unrecognized `loss_type=None` which triggers a warning; set explicitly
try:
    setattr(config, 'loss_type', 'ForCausalLMLoss')
except Exception:
    pass


# Prefer Trainer-managed device placement (DDP/Accelerate). Avoid device_map="auto" here.
# Enable TF32 for faster matmul on Ampere+ if available.
try:
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
except Exception:
    pass

# ---- Numerical stability: disable the cuDNN SDPA backend ----
# On Blackwell (B200, sm_100) PyTorch dispatches scaled_dot_product_attention to the
# cuDNN attention backend, whose bf16 BACKWARD kernel returns NaN gradients for the
# Monet latent forward (confirmed via torch.autograd anomaly detection:
# 'ScaledDotProductCudnnAttentionBackward0 returned nan values'). The NaN grads corrupt
# all parameters at the first optimizer step, so every subsequent step is NaN.
# Forcing the flash / mem-efficient / math SDPA backends keeps attention EXACT (no change
# to the training objective or any hyperparameter) while avoiding the buggy kernel.
if os.environ.get("MONET_DISABLE_CUDNN_SDP", "1") == "1":
    try:
        torch.backends.cuda.enable_cudnn_sdp(False)
        logging.info("Disabled cuDNN SDPA backend (B200 bf16 backward NaN workaround)")
    except Exception as _e:
        logging.warning(f"Could not disable cuDNN SDPA backend: {_e}")

model = Qwen3VLMonetForConditionalGeneration.from_pretrained(
    args.load_model_path,
    config=config,
    dtype=torch.bfloat16,
    attn_implementation="sdpa",
)

try:
    new_vocab_size = len(processor.tokenizer)
    model.resize_token_embeddings(new_vocab_size)
    model.config.vocab_size = new_vocab_size
    if hasattr(model.config, "text_config"):
        model.config.text_config.vocab_size = new_vocab_size
except Exception as e:
    logging.warning(f"resize_token_embeddings failed: {e}")

tokenizer = processor.tokenizer


latent_start_idx = processor.tokenizer("<abs_vis_token>", return_tensors="pt")["input_ids"][0]
latent_end_idx = processor.tokenizer("</abs_vis_token>", return_tensors="pt")["input_ids"][0]
latent_pad_idx = processor.tokenizer("<abs_vis_token_pad>", return_tensors="pt")["input_ids"][0]
observation_start_idx = processor.tokenizer("<observation>", return_tensors="pt")["input_ids"][0]
observation_end_idx = processor.tokenizer("</observation>", return_tensors="pt")["input_ids"][0]
end_pad_token_idx = processor.tokenizer("<|endoftext|>", return_tensors="pt")["input_ids"][0]
answer_start_pattern = processor.tokenizer("<|im_start|>assistant", return_tensors="pt")["input_ids"][0]
img_start_idx = processor.tokenizer("<|vision_start|>", return_tensors="pt")["input_ids"][0]
img_end_idx = processor.tokenizer("<|vision_end|>", return_tensors="pt")["input_ids"][0]
img_pad_idx = processor.tokenizer("<|image_pad|>", return_tensors="pt")["input_ids"][0]
SPECIAL_id = {
    "v_start": img_start_idx,
    "v_end": img_end_idx,
    "img_pad": img_pad_idx,
    "abs_start": latent_start_idx,
    "abs_end": latent_end_idx,
    "abs_pad": latent_pad_idx,
    "obs_start": observation_start_idx,
    "obs_end": observation_end_idx,
    "ans_start": answer_start_pattern
}

model.config.latent_token_id = int(latent_pad_idx)
model.config.latent_start_id = int(latent_start_idx)
model.config.latent_end_id = int(latent_end_idx)
model.config.answer_start_pattern = answer_start_pattern.tolist()

for param in model.visual.parameters():
    param.requires_grad = False


def collate_fn_sft_stage1(examples):
    # examples: list of {conversation: [...], sample_id: int}
    batch = {}
    batch['metadata'] = [ex['metadata'] for ex in examples]
    examples = [ex['data'] for ex in examples]
    texts = [processor.apply_chat_template(ex, tokenize=False) for ex in examples]

    # replace <abs_vis_token></abs_vis_token> with <|vision_start|><|image_pad|><|vision_end|> for each <|im_start|>assistant content
    texts = [replace_latent_placeholder_with_img_pad(text) for text in texts]
    #pdb.set_trace()
    ################################################
    # teacher
    ################################################
    image_inputs, _ = process_vision_info(examples)
    if args.image_resize == "global":
        image_inputs, new_sizes = resize_by_token_budget(image_inputs)
    elif args.image_resize == "clear_question_img":
        image_inputs, new_sizes = resize_diff(image_inputs) # resize_by_token_budget(image_inputs)
    teacher_texts = texts
    teacher_batch = processor(text=teacher_texts, images=image_inputs, return_tensors="pt", padding=True)
    total_image_pads = 0
    for txt in texts:
        total_image_pads += txt.count("<|image_pad|>")
    assert total_image_pads == len(image_inputs)
    batch['teacher_pixel_values'] = teacher_batch['pixel_values']
    batch['teacher_image_grid_thw'] = teacher_batch['image_grid_thw']
    batch['teacher_input_ids'] = teacher_batch['input_ids']
    batch['teacher_attention_mask'] = teacher_batch['attention_mask']

    observation_start_poss = find_ids_poss(batch["teacher_input_ids"], answer_start_pattern, observation_start_idx)
    observation_end_poss = find_ids_poss(batch["teacher_input_ids"], answer_start_pattern, observation_end_idx)
    batch["teacher_observation_poss"] = []
    assert len(observation_start_poss) == len(observation_end_poss)
    for start_poss, end_poss in zip(observation_start_poss, observation_end_poss):
        poss_of_a_sample = []
        if len(start_poss) > 0 and len(end_poss) > 0:
            assert len(start_poss) == len(end_poss), f"start_poss: {start_poss}, end_poss: {end_poss}"
            for start, end in zip(start_poss, end_poss):
                poss_of_a_sample.extend(list(range(start, end)))
        batch["teacher_observation_poss"].append(poss_of_a_sample)

    batch["teacher_labels"] = generate_labels_after_multi_token_start(batch["teacher_input_ids"], answer_start_pattern, ignore_ids=[end_pad_token_idx, img_pad_idx, img_start_idx, img_end_idx, observation_start_idx, observation_end_idx])
    return batch

def collate_fn_sft_stage2(examples):
    if _rank == 0:
        start_time = time()
    batch = {}
    metadata = [ex['metadata'] for ex in examples]
    examples = [ex['data'] for ex in examples]

    texts = [processor.apply_chat_template(ex, tokenize=False) for ex in examples]

    # replace `<abs_vis_token></abs_vis_token>`` with `<|vision_start|><|image_pad|><|vision_end|>`` for each `<|im_start|>assistant`` content
    texts = [replace_latent_placeholder_with_img_pad(text) for text in texts]

    # add `<abs_vis_token><abs_vis_token_pad>...</abs_vis_token>` after each `<|vision_start|><|image_pad|><|vision_end|>` for each `<|im_start|>assistant` content
    texts = add_latent_pad_after_auxiliary_img(texts, args.latent_size, "<abs_vis_token_pad>")

    image_inputs, _ = process_vision_info(examples)
    if args.image_resize == "global":
        image_inputs, new_sizes = resize_by_token_budget(image_inputs, global_max_pixels=args.sft_stage2_global_img_tokens*28*28, per_img_max_pixels=args.sft_stage2_per_img_tokens*28*28)
    elif args.image_resize == "clear_question_img":
        image_inputs, new_sizes = resize_diff(image_inputs)

    total_image_pads = 0
    for txt in texts:
        total_image_pads += txt.count("<|vision_start|><|image_pad|>")
    assert total_image_pads == len(image_inputs)
    batch = processor(text=texts, images=image_inputs, return_tensors="pt", padding=True)
    batch['metadata'] = metadata
    if not args.not_use_4d:
        attn_mask_4d, _ = build_4d_attn(
            input_ids=batch["input_ids"],
            pad_mask=batch["attention_mask"],
            token_ids=SPECIAL_id,
            not_mask_image=args.not_mask_image,
            mask_latent=args.mask_latent,
            observation_tokens_cannot_see_question_image=args.observation_tokens_cannot_see_question_image,
            observation_tokens_only_see_question_and_latent=args.observation_tokens_only_see_question_and_latent,
            latent_can_see_all_previous=args.latent_can_see_all_previous,
            return_type='bool',
            mask_question_image=args.mask_question_image
        )
        batch["attention_mask_4d"] = {"full_attention": attn_mask_4d }

    if args.sft_stage2_align_poss == 'latent_end':
        batch["latent_end_poss"] = find_ids_poss(batch["input_ids"], answer_start_pattern, latent_end_idx)

    if args.online_teacher:
        # Build a separate teacher batch matching `precompute_teacher_reps.collate_fn_precompute_teacher_rep`:
        # text gets only `replace_latent_placeholder_with_img_pad` (no latent-pad insertion),
        # and images use precompute's default budget (2000/1280) so pooled shapes match offline reps.
        teacher_texts = [processor.apply_chat_template(ex, tokenize=False) for ex in examples]
        teacher_texts = [replace_latent_placeholder_with_img_pad(text) for text in teacher_texts]
        teacher_image_inputs, _ = process_vision_info(examples)
        if args.image_resize == "global":
            teacher_image_inputs, _ = resize_by_token_budget(teacher_image_inputs)
        elif args.image_resize == "clear_question":
            # Mirror src/precompute_teacher_reps.py:131 verbatim — that file checks the
            # string "clear_question" (no _img), which never matches the argparser's
            # only valid "clear_question_img" choice, so offline silently skips resize.
            # We match the (buggy) offline behavior here to preserve parity; fix in
            # both files together if/when the typo is corrected.
            teacher_image_inputs, _ = resize_diff(teacher_image_inputs)
        teacher_batch = processor(text=teacher_texts, images=teacher_image_inputs,
                                  return_tensors="pt", padding=True)
        batch["teacher_input_ids"] = teacher_batch["input_ids"]
        batch["teacher_attention_mask"] = teacher_batch["attention_mask"]
        batch["teacher_pixel_values"] = teacher_batch["pixel_values"]
        batch["teacher_image_grid_thw"] = teacher_batch["image_grid_thw"]
        batch["teacher_aux_image_blocks"] = [
            find_aux_image_token_blocks(batch["teacher_input_ids"][b], SPECIAL_id)
            for b in range(batch["teacher_input_ids"].size(0))
        ]

    if args.allow_no_observation:
        batch["latent_pad_poss"] = find_ids_poss(batch["input_ids"], answer_start_pattern, latent_pad_idx)
        batch["observation_poss"] = [[] for _ in range(batch["input_ids"].size(0))]
    else:
        observation_start_poss = find_ids_poss(batch["input_ids"], answer_start_pattern, observation_start_idx)
        observation_end_poss = find_ids_poss(batch["input_ids"], answer_start_pattern, observation_end_idx)
        batch["observation_poss"] = []
        assert len(observation_start_poss) == len(observation_end_poss)
        for start_poss, end_poss in zip(observation_start_poss, observation_end_poss):
            poss_of_a_sample = []
            if len(start_poss) > 0 and len(end_poss) > 0:
                assert len(start_poss) == len(end_poss), f"start_poss: {start_poss}, end_poss: {end_poss}"
                for start, end in zip(start_poss, end_poss):
                    poss_of_a_sample.extend(list(range(start, end)))
            batch["observation_poss"].append(poss_of_a_sample)

    if args.only_predict_obs:
        batch["labels"] = generate_labels_after_multi_token_start_only_allow(batch["input_ids"], answer_start_pattern, allowed_poss=batch["observation_poss"])
    else:
        batch["labels"] = generate_labels_after_multi_token_start(batch["input_ids"], answer_start_pattern, ignore_ids=[end_pad_token_idx,
        latent_pad_idx, latent_end_idx, img_pad_idx, img_start_idx, img_end_idx, observation_start_idx, observation_end_idx])

    return batch

def collate_fn_sft_stage3(examples, alignment="boxed_start"):
    # Support wrapped examples providing sample_id
    batch = {}
    batch['metadata'] = [ex['metadata'] for ex in examples]
    examples = [ex['data'] for ex in examples]
    batch_user_img_cnts = [sum(1 for step in examples[i][1]['content'] if step["type"] == "image") for i in range(len(examples))]
    batch_assistant_img_cnts = [sum(1 for step in examples[i][2]['content'] if step["type"] == "image") for i in range(len(examples))]
    texts = [processor.apply_chat_template(ex, tokenize=False) for ex in examples]

    # replace <abs_vis_token></abs_vis_token> with <|vision_start|><|image_pad|><|vision_end|> for each <|im_start|>assistant content
    texts = [replace_latent_placeholder_with_img_pad(text) for text in texts]
    image_inputs, _ = process_vision_info(examples)
    image_inputs, new_sizes = resize_by_token_budget(image_inputs, global_max_pixels=args.sft_stage3_img_tokens*28*28, per_img_max_pixels=args.sft_stage3_img_tokens*28*28,)

    ################################################
    # student
    ################################################
    # replace <|vision_start|><|image_pad|><|vision_end|> with <abs_vis_token><abs_vis_token_pad>...</abs_vis_token> for each <|im_start|>assistant content
    student_texts = replace_img_pad_with_latent_pad(texts, args.latent_size, "<abs_vis_token_pad>")
    user_examples = remove_auxiliary_images(examples)
    user_image_inputs, _ = process_vision_info(user_examples)
    resize_ptr = 0
    b_ptr = 0
    usr_img_cnt_accum = 0
    if new_sizes is not None:
        for i, img in enumerate(user_image_inputs):
            img = img.resize(new_sizes[resize_ptr], Image.BICUBIC)
            user_image_inputs[i] = img
            resize_ptr += 1
            usr_img_cnt_accum += 1
            if usr_img_cnt_accum == batch_user_img_cnts[b_ptr]:
                resize_ptr += batch_assistant_img_cnts[b_ptr] # user_image_inputs only contain question images of each batch sample, so we need to skip the helper images in the new_sizes by adding batch_assistant_img_cnts[i]
                b_ptr += 1
                usr_img_cnt_accum = 0
    student_batch = processor(text=student_texts, images=user_image_inputs, return_tensors="pt", padding=True)
    total_image_pads = 0
    for txt in student_texts:
        total_image_pads += txt.count("<|image_pad|>")
    assert total_image_pads == len(user_image_inputs)
    batch['student_pixel_values'] = student_batch['pixel_values']
    batch['student_image_grid_thw'] = student_batch['image_grid_thw']
    batch["student_input_ids"] = student_batch["input_ids"]
    batch["student_attention_mask"] = student_batch["attention_mask"]

    # Input-image attention mask: OFF BY DEFAULT. With the defaults
    # (--stage3_input_img_mask_ratio == 0.0 and --stage3_img_mask_curriculum not set), the only
    # thing that can trigger the 4D mask is the pre-existing --mask_latent, and the input-image
    # mask ratio passed below is 0.0 -> apply_input_img_attn_mask is a no-op. So by default this
    # block reproduces the original Monet behavior (no input-image masking). The two paths below
    # fire ONLY when one of those flags is explicitly opted into:
    #   - STATIC (curriculum off): sample the effective ratio per batch from
    #     [0, stage3_input_img_mask_ratio] here, so the training distribution smoothly covers
    #     ratio=0 (matches inference) up to the max (forces latent use).
    #   - CURRICULUM (--stage3_img_mask_curriculum): build only the BASE mask here (ratio=0);
    #     the trainer applies the per-step decayed ratio, since collate (a dataloader worker)
    #     cannot see global_step. Final steps decay to ratio=0 -> match inference exactly.
    max_img_mask_ratio = getattr(args, 'stage3_input_img_mask_ratio', 0.0)  # default 0.0 -> off
    curriculum = getattr(args, 'stage3_img_mask_curriculum', False)         # default False -> off
    if args.mask_latent or max_img_mask_ratio > 0 or curriculum:
        if curriculum:
            effective_img_mask_ratio = 0.0  # applied per-step in the trainer
        elif max_img_mask_ratio > 0:
            effective_img_mask_ratio = random.uniform(0.0, max_img_mask_ratio)
        else:
            effective_img_mask_ratio = 0.0
        attn_mask_4d = build_4d_attn_wo_helper_images(
            input_ids=batch["student_input_ids"],
            pad_mask=batch["student_attention_mask"],
            token_ids=SPECIAL_id,
            mask_latent=getattr(args, 'mask_latent', False),
            input_img_mask_ratio=effective_img_mask_ratio,
        )
        batch["student_attention_mask_4d"] = {"full_attention": attn_mask_4d }

    batch["student_alignment_poss"] = find_ids_poss(batch["student_input_ids"], answer_start_pattern, latent_pad_idx)

    if args.online_teacher:
        # Build a separate teacher batch matching `precompute_teacher_latents.collate_fn_precompute_teacher_latents`:
        # Stage-2-style text (aux image present + latent pads after each aux), and images use
        # precompute's per-latents budget (1000/500) so latent shapes match offline files.
        teacher_texts = add_latent_pad_after_auxiliary_img(texts, args.latent_size, "<abs_vis_token_pad>")
        teacher_image_inputs, _ = process_vision_info(examples)
        if args.image_resize == "global":
            teacher_image_inputs, _ = resize_by_token_budget(
                teacher_image_inputs,
                global_max_pixels=1000 * 28 * 28,
                per_img_max_pixels=500 * 28 * 28,
            )
        elif args.image_resize == "clear_question_img":
            teacher_image_inputs, _ = resize_diff(teacher_image_inputs)
        teacher_batch = processor(text=teacher_texts, images=teacher_image_inputs,
                                  return_tensors="pt", padding=True)
        batch["teacher_input_ids"] = teacher_batch["input_ids"]
        batch["teacher_attention_mask"] = teacher_batch["attention_mask"]
        batch["teacher_pixel_values"] = teacher_batch["pixel_values"]
        batch["teacher_image_grid_thw"] = teacher_batch["image_grid_thw"]
        if not args.not_use_4d:
            teacher_attn_mask_4d, _ = build_4d_attn(
                input_ids=teacher_batch["input_ids"],
                pad_mask=teacher_batch["attention_mask"],
                token_ids=SPECIAL_id,
                not_mask_image=args.not_mask_image,
                mask_latent=args.mask_latent,
                observation_tokens_cannot_see_question_image=args.observation_tokens_cannot_see_question_image,
                observation_tokens_only_see_question_and_latent=args.observation_tokens_only_see_question_and_latent,
                latent_can_see_all_previous=args.latent_can_see_all_previous,
                return_type='bool',
                mask_question_image=args.mask_question_image,
            )
            batch["teacher_attention_mask_4d"] = {"full_attention": teacher_attn_mask_4d}

    if args.allow_no_observation:
        batch["observation_poss"] = [[] for _ in range(batch["student_input_ids"].size(0))]
    else:
        observation_start_poss = find_ids_poss(batch["student_input_ids"], answer_start_pattern, observation_start_idx)
        observation_end_poss = find_ids_poss(batch["student_input_ids"], answer_start_pattern, observation_end_idx)
        batch["observation_poss"] = []
        assert len(observation_start_poss) == len(observation_end_poss)
        for start_poss, end_poss in zip(observation_start_poss, observation_end_poss):
            poss_of_a_sample = []
            if len(start_poss) > 0 and len(end_poss) > 0:
                assert len(start_poss) == len(end_poss), f"start_poss: {start_poss}, end_poss: {end_poss}"
                for start, end in zip(start_poss, end_poss):
                    poss_of_a_sample.extend(list(range(start+1, end)))
            batch["observation_poss"].append(poss_of_a_sample)

    # mask tokens of '<|im_start|>assistant', '<|endoftext|>', and '<abs_vis_token_pad>'
    batch["student_labels"] = generate_labels_after_multi_token_start(batch["student_input_ids"], answer_start_pattern, ignore_ids=[img_pad_idx, img_start_idx, img_end_idx, end_pad_token_idx, latent_pad_idx, latent_end_idx, observation_start_idx, observation_end_idx])

    return batch


preprocess_function = task_preporcess_config[args.task]
all_train_dataset = []
for data_path in args.data_path:
    if data_path.endswith('.jsonl'):
        train_dataset = load_jsonl_dataset(data_path)
    elif data_path.endswith('.json'):
        train_dataset = load_json_dataset(data_path)
    all_train_dataset.extend(train_dataset[:])
if args.shuffle_train:
    random.seed(42)
    random.shuffle(all_train_dataset)

train_dataset = []
cur_max = -1
for i, sample in tqdm(enumerate(all_train_dataset[:]), desc="Collecting training data and length check...", total=len(all_train_dataset)):
    processed = preprocess_function(sample, dataset_root=args.dataset_root, allow_no_observation=args.allow_no_observation)
    if processed is not None:
        train_dataset.append(processed)

#train_dataset = [d for d in [preprocess_function(sample) for sample in all_train_dataset[:]] if d is not None]


dataset_names = ""
for data_path in args.data_path:
    dataset_name = data_path.split("/")[-2]
    dataset_names += f"-{dataset_name}"


save_dir = args.save_model_path

if args.stage == 'sft_stage1':
    CustomTrainer = CustomTrainerSFT_STAGE1
    collate_fn = partial(collate_fn_sft_stage1)
elif args.stage == 'sft_stage2':
    CustomTrainer = CustomTrainerSFT_STAGE2
    collate_fn = partial(collate_fn_sft_stage2)
elif args.stage == 'sft_stage3':
    CustomTrainer = CustomTrainerSFT_STAGE3
    collate_fn = partial(collate_fn_sft_stage3)

if args.deepspeed != "":
    print(f"Note: DeepSpeed is enabled. Using the deepspeed config in {args.deepspeed} (the bsz per device and gradient_accumulation_steps will be adopted from the deepspeed config)")
is_parallel = int(os.environ.get("WORLD_SIZE", "1")) > 1
gradient_checkpointing = True


training_args = SFTConfig(
    output_dir=save_dir,
    num_train_epochs=args.epochs,
    max_steps=args.max_steps,
    per_device_train_batch_size=args.bsz,
    gradient_accumulation_steps=args.grad_accum_steps,
    # Ratio (not absolute steps) so warmup scales with total_steps across data sizes (40k..500k).
    # Absolute warmup_steps=10 was ~1.6% of a 40k run but only ~0.27% of a 500k run (effectively no warmup).
    warmup_ratio=0.03,
    learning_rate=args.lr,
    lr_scheduler_type=args.lr_scheduler_type,
    weight_decay=args.weight_decay,
    logging_steps=args.log_freq,
    save_strategy="steps",
    save_steps=args.save_freq,
    save_total_limit=30,
    save_only_model=True,  # skip optimizer save (CPU-offload gather OOMs the SLURM cgroup at save)
    optim="adamw_torch_fused",
    bf16=True,
    push_to_hub=False,
    remove_unused_columns=False,
    gradient_checkpointing=gradient_checkpointing,
    dataset_text_field="",
    dataset_kwargs={"skip_prepare_dataset": True},
    report_to=['wandb'] if args.wandb_name is not None else [],
    logging_dir='./logs/',
    logging_strategy='steps',
    # Avoid FLOPs estimation logs (set to False through env if needed)
    disable_tqdm=False,
    # DDP related
    ddp_backend="nccl" if is_parallel else None,
    ddp_find_unused_parameters=False if is_parallel else None,
    dataloader_num_workers=4 if is_parallel else 0,
    dataloader_pin_memory=True,
    # Save only on global rank 0 when running multi-node
    save_on_each_node=False,
    # DeepSpeed config (if provided via --deepspeed)
    deepspeed=(args.deepspeed if getattr(args, 'deepspeed', '') else None),
)

# ---- Inject custom SFT analysis flags into training_args so CustomTrainerSFT can access them ----
if args.stage == 'sft_stage1':
    setattr(training_args, 'ce_emphasize_factor', args.ce_emphasize_factor)
    setattr(training_args, 'teacher_reps_dir', args.teacher_reps_dir)
elif args.stage in ['sft_stage2','sft_stage3']:
    setattr(training_args, 'ce_emphasize_factor', args.ce_emphasize_factor)
    setattr(training_args, 'alignment_layer', args.alignment_layer)
    setattr(training_args, 'alignment_weight', args.alignment_weight)
    setattr(training_args, 'gradient_checkpointing_kwargs', {"use_reentrant": False})
    setattr(training_args, 'latent_size', args.latent_size)
    setattr(training_args, 'emphasize_latent_weight', args.emphasize_latent_weight)
    setattr(training_args, 'teacher_reps_dir', args.teacher_reps_dir)
    setattr(training_args, 'teacher_latent_dir', args.teacher_latent_dir)
    setattr(training_args, 'image_resize', args.image_resize)
    setattr(training_args, 'sft_stage2_align_poss', args.sft_stage2_align_poss)
    # Stage-3 input-image attention-mask curriculum (applied per-step in the trainer).
    setattr(training_args, 'stage3_img_mask_curriculum', getattr(args, 'stage3_img_mask_curriculum', False))
    setattr(training_args, 'stage3_img_mask_start', getattr(args, 'stage3_img_mask_start', 0.7))
    setattr(training_args, 'stage3_img_mask_end', getattr(args, 'stage3_img_mask_end', 0.0))
    setattr(training_args, 'stage3_img_mask_schedule', getattr(args, 'stage3_img_mask_schedule', 'linear'))
    setattr(training_args, 'special_token_ids', SPECIAL_id)

# Optional in-process teacher to skip the offline export step.
# When unset, the trainer falls back to `load_offline_tensor` exactly as before.
online_teacher = None
if args.online_teacher:
    if args.stage == 'sft_stage1':
        raise ValueError("--online_teacher is only meaningful for sft_stage2 / sft_stage3")
    if not args.online_teacher_model_path:
        raise ValueError("--online_teacher requires --online_teacher_model_path")

    from src.online_teacher import OnlineTeacherStage2, OnlineTeacherStage3

    _local_rank = int(os.environ.get("LOCAL_RANK", os.environ.get("RANK", "0")))
    if torch.cuda.is_available():
        try:
            torch.cuda.set_device(_local_rank)
        except Exception:
            pass
        _teacher_device = torch.device(f"cuda:{_local_rank}")
    else:
        _teacher_device = torch.device("cpu")

    if args.stage == 'sft_stage2':
        # Cache dir reuses --teacher_reps_dir (same filename layout as offline Step 1).
        online_teacher = OnlineTeacherStage2(
            model_path=args.online_teacher_model_path,
            tokenizer_len=len(processor.tokenizer),
            special_token_ids=SPECIAL_id,
            device=_teacher_device,
            dtype=torch.bfloat16,
            cache_dir=args.teacher_reps_dir,
            answer_start_pattern=answer_start_pattern,
            alignment_layer=args.alignment_layer,
            latent_size=args.latent_size,
        )
    else:  # sft_stage3
        # Cache dir reuses --teacher_latent_dir (same filename layout as offline Step 3).
        online_teacher = OnlineTeacherStage3(
            model_path=args.online_teacher_model_path,
            tokenizer_len=len(processor.tokenizer),
            special_token_ids=SPECIAL_id,
            device=_teacher_device,
            dtype=torch.bfloat16,
            cache_dir=args.teacher_latent_dir,
            answer_start_pattern=answer_start_pattern,
            alignment_layer=args.alignment_layer,
        )

# Initialize the trainer (callbacks that need trainer instance will be added after)
trainer = CustomTrainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    data_collator=collate_fn,
    processing_class=processor,
    exp_name=args.save_model_path.split('/')[-1],
    online_teacher=online_teacher,
)


trainer.train(resume_from_checkpoint=args.resume_from_checkpoint)
trainer.save_model(training_args.output_dir)