File size: 4,246 Bytes
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Method A - PhyCausal-LNP.

Hierarchical substructure set encoding + physically biased set attention +
causal/environment disentanglement with gradient reversal, trained with a
Huber regression, a within-study pairwise ranking loss, an adversarial domain
loss, an environment-absorption loss and an orthogonality penalty.
"""

from __future__ import annotations

import math
from typing import Sequence

import torch
import torch.nn as nn
import torch.nn.functional as F

from ..store import FeatureStore
from ..trainer import NeuralModel, TrainConfig
from .blocks import grad_reverse
from .set_base import HierarchicalSetEncoder, PHYS_DIM


class PhyCausalModule(nn.Module):
    def __init__(
        self,
        fp_dim: int,
        ctx_dim: int,
        n_studies: int,
        d_model: int = 192,
        n_heads: int = 6,
        n_layers: int = 3,
        z_dim: int = 96,
        dropout: float = 0.1,
        lam_rank: float = 0.5,
        lam_adv: float = 0.1,
        lam_env: float = 0.1,
        lam_ortho: float = 0.05,
        rank_gamma: float = 2.0,
        use_physics_bias: bool = True,
        use_condition: bool = True,
    ):
        super().__init__()
        self.encoder = HierarchicalSetEncoder(
            fp_dim=fp_dim, ctx_dim=ctx_dim, d_model=d_model, n_heads=n_heads,
            n_layers=n_layers, dropout=dropout, phys_dim=PHYS_DIM,
        )
        self.causal = nn.Sequential(nn.Linear(d_model, z_dim), nn.LayerNorm(z_dim), nn.SiLU())
        self.env = nn.Sequential(nn.Linear(d_model, z_dim), nn.LayerNorm(z_dim), nn.SiLU())
        self.predictor = nn.Sequential(nn.Linear(z_dim, 64), nn.SiLU(), nn.Dropout(dropout), nn.Linear(64, 1))
        self.dom_c = nn.Sequential(nn.Linear(z_dim, 64), nn.SiLU(), nn.Linear(64, n_studies))
        self.dom_e = nn.Sequential(nn.Linear(z_dim, 64), nn.SiLU(), nn.Linear(64, n_studies))
        self.lam_rank, self.lam_adv, self.lam_env, self.lam_ortho = lam_rank, lam_adv, lam_env, lam_ortho
        self.rank_gamma = rank_gamma
        self.use_physics_bias = use_physics_bias
        self.use_condition = use_condition

    def forward(self, batch, grl_alpha: float = 1.0):
        z, z_lnp, z_cond, nodes = self.encoder(batch, use_physics=self.use_physics_bias)
        if not self.use_condition:
            z = z_lnp
        z_c = self.causal(z)
        z_e = self.env(z)
        y_hat = self.predictor(z_c).squeeze(-1)
        d_c = self.dom_c(grad_reverse(z_c, grl_alpha))
        d_e = self.dom_e(z_e)
        return {"y_hat": y_hat, "z_c": z_c, "z_e": z_e, "d_c": d_c, "d_e": d_e, "z": z}

    def compute_loss(self, batch, out, epoch=0, n_epochs=1):
        p = min(1.0, epoch / max(1.0, 0.3 * n_epochs))
        grl_alpha = 2.0 / (1.0 + math.exp(-10.0 * p)) - 1.0
        reg = F.smooth_l1_loss(out["y_hat"], batch["y"])

        study = batch["study_id"]
        same = study[:, None] == study[None, :]
        diff = batch["y"][:, None] - batch["y"][None, :]
        valid = same & (diff > 1e-4)
        if valid.any():
            pred_diff = out["y_hat"][:, None] - out["y_hat"][None, :]
            rank = F.softplus(-self.rank_gamma * pred_diff[valid]).mean()
        else:
            rank = torch.zeros((), device=reg.device)

        adv = F.cross_entropy(out["d_c"], study)
        env = F.cross_entropy(out["d_e"], study)

        zc = out["z_c"]
        ze = out["z_e"]
        zc = (zc - zc.mean(0)) / (zc.std(0) + 1e-6)
        ze = (ze - ze.mean(0)) / (ze.std(0) + 1e-6)
        ortho = ((zc.t() @ ze) / max(1, zc.shape[0])).pow(2).mean()

        total = reg + self.lam_rank * rank + self.lam_adv * adv + self.lam_env * env + self.lam_ortho * ortho
        return total, {
            "reg": float(reg.detach()), "rank": float(rank.detach()),
            "adv": float(adv.detach()), "env": float(env.detach()), "ortho": float(ortho.detach()),
        }


class PhyCausalLNP(NeuralModel):
    name = "phcausal"

    def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
        return PhyCausalModule(
            fp_dim=store.il_fp.shape[1], ctx_dim=store.ctx_dim, n_studies=store.n_studies, **self.kwargs
        )

    def need(self) -> Sequence[str]:
        return ("y", "ctx", "ratios", "nodes", "helpers", "study_id")