File size: 24,032 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
from trl import SFTTrainer, SFTConfig
from typing import Optional
import logging
import torch
import os, csv, torch, datetime
import gc
import numpy as np
import math
from time import time
from src.utils import apply_input_img_attn_mask

def compute_latents_only_loss(latents, loss_for_latents):
    '''
    Compute a loss (`loss_for_latents`) that backpropagates only through the latent embeddings `latents`.
    '''
    def _flatten_tensors(x):
                # Flatten nested [list/tuple of Tensors] into a flat list of Tensors
                if isinstance(x, (list, tuple)):
                    out = []
                    for y in x:
                        out.extend(_flatten_tensors(y))
                    return out
                return [x]

    ce_vec_list = _flatten_tensors(latents)
    grads = torch.autograd.grad(
        outputs=loss_for_latents,
        inputs=ce_vec_list,
        retain_graph=True,   # we won't reuse the 3rd graph
        create_graph=False,   # stop higher-order graph
        allow_unused=True     # in case some ce vectors are not used
    )

    # Replace None with zeros for unused elements
    safe_grads = []
    for v, g in zip(ce_vec_list, grads):
        if g is None:
            # Create a zero tensor on the same device/dtype/shape
            g = torch.zeros_like(v)
        safe_grads.append(g.detach())  # detach to stop any 3rd-forward param pathg

    proxy_loss = torch.stack([(v * g).sum() for v, g in zip(ce_vec_list, safe_grads)]).sum()
    return proxy_loss

def load_offline_tensor(tensor_dir, batch_metadata, alignment_layer="all_layers", rep_type="rep", align_poss="obs"):
    '''
    Load precomputed teacher representations (observation tokens for the alignment in SFT stage 2 or the latent embeddings for SFT stage 3)
    '''
    teacher_reps = None
    latents_list = []
    for metadata in batch_metadata:
        dataset_name = metadata['dataset_name']
        sample_id = metadata['sample_id']
        metadata_info = f"{alignment_layer}_{dataset_name}_{sample_id}"
        if align_poss == 'obs':
            metadata_str = f"{rep_type}_{metadata_info}.pt"
        elif align_poss == 'latent_end':
            metadata_str = f"{rep_type}_latent_end_{metadata_info}.pt"
        path = os.path.join(tensor_dir, metadata_str)
        if not os.path.isfile(path):
            latents_list = []
            raise RuntimeError(f"Missing teacher latent file: {path}")
        data = torch.load(path, map_location='cpu')
        latents_list.append(data['latent'].detach())
    if batch_metadata is not None and len(latents_list) == len(batch_metadata):
        teacher_reps = latents_list
    return teacher_reps


class CustomTrainerSFT_STAGE1(SFTTrainer):
    def __init__(self, *args, **kwargs):
        self.exp_name =kwargs.pop('exp_name')
        kwargs.pop('online_teacher', None)  # accepted for symmetry; unused in stage 1
        # accept processing_class (preferred) and fall back to tokenizer for backward compat
        if 'processing_class' not in kwargs and 'tokenizer' in kwargs:
            kwargs['processing_class'] = kwargs.pop('tokenizer')
        super().__init__(*args, **kwargs)
        self.observation_token_acc = 0.
        self.observation_token_acc_step = 0
        self.teacher_ce_cum = 0.0        # cumulative student CE loss
        self.teacher_ce_steps = 0

    def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
        """
        Compute training loss and additionally compute token accuracies
        """
        inputs['latent_mode'] = False
        inputs['input_ids'] = inputs['teacher_input_ids']
        inputs['attention_mask'] = inputs['teacher_attention_mask']
        inputs['pixel_values'] = inputs['teacher_pixel_values']
        inputs['image_grid_thw'] = inputs['teacher_image_grid_thw']
        inputs['labels'] = inputs['teacher_labels']
        inputs['ce_emphasize_poss'] = inputs['teacher_observation_poss']
        # Dynamic warmup factor passed to model.forward
        inputs['ce_emphasize_factor'] = self.args.ce_emphasize_factor
        inputs['loss_type'] = ['ce']
        inputs['compute_emphasize_acc'] = True
        (teacher_ce_loss, teacher_outputs) = super().compute_loss(
                model,
                inputs,
                return_outputs=True, num_items_in_batch=num_items_in_batch
            )

        self.teacher_ce_cum += teacher_ce_loss.item()
        self.teacher_ce_steps += 1

        if getattr(teacher_outputs, 'mean_emphasize_acc', None) is not None:
            self.observation_token_acc += getattr(teacher_outputs, 'mean_emphasize_acc')
            self.observation_token_acc_step += 1

        del teacher_outputs
        gc.collect()
        torch.cuda.empty_cache()

        return (teacher_ce_loss, None) if return_outputs else teacher_ce_loss

    def on_epoch_end(self):
        return super().on_epoch_end()

    def log(self, logs: dict, start_time: float | None = None):
        # Merge our rolling averages into the standard logs once per logging call
        merged = dict(logs)
        if self.teacher_ce_steps > 0:
            merged["student_ce_loss"] = round(self.teacher_ce_cum / max(1, self.teacher_ce_steps), 6)
            self.teacher_ce_cum = 0.0
            self.teacher_ce_steps = 0
        if self.observation_token_acc_step > 0:
            merged["observation_token_acc"] = round(self.observation_token_acc/ max(1, self.observation_token_acc_step), 6)
            self.observation_token_acc = 0.
            self.observation_token_acc_step = 0

        # Call parent to keep default behavior (console/TB/W&B/etc.)
        return super().log(merged, start_time)



class CustomTrainerSFT_STAGE2(SFTTrainer):
    def __init__(self, *args, **kwargs):
        self.exp_name = kwargs.pop('exp_name')
        self.online_teacher = kwargs.pop('online_teacher', None)
        # accept processing_class (preferred) and fall back to tokenizer for backward compat
        if 'processing_class' not in kwargs and 'tokenizer' in kwargs:
            kwargs['processing_class'] = kwargs.pop('tokenizer')
        super().__init__(*args, **kwargs)

        self.ce_emphasize_factor = self.args.ce_emphasize_factor
        self.teacher_ce_loss_cum = 0.0        # cumulative teacher CE loss
        self.teacher_ce_loss_steps = 0
        self.observation_token_acc = 0.
        self.observation_token_acc_step = 0
        self.alignment_loss_cum = 0.
        self.alignment_loss_steps = 0


    def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
        """
        Compute training loss and additionally compute token accuracies
        """
        # ------------------------------------------------------------------
        # Latent forward to get ce_patch_pos (positions of latent embeddings) and ce_patch_vec (latent embeddings).
        # Multiple forward is needed since we need to autoregressively generate latents.
        # ------------------------------------------------------------------
        inputs['latent_mode'] = True
        inputs['loss_type'] = []
        model.gradient_checkpointing_disable() # since we set use_cache=True in latent forward, we must disable grad checkpointing
        outputs = model(**inputs, return_dict=True, output_hidden_states=False)

        # ------------------------------------------------------------------
        # Insert the collected latent embeddings into the latent positions, and forward once.
        # ------------------------------------------------------------------
        model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
        inputs['latent_mode'] = False
        inputs['ce_patch_pos'] = outputs.ce_patch_pos
        inputs['ce_patch_vec'] = outputs.ce_patch_vec
        no_text_mode = 'latent_pad_poss' in inputs
        inputs['ce_emphasize_poss'] = [] if no_text_mode else inputs['observation_poss']
        inputs['ce_emphasize_factor'] = self.ce_emphasize_factor
        inputs['loss_type'] = ['ce']
        if self.args.alignment_weight != 0:
            inputs['loss_type'].append('alignment')

        inputs['compute_emphasize_acc'] = False if no_text_mode else True
        # Ensure training forward does NOT request attentions (prevents checkpoint recompute mismatch)
        inputs.pop('output_attentions', None)
        inputs.pop('attn_analysis', None)

        if self.args.alignment_weight != 0:
            # Teacher representations: in-process when --online_teacher is set, otherwise from disk.
            # Both paths return list[CPU Tensor [L+1, N*latent_size, D]] with the same content.
            if self.online_teacher is not None:
                teacher_reps = self.online_teacher(inputs)
            else:
                teacher_reps = load_offline_tensor(
                    self.args.teacher_reps_dir,
                    batch_metadata=inputs['metadata'],
                    alignment_layer=self.args.alignment_layer,
                )
            inputs['alignment_poss'] = inputs['latent_pad_poss'] if no_text_mode else inputs['observation_poss']

            inputs['teacher_hidden_states_for_alignment'] = teacher_reps

        teacher_ce_loss, teacher_output = super().compute_loss(
                model,
                inputs,
                return_outputs=True, num_items_in_batch=num_items_in_batch
            )

        alignment_loss = teacher_output.loss_dict.get('alignment', torch.tensor(0.0))
        if self.args.emphasize_latent_weight != 0.0 and alignment_loss.item() != 0.0: # latent-only backpropagation for alignment loss
            latent_only_loss = compute_latents_only_loss(outputs.ce_patch_vec, self.args.alignment_weight * alignment_loss)
            loss = self.args.emphasize_latent_weight * latent_only_loss + teacher_ce_loss
        else:
            loss = teacher_ce_loss + self.args.alignment_weight * alignment_loss

        if getattr(teacher_output, 'mean_emphasize_acc', None) is not None:
            self.observation_token_acc += getattr(teacher_output, 'mean_emphasize_acc')
            self.observation_token_acc_step += 1

        self.teacher_ce_loss_cum += teacher_ce_loss.item()
        self.teacher_ce_loss_steps += 1
        self.alignment_loss_cum += alignment_loss.item()
        self.alignment_loss_steps += 1

        # Light-touch cleanup without forcing GPU sync every step
        #del teacher_outputs
        step = int(getattr(self.state, 'global_step', 0) or 0)
        if step % 50 == 0:
            try:
                gc.collect()
                # Avoid calling empty_cache() each step
                torch.cuda.empty_cache()
            except Exception:
                pass

        return (loss, None) if return_outputs else loss


    def on_epoch_end(self):
        return super().on_epoch_end()

    def log(self, logs: dict, start_time: float | None = None):
        # Merge our rolling averages into the standard logs once per logging call
        merged = dict(logs)
        if self.teacher_ce_loss_cum > 0:
            merged["teacher_ce_loss"] = round(self.teacher_ce_loss_cum / max(1, self.teacher_ce_loss_steps), 6)
            self.teacher_ce_loss_cum = 0.0
            self.teacher_ce_loss_steps = 0
        if self.alignment_loss_cum > 0:
            merged[f'alignment_loss'] = round(self.alignment_loss_cum / max(1, self.alignment_loss_steps), 6)
            self.alignment_loss_cum = 0.0
            self.alignment_loss_steps = 0
        if self.observation_token_acc_step > 0:
            merged["observation_token_acc"] = round(self.observation_token_acc/ max(1, self.observation_token_acc_step), 6)
            self.observation_token_acc = 0.
            self.observation_token_acc_step = 0


        # Call parent to keep default behavior (console/TB/W&B/etc.)
        return super().log(merged, start_time)

class CustomTrainerSFT_STAGE3(SFTTrainer):
    def __init__(self, *args, **kwargs):
        self.exp_name =kwargs.pop('exp_name')
        self.online_teacher = kwargs.pop('online_teacher', None)
        super().__init__(*args, **kwargs)
        self.alignment_weight = self.args.alignment_weight
        self.ce_emphasize_factor: float = float(getattr(self.args, 'ce_emphasize_factor', 1.0))
        # Where to read precomputed teacher latents (also reused as the online cache dir)
        self.teacher_latent_dir = getattr(self.args, 'teacher_latent_dir', None)
        if self.online_teacher is None and not self.teacher_latent_dir:
            raise ValueError("teacher_latent_dir must be specified for offline SFT Stage 3")

        self.observation_token_acc = 0.
        self.observation_token_acc_step = 0
        self.al_loss_cum = 0.0       # cumulative alignment loss since last log
        self.al_steps = 0            # number of micro-steps accumulated
        self.student_ce_loss_cum = 0.0        # cumulative student CE loss
        self.student_ce_loss_steps = 0

        # ---- Stage-3 input-image attention-mask curriculum ----
        # OFF BY DEFAULT: img_mask_curriculum defaults to False, so the per-step masking block in
        # compute_loss is skipped entirely and training matches the original Monet (no mask).
        # When enabled, decay the answer->input-image masking ratio from `start` to `end` over
        # training so the final steps match inference (where the model sees the full input image).
        # Applied here (not in collate) because only the trainer sees global_step / max_steps.
        self.img_mask_curriculum = bool(getattr(self.args, 'stage3_img_mask_curriculum', False))
        self.img_mask_start = float(getattr(self.args, 'stage3_img_mask_start', 0.7))
        self.img_mask_end = float(getattr(self.args, 'stage3_img_mask_end', 0.0))
        self.img_mask_schedule = str(getattr(self.args, 'stage3_img_mask_schedule', 'linear'))
        self.special_token_ids = getattr(self.args, 'special_token_ids', None)
        self._cur_img_mask_ratio = 0.0  # last applied ratio, for logging
        if self.img_mask_curriculum and self.special_token_ids is None:
            raise ValueError("stage3_img_mask_curriculum requires special_token_ids on training_args")

    def _curriculum_img_mask_ratio(self) -> float:
        """Ratio for the current optimizer step: start -> end as global_step -> max_steps."""
        max_steps = float(getattr(self.state, 'max_steps', 0) or 0)
        step = float(getattr(self.state, 'global_step', 0) or 0)
        progress = min(1.0, max(0.0, step / max_steps)) if max_steps > 0 else 0.0
        if self.img_mask_schedule == 'cosine':
            frac = 0.5 * (1.0 + math.cos(math.pi * progress))  # 1 -> 0
        else:  # linear
            frac = 1.0 - progress
        return self.img_mask_end + (self.img_mask_start - self.img_mask_end) * frac

    def _raise_if_nonfinite_loss(self, name: str, value, inputs):
        if not torch.is_tensor(value):
            return
        value_detached = value.detach()
        if torch.isfinite(value_detached).all().item():
            return

        labels = inputs.get('labels', inputs.get('student_labels'))
        valid_label_count = None
        if torch.is_tensor(labels):
            valid_label_count = int((labels != -100).sum().detach().cpu().item())

        align_poss = inputs.get('alignment_poss', inputs.get('student_alignment_poss', []))
        align_counts = []
        for poss in align_poss:
            try:
                align_counts.append(len(poss))
            except TypeError:
                align_counts.append(None)

        metadata_preview = []
        for item in inputs.get('metadata', [])[:2]:
            if isinstance(item, dict):
                metadata_preview.append({
                    'dataset_name': item.get('dataset_name'),
                    'sample_id': item.get('sample_id'),
                })
            else:
                metadata_preview.append(str(item))

        flat = value_detached.reshape(-1).float()
        first_value = float(flat[0].detach().cpu().item()) if flat.numel() else float('nan')
        raise RuntimeError(
            f"[stage3] non-finite {name}: first_value={first_value}, "
            f"shape={tuple(value_detached.shape)}, global_step={getattr(self.state, 'global_step', None)}, "
            f"valid_label_count={valid_label_count}, alignment_counts={align_counts}, "
            f"metadata={metadata_preview}"
        )

    def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
        """
        Compute training loss for SFT stage3 with optional cached teacher latents.
        """
        # ---- optional param-finiteness probe (env-gated) ----
        if os.environ.get("MONET_NAN_DEBUG", ""):
            _step = int(getattr(self.state, 'global_step', 0) or 0)
            _bad = 0
            for _n, _p in model.named_parameters():
                if _p is not None and _p.numel() and not torch.isfinite(_p.data).all():
                    _bad += 1
                    if _bad <= 3:
                        logging.error(f"[NAN_DEBUG] param NON-FINITE at step={_step}: {_n}")
            if _bad:
                logging.error(f"[NAN_DEBUG] total non-finite params at step={_step}: {_bad}")

        # Teacher latents: in-process when --online_teacher is set, otherwise from disk.
        # Both paths return list[CPU Tensor [L+1, N*latent_size, D]] with the same content.
        if self.online_teacher is not None:
            teacher_latents = self.online_teacher(inputs)
        else:
            teacher_latents = load_offline_tensor(
                self.teacher_latent_dir,
                batch_metadata=inputs['metadata'],
                alignment_layer=self.args.alignment_layer,
                rep_type="latent",
            )

        # ------------------------------------------------------------------
        # Latent forward to get ce_patch_pos (positions of latent embeddings) and ce_patch_vec (latent embeddings)
        # ------------------------------------------------------------------
        inputs['latent_mode'] = True
        inputs['input_ids'] = inputs['student_input_ids']
        inputs['attention_mask'] = inputs['student_attention_mask']
        inputs['pixel_values'] = inputs['student_pixel_values']
        inputs['image_grid_thw'] = inputs['student_image_grid_thw']
        if 'labels' in inputs:
            inputs.pop('labels')
        inputs['alignment_poss'] = inputs['student_alignment_poss']
        # Forward 1 only autoregressively generates student latents. The teacher
        # alignment loss is computed and used in Forward 2 below, so do not pass
        # teacher latents here; otherwise the latent forward does extra unused work
        # and disables the grouped batched latent path.
        inputs.pop('teacher_hidden_states_for_alignment', None)
        model.gradient_checkpointing_disable() # since we set use_cache=True in latent forward, we must disable grad checkpointing
        inputs['loss_type'] = []
        inputs['output_hidden_states'] = False
        student_outputs_latent = model(**inputs)

        # ---- optional NaN localizer (env-gated, no effect when unset) ----
        if os.environ.get("MONET_NAN_DEBUG", ""):
            md = inputs.get('metadata', [])
            for _b, _v in enumerate(student_outputs_latent.ce_patch_vec):
                if torch.is_tensor(_v) and _v.numel() and not torch.isfinite(_v).all():
                    _info = md[_b] if _b < len(md) else _b
                    _amax = _v.abs().float().max().item()
                    logging.error(f"[NAN_DEBUG] Forward-1 ce_patch_vec NON-FINITE for sample={_info} "
                                  f"shape={tuple(_v.shape)} absmax={_amax}")
            for _b, _t in enumerate(teacher_latents or []):
                if torch.is_tensor(_t) and not torch.isfinite(_t).all():
                    _info = md[_b] if _b < len(md) else _b
                    logging.error(f"[NAN_DEBUG] teacher_latent NON-FINITE for sample={_info}")

        # Student CE forward
        inputs['latent_mode'] = False
        inputs['labels'] = inputs['student_labels']
        inputs['ce_patch_pos'] = student_outputs_latent.ce_patch_pos
        inputs['ce_patch_vec'] = student_outputs_latent.ce_patch_vec
        inputs['teacher_hidden_states_for_alignment'] = teacher_latents
        inputs['ce_emphasize_factor'] = self.ce_emphasize_factor
        has_observation_poss = any(inputs.get('observation_poss', []))
        inputs['ce_emphasize_poss'] = inputs['observation_poss'] if has_observation_poss else []
        model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
        inputs['loss_type'] = ['ce', 'alignment']
        inputs['compute_emphasize_acc'] = has_observation_poss
        if 'student_attention_mask_4d' in inputs:
            inputs['attention_mask_4d'] = inputs.pop('student_attention_mask_4d')
            # Curriculum: apply the per-step decayed answer->input-image attention mask
            # onto the (Forward-2) 4D mask the collate built with ratio=0.
            if self.img_mask_curriculum and self.special_token_ids is not None:
                ratio = self._curriculum_img_mask_ratio()
                self._cur_img_mask_ratio = ratio
                if ratio > 0.0:
                    apply_input_img_attn_mask(
                        inputs['attention_mask_4d']['full_attention'],
                        inputs['student_input_ids'],
                        self.special_token_ids,
                        ratio,
                    )
        (student_ce_loss, student_outputs) = super().compute_loss(
            model, inputs, return_outputs=True, num_items_in_batch=num_items_in_batch
        )
        if getattr(student_outputs, 'mean_emphasize_acc', None) is not None:
            self.observation_token_acc += getattr(student_outputs, 'mean_emphasize_acc')
            self.observation_token_acc_step += 1
        alignment_loss = student_outputs.loss_dict['alignment']
        self._raise_if_nonfinite_loss('student_ce_loss', student_ce_loss, inputs)
        self._raise_if_nonfinite_loss('alignment_loss', alignment_loss, inputs)
        loss = student_ce_loss + self.alignment_weight * alignment_loss
        self._raise_if_nonfinite_loss('total_loss', loss, inputs)
        outputs_student_loss = student_ce_loss.item()

        del student_outputs
        step = int(getattr(self.state, 'global_step', 0) or 0)
        if step > 0 and (step % 20 == 0):
            try:
                gc.collect()
                torch.cuda.empty_cache()
            except Exception:
                pass

        # Logging
        self.al_loss_cum += float(alignment_loss.detach().item())
        self.al_steps += 1
        self.student_ce_loss_cum += outputs_student_loss
        self.student_ce_loss_steps += 1

        return (loss, None) if return_outputs else loss

    def log(self, logs: dict, start_time: float | None = None):
        # Merge our rolling averages into the standard logs once per logging call
        merged = dict(logs)
        if self.al_steps > 0:
            merged["alignment_loss"] = round(self.al_loss_cum / max(1, self.al_steps), 6)
            self.al_loss_cum = 0.0
            self.al_steps = 0
        if self.student_ce_loss_steps > 0:
            merged["student_ce_loss"] = round(self.student_ce_loss_cum / max(1, self.student_ce_loss_steps), 6)
            self.student_ce_loss_cum = 0.0
            self.student_ce_loss_steps = 0
        if self.observation_token_acc_step > 0:
            merged["observation_token_acc"] = round(self.observation_token_acc/ max(1, self.observation_token_acc_step), 6)
            self.observation_token_acc = 0.
            self.observation_token_acc_step = 0
        if self.img_mask_curriculum:
            merged["img_mask_ratio"] = round(self._cur_img_mask_ratio, 6)

        # Call parent to keep default behavior (console/TB/W&B/etc.)
        return super().log(merged, start_time)