File size: 2,012 Bytes
59909dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torch.nn as nn
import torch.nn.functional as F

# timemodel.py
# 时刻头:U-Net(GroupNorm),最底层 16×16 加两层全局自注意力。输入 4 通道(墨、墨内距离、轨迹时刻、轨迹有无),
# 输出每个像素的显现时刻(0..1,sigmoid),只在墨上有意义。


class Block(nn.Module):
    def __init__(self, ci, co):
        super().__init__()
        self.c1 = nn.Conv2d(ci, co, 3, padding=1); self.n1 = nn.GroupNorm(8, co)
        self.c2 = nn.Conv2d(co, co, 3, padding=1); self.n2 = nn.GroupNorm(8, co)
        self.sk = nn.Conv2d(ci, co, 1) if ci != co else nn.Identity()

    def forward(self, x):
        h = F.silu(self.n1(self.c1(x))); h = F.silu(self.n2(self.c2(h)))
        return h + self.sk(x)


class TimeNet(nn.Module):
    def __init__(self, ch=(32, 64, 128, 192, 256), att=2):
        super().__init__()
        self.inc = Block(4, ch[0])
        self.down = nn.ModuleList([Block(ch[i], ch[i + 1]) for i in range(len(ch) - 1)])
        self.pos = nn.Parameter(torch.zeros(1, 16 * 16, ch[-1]))
        self.att = nn.TransformerEncoder(nn.TransformerEncoderLayer(ch[-1], 8, ch[-1] * 3, 0.0, batch_first=True, norm_first=True), att)
        self.up = nn.ModuleList([Block(ch[i + 1] + ch[i], ch[i]) for i in reversed(range(len(ch) - 1))])
        self.out = nn.Conv2d(ch[0], 1, 1)

    def forward(self, x):
        """x [B,4,256,256] → 时刻 [B,256,256](0..1)。"""
        hs = [self.inc(x)]
        for b in self.down:
            hs.append(b(F.avg_pool2d(hs[-1], 2)))
        h = hs.pop(); B, C, H, W = h.shape
        h = self.att(h.flatten(2).transpose(1, 2) + self.pos[:, :H * W]).transpose(1, 2).view(B, C, H, W)
        for b in self.up:
            s = hs.pop(); h = b(torch.cat([F.interpolate(h, size=s.shape[-2:], mode="nearest"), s], 1))
        return torch.sigmoid(self.out(h))[:, 0]


def load(ckpt, dev="cuda"):
    m = TimeNet(); m.load_state_dict(torch.load(ckpt, map_location="cpu")); return m.to(dev).eval()