File size: 6,979 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
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
import torch
import torch.nn.functional as F
from seqmodel import K, seg_feat
from model import fourier

# seqinfer.py
# SegNet(full6)推理加速:权重原样读取,不重训。和 seqmodel.SegNet.generate 逐段贪心生成的数学过程相同,区别只在算法:
#   1. 自注意力 KV cache:每层缓存前文 token 的 K/V(按 tmax 预分配定长),每步只算新 token;
#   2. 交叉注意力 K/V 预计算:记忆(256 图 token + S 参考 token)的 K/V 每字只算一次,6 层解码 + 3 层细化共用;
#   3. 输入嵌入只算新 token(上一段的坐标特征 + 末两点处字形特征 + 位置编码)。
# 单步写成 step(t, 上一段, 连着, cache) 的形式,方便以后对照着搬到 WGSL / MNN。


def _heads(x, H):
    """[B,L,d] → [B,H,L,d/H]。"""
    B, L, d = x.shape
    return x.view(B, L, H, d // H).transpose(1, 2)


def _merge(x):
    B, H, L, dh = x.shape
    return x.transpose(1, 2).reshape(B, L, H * dh)


def _kv(mha, mem):
    """交叉注意力:记忆的 K/V(每字算一次)。"""
    d = mha.embed_dim; W, b = mha.in_proj_weight, mha.in_proj_bias
    return _heads(F.linear(mem, W[d:2 * d], b[d:2 * d]), mha.num_heads), _heads(F.linear(mem, W[2 * d:], b[2 * d:]), mha.num_heads)


def _cross(mha, x, kv, mask):
    """交叉注意力:只算 query 的投影,K/V 用预计算的。mask [B,1,1,M] 布尔,真 = 可见。"""
    d = mha.embed_dim; W, b = mha.in_proj_weight, mha.in_proj_bias
    q = _heads(F.linear(x, W[:d], b[:d]), mha.num_heads)
    o = F.scaled_dot_product_attention(q, kv[0].to(q.dtype), kv[1].to(q.dtype), attn_mask=mask)
    return mha.out_proj(_merge(o))


def _self(mha, x):
    """普通自注意力(细化层里段内 K 个点互相看,不需要缓存)。"""
    q, k, v = F.linear(x, mha.in_proj_weight, mha.in_proj_bias).chunk(3, -1)
    H = mha.num_heads
    return mha.out_proj(_merge(F.scaled_dot_product_attention(_heads(q, H), _heads(k, H), _heads(v, H))))


class Cache:
    """一批字的推理状态:字形特征图、各层交叉注意力 K/V、各解码层自注意力 KV cache(定长 tmax)。"""

    def __init__(self, model, img, q, m, drop=None, tmax=96, fp32_heads=False):
        self.m = model; self.tmax = tmax; self.fp32_heads = fp32_heads
        self.fmap, mem, mpad = model.memory(img, q, m, drop)
        self.mask = (~mpad)[:, None, None]
        self.ca_dec = [_kv(l.ca, mem) for l in model.layers]
        self.ca_ref = [_kv(l.ca, mem) for l in model.refs]
        self.sk = [None] * len(model.layers); self.sv = [None] * len(model.layers)
        self.B = img.shape[0]

    def embed(self, t, seg, cont):
        """第 t 个位置的输入 token:t=0 是 BOS,否则是上一段([B,K,2])的特征。"""
        m = self.m
        if t == 0:
            x = m.bos.expand(self.B, 1, -1)
        else:
            prev = seg[:, None]
            s = F.grid_sample(self.fmap.float(), prev[:, :, [-2, -1]].float(), align_corners=False)
            x = m.seg_in(seg_feat(prev)) + m.cont_in(cont[:, None].long()) + m.loc_in(s.permute(0, 2, 3, 1).flatten(-2).to(prev.dtype))
        return x + m.tpos[None, t:t + 1]

    def step(self, t, seg, cont):
        """喂入第 t 个位置的 token,返回它预测的下一段:(细化后点 [B,K,2],连着 logit [B],写完 logit [B])。"""
        return self.head(self.dec(t, self.embed(t, seg, cont)))

    def dec(self, t, x):
        """6 层因果解码(自注意力走 KV cache)。"""
        m = self.m
        for i, l in enumerate(m.layers):
            h = l.n0(x); a = l.sa; d = a.embed_dim; H = a.num_heads
            qh, kh, vh = (_heads(z, H) for z in F.linear(h, a.in_proj_weight, a.in_proj_bias).chunk(3, -1))
            if self.sk[i] is None:
                self.sk[i] = kh.new_zeros(self.B, H, self.tmax + 1, d // H); self.sv[i] = vh.new_zeros(self.B, H, self.tmax + 1, d // H)
            self.sk[i][:, :, t] = kh[:, :, 0]; self.sv[i][:, :, t] = vh[:, :, 0]
            o = F.scaled_dot_product_attention(qh, self.sk[i][:, :, :t + 1], self.sv[i][:, :, :t + 1])
            x = x + a.out_proj(_merge(o))
            x = x + _cross(l.ca, l.n1(x), self.ca_dec[i], self.mask)
            x = x + l.ff(l.n2(x))
        return x

    def head(self, x):
        """粗位置 + 3 层细化 + 连着 / 写完。"""
        m = self.m; h = m.nf(x); B = self.B
        pos = m.coarse(h).float().view(B, 1, K, 2)
        qp = m.pt_in(h)[:, :, None] + m.point.weight[None, None]
        for l, kv in zip(m.refs, self.ca_ref):
            qp, pos = ref_step(l, qp, pos, self.fmap, kv, self.mask)
        if self.fp32_heads:                                  # 连着 / 写完 是硬阈值决策:在 fp32 里算,减少低精度翻转
            with torch.autocast(h.device.type, enabled=False):
                hf = h.float(); return pos[:, 0], F.linear(hf, m.cont.weight.float(), m.cont.bias.float())[:, 0, 0], F.linear(hf, m.end.weight.float(), m.end.bias.float())[:, 0, 0]
        return pos[:, 0], m.cont(h).squeeze(-1).float()[:, 0], m.end(h).squeeze(-1).float()[:, 0]


def ref_step(l, q, pos, fmap, kv, mask):
    """RefLayer.forward 的同一计算,交叉注意力改用预计算的 K/V。q [B,1,K,d],pos [B,1,K,2]。"""
    B, T, Kk, d = q.shape
    off = l.off(q).view(B, T * Kk, l.P, 2).tanh() * 0.12
    s = F.grid_sample(fmap.float(), pos.reshape(B, T * Kk, 1, 2).float() + off.float(), align_corners=False)
    w = l.w(q).view(B, T * Kk, l.P).softmax(-1)
    q = q + l.loc((s * w[:, None].to(s.dtype)).sum(-1).transpose(1, 2)).view(B, T, Kk, d)
    h = (l.n0(q) + l.pos(fourier(pos))).view(B * T, Kk, d)
    q = q + _self(l.sa, h).view(B, T, Kk, d)
    q = q + _cross(l.ca, l.n1(q).view(B, T * Kk, d), kv, mask).view(B, T, Kk, d)
    q = q + l.ff(l.n2(q))
    return q, pos + l.head(l.n3(q)).float()


@torch.no_grad()
def generate(model, img, q, m, drop=None, tmax=96, fp32_heads=False):
    """和 SegNet.generate 同样的贪心逐段生成和返回格式,用 KV cache。"""
    c = Cache(model, img, q, m, drop, tmax, fp32_heads)
    B = img.shape[0]; dev = img.device
    segs = torch.zeros(B, tmax + 1, K, 2, device=dev); pc = torch.zeros(B, tmax + 1, dtype=torch.bool, device=dev)
    done = torch.zeros(B, dtype=torch.bool, device=dev); length = torch.full((B,), tmax, device=dev)
    ramp = torch.linspace(1, 0, K, device=dev)[:, None]; n = 0
    for t in range(tmax):
        p, lc, le = c.step(t, segs[:, t], pc[:, t])
        cc = (lc > 0) & (t > 0); e = le > 0
        fin = e & ~done; length[fin] = t; done |= e
        if done.all():
            break
        if t > 0:
            p = torch.where(cc[:, None, None], p + (segs[:, t, -1:] - p[:, :1]) * ramp, p)
        segs[:, t + 1] = p.to(segs.dtype); pc[:, t + 1] = cc; n = t + 1
    res = []
    for b in range(B):
        k = min(int(length[b].item()), n)
        res.append((segs[b, 1:k + 1].float().cpu().numpy(), pc[b, 1:k + 1].cpu().numpy()))
    return res