| 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): |
| |
| 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, |
| create_graph=False, |
| allow_unused=True |
| ) |
|
|
| |
| safe_grads = [] |
| for v, g in zip(ce_vec_list, grads): |
| if g is None: |
| |
| g = torch.zeros_like(v) |
| safe_grads.append(g.detach()) |
|
|
| 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) |
| |
| 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 |
| 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'] |
| |
| 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): |
| |
| 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 |
|
|
| |
| 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) |
| |
| 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 |
| 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 |
| """ |
| |
| |
| |
| |
| inputs['latent_mode'] = True |
| inputs['loss_type'] = [] |
| model.gradient_checkpointing_disable() |
| outputs = model(**inputs, return_dict=True, output_hidden_states=False) |
|
|
| |
| |
| |
| 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 |
| |
| inputs.pop('output_attentions', None) |
| inputs.pop('attn_analysis', None) |
|
|
| if self.args.alignment_weight != 0: |
| |
| |
| 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_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 |
|
|
| |
| |
| step = int(getattr(self.state, 'global_step', 0) or 0) |
| if step % 50 == 0: |
| try: |
| gc.collect() |
| |
| 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): |
| |
| 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 |
|
|
|
|
| |
| 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)) |
| |
| 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 |
| self.al_steps = 0 |
| self.student_ce_loss_cum = 0.0 |
| self.student_ce_loss_steps = 0 |
|
|
| |
| |
| |
| |
| |
| |
| 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 |
| 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)) |
| else: |
| 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. |
| """ |
| |
| 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}") |
|
|
| |
| |
| 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", |
| ) |
|
|
| |
| |
| |
| 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'] |
| |
| |
| |
| |
| inputs.pop('teacher_hidden_states_for_alignment', None) |
| model.gradient_checkpointing_disable() |
| inputs['loss_type'] = [] |
| inputs['output_hidden_states'] = False |
| student_outputs_latent = model(**inputs) |
|
|
| |
| 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}") |
|
|
| |
| 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') |
| |
| |
| 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 |
|
|
| |
| 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): |
| |
| 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) |
|
|
| |
| return super().log(merged, start_time) |
|
|