File size: 6,081 Bytes
ff37249
 
 
 
 
818f91f
 
 
 
 
 
 
ff37249
 
 
818f91f
ff37249
818f91f
ff37249
 
 
 
 
818f91f
 
 
 
 
 
ff37249
818f91f
 
 
ff37249
818f91f
 
 
ff37249
818f91f
 
ff37249
 
 
 
 
 
818f91f
ff37249
818f91f
 
 
 
 
 
 
ff37249
818f91f
ff37249
818f91f
ff37249
818f91f
 
ff37249
 
818f91f
 
ff37249
 
 
 
818f91f
ff37249
 
818f91f
 
ff37249
 
 
 
 
 
818f91f
 
ff37249
818f91f
 
 
 
ff37249
 
818f91f
ff37249
818f91f
 
 
ff37249
818f91f
 
 
 
 
 
ff37249
 
818f91f
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
import torch
from torch import nn
from aio.interface import NCV, NMV
from aio.actor import unpack
from aio.sim.model import KNOTS, LAB_LAGS, NLAB, MT, P_DMC, LAM_DMC, LAM_REL
J = 240
SPAN = 0.45
RATE = 0.95
LEVEL = 0.95
S_CLIP = 12.0
AGE = 40
SMEM = NMV * J + NMV + NCV

def hat(lags, knots):
    t = torch.as_tensor(lags, dtype=torch.float64)
    L = torch.tensor((0,) + tuple(knots), dtype=torch.float64)
    one = torch.ones_like(t)
    return torch.stack([torch.minimum(((t - L[l - 1]) / (L[l] - L[l - 1])).clamp(0, 1), ((L[l + 1] - t) / (L[l + 1] - L[l])).clamp(0, 1) if l + 1 < len(L) else one) for l in range(1, len(L))], 1)

class Formula(nn.Module):

    def __init__(self, knots=LAB_LAGS):
        super().__init__()
        self.knots, last = (tuple(knots), knots[-1])
        age, lags = (1 + torch.arange(J), torch.tensor(LAB_LAGS))
        B = lambda t: hat(t, knots)
        W = torch.stack([B(age + L) - B(age) for L in LAB_LAGS], 0)
        V = ((age[None] + lags[:, None] - last).clamp_min(0) - (age[None] - last).clamp_min(0)).double() / (last - knots[-2])
        W1 = list((1 - RATE) * (B(age) - B(age - 1)))
        for j in range(1, J):
            W1[j] = W1[j] + RATE * W1[j - 1]
        self.ends = (float(last - knots[-2]), float(knots[-2] - knots[-3]))
        WA = torch.stack([B(age) - B((age - a).clamp_min(0)) for a in range(AGE + 1)], 0)
        q = torch.arange(P_DMC)
        A = torch.stack([B((q - t + 1).clamp_min(0)) for t in MT], 0)
        for name, x in (('W', W.flip(1).reshape(NLAB, J, -1).permute(1, 0, 2).reshape(J, -1)), ('V', V.flip(1).T), ('W1', torch.stack(W1, 0).flip(0)), ('WA', WA.flip(1).permute(1, 0, 2).reshape(J, -1))):
            self.register_buffer(name, x.float().contiguous(), persistent=False)
        self.register_buffer('lags', lags.float(), persistent=False)
        self.register_buffer('C', torch.einsum('mqk,nql->mnkl', A, A), persistent=False)
        self.register_buffer('F', torch.einsum('mqk,ql->mlk', A, hat(q + 1, LAB_LAGS)), persistent=False)

    @torch.no_grad()
    def memory(self, obs, state=None):
        cv, mv, _ = unpack(obs)
        b, T = obs.shape[:2]
        state = obs.new_zeros(b, SMEM) if state is None else state
        hist, wide, dys = (state[:, :NMV * J].reshape(b, NMV, J).float(), state[:, NMV * J:NMV * J + NMV].float(), state[:, NMV * J + NMV:].float())
        mm = mv[..., -1].float()
        inv = (mm / mv[..., 2].float().clamp_min(1e-06)).nan_to_num(0.0, 0.0, 0.0)
        wide = torch.maximum(wide[:, None], inv.cummax(1).values)
        du = (mv[..., 1].float() * mm).nan_to_num(0.0, 0.0, 0.0).clamp(-1000.0, 1000.0) * SPAN * inv / wide.clamp_min(1e-09)
        win = torch.cat((hist, du.transpose(1, 2)), -1).unfold(-1, J, 1)[:, :, 1:]
        Z = (win @ self.W).reshape(b, NMV, T, NLAB, -1).transpose(1, 2)
        tail, Z1 = ((win @ self.V).transpose(1, 2), (win @ self.W1).transpose(1, 2))
        dy, out = ((cv[..., 1] * cv[..., -1]).float().nan_to_num(0.0, 0.0, 0.0).clamp(-1000.0, 1000.0), [])
        for t in range(T):
            dys = RATE * dys + (1 - RATE) * dy[:, t]
            out.append(dys)
        old, since = ((torch.expm1(cv[..., 8].float().clamp(0.0, 6.0)) * cv[..., -1].float()).round().clamp(0, AGE).long(), None)
        has = (old > 0).flatten(1).any(1)
        if bool(has.any()):
            G = (win[has] @ self.WA).reshape(-1, NMV, T, AGE + 1, self.WA.shape[1] // (AGE + 1)).permute(0, 2, 1, 3, 4)
            G = torch.gather(G[:, :, None].expand(-1, -1, NCV, -1, -1, -1), 4, old[has][:, :, :, None, None, None].expand(-1, -1, -1, NMV, 1, G.shape[-1]))[:, :, :, :, 0]
            since = G.new_zeros(b, T, NCV, NMV, G.shape[-1]).index_copy(0, has.nonzero()[:, 0], G)
        state = torch.cat((win[:, :, -1].reshape(b, NMV * J), wide[:, -1], dys), -1).to(state.dtype)
        return ((Z, tail, Z1, torch.stack(out, 1), SPAN / wide.clamp_min(1e-09) * mm, since), state)

    @staticmethod
    def weight(obs):
        cv = unpack(obs)[0].float()
        return cv[..., 5].clamp_min(0.0).sqrt() * cv[..., 6] * cv[..., -1]

    def rising(self, S):
        a, b = ((S[..., -1] - S[..., -2]).abs().sum(-1) / self.ends[0], (S[..., -2] - S[..., -3]).abs().sum(-1) / self.ends[1])
        return ((a > LEVEL * b) & (a > 1e-09)).to(S.dtype)

    def heading(self, obs, S, mem):
        Z, tail, Z1, dys = (x.to(S.dtype) for x in mem[:4])
        cv = unpack(obs)[0]
        lev = self.rising(S.detach())
        pend = torch.einsum('btaik,btilk->btal', S, Z)
        more = torch.einsum('btai,btil->btal', S[..., -1] - S[..., -2], tail)
        rate = dys - torch.einsum('btaik,btik->bta', S, Z1)
        now = -cv[..., 0].to(S.dtype)
        if mem[5] is not None:
            now = now - torch.einsum('btaik,btaik->bta', S, mem[5].to(S.dtype))
        E, w = (now[..., None] - pend - lev[..., None] * (more + rate[..., None] * self.lags.to(S.dtype)), self.weight(obs).to(S.dtype))
        return (E * w[..., None], rate * w, lev)

    def move(self, obs, S, E, mem, chunk=2048):
        b, T, M = (S.shape[0], S.shape[1], len(MT))
        w = self.weight(obs)[:, :, :NMV].flatten(0, 1).double()
        s = S[:, :, :NMV].flatten(0, 1).double() * w[:, :, None, None]
        e, out = (E[:, :, :NMV].flatten(0, 1).double(), [])
        first = torch.eye(M * NMV, NMV, dtype=torch.float64, device=S.device)
        for a in range(0, s.shape[0], chunk):
            sa = s[a:a + chunk]
            with torch.no_grad():
                G = torch.einsum('xijkl,mnkl->xminj', torch.einsum('xaik,xajl->xijkl', sa, sa), self.C).reshape(-1, M * NMV, M * NMV)
                H = G + torch.diag_embed(LAM_DMC * P_DMC + LAM_REL * G.diagonal(dim1=1, dim2=2))
                Y = torch.linalg.solve_ex(H, first.expand(H.shape[0], -1, -1))[0].nan_to_num(0.0, 0.0, 0.0)
            g = torch.einsum('xaik,mlk,xal->xmi', sa, self.F, e[a:a + chunk]).reshape(-1, M * NMV)
            out.append(torch.einsum('xqi,xq->xi', Y, g))
        slew = mem[4]
        return (torch.cat(out, 0).reshape(b, T, NMV) / slew.double().clamp_min(1e-09)).float() * (slew > 0)