"""真实图像序列的答案CE输入;保持MEMO/Qwen3图像路径,只对assistant答案监督。""" import hashlib import json import os from pathlib import Path import re import time import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from PIL import Image from qwen_vl_utils import process_vision_info from cgvm.media import load_images _MEM_MARKER = '\nRetrieved observed memory (fallible descriptions; verify against images):\n' _TC_REFUSAL_PROMPT_SUFFIX = ( "If you believe the video content so far can answer this question, " "please provide the answer directly. Otherwise, reply with 'No, I can't respond for now.'" ) # 预加载训练清单中的真实事件时间窗,用于识别无视觉命中的盲训延迟样本(ZERO_HIT)并降权,防止强迫模型在缺失证据时产生幻觉 _MANIFEST_GT_WINDOWS = {} _DEFAULT_MANIFEST = Path(__file__).resolve().parents[1] / 'manifests/online_pilot20k.frozen.jsonl' if _DEFAULT_MANIFEST.exists(): try: for _line in _DEFAULT_MANIFEST.open(): _row = json.loads(_line) if 'annotation_start' in _row and 'annotation_end' in _row: _MANIFEST_GT_WINDOWS[_row['id']] = (float(_row['annotation_start']), float(_row['annotation_end'])) except Exception: pass def format_causal_frame_header(frames, query_time: float) -> str: """将 EvidenceBuilder 原生构造的帧角色(history/current)、物理时间戳与截止时间显式序列化,使训推两端 Reader 具备统一的因果时空锚点。""" if os.environ.get('CGVM_FRAME_ROLE_HEADER', '1') != '1' or not frames: return '' hist_items = [] cur_items = [] for idx, f in enumerate(frames, 1): tag = f"#{idx} ({float(f['timestamp']):.1f}s)" if f.get('role') == 'history': hist_items.append(tag) else: cur_items.append(tag) lines = [ f"Observed video evidence up to query_time={float(query_time):.1f}s " f"({len(frames)} frames in chronological order):" ] if hist_items: lines.append("- Retrieved history frames (past events): " + ", ".join(hist_items)) if cur_items: lines.append("- Current live window frames (present moment near query_time): " + ", ".join(cur_items)) elif cur_items: lines.append("- Observed frames across full prefix (start to query_time): " + ", ".join(cur_items)) return "\n".join(lines) + "\n\n" def check_visual_gt_support(pack): """检查当前样本选入的16帧是否命中真实标注区间;返回(is_delayed, has_gt_hit)。""" qid = pack.get('id') if qid not in _MANIFEST_GT_WINDOWS: return False, True gt_s, gt_e = _MANIFEST_GT_WINDOWS[qid] qt = float(pack.get('query_time', 0.0)) if gt_s > qt + 1e-6: # 未发生前缀样本(拒答/0次发生) return False, True is_delayed = (qt - gt_e) > 2.0 frames = pack.get('frames', []) has_hit = any((gt_s - 1.5) <= float(f['timestamp']) <= (gt_e + 1.5) for f in frames) return is_delayed, has_hit def _build_count_options(target_count: str, digest: bytes): """构造包含 0. / 1. / 2. / 3. 的确定性四选项列表,并返回目标字母与完整选项文本。""" letters = ['A', 'B', 'C', 'D'] # 根据 digest 确定性地排列 ['0.', '1.', '2.', '3.'] base_vals = ['0.', '1.', '2.', '3.'] shift = digest[0] % 4 vals = base_vals[shift:] + base_vals[:shift] options = [[letters[i], vals[i]] for i in range(4)] target_idx = vals.index(target_count) return options, letters[target_idx], f"{letters[target_idx]}. {target_count}" def align_training_qa_format( prompt_text: str, answer_text: str, sample_id: str, is_delayed: bool = False, has_gt_hit: bool = True, query_time: float = 0.0, ): """R2.5 对齐策略: 1. 50/50 保留完整选项语义文本监督('B. ...')与单字母指令遵循监督('B'),恢复细粒度动作/空间/属性视觉语义对齐; 2. 修正计数词边界正则(杜绝 countertop/encounter 误判),仅在短未发生前缀(query_time<=45s)构造 0.,并按真实子事件步数构造 1./2./3. 均衡正样本,消除 2./3. 恒负干扰项偏置; 3. 对无视觉命中的盲训延迟样本(ZERO_HIT)降权(0.05),对长文本主题摘要适度降权(0.35),对超额拒答样本适度降权(0.35)。 """ if os.environ.get('CGVM_ALIGN_MC_FORMAT', '1') != '1': return prompt_text, answer_text, 1.0 # R2.6 新增细粒度时序/运动多选扩充样本已在导出时完成 2~5 选项随机均衡排布与标准指令对齐,直接保持 1.0 权重原样监督 if str(sample_id).startswith('r26m-'): return prompt_text, answer_text, 1.0 if _MEM_MARKER in prompt_text: head, mem_tail = prompt_text.split(_MEM_MARKER, 1) mem_suffix = _MEM_MARKER + mem_tail else: head, mem_suffix = prompt_text, '' ans_clean = answer_text.strip() is_refusal = ans_clean.lower().replace('’', "'") in { "no, i can't respond for now.", "no, i can't respond for now", "unable to answer" } if 'Options:' not in head: if not is_refusal: w = 0.05 if (is_delayed and not has_gt_hit) else 0.15 return prompt_text, answer_text, w if _TC_REFUSAL_PROMPT_SUFFIX not in head: return prompt_text, answer_text, 0.35 head = head.replace(_TC_REFUSAL_PROMPT_SUFFIX, '').rstrip() instruction = ( "\nIf the question cannot be answered from the video content observed so far, " "respond only with 'Unable to answer'." ) return head + instruction + mem_suffix, 'Unable to answer', 0.35 had_refusal_suffix = _TC_REFUSAL_PROMPT_SUFFIX in head if had_refusal_suffix: head = head.replace(' ' + _TC_REFUSAL_PROMPT_SUFFIX, '').replace(_TC_REFUSAL_PROMPT_SUFFIX, '').rstrip() q_part, opt_part = head.split('Options:', 1) opt_matches = list( re.finditer(r'(?:^|\n)\s*([A-D])\.\s*(.+?)(?=(?:\n\s*[A-D]\.\s+)|\Z)', opt_part.strip(), flags=re.S) ) if len(opt_matches) < 2: return prompt_text, answer_text, 0.35 options = [[m.group(1), m.group(2).strip()] for m in opt_matches] digest = hashlib.sha256(str(sample_id).encode('utf-8')).digest() use_ovo_style = (digest[1] % 2) == 1 is_count_q = bool(re.search(r'\b(how many|times|count)\b', q_part.lower())) target_letter = None target_full = None loss_weight = 1.0 force_single_letter = False if is_refusal: # 情况A:仅在短未发生前缀(query_time <= 45s)上确定性抽样构造真实 0. 次发生题(~55条),避免长前缀盲猜 0. if (not is_count_q) and (0.0 < float(query_time) <= 45.0) and (digest[5] % 5 == 0) and len(options) == 4: ev_desc = options[digest[0] % len(options)][1].rstrip('.;').strip() q_part = ( "Answer the question using the observed video frames.\n" f"Question: How many times in total has \"{ev_desc}\" occurred in the video so far?" ) options, target_letter, target_full = _build_count_options('0.', digest) use_ovo_style = False force_single_letter = True loss_weight = 1.0 else: existing = [i for i, (_, text) in enumerate(options) if 'unable to answer' in text.lower()] if existing: idx = existing[0] else: idx = digest[0] % len(options) options[idx][1] = 'Unable to answer' target_letter = options[idx][0] target_full = f"{target_letter}. Unable to answer" use_ovo_style = True force_single_letter = True loss_weight = 0.35 else: m_ans = re.match(r'^([A-D])(?:\.|\b)', ans_clean) if not m_ans: return prompt_text, answer_text, 0.35 target_letter = m_ans.group(1) if is_delayed and not has_gt_hit: # 盲训延迟样本降权至 0.05,避免无视觉帧支撑时强行拟合导致模型忽视视觉帧 return prompt_text, answer_text, 0.05 target_idx = next((i for i, (ltr, _) in enumerate(options) if ltr == target_letter), None) target_txt = options[target_idx][1] if target_idx is not None else ans_clean sub_steps = [ s.strip() for s in re.split(r',\s*(?:and\s+|then\s+)?|\s+then\s+|\s+followed by\s+', target_txt) if len(s.split()) >= 2 ] synth_count = None if target_idx is not None and len(options) == 4 and (not is_count_q) and ('unable to answer' not in target_txt.lower()): if len(sub_steps) == 3 and (digest[5] % 7 == 0): synth_count = '3.' elif len(sub_steps) == 2 and (digest[5] % 4 == 0): synth_count = '2.' elif len(sub_steps) == 1 and (2 <= len(target_txt.split()) <= 15) and (digest[5] % 75 == 1): synth_count = '1.' # 情况B:与 0. 严格均衡的 1. / 2. / 3. 发生次数与多步子事件计数验证题(各~60条),彻底消除 2./3. 恒负干扰项偏置 if synth_count is not None: ev_desc = target_txt.rstrip('.;').strip() if synth_count == '1.': q_part = ( "Answer the question using the observed video frames.\n" f"Question: How many times in total has \"{ev_desc}\" occurred in the video so far?" ) else: q_part = ( "Answer the question using the observed video frames.\n" f"Question: How many distinct actions or events in \"{ev_desc}\" have occurred in the video so far?" ) options, target_letter, target_full = _build_count_options(synth_count, digest) use_ovo_style = False force_single_letter = True loss_weight = 1.0 else: # 在原配对可回答样本中按10%温和比例将某一错误干扰项替换为 Unable to answer,防止模型见到该词盲选 if had_refusal_suffix and (digest[2] % 10 == 0): wrong_indices = [ i for i, (ltr, txt) in enumerate(options) if ltr != target_letter and 'unable to answer' not in txt.lower() ] if wrong_indices: rep_idx = wrong_indices[digest[3] % len(wrong_indices)] options[rep_idx][1] = 'Unable to answer' target_full = f"{target_letter}. {options[target_idx][1]}" if target_idx is not None else ans_clean # 50% 保留完整选项语义文本监督(强化视觉与动作/空间词汇对齐),50% 监督单字母指令遵循 force_single_letter = (digest[4] % 2 == 1) loss_weight = 1.0 if not force_single_letter: opt_str = '\n'.join(f'{ltr}. {txt}' for ltr, txt in options) new_head = q_part.rstrip() + '\nOptions:\n' + opt_str return new_head + mem_suffix, target_full, loss_weight if use_ovo_style: opt_str = '; '.join(f'{ltr}. {txt}' for ltr, txt in options) + ';' new_head = ( q_part.rstrip() + '\nOptions:\n' + opt_str + '\n\nRespond only with the letter corresponding to your chosen option (e.g., A, B, C). \n' + 'Do not include any additional text or explanation in your response.' ) else: opt_str = '\n'.join(f'{ltr}. {txt}' for ltr, txt in options) new_head = ( q_part.rstrip() + '\n\nOptions:\n' + opt_str + '\n\nPlease select the most appropriate answer and output the option letter only (e.g., A).' ) return new_head + mem_suffix, target_letter, loss_weight def prepare(pack, processor): frames=pack['frames'] if not 08 or len(frames)>16: raise ValueError('证据包违反历史8帧或总16帧上限') if any(f['timestamp']>pack['query_time']+1e-6 for f in frames): raise ValueError('证据包含未来帧') if [float(f['timestamp']) for f in frames]!=sorted(float(f['timestamp']) for f in frames): raise ValueError('Reader证据必须按真实时间排列') media_cost={};images=load_images(frames,metrics=media_cost) is_delayed, has_gt_hit = check_visual_gt_support(pack) aligned_prompt, aligned_answer, loss_weight = align_training_qa_format( pack['prompt'], pack['answer'], pack['id'], is_delayed=is_delayed, has_gt_hit=has_gt_hit, query_time=float(pack.get('query_time', 0.0)), ) frame_header = format_causal_frame_header(frames, pack['query_time']) full_prompt = frame_header + aligned_prompt content=[{'type':'image','image':image} for image in images]+[{'type':'text','text':full_prompt}] user=[{'role':'user','content':content}] full=user+[{'role':'assistant','content':aligned_answer}] prefix=processor.apply_chat_template(user,tokenize=False,add_generation_prompt=True) text=processor.apply_chat_template(full,tokenize=False,add_generation_prompt=False) if not text.startswith(prefix):raise ValueError('训练/推理assistant模板前缀不一致') image_inputs,_,_=process_vision_info(user,image_patch_size=16,return_video_kwargs=True,return_video_metadata=True) inputs=processor(text=[text],images=image_inputs,videos=None,padding=False,return_tensors='pt') suffix=text[len(prefix):] suffix_ids=processor.tokenizer(suffix,add_special_tokens=False).input_ids if not suffix_ids:raise ValueError('答案没有可监督token') if inputs.input_ids[0,-len(suffix_ids):].tolist()==suffix_ids: answer_start=inputs.input_ids.shape[-1]-len(suffix_ids) else: # 只有分词边界跨前缀时才重做prefix处理,不能凭字符数mask答案。 prefix_inputs=processor(text=[prefix],images=image_inputs,videos=None,padding=False,return_tensors='pt') answer_start=prefix_inputs.input_ids.shape[-1] if inputs.input_ids[0,:answer_start].tolist()!=prefix_inputs.input_ids[0].tolist(): raise ValueError('无法精确定位答案token,拒绝输入监督泄漏') labels=inputs.input_ids.clone();labels[:,:answer_start]=-100 if not (labels!=-100).any():raise ValueError('答案mask后无监督') text_tokens=len(processor.tokenizer(full_prompt,add_special_tokens=False).input_ids) if text_tokens>4096 or inputs.input_ids.shape[-1]>32768: raise ValueError('输入超过冻结文本/总token上限,需要两组共同修复') inputs['labels']=labels audit=dict(id=pack['id'],frames=len(frames),query_time=pack['query_time'], loss_weight=float(loss_weight), max_support_time=max(f['timestamp'] for f in frames), prompt_masked_tokens=answer_start,answer_tokens=int((labels!=-100).sum()), input_tokens=int(inputs.input_ids.shape[-1]),processed_rgb_pixels=int(inputs.pixel_values.numel()//3), raw_pixels=sum(image.width*image.height for image in images)) audit.update(media_cost) return inputs,audit class ReaderMicrobatchDataset(Dataset): """多进程异步预取Dataset:严格按照(step, micro, rank)确定性下标顺序解码缩放图像并构造Reader输入,不消耗主进程RNG。""" def __init__(self, packs, order, start_step, total_steps, global_batch, grad_accum, world, rank, processor): self.packs = packs self.processor = processor self.schedule = [] for s in range(start_step, total_steps): count = min(global_batch, len(order) - s * global_batch) for m in range((count + world - 1) // world): position = s * global_batch + m * world + rank # 尾批DDP各rank同逻辑QA槽位;负索引为零权重占位,不能丢QA。 idx = order[position] if position < len(order) else -order[s * global_batch] - 1 self.schedule.append((s, m, idx)) def __len__(self): return len(self.schedule) def __getitem__(self, i): s, m, idx = self.schedule[i] pack = self.packs[idx if idx >= 0 else -idx - 1] t0 = time.perf_counter() inputs, audit = prepare(pack, self.processor) elapsed = time.perf_counter() - t0 return s, m, idx, dict(inputs), audit, elapsed def build_reader_loader(packs, order, start_step, total_steps, global_batch, grad_accum, world, rank, processor, num_workers=4, prefetch_factor=2): dataset = ReaderMicrobatchDataset(packs, order, start_step, total_steps, global_batch, grad_accum, world, rank, processor) if num_workers <= 0: return DataLoader(dataset, batch_size=None, shuffle=False, num_workers=0) return DataLoader( dataset, batch_size=None, shuffle=False, num_workers=num_workers, prefetch_factor=prefetch_factor, pin_memory=True, persistent_workers=False, ) def group_microbatches(step_items, max_micro_batch_size: int, max_padded_tokens: int = 10240): """将单卡单步内的样本按长度自适应分组为1..max_micro_batch_size的微批次,避免悬殊长度产生的无谓padding浪费。""" if max_micro_batch_size <= 1 or len(step_items) <= 1: return [[item] for item in step_items] sorted_items = sorted(step_items, key=lambda x: int(x[3]['input_ids'].shape[-1])) groups = [] cur = [] for item in sorted_items: seq_len = int(item[3]['input_ids'].shape[-1]) if not cur: cur.append(item) continue min_len = int(cur[0][3]['input_ids'].shape[-1]) new_count = len(cur) + 1 if new_count <= max_micro_batch_size and seq_len <= min_len * 1.55 and seq_len * new_count <= max_padded_tokens: cur.append(item) else: groups.append(cur) cur = [item] if cur: groups.append(cur) return groups def forward_and_answer_ce(ddp_model, chunk_items, pad_token_id: int, device: torch.device, kl_weight: float = 0.15): """支持单样本或多样本合并前向,仅抽出每个样本的答案token计算FP32交叉熵,并施加样本质量权重与冻结基座功能保持KL锚定。""" peft_model = ddp_model.module if hasattr(ddp_model, 'module') else ddp_model use_kl = (kl_weight > 0.0) and hasattr(peft_model, 'disable_adapter') if len(chunk_items) == 1: inputs_dict = chunk_items[0][3] audit_dict = chunk_items[0][4] w = float(audit_dict.get('loss_weight', 1.0)) if chunk_items[0][2] >= 0 else 0.0 labels = inputs_dict['labels'].to(device, non_blocking=True) model_inputs = { k: (v.to(device, non_blocking=True) if isinstance(v, torch.Tensor) else v) for k, v in inputs_dict.items() if k not in ('labels', 'loss_weight') } mask = labels[0, 1:] != -100 base_ans_logits = None if use_kl: with torch.no_grad(), peft_model.disable_adapter(): base_outputs = peft_model(**model_inputs, use_cache=False) base_ans_logits = base_outputs.logits[0, :-1][mask].detach().float() del base_outputs outputs = ddp_model(**model_inputs, use_cache=False) logits = outputs.logits ans_logits = logits[0, :-1][mask].float() ans_targets = labels[0, 1:][mask] ce_loss = F.cross_entropy(ans_logits, ans_targets, reduction='mean') if base_ans_logits is not None: with torch.no_grad(): p_base = F.softmax(base_ans_logits, dim=-1) kl_loss = F.kl_div(F.log_softmax(ans_logits, dim=-1), p_base, reduction='batchmean') loss = ce_loss + kl_weight * kl_loss else: loss = ce_loss weighted_loss = loss * w return weighted_loss, [loss.detach()] lengths = [int(item[3]['input_ids'].shape[-1]) for item in chunk_items] max_len = max(lengths) padded_input_ids = [] padded_attn_mask = [] padded_mm_token_type_ids = [] has_mm_type = 'mm_token_type_ids' in chunk_items[0][3] pixel_values_list = [] grid_thw_list = [] labels_list = [] for item, seq_len in zip(chunk_items, lengths): d = item[3] pad_len = max_len - seq_len ids = d['input_ids'] mask = d['attention_mask'] if pad_len > 0: ids = F.pad(ids, (0, pad_len), value=pad_token_id) mask = F.pad(mask, (0, pad_len), value=0) padded_input_ids.append(ids) padded_attn_mask.append(mask) if has_mm_type and 'mm_token_type_ids' in d: mm = d['mm_token_type_ids'] if pad_len > 0: mm = F.pad(mm, (0, pad_len), value=0) padded_mm_token_type_ids.append(mm) if 'pixel_values' in d and d['pixel_values'] is not None: pixel_values_list.append(d['pixel_values']) if 'image_grid_thw' in d and d['image_grid_thw'] is not None: grid_thw_list.append(d['image_grid_thw']) labels_list.append(d['labels'].to(device, non_blocking=True)) model_inputs = { 'input_ids': torch.cat(padded_input_ids, dim=0).to(device, non_blocking=True), 'attention_mask': torch.cat(padded_attn_mask, dim=0).to(device, non_blocking=True), } if has_mm_type and len(padded_mm_token_type_ids) == len(chunk_items): model_inputs['mm_token_type_ids'] = torch.cat(padded_mm_token_type_ids, dim=0).to(device, non_blocking=True) if pixel_values_list: model_inputs['pixel_values'] = torch.cat(pixel_values_list, dim=0).to(device, non_blocking=True) if grid_thw_list: model_inputs['image_grid_thw'] = torch.cat(grid_thw_list, dim=0).to(device, non_blocking=True) base_ans_logits_list = None if use_kl: base_ans_logits_list = [] with torch.no_grad(), peft_model.disable_adapter(): base_outputs = peft_model(**model_inputs, use_cache=False) for b, (seq_len, labels_b) in enumerate(zip(lengths, labels_list)): mask_b = labels_b[0, 1:seq_len] != -100 base_ans_logits_list.append(base_outputs.logits[b, :seq_len - 1][mask_b].detach().float()) del base_outputs outputs = ddp_model(**model_inputs, use_cache=False) logits = outputs.logits sample_losses = [] for b, (seq_len, labels_b) in enumerate(zip(lengths, labels_list)): mask_b = labels_b[0, 1:seq_len] != -100 ans_logits_b = logits[b, :seq_len - 1][mask_b].float() ans_targets_b = labels_b[0, 1:seq_len][mask_b] ce_b = F.cross_entropy(ans_logits_b, ans_targets_b, reduction='mean') if base_ans_logits_list is not None: with torch.no_grad(): p_base_b = F.softmax(base_ans_logits_list[b], dim=-1) kl_b = F.kl_div(F.log_softmax(ans_logits_b, dim=-1), p_base_b, reduction='batchmean') loss_b = ce_b + kl_weight * kl_b else: loss_b = ce_b sample_losses.append(loss_b) # 占位仍走有梯度的计算图以保持DDP参与,真实样本乘以各自的样本质量权重 loss_weight total_chunk_loss = torch.stack([ loss * float(item[4].get('loss_weight', 1.0)) if item[2] >= 0 else loss * 0.0 for loss, item in zip(sample_losses, chunk_items) ]).sum() return total_chunk_loss, [l.detach() for l in sample_losses]