Datasets:
Download src/explicit_learning/training/papo.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/training/papo.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/training/papo.py
-
curl -L -o papo.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/training/papo.py
14.4 kB
| """PAPO-G objective adapter for the pinned TRL 1.9.1 stack. | |
| TRL 1.9.1 no longer ships ``trl.experimental.papo``. This narrow adapter | |
| ports the Apache-2.0 PAPO-G perception term from TRL 0.29.1 onto the current | |
| ``GRPOTrainer`` while delegating the complete policy loss, vLLM importance | |
| sampling, and logging implementation to the pinned parent trainer. | |
| Only ``pixel_values`` are cloned and masked. Prompt IDs, attention masks, | |
| question text, choices, and completion IDs are never mutated. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import math | |
| from collections.abc import Mapping | |
| from typing import Any | |
| import torch | |
| from trl import GRPOTrainer | |
| from .aligned_grpo import AlignedGRPOTrainer | |
| from .papo_contract import ( | |
| GAMMA_ZERO_GRADIENT_ABS_FLOOR, | |
| GAMMA_ZERO_GRADIENT_REL_TOL, | |
| PAPO_PROBE_MAX_DEGENERATE_BATCHES, | |
| validate_trl_parent_contract, | |
| ) | |
| validate_trl_parent_contract(GRPOTrainer) | |
| class PAPOTrainer(AlignedGRPOTrainer): | |
| """TRL 1.9.1 GRPO plus the frozen PAPO-G implicit perception objective.""" | |
| def __init__(self, *args: Any, papo_config: Mapping[str, Any], **kwargs: Any) -> None: | |
| if str(papo_config.get("variant")) != "PAPO-G": | |
| raise ValueError("controlled adapter supports PAPO-G only") | |
| self.perception_loss_weight = float(papo_config["perception_loss_weight"]) | |
| self.mask_ratio = float(papo_config["mask_ratio"]) | |
| self.mask_type = str(papo_config["mask_type"]) | |
| self.der_loss_weight1 = float(papo_config["der_loss_weight1"]) | |
| self.der_loss_weight2 = float(papo_config["der_loss_weight2"]) | |
| self._probe_pending = bool(papo_config.get("require_gpu_contract_probe", False)) | |
| self.papo_gpu_contract_probe: dict[str, Any] | None = None | |
| self._probe_degenerate_batches = 0 | |
| self._last_mask_keep_ratio: float | None = None | |
| if not 0.0 < self.mask_ratio < 1.0: | |
| raise ValueError("PAPO mask_ratio must be in (0,1)") | |
| if self.mask_type != "random": | |
| raise ValueError("controlled PAPO adapter supports random masking only") | |
| if self.der_loss_weight1 != 0.0 or self.der_loss_weight2 != 0.0: | |
| raise ValueError("controlled PAPO-G freezes both DER weights at zero") | |
| if self.perception_loss_weight < 0.0: | |
| raise ValueError("PAPO perception_loss_weight must be non-negative") | |
| self._capture_papo_forward = False | |
| self._papo_original: tuple[torch.Tensor, torch.Tensor] | None = None | |
| super().__init__(*args, **kwargs) | |
| def _get_per_token_logps_and_entropies( | |
| self, *args: Any, **kwargs: Any | |
| ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: | |
| result = super()._get_per_token_logps_and_entropies(*args, **kwargs) | |
| if self._capture_papo_forward and self._papo_original is None: | |
| self._papo_original = (result[0], result[1]) | |
| return result | |
| def _masked_pixels(self, pixel_values: torch.Tensor) -> torch.Tensor: | |
| """Apply the upstream PAPO random scalar mask to a cloned tensor.""" | |
| keep = torch.rand_like(pixel_values, dtype=torch.float32) > self.mask_ratio | |
| self._last_mask_keep_ratio = float(keep.float().mean().item()) | |
| return pixel_values.clone() * keep.to(dtype=pixel_values.dtype) | |
| def _tensor_sha256(value: torch.Tensor) -> str: | |
| payload = value.detach().contiguous().view(torch.uint8).cpu().numpy().tobytes() | |
| return hashlib.sha256(payload).hexdigest() | |
| def _compute_loss(self, model: Any, inputs: Mapping[str, Any]) -> torch.Tensor: | |
| self._papo_original = None | |
| self._capture_papo_forward = True | |
| try: | |
| policy_loss = super()._compute_loss(model, inputs) | |
| finally: | |
| self._capture_papo_forward = False | |
| if self._papo_original is None: | |
| raise RuntimeError("PAPO could not capture the original-image policy forward") | |
| pixel_values = inputs.get("pixel_values") | |
| if not isinstance(pixel_values, torch.Tensor): | |
| raise RuntimeError("PAPO requires tensor pixel_values in every training batch") | |
| prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] | |
| completion_ids, completion_mask = ( | |
| inputs["completion_ids"], | |
| inputs["completion_mask"], | |
| ) | |
| input_ids = torch.cat([prompt_ids, completion_ids], dim=1) | |
| attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) | |
| logits_to_keep = completion_ids.size(1) | |
| original_logps, _ = self._papo_original | |
| probe_tensors = ( | |
| { | |
| "pixel_values": pixel_values.detach().clone(), | |
| "prompt_ids": prompt_ids.detach().clone(), | |
| "prompt_mask": prompt_mask.detach().clone(), | |
| "completion_ids": completion_ids.detach().clone(), | |
| "completion_mask": completion_mask.detach().clone(), | |
| } | |
| if self._probe_pending | |
| else None | |
| ) | |
| if self._probe_pending: | |
| if pixel_values.is_cuda: | |
| generator_state = torch.cuda.get_rng_state(pixel_values.device) | |
| else: | |
| generator_state = torch.random.get_rng_state() | |
| masked_pixels = self._masked_pixels(pixel_values) | |
| after_mask_state = ( | |
| torch.cuda.get_rng_state(pixel_values.device) | |
| if pixel_values.is_cuda | |
| else torch.random.get_rng_state() | |
| ) | |
| if pixel_values.is_cuda: | |
| torch.cuda.set_rng_state(generator_state, pixel_values.device) | |
| else: | |
| torch.random.set_rng_state(generator_state) | |
| replay_pixels = self._masked_pixels(pixel_values) | |
| deterministic_mask_replay = torch.equal(masked_pixels, replay_pixels) | |
| if pixel_values.is_cuda: | |
| torch.cuda.set_rng_state(after_mask_state, pixel_values.device) | |
| else: | |
| torch.random.set_rng_state(after_mask_state) | |
| else: | |
| masked_pixels = self._masked_pixels(pixel_values) | |
| deterministic_mask_replay = True | |
| masked_logps, _, _ = super()._get_per_token_logps_and_entropies( | |
| model, | |
| input_ids, | |
| attention_mask, | |
| logits_to_keep, | |
| compute_entropy=True, | |
| compute_aux_loss=False, | |
| pixel_values=masked_pixels, | |
| image_grid_thw=inputs.get("image_grid_thw"), | |
| num_images=inputs.get("num_images"), | |
| pixel_attention_mask=inputs.get("pixel_attention_mask"), | |
| spatial_shapes=inputs.get("spatial_shapes"), | |
| num_tiles=inputs.get("num_tiles"), | |
| image_sizes=inputs.get("image_sizes"), | |
| token_type_ids=inputs.get("token_type_ids"), | |
| mm_token_type_ids=inputs.get("mm_token_type_ids"), | |
| image_position_ids=inputs.get("image_position_ids"), | |
| ) | |
| perception_kl = ( | |
| torch.exp(masked_logps - original_logps) - (masked_logps - original_logps) - 1 | |
| ) | |
| perception_kl = torch.clamp(perception_kl, min=0.0, max=0.2) | |
| active = completion_mask | |
| if "tool_mask" in inputs: | |
| active = active * inputs["tool_mask"] | |
| mean_kl = (perception_kl * active).sum() / active.sum().clamp(min=1.0) | |
| mode = "train" if self.model.training else "eval" | |
| normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 | |
| perception_term = self.perception_loss_weight * mean_kl / normalizer | |
| if self._probe_pending: | |
| assert probe_tensors is not None | |
| mean_kl_value = float(mean_kl.detach().item()) | |
| if mean_kl_value <= 0.0: | |
| # Image-invariant batch: the 60% mask left the completion logps | |
| # bit-exact identical, so mean_kl is exactly 0.0 and a zero | |
| # perception gradient is the CORRECT result -- not a wiring | |
| # failure. Defer the probe to a later batch with real perception | |
| # signal instead of finalizing (and failing) on this one. Fail | |
| # loudly only when the masked forward never perturbs the logits, | |
| # which would indicate a genuine masking/forward wiring bug. | |
| self._probe_degenerate_batches += 1 | |
| if self._probe_degenerate_batches > PAPO_PROBE_MAX_DEGENERATE_BATCHES: | |
| raise RuntimeError( | |
| "PAPO GPU contract probe could not find a perception-live " | |
| f"batch in {PAPO_PROBE_MAX_DEGENERATE_BATCHES} consecutive " | |
| "steps (every batch read mean_kl == 0.0). This indicates the " | |
| "masked forward does not affect completion logits (a " | |
| "masking/forward wiring bug) or the probe batch order is " | |
| "image-invariant; refusing to certify." | |
| ) | |
| self._metrics[mode]["papo/perception_kl"].append( | |
| self.accelerator.gather(mean_kl.detach()).nanmean().item() | |
| ) | |
| return policy_loss - perception_term | |
| unchanged = { | |
| name: torch.equal(inputs[name], snapshot) | |
| for name, snapshot in probe_tensors.items() | |
| } | |
| trainable = [parameter for parameter in model.parameters() if parameter.requires_grad] | |
| zero_gamma_loss = policy_loss - (0.0 * mean_kl / normalizer) | |
| parent_gradients = torch.autograd.grad( | |
| policy_loss, | |
| trainable, | |
| retain_graph=True, | |
| allow_unused=True, | |
| ) | |
| gamma_zero_gradients = torch.autograd.grad( | |
| zero_gamma_loss, | |
| trainable, | |
| retain_graph=True, | |
| allow_unused=True, | |
| ) | |
| gamma_zero_gradient_max_abs_diff = 0.0 | |
| gamma_zero_gradient_structure_equal = True | |
| parent_gradient_max_abs = 0.0 | |
| for parent_gradient, gamma_zero_gradient in zip( | |
| parent_gradients, | |
| gamma_zero_gradients, | |
| strict=True, | |
| ): | |
| if (parent_gradient is None) != (gamma_zero_gradient is None): | |
| gamma_zero_gradient_structure_equal = False | |
| break | |
| if parent_gradient is not None and gamma_zero_gradient is not None: | |
| gamma_zero_gradient_max_abs_diff = max( | |
| gamma_zero_gradient_max_abs_diff, | |
| float( | |
| (parent_gradient.detach() - gamma_zero_gradient.detach()) | |
| .abs() | |
| .max() | |
| .item() | |
| ), | |
| ) | |
| parent_gradient_max_abs = max( | |
| parent_gradient_max_abs, | |
| float(parent_gradient.detach().abs().max().item()), | |
| ) | |
| gamma_zero_gradient_within_tolerance = ( | |
| gamma_zero_gradient_max_abs_diff | |
| <= GAMMA_ZERO_GRADIENT_REL_TOL * parent_gradient_max_abs | |
| + GAMMA_ZERO_GRADIENT_ABS_FLOOR | |
| ) | |
| perception_gradients = torch.autograd.grad( | |
| perception_term, | |
| trainable, | |
| retain_graph=True, | |
| allow_unused=True, | |
| ) | |
| gradient_sq = sum( | |
| float(gradient.detach().float().pow(2).sum().item()) | |
| for gradient in perception_gradients | |
| if gradient is not None | |
| ) | |
| perception_gradient_norm = math.sqrt(gradient_sq) | |
| gamma_zero_max_abs_diff = float( | |
| (zero_gamma_loss.detach() - policy_loss.detach()).abs().max().item() | |
| ) | |
| observed_mask_ratio = 1.0 - float(self._last_mask_keep_ratio or 0.0) | |
| passed = ( | |
| all(unchanged.values()) | |
| and deterministic_mask_replay | |
| and 0.55 <= observed_mask_ratio <= 0.65 | |
| and gamma_zero_max_abs_diff == 0.0 | |
| and gamma_zero_gradient_structure_equal | |
| and gamma_zero_gradient_within_tolerance | |
| and math.isfinite(float(mean_kl.detach().item())) | |
| and float(mean_kl.detach().item()) > 0.0 | |
| and math.isfinite(perception_gradient_norm) | |
| and perception_gradient_norm > 0.0 | |
| ) | |
| self.papo_gpu_contract_probe = { | |
| "schema_version": 1, | |
| "status": "passed" if passed else "failed", | |
| "input_tensors_unchanged": unchanged, | |
| "prompt_ids_sha256": self._tensor_sha256(prompt_ids), | |
| "prompt_mask_sha256": self._tensor_sha256(prompt_mask), | |
| "completion_ids_sha256": self._tensor_sha256(completion_ids), | |
| "completion_mask_sha256": self._tensor_sha256(completion_mask), | |
| "original_pixels_sha256": self._tensor_sha256(pixel_values), | |
| "masked_pixels_sha256": self._tensor_sha256(masked_pixels), | |
| "deterministic_mask_replay": deterministic_mask_replay, | |
| "requested_mask_ratio": self.mask_ratio, | |
| "observed_mask_ratio": observed_mask_ratio, | |
| "gamma_zero_loss_max_abs_diff": gamma_zero_max_abs_diff, | |
| "gamma_zero_gradient_structure_equal": (gamma_zero_gradient_structure_equal), | |
| "gamma_zero_gradient_max_abs_diff": (gamma_zero_gradient_max_abs_diff), | |
| "gamma_zero_parent_gradient_max_abs": (parent_gradient_max_abs), | |
| "perception_kl": float(mean_kl.detach().item()), | |
| "perception_gradient_norm": perception_gradient_norm, | |
| "der_loss_weight1": self.der_loss_weight1, | |
| "der_loss_weight2": self.der_loss_weight2, | |
| } | |
| self._probe_pending = False | |
| if not passed: | |
| raise RuntimeError( | |
| f"PAPO GPU contract probe failed: {self.papo_gpu_contract_probe}" | |
| ) | |
| self._metrics[mode]["papo/perception_kl"].append( | |
| self.accelerator.gather(mean_kl.detach()).nanmean().item() | |
| ) | |
| return policy_loss - perception_term | |