File size: 6,007 Bytes
ca17769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 入口: DA3-Small の ViT-S(Apache 2.0、Copyright 2025 The Depth Anything 3 Team)。
#  計算は公式 depth_anything_3/model/dinov2 を 1 コマ用に写したもの。重みは固定して使う(DA3-SMALL の model.safetensors を読む)。
import math, torch, torch.nn as nn, torch.nn.functional as F
from safetensors import safe_open

# ---------------------------------------------------------------- ② 入口(DA3-Small の ViT-S)
class Rope2D(nn.Module):
    def __init__(s, freq=100.0):
        super().__init__(); s.f = freq; s.cache = {}
    def comp(s, dim, n, dev, dt):
        k = (dim, n, dev, dt)
        if k not in s.cache:
            inv = 1.0 / (s.f ** (torch.arange(0, dim, 2, device=dev).float() / dim))
            a = torch.einsum("i,j->ij", torch.arange(n, device=dev, dtype=inv.dtype), inv).to(dt)
            a = torch.cat((a, a), -1); s.cache[k] = (a.cos(), a.sin())
        return s.cache[k]
    @staticmethod
    def rot(x):
        h = x.shape[-1] // 2; return torch.cat((-x[..., h:], x[..., :h]), -1)
    def one(s, t, p, c, si):
        cc = F.embedding(p, c)[:, None]; ss = F.embedding(p, si)[:, None]
        return t * cc + s.rot(t) * ss
    def forward(s, t, pos):
        d = t.size(-1) // 2
        c, si = s.comp(d, int(pos.max()) + 1, t.device, t.dtype)
        a, b = t.chunk(2, -1)
        return torch.cat((s.one(a, pos[..., 0], c, si), s.one(b, pos[..., 1], c, si)), -1)

class Attn(nn.Module):
    def __init__(s, d, h, qk_norm, rope):
        super().__init__(); s.h = h
        s.qkv = nn.Linear(d, 3 * d); s.proj = nn.Linear(d, d); s.rope = rope
        s.q_norm = nn.LayerNorm(d // h) if qk_norm else nn.Identity()
        s.k_norm = nn.LayerNorm(d // h) if qk_norm else nn.Identity()
    def forward(s, x, pos=None):
        B, N, C = x.shape
        q, k, v = s.qkv(x).reshape(B, N, 3, s.h, C // s.h).permute(2, 0, 3, 1, 4)
        q, k = s.q_norm(q), s.k_norm(k)
        if s.rope is not None and pos is not None:
            q, k = s.rope(q, pos), s.rope(k, pos)
        x = F.scaled_dot_product_attention(q, k, v)
        return s.proj(x.transpose(1, 2).reshape(B, N, C))

class LS(nn.Module):
    def __init__(s, d): super().__init__(); s.gamma = nn.Parameter(torch.ones(d))
    def forward(s, x): return x * s.gamma

class Mlp(nn.Module):
    def __init__(s, d, hd): super().__init__(); s.fc1 = nn.Linear(d, hd); s.fc2 = nn.Linear(hd, d)
    def forward(s, x): return s.fc2(F.gelu(s.fc1(x)))

class Blk(nn.Module):
    def __init__(s, d, h, qk_norm, rope):
        super().__init__()
        s.norm1 = nn.LayerNorm(d, eps=1e-6); s.attn = Attn(d, h, qk_norm, rope); s.ls1 = LS(d)
        s.norm2 = nn.LayerNorm(d, eps=1e-6); s.mlp = Mlp(d, 4 * d); s.ls2 = LS(d)
    def forward(s, x, pos=None):
        x = x + s.ls1(s.attn(s.norm1(x), pos)); return x + s.ls2(s.mlp(s.norm2(x)))

class DA3Encoder(nn.Module):
    """1 コマ(公式の S=1 と同じ)用。出力: 層 5,7,9,11 の [局所, 全体] を連結した 768 次元(四角ごと)"""
    def __init__(s, path):
        super().__init__()
        d, s.ps = 384, 14
        s.rope = Rope2D(100.0)
        s.patch_embed = nn.Conv2d(3, d, 14, 14)
        s.cls_token = nn.Parameter(torch.zeros(1, 1, d)); s.camera_token = nn.Parameter(torch.zeros(1, 2, d))
        s.pos_embed = nn.Parameter(torch.zeros(1, 1370, d))
        s.blocks = nn.ModuleList([Blk(d, 6, i >= 4, s.rope if i >= 4 else None) for i in range(12)])
        s.norm = nn.LayerNorm(d, eps=1e-6)
        s.out_layers = [5, 7, 9, 11]
        sd = {}
        with safe_open(path, "pt") as f:
            for k in f.keys():
                if k.startswith("model.backbone.pretrained."):
                    sd[k[len("model.backbone.pretrained."):].replace("patch_embed.proj.", "patch_embed.")] = f.get_tensor(k)
        missing, unexpected = s.load_state_dict(sd, strict=False)
        assert not unexpected and all("rope" in m for m in missing), (missing, unexpected)
        s.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1), persistent=False)
        s.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1), persistent=False)

    def pos_enc(s, H, W):
        pe = s.pos_embed.float(); cls, p = pe[:, :1], pe[:, 1:]
        h0, w0 = H // 14, W // 14
        p = F.interpolate(p.reshape(1, 37, 37, -1).permute(0, 3, 1, 2), mode="bicubic", antialias=False,
                          scale_factor=((h0 + 0.1) / 37, (w0 + 0.1) / 37))
        assert p.shape[-2:] == (h0, w0)
        return torch.cat([cls, p.permute(0, 2, 3, 1).reshape(1, h0 * w0, -1)], 1)

    def forward(s, img):  # img [B,3,H,W] 0..1
        B, _, H, W = img.shape
        x = s.patch_embed((img - s.mean) / s.std).flatten(2).transpose(1, 2)
        x = torch.cat([s.cls_token.expand(B, -1, -1), x], 1) + s.pos_enc(H, W).to(x.dtype)
        h0, w0 = H // 14, W // 14
        yx = torch.cartesian_prod(torch.arange(h0, device=img.device), torch.arange(w0, device=img.device))
        pos = torch.cat([torch.zeros(1, 2, dtype=torch.long, device=img.device), yx + 1], 0)[None].expand(B, -1, -1)
        pos_nd = torch.cat([torch.zeros(1, 2, dtype=torch.long, device=img.device),
                            torch.ones_like(yx)], 0)[None].expand(B, -1, -1)
        outs, local_x = [], x
        for i, blk in enumerate(s.blocks):
            if i == 4:
                x = x.clone(); x[:, 0] = s.camera_token[:, 0]
            if i >= 4 and i % 2 == 1:
                x = blk(x, pos_nd)          # 公式の「全体」見比べ(1 コマなので同じ写真の中)
            else:
                x = blk(x, pos if i >= 4 else None); local_x = x
            if i in s.out_layers:
                outs.append(torch.cat([local_x, s.norm(x)], -1)[:, 1:])
        return outs  # 4 個の [B, N, 768]

# ---------------------------------------------------------------- 位置の印