File size: 14,436 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)

    @staticmethod
    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