File size: 3,829 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Feature admission: the Tiwari rule.

A feature may enter z_t only if it is both
  (a) probe-aligned    - it carries signal about the unsafe commitment label on
                         the commitment contrast, and
  (b) behaviourally sensitive - ablating it changes the action the decision
                         function takes, not merely a probe readout.

The three sets (shared, probe-only, random) are ablated and steered under a
coherence gate, and flip rates are logged for all three. The test is
pre-registered; see PRE_REGISTRATION.md, H1 and F1.

Definition used for "behavioural sensitivity": the decision function is the
CLSA risk head applied to the candidate set. A feature set flips if zeroing it
changes the argmin-risk candidate on an item. This is a property of the agent's
policy, not a claim about the backbone's own behaviour, and is reported as such.
"""
from __future__ import annotations

import numpy as np
from scipy.stats import pearsonr


def alignment_scores(z: np.ndarray, y: np.ndarray) -> np.ndarray:
    """|point-biserial correlation| of each feature with the commitment label."""
    scores = np.zeros(z.shape[1], dtype=np.float32)
    if y.sum() < 3 or (len(y) - y.sum()) < 3:
        return scores
    for j in range(z.shape[1]):
        col = z[:, j]
        if float(col.std()) < 1e-9:
            continue
        try:
            r, _ = pearsonr(col, y)
        except Exception:
            r = 0.0
        scores[j] = abs(0.0 if np.isnan(r) else r)
    return scores


def choose_features(
    align: np.ndarray, flip_scores: np.ndarray, align_thr: float, flip_thr: float
) -> dict[str, np.ndarray]:
    """Shared (aligned and sensitive), probe-only (aligned, insensitive)."""
    aligned = align >= align_thr
    sensitive = flip_scores >= flip_thr
    shared = aligned & sensitive
    probe_only = aligned & ~sensitive
    if not shared.any():
        # Keep the most aligned sensitive feature so the hybrid state is non-empty;
        # this fallback is logged as a deviation in the admission report.
        candidates = np.where(sensitive)[0]
        if len(candidates):
            best = candidates[np.argmax(align[candidates])]
            shared = np.zeros_like(aligned)
            shared[best] = True
            probe_only = probe_only & ~shared
    return {"shared": shared, "probe_only": probe_only}


def random_set(n_features: int, size: int, exclude: np.ndarray, seed: int) -> np.ndarray:
    rng = np.random.default_rng(seed)
    pool = [j for j in range(n_features) if not exclude[j]]
    pick = rng.choice(pool, size=min(size, len(pool)), replace=False) if pool else []
    mask = np.zeros(n_features, dtype=bool)
    mask[list(pick)] = True
    return mask


def flip_rate(score_fn, Z: np.ndarray, masks: list[np.ndarray], batch: int = 256) -> float:
    """Fraction of items whose chosen action changes when a feature set is zeroed.

    score_fn(z_batch, action_index) -> risk scores; the chosen action is the
    argmin. Ablation zeroes the masked features.
    """
    if not masks:
        return 0.0
    n = Z.shape[0]
    flips = 0
    base_scores = score_fn(Z)
    base_choice = np.argmin(base_scores, axis=1)
    for mask in masks:
        Z2 = Z.copy()
        Z2[:, mask] = 0.0
        choice = np.argmin(score_fn(Z2), axis=1)
        flips += int((choice != base_choice).sum())
    return float(flips / (n * len(masks))) if n else 0.0


def steering_effect(score_fn, Z: np.ndarray, mask: np.ndarray, strength: float = 2.0) -> float:
    """Mean absolute change in risk score under a scaled intervention on a set."""
    if not mask.any():
        return 0.0
    Z2 = Z.copy()
    Z2[:, mask] = Z2[:, mask] * strength
    return float(np.mean(np.abs(score_fn(Z2) - score_fn(Z))))