Download code/ownhead.py from lantudou/bihua: direct link, hf CLI and curl.
- Browser
- Download file 5.2 kB
-
https://huggingface.co/lantudou/bihua/resolve/main/code/ownhead.py
- Command line
-
hf download hf://lantudou/bihua/code/ownhead.py
-
curl -L -o ownhead.py https://huggingface.co/lantudou/bihua/resolve/main/code/ownhead.py
5.2 kB
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| # ownhead.py | |
| # own2:墨像素归属模型,复用 full6 的字形编码器。full6 编码器冻结不动,own2 只有一个小 U-Net 头(约 2M 参数): | |
| # 输入 own1 同样的 4 通道图(墨、墨内距离、轨迹时刻图、轨迹有无,降到 128²),在 64² 拼 full6 的 fmap、16² 加 full6 的图 token | |
| # 后过两层自注意力,再升回 128² 和 full6 s0 层特征融合,得到像素特征;查询和 own1 相同。logits 在 128² 上算,双线性放大到 256² 再 argmax。 | |
| # 头和训练它时的那份 full6 绑定:换了 full6 权重就要重训头。 | |
| NP = 32 # 每条笔迹重采样的点数 | |
| def enc_feats(enc, img): | |
| """单独跑一次 full6 编码器,返回 own2 要的 (s0 输出 [B,48,128,128], fmap [B,128,64,64], 图 token [B,256,192])。""" | |
| z = enc.s0(img); a = enc.s1(z); b = enc.s2(a); c = enc.s3(b) | |
| f = enc.p1(a) + F.interpolate(enc.p2(b), scale_factor=2, mode='bilinear') + F.interpolate(enc.p3(c), scale_factor=4, mode='bilinear') | |
| return z, enc.out(f), enc.g(c.flatten(2).transpose(1, 2)) + enc.gpos | |
| class EncTap: | |
| """挂在 full6 编码器上,记下最近一次前向的三样特征,让 own2 直接复用 full6 生成时算过的编码,不必再跑一遍。""" | |
| def __init__(self, full6): | |
| self.z = self.f = self.g = None | |
| full6.enc.s0.register_forward_hook(lambda mod, inp, out: setattr(self, 'z', out)) | |
| full6.enc.register_forward_hook(self._enc) | |
| def _enc(self, mod, inp, out): | |
| self.f, self.g = out | |
| def feats(self): | |
| return self.z, self.f, self.g | |
| class Blk(nn.Module): | |
| """3×3 卷积 + GroupNorm + SiLU 的残差块。""" | |
| def __init__(self, c, dil=1): | |
| super().__init__() | |
| self.a = nn.Conv2d(c, c, 3, padding=dil, dilation=dil); self.n = nn.GroupNorm(8, c) | |
| def forward(self, x): | |
| return x + F.silu(self.n(self.a(x))) | |
| class OwnHead(nn.Module): | |
| def __init__(self, d=64): | |
| super().__init__() | |
| self.d = d | |
| self.inp = nn.Sequential(nn.Conv2d(4, 32, 3, padding=1), nn.SiLU(), Blk(32)) | |
| self.d64 = nn.Sequential(nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.SiLU()) | |
| self.m64 = nn.Sequential(nn.Conv2d(64 + 128, 96, 1), nn.GroupNorm(8, 96), nn.SiLU(), Blk(96), Blk(96)) | |
| self.d32 = nn.Sequential(nn.Conv2d(96, 128, 3, stride=2, padding=1), nn.GroupNorm(8, 128), nn.SiLU(), Blk(128)) | |
| self.d16 = nn.Conv2d(128, 192, 3, stride=2, padding=1) | |
| self.att = nn.TransformerEncoder(nn.TransformerEncoderLayer(192, 6, 192 * 3, 0.0, batch_first=True, norm_first=True), 2, | |
| enable_nested_tensor=False) | |
| self.u32 = nn.Sequential(nn.Conv2d(192 + 128, 128, 1), nn.GroupNorm(8, 128), nn.SiLU(), Blk(128)) | |
| self.u64 = nn.Sequential(nn.Conv2d(128 + 96, 96, 1), nn.GroupNorm(8, 96), nn.SiLU(), Blk(96)) | |
| self.fuse = nn.Sequential(nn.Conv2d(96 + 48 + 32, 64, 1), nn.GroupNorm(8, 64), nn.SiLU(), Blk(64), Blk(64), nn.Conv2d(64, d, 1)) | |
| self.q = nn.Sequential(nn.Linear(d * 5 + 8, 256), nn.SiLU(), nn.Linear(256, 256), nn.SiLU(), nn.Linear(256, d)) | |
| def pixel(self, x, z, f, g): | |
| """x [B,4,256,256](同 own1 的输入),z / f / g 是 full6 编码器特征 → 像素特征 [B,d,128,128]。""" | |
| h128 = self.inp(F.avg_pool2d(x, 2)) | |
| h64 = self.m64(torch.cat([self.d64(h128), f], 1)) | |
| h32 = self.d32(h64) | |
| h16 = self.d16(h32); B, C, H, W = h16.shape | |
| t = self.att(h16.flatten(2).transpose(1, 2) + g).transpose(1, 2).reshape(B, C, H, W) | |
| u = self.u32(torch.cat([F.interpolate(t, scale_factor=2, mode='nearest'), h32], 1)) | |
| u = self.u64(torch.cat([F.interpolate(u, scale_factor=2, mode='bilinear'), h64], 1)) | |
| return self.fuse(torch.cat([F.interpolate(u, scale_factor=2, mode='bilinear'), z, h128], 1)) | |
| def forward(self, x, z, f, g, pens, pm): | |
| """→ 归属 logits [B,P,256,256](128² 上算,双线性放大;无效笔迹为 -1e4)。对笔迹维 argmax 得到归属。""" | |
| Fm = self.pixel(x, z, f, g).float(); B, P, N, _ = pens.shape | |
| smp = F.grid_sample(Fm, pens.view(B, P * N, 1, 2), align_corners=False).view(B, self.d, P, N).permute(0, 2, 3, 1) | |
| parts = [smp.mean(2)] + [smp[:, :, i] for i in (0, N // 3, 2 * N // 3, N - 1)] | |
| k = torch.arange(P, device=x.device).float()[None].expand(B, P); n = pm.sum(1, keepdim=True).float().clamp(min=1) | |
| L = (pens[:, :, 1:] - pens[:, :, :-1]).norm(dim=-1).sum(-1) | |
| extra = torch.cat([pens[:, :, 0], pens[:, :, -1], (k / n)[..., None], (k / 8)[..., None], L[..., None], (n / 10).expand(B, P)[..., None]], -1) | |
| q = self.q(torch.cat(parts + [extra], -1)).float() | |
| lg = torch.einsum("bdhw,bpd->bphw", Fm, q) / self.d ** 0.5 | |
| lg = F.interpolate(lg, scale_factor=2, mode='bilinear') # 先放大 logits 再 argmax;在 128² 上 argmax 再放大编号图会差不少 | |
| return lg.masked_fill(~pm[:, :, None, None], -1e4) | |
| def load(ckpt, dev="cuda"): | |
| m = OwnHead(); m.load_state_dict(torch.load(ckpt, map_location="cpu")); return m.to(dev).eval() | |