bihua / code /seqmodel.py
lantudou's picture
bihua: full6, own2, own1 weights, PyTorch inference code, model card
59909dd
Raw History Blame Contribute Delete
8.53 kB
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import Encoder, fourier
# seqmodel.py
# 逐段生成的笔迹模型:卷积编码器(同 StrokeNet)看字形;楷书参考笔画编码成一组可选的参考 token;
# 因果 Transformer 解码器按书写顺序逐段预测:下一段的 K 个点 + “和上一段连着”标记 + “写完了”标记。
# 每段先由解码器 token 直接回归粗位置,再用几层“在当前点附近取字形特征”的细化层把点挪到墨上。
K = 16
TPOS = 128
def seg_feat(p):
"""段 [...,K,2] → 坐标拉平 + 4 个点的傅里叶编码。"""
idx = [0, 5, 10, K - 1]
return torch.cat([p.flatten(-2), fourier(p[..., idx, :]).flatten(-2)], -1)
SEGF = 2 * K + 4 * 32
class DecLayer(nn.Module):
def __init__(self, d, heads=6):
super().__init__()
self.sa = nn.MultiheadAttention(d, heads, batch_first=True); self.ca = nn.MultiheadAttention(d, heads, batch_first=True)
self.ff = nn.Sequential(nn.Linear(d, d * 4), nn.SiLU(), nn.Linear(d * 4, d))
self.n0, self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d), nn.LayerNorm(d)
def forward(self, x, mem, mpad, causal):
h = self.n0(x); x = x + self.sa(h, h, h, attn_mask=causal, need_weights=False)[0]
x = x + self.ca(self.n1(x), mem, mem, key_padding_mask=mpad, need_weights=False)[0]
return x + self.ff(self.n2(x))
class RefLayer(nn.Module):
"""段内点的细化层:每个点在当前位置周围取字形特征,段内点互相注意,再看一眼全局,输出位置修正。"""
def __init__(self, d, df, heads=6, P=8):
super().__init__()
self.P = P
self.off = nn.Linear(d, P * 2); self.w = nn.Linear(d, P); self.loc = nn.Linear(df, d)
nn.init.zeros_(self.off.weight)
with torch.no_grad():
a = torch.arange(P) * 2 * math.pi / P
self.off.bias.copy_(torch.stack([a.cos(), a.sin()], 1).flatten() * 0.5)
self.pos = nn.Sequential(nn.Linear(32, d), nn.SiLU(), nn.Linear(d, d))
self.sa = nn.MultiheadAttention(d, heads, batch_first=True); self.ca = nn.MultiheadAttention(d, heads, batch_first=True)
self.ff = nn.Sequential(nn.Linear(d, d * 3), nn.SiLU(), nn.Linear(d * 3, d))
self.n0, self.n1, self.n2, self.n3 = (nn.LayerNorm(d) for _ in range(4))
self.head = nn.Sequential(nn.Linear(d, d), nn.SiLU(), nn.Linear(d, 2))
nn.init.zeros_(self.head[-1].weight); nn.init.zeros_(self.head[-1].bias)
def forward(self, q, pos, fmap, mem, mpad):
"""q [B,T,K,d],pos [B,T,K,2]。"""
B, T, Kk, d = q.shape
off = self.off(q).view(B, T * Kk, self.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 = self.w(q).view(B, T * Kk, self.P).softmax(-1)
q = q + self.loc((s * w[:, None].to(s.dtype)).sum(-1).transpose(1, 2)).view(B, T, Kk, d)
h = (self.n0(q) + self.pos(fourier(pos))).view(B * T, Kk, d)
q = q + self.sa(h, h, h, need_weights=False)[0].view(B, T, Kk, d)
q = q + self.ca(self.n1(q).view(B, T * Kk, d), mem, mem, key_padding_mask=mpad, need_weights=False)[0].view(B, T, Kk, d)
q = q + self.ff(self.n2(q))
return q, pos + self.head(self.n3(q)).float()
class SegNet(nn.Module):
def __init__(self, d=192, df=128, layers=6, refine=3, S=40):
super().__init__()
self.enc = Encoder(df, d)
self.ref_in = nn.Sequential(nn.Linear(SEGF, d), nn.SiLU(), nn.Linear(d, d)); self.ref_ord = nn.Embedding(S, d)
self.seg_in = nn.Sequential(nn.Linear(SEGF, d), nn.SiLU(), nn.Linear(d, d)); self.cont_in = nn.Embedding(2, d)
self.loc_in = nn.Linear(df * 2, d) # 上一段末端两点处的局部字形特征
self.bos = nn.Parameter(torch.zeros(d)); self.tpos = nn.Parameter(torch.randn(TPOS, d) * 0.02)
self.kind = nn.Parameter(torch.randn(2, d) * 0.02) # 记忆里区分“图 token / 参考 token”
self.layers = nn.ModuleList([DecLayer(d) for _ in range(layers)])
self.nf = nn.LayerNorm(d)
self.coarse = nn.Sequential(nn.Linear(d, d), nn.SiLU(), nn.Linear(d, 2 * K))
self.cont = nn.Linear(d, 1); self.end = nn.Linear(d, 1)
self.pt_in = nn.Linear(d, d); self.point = nn.Embedding(K, d)
self.refs = nn.ModuleList([RefLayer(d, df) for _ in range(refine)])
def memory(self, img, q, m, drop=None):
"""编码字形和参考:返回 (fmap, mem [B,256+S,d], 记忆掩码)。drop [B] 为真的样本不看参考。"""
fmap, g = self.enc(img)
r = self.ref_in(seg_feat(q)) + self.ref_ord.weight[None, :q.shape[1]] + self.kind[1]
mem = torch.cat([g + self.kind[0], r], 1)
rp = ~m if drop is None else (~m | drop[:, None])
mpad = torch.cat([torch.zeros(g.shape[:2], dtype=torch.bool, device=g.device), rp], 1)
return fmap, mem, mpad
def decode(self, fmap, mem, mpad, prev, prev_cont, last=False):
"""prev [B,T,K,2]:作为输入的前文段(第 0 个位置是 BOS,内容忽略);prev_cont [B,T]。
返回每个位置预测的下一段:(各层点位置列表 [B,T,K,2],连着 logit [B,T],写完 logit [B,T])。"""
B, T = prev.shape[:2]
tail = prev[:, :, [-2, -1]] # 上一段末两点
s = F.grid_sample(fmap.float(), tail.float(), align_corners=False) # [B,C,T,2]
x = self.seg_in(seg_feat(prev)) + self.cont_in(prev_cont.long()) + self.loc_in(s.permute(0, 2, 3, 1).flatten(-2).to(prev.dtype))
x = torch.cat([self.bos.expand(B, 1, -1), x[:, 1:]], 1) + self.tpos[None, :T]
causal = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), 1)
for l in self.layers:
x = l(x, mem, mpad, causal)
h = self.nf(x)
if last: # 生成时只细化最后一个位置
h = h[:, -1:]; T = 1
pos = self.coarse(h).float().view(B, T, K, 2); outs = [pos]
qp = self.pt_in(h)[:, :, None] + self.point.weight[None, None]
for l in self.refs:
qp, pos = l(qp, pos.detach(), fmap, mem, mpad); outs.append(pos)
return outs, self.cont(h).squeeze(-1).float(), self.end(h).squeeze(-1).float()
def forward(self, img, q, m, segs, cont, drop=None):
"""训练(teacher forcing):输入是 [BOS, 段1..段T],第 t 个位置预测段 t+1,最后一个位置预测“写完”。"""
fmap, mem, mpad = self.memory(img, q, m, drop)
B = segs.shape[0]
prev = torch.cat([torch.zeros_like(segs[:, :1]), segs], 1); pc = torch.cat([torch.zeros_like(cont[:, :1]), cont], 1)
return self.decode(fmap, mem, mpad, prev, pc)
@torch.no_grad()
def generate(self, img, q, m, drop=None, tmax=96):
"""逐段生成(贪心)。返回每个样本的 (段 [T,K,2], 连着 [T])。连着的段把起点吸到上一段终点(整段线性渐变平移)。"""
fmap, mem, mpad = self.memory(img, q, m, drop)
B = img.shape[0]; dev = img.device
prev = torch.zeros(B, 1, K, 2, device=dev); pc = torch.zeros(B, 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]
for t in range(tmax):
outs, lc, le = self.decode(fmap, mem, mpad, prev, pc, last=True)
p = outs[-1][:, -1]; c = (lc[:, -1] > 0) & (t > 0); e = le[:, -1] > 0
fin = e & ~done; length[fin] = t; done |= e
if done.all():
break
if t > 0:
p = torch.where(c[:, None, None], p + (prev[:, -1, -1:] - p[:, :1]) * ramp, p)
prev = torch.cat([prev, p[:, None].to(prev.dtype)], 1); pc = torch.cat([pc, c[:, None]], 1)
res = []
for b in range(B):
n = int(length[b].item()); n = min(n, prev.shape[1] - 1)
res.append((prev[b, 1:n + 1].float().cpu().numpy(), pc[b, 1:n + 1].cpu().numpy()))
return res
def load(ckpt, dev="cuda"):
sd = torch.load(ckpt, map_location="cpu")
nl = 1 + max(int(k.split(".")[1]) for k in sd if k.startswith("layers.")); nr = 1 + max(int(k.split(".")[1]) for k in sd if k.startswith("refs."))
m = SegNet(layers=nl, refine=nr); m.load_state_dict(sd)
return m.to(dev).eval()