Datasets:
Download src/explicit_learning/training/evi_po.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 40.8 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/training/evi_po.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/training/evi_po.py
-
curl -L -o evi_po.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/training/evi_po.py
40.8 kB
| """EVI-PO objective adapter for the pinned TRL 1.9.1 GRPO backend. | |
| The parent trainer owns rollout, rewards, importance sampling, reference KL, | |
| and the complete GRPO answer loss. This adapter adds only the registered | |
| grouped objective: | |
| ``L = L_GRPO-answer + lambda_dir * L_direction + lambda_evid * L_evidence``. | |
| Intervention state names and evidence metadata remain loader-side. Generated | |
| and inference responses still contain only ``<answer>...</answer>``. | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import math | |
| from collections import Counter | |
| from collections.abc import Mapping, Sequence | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| import torch.nn.functional as F | |
| from trl import GRPOTrainer | |
| from ..hashing import canonical_json_hash | |
| from ..renderers.node_map import decode_uint32_png | |
| from .aligned_grpo import AlignedGRPOTrainer | |
| from .answers import UNANSWERABLE_TOKEN | |
| from .evi_po_contract import ( | |
| EVI_PO_ADAPTER_VERSION, | |
| validate_trl_parent_contract, | |
| ) | |
| validate_trl_parent_contract(GRPOTrainer) | |
| class EVIObjectiveError(RuntimeError): | |
| """Raised instead of silently dropping a registered EVI loss term.""" | |
| def _mapping(value: Any, label: str) -> Mapping[str, Any]: | |
| if not isinstance(value, Mapping): | |
| raise EVIObjectiveError(f"{label} must be an object") | |
| return value | |
| def directional_loss( | |
| scores: Mapping[str, Mapping[str, torch.Tensor]], | |
| *, | |
| candidate_targets: Sequence[str], | |
| full_answer: str, | |
| substitute_answer: str | None, | |
| margin: float, | |
| ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: | |
| """Compute JS(FULL, CONTROL) plus every available directional hinge.""" | |
| full_scores = _mapping(scores.get("FULL"), "FULL candidate scores") | |
| control_scores = _mapping(scores.get("CONTROL"), "CONTROL candidate scores") | |
| try: | |
| full_vector = torch.stack([full_scores[target] for target in candidate_targets]) | |
| control_vector = torch.stack([control_scores[target] for target in candidate_targets]) | |
| except KeyError as exc: | |
| raise EVIObjectiveError(f"candidate score missing for JS support: {exc}") from exc | |
| log_p = F.log_softmax(full_vector.float(), dim=0) | |
| log_q = F.log_softmax(control_vector.float(), dim=0) | |
| p, q = log_p.exp(), log_q.exp() | |
| mixture = 0.5 * (p + q) | |
| log_mixture = mixture.clamp_min(torch.finfo(mixture.dtype).tiny).log() | |
| js = 0.5 * ((p * (log_p - log_mixture)).sum() + (q * (log_q - log_mixture)).sum()) | |
| missing_scores = _mapping(scores.get("MISSING"), "MISSING candidate scores") | |
| try: | |
| missing_hinge = F.relu( | |
| torch.as_tensor(margin, device=js.device, dtype=js.dtype) | |
| - missing_scores[UNANSWERABLE_TOKEN].float() | |
| + missing_scores[full_answer].float() | |
| ) | |
| except KeyError as exc: | |
| raise EVIObjectiveError(f"MISSING directional score is absent: {exc}") from exc | |
| substitute_hinge = js.new_zeros(()) | |
| if substitute_answer is not None: | |
| substitute_scores = _mapping(scores.get("SUBSTITUTE"), "SUBSTITUTE candidate scores") | |
| try: | |
| substitute_hinge = F.relu( | |
| torch.as_tensor(margin, device=js.device, dtype=js.dtype) | |
| - substitute_scores[substitute_answer].float() | |
| + substitute_scores[full_answer].float() | |
| ) | |
| except KeyError as exc: | |
| raise EVIObjectiveError(f"SUBSTITUTE directional score is absent: {exc}") from exc | |
| components = { | |
| "js_full_control": js, | |
| "substitute_hinge": substitute_hinge, | |
| "missing_hinge": missing_hinge, | |
| } | |
| return js + substitute_hinge + missing_hinge, components | |
| def evidence_alignment_loss( | |
| attention: torch.Tensor, | |
| *, | |
| completion_positions: torch.Tensor, | |
| visual_positions: torch.Tensor, | |
| evidence_visual_mask: torch.Tensor, | |
| ) -> torch.Tensor: | |
| """Cross-entropy from response-to-image attention to a certified mask.""" | |
| if attention.ndim != 4 or attention.size(0) != 1: | |
| raise EVIObjectiveError( | |
| f"usable attention must have shape (1,H,Q,K), got {tuple(attention.shape)}" | |
| ) | |
| if not torch.isfinite(attention).all(): | |
| raise EVIObjectiveError("attention tensor contains NaN or Inf") | |
| completion_indices = completion_positions.nonzero(as_tuple=False).flatten() | |
| visual_indices = visual_positions.nonzero(as_tuple=False).flatten() | |
| if completion_indices.numel() == 0: | |
| raise EVIObjectiveError("evidence forward has no response-token queries") | |
| if visual_indices.numel() == 0: | |
| raise EVIObjectiveError("evidence forward has no image-token keys") | |
| if evidence_visual_mask.ndim != 1 or evidence_visual_mask.numel() != visual_indices.numel(): | |
| raise EVIObjectiveError("projected evidence mask does not align with image-token positions") | |
| target = evidence_visual_mask.to(device=attention.device, dtype=torch.float32) | |
| if not bool(target.any()): | |
| raise EVIObjectiveError("projected evidence mask has no positive visual token") | |
| selected = ( | |
| attention[0] | |
| .index_select(1, completion_indices.to(attention.device)) | |
| .index_select(2, visual_indices.to(attention.device)) | |
| .float() | |
| ) | |
| visual_attention = selected.mean(dim=(0, 1)) | |
| mass = visual_attention.sum() | |
| if not torch.isfinite(mass) or float(mass.detach().item()) <= 0.0: | |
| raise EVIObjectiveError("response has no finite positive attention mass on image tokens") | |
| prediction = visual_attention.clamp_min(torch.finfo(torch.float32).tiny) | |
| prediction = prediction / prediction.sum() | |
| target = target / target.sum() | |
| loss = -(target * prediction.log()).sum() | |
| if not torch.isfinite(loss): | |
| raise EVIObjectiveError("evidence alignment loss is NaN or Inf") | |
| return loss | |
| def _pixel_evidence_mask(spec: Mapping[str, Any]) -> torch.Tensor: | |
| source = str(spec.get("source", "")) | |
| width, height = int(spec.get("width", 0)), int(spec.get("height", 0)) | |
| if width <= 0 or height <= 0: | |
| raise EVIObjectiveError("evidence source has invalid pixel dimensions") | |
| if source == "executor_dependency_nodes_projected_through_node_map": | |
| path = Path(str(spec.get("node_map_path", ""))) | |
| if not path.is_file(): | |
| raise EVIObjectiveError("executor node-map evidence is missing") | |
| owners = decode_uint32_png(path.read_bytes()) | |
| table = spec.get("node_table") | |
| dependencies = spec.get("dependency_node_ids") | |
| if not isinstance(table, list) or not isinstance(dependencies, list): | |
| raise EVIObjectiveError("executor evidence metadata is malformed") | |
| indices = [table.index(node_id) for node_id in dependencies if node_id in table] | |
| import numpy as np | |
| mask = np.isin(owners, indices) if indices else np.zeros_like(owners, dtype=bool) | |
| tensor = torch.from_numpy(mask.copy()) | |
| elif source == "source_annotation_explicit_mask": | |
| path = Path(str(spec.get("mask_path", ""))) | |
| if not path.is_file(): | |
| raise EVIObjectiveError("source evidence mask is missing") | |
| import numpy as np | |
| from PIL import Image | |
| with Image.open(path) as image: | |
| mask = np.asarray(image.convert("L")) > 0 | |
| tensor = torch.from_numpy(mask.copy()) | |
| elif source == "source_annotation_bboxes": | |
| regions = spec.get("regions") | |
| if not isinstance(regions, list) or not regions: | |
| raise EVIObjectiveError("source evidence regions are missing") | |
| tensor = torch.zeros((height, width), dtype=torch.bool) | |
| for value in regions: | |
| region = _mapping(value, "source evidence region") | |
| bbox = region.get("bbox_xyxy") | |
| if not isinstance(bbox, list) or len(bbox) != 4: | |
| raise EVIObjectiveError("source evidence bbox is malformed") | |
| x0, y0, x1, y1 = (float(item) for item in bbox) | |
| left, top = max(0, math.floor(x0)), max(0, math.floor(y0)) | |
| right, bottom = min(width, math.ceil(x1)), min(height, math.ceil(y1)) | |
| tensor[top:bottom, left:right] = True | |
| else: | |
| raise EVIObjectiveError(f"unsupported evidence source: {source!r}") | |
| if tuple(tensor.shape) != (height, width): | |
| raise EVIObjectiveError( | |
| f"evidence mask shape {tuple(tensor.shape)} != declared {(height, width)}" | |
| ) | |
| positive = int(tensor.sum().item()) | |
| if positive != int(spec.get("positive_pixel_count", -1)) and source != ( | |
| "source_annotation_bboxes" | |
| ): | |
| raise EVIObjectiveError("evidence positive-pixel count drift") | |
| if positive <= 0: | |
| raise EVIObjectiveError("pixel evidence mask is empty") | |
| return tensor | |
| def project_evidence_to_visual_tokens( | |
| spec: Mapping[str, Any], | |
| *, | |
| image_grid_thw: torch.Tensor, | |
| spatial_merge_size: int, | |
| ) -> torch.Tensor: | |
| """Max-pool certified source pixels onto Qwen's merged visual-token grid.""" | |
| if image_grid_thw.numel() != 3: | |
| raise EVIObjectiveError("evidence projection requires one image_grid_thw row") | |
| temporal, grid_h, grid_w = ( | |
| int(value) for value in image_grid_thw.detach().cpu().reshape(-1).tolist() | |
| ) | |
| if ( | |
| temporal <= 0 | |
| or grid_h <= 0 | |
| or grid_w <= 0 | |
| or spatial_merge_size <= 0 | |
| or grid_h % spatial_merge_size | |
| or grid_w % spatial_merge_size | |
| ): | |
| raise EVIObjectiveError("image grid is incompatible with the configured spatial merge size") | |
| token_h, token_w = grid_h // spatial_merge_size, grid_w // spatial_merge_size | |
| pixels = _pixel_evidence_mask(spec).float()[None, None] | |
| pooled = F.adaptive_max_pool2d(pixels, (token_h, token_w))[0, 0].bool().flatten() | |
| projected = pooled.repeat(temporal) | |
| if not bool(projected.any()): | |
| raise EVIObjectiveError("pixel evidence vanished during visual-token projection") | |
| return projected | |
| class EVITrainer(AlignedGRPOTrainer): | |
| """Pinned GRPO plus grouped directional and certified-evidence losses.""" | |
| def __init__(self, *args: Any, evi_po_config: Mapping[str, Any], **kwargs: Any) -> None: | |
| if evi_po_config.get("adapter_version") != EVI_PO_ADAPTER_VERSION: | |
| raise ValueError("frozen EVI-PO adapter identity mismatch") | |
| expected_contract = { | |
| "required_relationships": ["FULL", "CONTROL", "MISSING"], | |
| "optional_relationships": ["SUBSTITUTE"], | |
| "candidate_support": "group_answers_plus_unanswerable", | |
| "evidence_supervision_relation": "FULL", | |
| "evidence_sources": [ | |
| "executor_dependency_nodes_projected_through_node_map", | |
| "source_annotation_explicit_mask", | |
| "source_annotation_bboxes", | |
| ], | |
| "attention_capture": "last_full_attention_layer_eager_forward_hook", | |
| "zero_weight_reduction": "exact_parent_grpo_path", | |
| } | |
| drift = { | |
| key: (evi_po_config.get(key), expected) | |
| for key, expected in expected_contract.items() | |
| if evi_po_config.get(key) != expected | |
| } | |
| if drift: | |
| raise ValueError(f"frozen EVI-PO data/objective contract drift: {drift}") | |
| self.lambda_direction = float(evi_po_config["lambda_direction"]) | |
| self.lambda_evidence = float(evi_po_config["lambda_evidence"]) | |
| self.direction_margin = float(evi_po_config["margin"]) | |
| if ( | |
| not math.isfinite(self.lambda_direction) | |
| or not math.isfinite(self.lambda_evidence) | |
| or min(self.lambda_direction, self.lambda_evidence) < 0.0 | |
| ): | |
| raise ValueError("EVI-PO loss weights must be finite and non-negative") | |
| if not math.isfinite(self.direction_margin) or self.direction_margin < 0.0: | |
| raise ValueError("EVI-PO direction margin must be finite and non-negative") | |
| self._probe_pending = bool(evi_po_config.get("require_gpu_contract_probe", False)) | |
| if self._probe_pending and (self.lambda_direction <= 0.0 or self.lambda_evidence <= 0.0): | |
| raise ValueError( | |
| "the EVI GPU contract probe requires positive direction and evidence weights" | |
| ) | |
| self.evi_gpu_contract_probe: dict[str, Any] | None = None | |
| self._last_evidence_diagnostics: dict[str, Any] | None = None | |
| super().__init__(*args, **kwargs) | |
| active = self.lambda_direction > 0.0 or self.lambda_evidence > 0.0 | |
| # Init-time pins: attributes the GRPO parent sets in its own ``__init__``. | |
| # ``current_gradient_accumulation_steps`` is intentionally excluded — | |
| # transformers assigns it inside the training loop | |
| # (``_inner_training_loop``), so it is absent at construction and only | |
| # read later in ``_compute_loss`` (the loss normalizer), by which point | |
| # it is guaranteed set. | |
| required_parent_attributes = ( | |
| "model_kwarg_keys", | |
| "_tokenizer", | |
| "chat_template_kwargs", | |
| "_metrics", | |
| ) | |
| missing_parent_attributes = [ | |
| name for name in required_parent_attributes if not hasattr(self, name) | |
| ] | |
| if active and missing_parent_attributes: | |
| raise EVIObjectiveError( | |
| "pinned GRPO parent attributes are absent: " + ", ".join(missing_parent_attributes) | |
| ) | |
| if active and "logits_to_keep" not in self.model_kwarg_keys: | |
| raise EVIObjectiveError("EVI-PO requires a model forward with logits_to_keep support") | |
| self._image_token_id = ( | |
| self._resolve_image_token_id() if self.lambda_evidence > 0.0 else None | |
| ) | |
| def _resolve_image_token_id(self) -> int: | |
| """Resolve Qwen's visual placeholder without trusting a TRL private attr.""" | |
| model = self.accelerator.unwrap_model(self.model) | |
| configs = [ | |
| getattr(model, "config", None), | |
| getattr(getattr(model, "config", None), "text_config", None), | |
| ] | |
| for config in configs: | |
| value = getattr(config, "image_token_id", None) | |
| if isinstance(value, int) and value >= 0: | |
| return value | |
| tokenizer = self._tokenizer | |
| candidates = [ | |
| getattr(self.processing_class, "image_token", None), | |
| getattr(tokenizer, "image_token", None), | |
| "<|image_pad|>", | |
| ] | |
| convert = getattr(tokenizer, "convert_tokens_to_ids", None) | |
| if callable(convert): | |
| unk_id = getattr(tokenizer, "unk_token_id", None) | |
| for token in candidates: | |
| if not isinstance(token, str) or not token: | |
| continue | |
| value = convert(token) | |
| if isinstance(value, int) and value >= 0 and value != unk_id: | |
| return value | |
| raise EVIObjectiveError("cannot resolve Qwen's image-placeholder token ID") | |
| def _generate_and_score_completions( | |
| self, | |
| inputs: list[dict[str, torch.Tensor | Any]], | |
| ) -> dict[str, Any]: | |
| if self.lambda_direction == 0.0 and self.lambda_evidence == 0.0: | |
| raw_output = super()._generate_and_score_completions(inputs) | |
| if not isinstance(raw_output, Mapping): | |
| raise EVIObjectiveError("parent GRPO output is not a mapping") | |
| return dict(raw_output) | |
| grouped = [example.get("evi_group") for example in inputs] | |
| if any(not isinstance(group, Mapping) for group in grouped): | |
| raise EVIObjectiveError("EVI-PO rollout row lacks a grouped relationship") | |
| raw_output = super()._generate_and_score_completions(inputs) | |
| if not isinstance(raw_output, Mapping): | |
| raise EVIObjectiveError("parent GRPO output is not a mapping") | |
| output = dict(raw_output) | |
| completion_ids = output.get("completion_ids") | |
| if not isinstance(completion_ids, torch.Tensor) or completion_ids.ndim < 1: | |
| raise EVIObjectiveError("parent GRPO output lacks completion_ids") | |
| if completion_ids.size(0) != len(grouped): | |
| raise EVIObjectiveError("parent completion batch no longer aligns with EVI rows") | |
| keys: list[tuple[str, str]] = [] | |
| for example, group in zip(inputs, grouped, strict=True): | |
| assert isinstance(group, Mapping) | |
| slot_id = example.get("slot_id") | |
| group_id = group.get("group_id") | |
| if not isinstance(slot_id, str) or not isinstance(group_id, str): | |
| raise EVIObjectiveError("EVI row lacks its slot/group identity") | |
| keys.append((slot_id, group_id)) | |
| counts = Counter(keys) | |
| seen: set[tuple[str, str]] = set() | |
| attached: list[dict[str, Any] | None] = [] | |
| for key, group in zip(keys, grouped, strict=True): | |
| assert isinstance(group, Mapping) | |
| if key in seen: | |
| attached.append(None) | |
| continue | |
| seen.add(key) | |
| scaled = copy.deepcopy(dict(group)) | |
| # RepeatSampler emits one identical EVI group per sampled completion. | |
| # Evaluate each local slot once and retain its exact batch weight. | |
| scaled["_loss_scale"] = counts[key] | |
| attached.append(scaled) | |
| output["evi_group"] = attached | |
| return output | |
| def _relationship(group: Mapping[str, Any], name: str) -> Mapping[str, Any]: | |
| relationships = group.get("relationships") | |
| if not isinstance(relationships, list): | |
| raise EVIObjectiveError("EVI group relationships must be a list") | |
| matches = [ | |
| value | |
| for value in relationships | |
| if isinstance(value, Mapping) and value.get("relation") == name | |
| ] | |
| if len(matches) != 1: | |
| raise EVIObjectiveError(f"EVI group must contain exactly one {name} relationship") | |
| return matches[0] | |
| def _encode_candidates( | |
| self, | |
| group: Mapping[str, Any], | |
| requests: Sequence[tuple[str, str]], | |
| ) -> tuple[dict[str, torch.Tensor], torch.Tensor, list[tuple[str, str]]]: | |
| try: | |
| from trl.data_utils import apply_chat_template, prepare_multimodal_messages | |
| except ImportError as exc: | |
| raise EVIObjectiveError("TRL multimodal chat utilities are unavailable") from exc | |
| from PIL import Image | |
| texts: list[str] = [] | |
| completion_token_ids: list[list[int]] = [] | |
| batch_images: list[list[Any]] = [] | |
| labels: list[tuple[str, str]] = [] | |
| for relation_name, target in requests: | |
| relation = self._relationship(group, relation_name) | |
| raw_paths = relation.get("image_paths") | |
| prompt = relation.get("prompt") | |
| if ( | |
| not isinstance(raw_paths, list) | |
| or len(raw_paths) != 1 | |
| or not isinstance(prompt, list) | |
| ): | |
| raise EVIObjectiveError( | |
| f"{relation_name} candidate scoring requires one image and one prompt" | |
| ) | |
| path = Path(str(raw_paths[0])) | |
| try: | |
| with Image.open(path) as image: | |
| images = [image.convert("RGB").copy()] | |
| except OSError as exc: | |
| raise EVIObjectiveError(f"cannot load EVI image {path}: {exc}") from exc | |
| completion = [ | |
| { | |
| "role": "assistant", | |
| "content": [{"type": "text", "text": f"<answer>{target}</answer>"}], | |
| } | |
| ] | |
| rendered = apply_chat_template( | |
| { | |
| "prompt": prepare_multimodal_messages( | |
| copy.deepcopy(prompt), | |
| images=images, | |
| ), | |
| "completion": prepare_multimodal_messages(completion), | |
| }, | |
| self.processing_class, | |
| **self.chat_template_kwargs, | |
| ) | |
| prompt_text, completion_text = rendered.get("prompt"), rendered.get("completion") | |
| if ( | |
| not isinstance(prompt_text, str) | |
| or not isinstance(completion_text, str) | |
| or not completion_text | |
| ): | |
| raise EVIObjectiveError("TRL candidate chat template returned malformed text") | |
| ids = self._tokenizer.encode(completion_text, add_special_tokens=False) | |
| if not isinstance(ids, list) or not ids: | |
| raise EVIObjectiveError("candidate response has no target tokens") | |
| texts.append(prompt_text + completion_text) | |
| completion_token_ids.append([int(value) for value in ids]) | |
| batch_images.append(images) | |
| labels.append((relation_name, target)) | |
| encoded = self.processing_class( | |
| images=batch_images, | |
| text=texts, | |
| padding=True, | |
| padding_side="left", | |
| return_tensors="pt", | |
| ) | |
| if not isinstance(encoded, Mapping): | |
| raise EVIObjectiveError("processor candidate batch is not a mapping") | |
| device = self.accelerator.device | |
| tensors = { | |
| str(key): value.to(device) | |
| for key, value in encoded.items() | |
| if isinstance(value, torch.Tensor) | |
| } | |
| input_ids = tensors.get("input_ids") | |
| attention_mask = tensors.get("attention_mask") | |
| if input_ids is None or attention_mask is None: | |
| raise EVIObjectiveError("processor candidate batch lacks input IDs or mask") | |
| completion_positions = torch.zeros_like(input_ids, dtype=torch.bool) | |
| for index, expected_ids in enumerate(completion_token_ids): | |
| valid_positions = attention_mask[index].bool().nonzero(as_tuple=False).flatten() | |
| valid = input_ids[index].index_select(0, valid_positions) | |
| expected = torch.tensor(expected_ids, device=valid.device, dtype=valid.dtype) | |
| if valid.numel() < expected.numel() or not torch.equal( | |
| valid[-expected.numel() :], | |
| expected, | |
| ): | |
| raise EVIObjectiveError( | |
| "candidate completion is not a token-exact suffix of the multimodal sequence" | |
| ) | |
| if int(valid_positions[-1].item()) != input_ids.size(1) - 1: | |
| raise EVIObjectiveError("candidate processor did not honor left padding") | |
| completion_positions[index, valid_positions[-expected.numel() :]] = True | |
| return tensors, completion_positions, labels | |
| def _forward_inputs( | |
| tensors: Mapping[str, torch.Tensor], | |
| *, | |
| logits_to_keep: int, | |
| output_attentions: bool = False, | |
| ) -> dict[str, Any]: | |
| allowed = { | |
| "input_ids", | |
| "attention_mask", | |
| "pixel_values", | |
| "image_grid_thw", | |
| "pixel_attention_mask", | |
| "spatial_shapes", | |
| "image_sizes", | |
| "token_type_ids", | |
| "mm_token_type_ids", | |
| "image_position_ids", | |
| "num_images", | |
| "num_tiles", | |
| } | |
| inputs: dict[str, Any] = {key: value for key, value in tensors.items() if key in allowed} | |
| inputs["use_cache"] = False | |
| inputs["logits_to_keep"] = logits_to_keep | |
| if output_attentions: | |
| inputs["output_attentions"] = True | |
| return inputs | |
| def _candidate_scores( | |
| self, | |
| model: Any, | |
| group: Mapping[str, Any], | |
| ) -> tuple[dict[str, dict[str, torch.Tensor]], dict[str, torch.Tensor]]: | |
| raw_candidates = group.get("candidate_targets") | |
| if ( | |
| not isinstance(raw_candidates, list) | |
| or len(raw_candidates) not in {2, 3} | |
| or any(not isinstance(target, str) or not target for target in raw_candidates) | |
| or len(set(raw_candidates)) != len(raw_candidates) | |
| ): | |
| raise EVIObjectiveError("EVI candidate target support is malformed") | |
| candidates = [str(target) for target in raw_candidates] | |
| full_answer = candidates[0] | |
| substitute_answer = ( | |
| str(self._relationship(group, "SUBSTITUTE").get("target")) | |
| if any( | |
| isinstance(value, Mapping) and value.get("relation") == "SUBSTITUTE" | |
| for value in group.get("relationships", []) | |
| ) | |
| else None | |
| ) | |
| requests = [ | |
| *[("FULL", candidate) for candidate in candidates], | |
| *[("CONTROL", candidate) for candidate in candidates], | |
| ] | |
| if substitute_answer is not None: | |
| requests.extend( | |
| [ | |
| ("SUBSTITUTE", substitute_answer), | |
| ("SUBSTITUTE", full_answer), | |
| ] | |
| ) | |
| requests.extend( | |
| [ | |
| ("MISSING", UNANSWERABLE_TOKEN), | |
| ("MISSING", full_answer), | |
| ] | |
| ) | |
| tensors, completion_positions, labels = self._encode_candidates(group, requests) | |
| max_completion = int(completion_positions.sum(dim=1).max().item()) | |
| outputs = model(**self._forward_inputs(tensors, logits_to_keep=max_completion + 1)) | |
| logits = getattr(outputs, "logits", None) | |
| if not isinstance(logits, torch.Tensor) or logits.ndim != 3: | |
| raise EVIObjectiveError("candidate forward did not return logits") | |
| logits = logits[:, :-1, :] | |
| logits = logits[:, -max_completion:, :].float() | |
| target_ids = tensors["input_ids"][:, -max_completion:] | |
| mask = completion_positions[:, -max_completion:] | |
| selected = logits.gather(-1, target_ids.unsqueeze(-1)).squeeze(-1) | |
| logps = selected - torch.logsumexp(logits, dim=-1) | |
| mean_scores = (logps * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1) | |
| if not torch.isfinite(mean_scores).all(): | |
| raise EVIObjectiveError("candidate target log-likelihood is NaN or Inf") | |
| nested: dict[str, dict[str, torch.Tensor]] = {} | |
| for label, score in zip(labels, mean_scores, strict=True): | |
| relation, target = label | |
| nested.setdefault(relation, {})[target] = score | |
| return nested, { | |
| "full_answer": torch.tensor(0.0, device=mean_scores.device), | |
| "substitute_present": torch.tensor( | |
| float(substitute_answer is not None), | |
| device=mean_scores.device, | |
| ), | |
| } | |
| def _attention_module(model: Any) -> tuple[str, Any]: | |
| candidates: list[tuple[int, str, Any]] = [] | |
| for name, module in model.named_modules(): | |
| layer_index = getattr(module, "layer_idx", None) | |
| if ( | |
| isinstance(layer_index, int) | |
| and hasattr(module, "q_proj") | |
| and hasattr(module, "k_proj") | |
| and hasattr(module, "v_proj") | |
| and "Attention" in type(module).__name__ | |
| ): | |
| candidates.append((layer_index, name, module)) | |
| if not candidates: | |
| raise EVIObjectiveError( | |
| "model exposes no usable full-attention module for evidence supervision" | |
| ) | |
| _, name, module = max(candidates, key=lambda value: (value[0], value[1])) | |
| return name, module | |
| def _evidence_loss( | |
| self, | |
| model: Any, | |
| group: Mapping[str, Any], | |
| ) -> torch.Tensor: | |
| full = self._relationship(group, "FULL") | |
| target = full.get("target") | |
| evidence = full.get("evidence") | |
| if not isinstance(target, str) or not isinstance(evidence, Mapping): | |
| raise EVIObjectiveError("FULL relationship lacks target/evidence supervision") | |
| tensors, completion_positions, _ = self._encode_candidates( | |
| group, | |
| [("FULL", target)], | |
| ) | |
| input_ids = tensors["input_ids"] | |
| image_grid = tensors.get("image_grid_thw") | |
| if image_grid is None or image_grid.shape != (1, 3): | |
| raise EVIObjectiveError( | |
| "evidence supervision requires Qwen image_grid_thw for one image" | |
| ) | |
| if not isinstance(self._image_token_id, int): | |
| raise EVIObjectiveError("evidence loss has no image-placeholder token ID") | |
| visual_positions = input_ids[0].eq(self._image_token_id) | |
| merge_size = int(getattr(self.processing_class.image_processor, "merge_size", 0)) | |
| projected = project_evidence_to_visual_tokens( | |
| evidence, | |
| image_grid_thw=image_grid[0], | |
| spatial_merge_size=merge_size, | |
| ) | |
| if int(visual_positions.sum().item()) != projected.numel(): | |
| raise EVIObjectiveError( | |
| "processor image-token count differs from projected evidence grid" | |
| ) | |
| layer_name, attention_module = self._attention_module(model) | |
| config = getattr(attention_module, "config", None) | |
| if config is None or not hasattr(config, "_attn_implementation"): | |
| raise EVIObjectiveError("attention module has no switchable eager implementation") | |
| original_implementation = config._attn_implementation | |
| captured: list[torch.Tensor] = [] | |
| def capture(_module: Any, _inputs: Any, output: Any) -> None: | |
| if ( | |
| isinstance(output, tuple) | |
| and len(output) >= 2 | |
| and isinstance(output[1], torch.Tensor) | |
| ): | |
| captured.append(output[1]) | |
| hook = attention_module.register_forward_hook(capture) | |
| try: | |
| config._attn_implementation = "eager" | |
| from trl.models.utils import disable_gradient_checkpointing | |
| with disable_gradient_checkpointing( | |
| self.model, | |
| getattr(self.args, "gradient_checkpointing_kwargs", None), | |
| ): | |
| model( | |
| **self._forward_inputs( | |
| tensors, | |
| logits_to_keep=1, | |
| output_attentions=True, | |
| ) | |
| ) | |
| finally: | |
| hook.remove() | |
| config._attn_implementation = original_implementation | |
| if not captured: | |
| raise EVIObjectiveError( | |
| "eager evidence forward did not expose usable attention weights" | |
| ) | |
| attention = captured[-1] | |
| if not attention.requires_grad: | |
| raise EVIObjectiveError("captured evidence attention is detached from autograd") | |
| loss = evidence_alignment_loss( | |
| attention, | |
| completion_positions=completion_positions[0], | |
| visual_positions=visual_positions, | |
| evidence_visual_mask=projected, | |
| ) | |
| self._last_evidence_diagnostics = { | |
| "attention_layer": layer_name, | |
| "attention_shape": list(attention.shape), | |
| "attention_requires_grad": attention.requires_grad, | |
| "visual_token_count": int(visual_positions.sum().item()), | |
| "evidence_visual_token_count": int(projected.sum().item()), | |
| "evidence_source": str(evidence.get("source")), | |
| "evidence_contract_sha256": canonical_json_hash(dict(evidence)), | |
| } | |
| return loss | |
| def _gradient_norm(term: torch.Tensor, model: Any) -> float: | |
| trainable = [parameter for parameter in model.parameters() if parameter.requires_grad] | |
| gradients = torch.autograd.grad( | |
| term, | |
| trainable, | |
| retain_graph=True, | |
| allow_unused=True, | |
| ) | |
| squared = sum( | |
| float(gradient.detach().float().pow(2).sum().item()) | |
| for gradient in gradients | |
| if gradient is not None | |
| ) | |
| return math.sqrt(squared) | |
| def _compute_loss(self, model: Any, inputs: Mapping[str, Any]) -> torch.Tensor: | |
| policy_loss = super()._compute_loss(model, inputs) | |
| if self.lambda_direction == 0.0 and self.lambda_evidence == 0.0: | |
| return policy_loss | |
| raw_groups = inputs.get("evi_group") | |
| if not isinstance(raw_groups, list): | |
| raise EVIObjectiveError("prepared EVI batch lacks grouped metadata") | |
| active = [group for group in raw_groups if isinstance(group, Mapping)] | |
| batch_size = len(raw_groups) | |
| if batch_size <= 0: | |
| raise EVIObjectiveError("prepared EVI batch is empty") | |
| # NOTE: do NOT early-return when `active` is empty. The metric gathers below | |
| # are cross-rank collectives (accelerator.gather); an early return here would | |
| # make the per-micro-batch collective COUNT data-dependent per rank (a rank | |
| # whose sharded micro-batch has no active EVI groups would fire 0 gathers | |
| # while another fires 5), desyncing the NCCL FIFO and deadlocking multi-rank | |
| # training. Instead we fall through: the data loop is a no-op, the loss terms | |
| # reduce to zero, and the gathers fire on zero tensors with a FIXED count on | |
| # every rank. The returned loss is identical (policy_loss + 0 + 0). | |
| direction_terms: list[torch.Tensor] = [] | |
| evidence_terms: list[torch.Tensor] = [] | |
| component_terms: dict[str, list[torch.Tensor]] = { | |
| "js_full_control": [], | |
| "substitute_hinge": [], | |
| "missing_hinge": [], | |
| } | |
| for group in active: | |
| scale = int(group.get("_loss_scale", 0)) | |
| if scale <= 0: | |
| raise EVIObjectiveError("EVI group loss scale must be positive") | |
| candidates = group.get("candidate_targets") | |
| if not isinstance(candidates, list): | |
| raise EVIObjectiveError("EVI group candidate support is missing") | |
| full_answer = str(self._relationship(group, "FULL").get("target", "")) | |
| substitute_answer = None | |
| relationships = group.get("relationships") | |
| if isinstance(relationships, list): | |
| substitute_rows = [ | |
| value | |
| for value in relationships | |
| if isinstance(value, Mapping) and value.get("relation") == "SUBSTITUTE" | |
| ] | |
| if substitute_rows: | |
| substitute_answer = str(substitute_rows[0].get("target", "")) | |
| if self.lambda_direction > 0.0: | |
| scores, _ = self._candidate_scores(model, group) | |
| direction, components = directional_loss( | |
| scores, | |
| candidate_targets=[str(value) for value in candidates], | |
| full_answer=full_answer, | |
| substitute_answer=substitute_answer, | |
| margin=self.direction_margin, | |
| ) | |
| direction_terms.append(direction * scale) | |
| for name, value in components.items(): | |
| component_terms[name].append(value.detach()) | |
| if self.lambda_evidence > 0.0: | |
| full_evidence = self._relationship(group, "FULL").get("evidence") | |
| if isinstance(full_evidence, Mapping) and full_evidence.get( | |
| "evidence_available", False | |
| ): | |
| evidence_terms.append(self._evidence_loss(model, group) * scale) | |
| device = policy_loss.device | |
| direction_loss = ( | |
| torch.stack(direction_terms).sum() / batch_size | |
| if direction_terms | |
| else torch.zeros((), device=device) | |
| ) | |
| evidence_loss = ( | |
| torch.stack(evidence_terms).sum() / batch_size | |
| if evidence_terms | |
| else torch.zeros((), device=device) | |
| ) | |
| mode = "train" if self.model.training else "eval" | |
| normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 | |
| direction_term = self.lambda_direction * direction_loss / normalizer | |
| evidence_term = self.lambda_evidence * evidence_loss / normalizer | |
| # The GPU contract probe verifies that the direction AND evidence paths | |
| # produce real, positive gradients on GPU. It can only verify the | |
| # evidence path on a step that actually exercises it: ``evidence_terms`` | |
| # is empty whenever no active group in this micro-batch has | |
| # ``evidence_available`` (the zero-pixel graceful skip; ~1.7k/12k | |
| # structural GQA/CLEVR groups). On such a step ``evidence_loss`` is a | |
| # gradless ``torch.zeros`` (line ~792), so ``_gradient_norm`` would | |
| # crash in ``torch.autograd.grad`` ("element 0 of tensors does not | |
| # require grad"), and even if it returned 0 the probe's | |
| # ``evidence_gradient_norm <= 0.0`` clause would fail it. So we DEFER | |
| # the probe (leave ``_probe_pending`` armed) until a step whose shard | |
| # has at least one evidence-available group. ``direction_terms`` is | |
| # non-empty whenever ``active`` is (direction runs for every active | |
| # group), so ``active and evidence_terms`` guarantees both paths are | |
| # exercised this step. Because phase-2 is a NEW process, ``__init__`` | |
| # re-arms the probe and it fires on phase-2's first evidence step | |
| # (step 6+) rather than phase-2's first step (which may lack evidence). | |
| if self._probe_pending and active and evidence_terms: | |
| direction_gradient_norm = ( | |
| self._gradient_norm(direction_term, model) if self.lambda_direction > 0.0 else 0.0 | |
| ) | |
| evidence_gradient_norm = ( | |
| self._gradient_norm(evidence_term, model) if self.lambda_evidence > 0.0 else 0.0 | |
| ) | |
| if ( | |
| self.lambda_direction <= 0.0 | |
| or self.lambda_evidence <= 0.0 | |
| or not math.isfinite(float(direction_loss.detach().item())) | |
| or not math.isfinite(float(evidence_loss.detach().item())) | |
| or float(direction_loss.detach().item()) < 0.0 | |
| or float(evidence_loss.detach().item()) < 0.0 | |
| or not math.isfinite(direction_gradient_norm) | |
| or not math.isfinite(evidence_gradient_norm) | |
| or direction_gradient_norm <= 0.0 | |
| or evidence_gradient_norm <= 0.0 | |
| or not isinstance(self._last_evidence_diagnostics, dict) | |
| ): | |
| raise EVIObjectiveError("EVI-PO GPU objective contract probe failed") | |
| first_group = active[0] | |
| relationships = first_group.get("relationships") | |
| self.evi_gpu_contract_probe = { | |
| "schema_version": 1, | |
| "status": "passed", | |
| "adapter_version": EVI_PO_ADAPTER_VERSION, | |
| "relationship_states": { | |
| str(value["relation"]): str(value["state"]) | |
| for value in relationships | |
| if isinstance(value, Mapping) | |
| } | |
| if isinstance(relationships, list) | |
| else {}, | |
| "substitute_available": any( | |
| isinstance(value, Mapping) and value.get("relation") == "SUBSTITUTE" | |
| for value in relationships | |
| ) | |
| if isinstance(relationships, list) | |
| else False, | |
| "lambda_direction": self.lambda_direction, | |
| "lambda_evidence": self.lambda_evidence, | |
| "margin": self.direction_margin, | |
| "direction_loss": float(direction_loss.detach().item()), | |
| "evidence_loss": float(evidence_loss.detach().item()), | |
| "direction_gradient_norm": direction_gradient_norm, | |
| "evidence_gradient_norm": evidence_gradient_norm, | |
| **self._last_evidence_diagnostics, | |
| } | |
| self._probe_pending = False | |
| self._metrics[mode]["evi/direction_loss"].append( | |
| self.accelerator.gather(direction_loss.detach()).nanmean().item() | |
| ) | |
| self._metrics[mode]["evi/evidence_loss"].append( | |
| self.accelerator.gather(evidence_loss.detach()).nanmean().item() | |
| ) | |
| # Fire a FIXED number of component gathers on every rank (in a stable order) | |
| # so the cross-rank collective count never depends on whether this rank's | |
| # sharded micro-batch happened to contain active EVI groups. See the note | |
| # above on why the count must be rank-invariant. | |
| for name in ("js_full_control", "substitute_hinge", "missing_hinge"): | |
| values = component_terms[name] | |
| mean_value = torch.stack(values).mean() if values else torch.zeros((), device=device) | |
| self._metrics[mode][f"evi/{name}"].append( | |
| self.accelerator.gather(mean_value).nanmean().item() | |
| ) | |
| return policy_loss + direction_term + evidence_term | |