File size: 40,802 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
"""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

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

    @staticmethod
    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,
            ),
        }

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

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