vision.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. from functools import lru_cache
  2. import torch
  3. import torch.nn.functional as F
  4. from torch import nn
  5. @lru_cache(8)
  6. def get_vision_cos_sin(n_h: int, n_w: int, dim: int, theta: float):
  7. inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
  8. hpos = torch.arange(n_h).unsqueeze(1).expand(n_h, n_w)
  9. wpos = torch.arange(n_w).unsqueeze(0).expand(n_h, n_w)
  10. freqs = torch.stack([hpos, wpos], dim=-1).reshape(-1, 2, 1).float() * inv_freq
  11. freqs = freqs.flatten(1)
  12. return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1)
  13. def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
  14. dtype = x.dtype
  15. x1, x2 = x.float().chunk(2, dim=-1)
  16. return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1).to(dtype)
  17. class RMSNorm(nn.Module):
  18. def __init__(self, dim: int, eps: float = 1e-6):
  19. super().__init__()
  20. self.eps = eps
  21. self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
  22. def forward(self, x: torch.Tensor) -> torch.Tensor:
  23. dtype = x.dtype
  24. x = x.float()
  25. x = x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps)
  26. return (self.weight * x).to(dtype)
  27. class PatchEmbed(nn.Module):
  28. def __init__(self, args):
  29. super().__init__()
  30. self.proj = nn.Linear(3 * args.vision_patch_size ** 2, args.vision_dim)
  31. def forward(self, x: torch.Tensor) -> torch.Tensor:
  32. return self.proj(x.flatten(1))
  33. class Attention(nn.Module):
  34. def __init__(self, args):
  35. super().__init__()
  36. self.n_heads = args.vision_n_heads
  37. self.head_dim = args.vision_dim // args.vision_n_heads
  38. self.wqkv = nn.Linear(args.vision_dim, 3 * args.vision_dim)
  39. self.wo = nn.Linear(args.vision_dim, args.vision_dim)
  40. def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
  41. n = x.size(0)
  42. q, k, v = (t.view(n, self.n_heads, self.head_dim) for t in self.wqkv(x).chunk(3, dim=-1))
  43. q = apply_rotary(q, cos, sin)
  44. k = apply_rotary(k, cos, sin)
  45. o = F.scaled_dot_product_attention(q.transpose(0, 1), k.transpose(0, 1), v.transpose(0, 1))
  46. return self.wo(o.transpose(0, 1).reshape(n, -1))
  47. class MLP(nn.Module):
  48. def __init__(self, args):
  49. super().__init__()
  50. self.w1 = nn.Linear(args.vision_dim, 2 * args.vision_inter_dim, bias=False)
  51. self.w2 = nn.Linear(args.vision_inter_dim, args.vision_dim, bias=False)
  52. def forward(self, x: torch.Tensor) -> torch.Tensor:
  53. gate, up = self.w1(x).chunk(2, dim=-1)
  54. return self.w2(F.silu(gate) * up)
  55. class Block(nn.Module):
  56. def __init__(self, args):
  57. super().__init__()
  58. self.norm1 = RMSNorm(args.vision_dim)
  59. self.attn = Attention(args)
  60. self.norm2 = RMSNorm(args.vision_dim)
  61. self.mlp = MLP(args)
  62. def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
  63. x = x + self.attn(self.norm1(x), cos, sin)
  64. return x + self.mlp(self.norm2(x))
  65. class ViT(nn.Module):
  66. """DeepSeek ViT: full bidirectional attention over one image with 2D RoPE."""
  67. def __init__(self, args):
  68. super().__init__()
  69. self.rope_dim = args.vision_dim // args.vision_n_heads // 2
  70. self.rope_theta = args.vision_rope_theta
  71. self.patch_embed = PatchEmbed(args)
  72. self.blocks = nn.ModuleList([Block(args) for _ in range(args.vision_n_layers)])
  73. self.norm = RMSNorm(args.vision_dim)
  74. def forward(self, patches: torch.Tensor, n_h: int, n_w: int) -> torch.Tensor:
  75. x = self.patch_embed(patches)
  76. cos, sin = get_vision_cos_sin(n_h, n_w, self.rope_dim, self.rope_theta)
  77. for block in self.blocks:
  78. x = block(x, cos, sin)
  79. return self.norm(x)
  80. class Aligner(nn.Module):
  81. def __init__(self, args):
  82. super().__init__()
  83. self.downsample_ratio = args.vision_downsample_ratio
  84. in_dim = args.vision_dim * self.downsample_ratio ** 2
  85. self.w1 = nn.Linear(in_dim, args.dim)
  86. self.w2 = nn.Linear(args.dim, args.dim)
  87. def forward(self, x: torch.Tensor, n_h: int, n_w: int) -> torch.Tensor:
  88. r = self.downsample_ratio
  89. x = x.view(n_h, n_w, -1).permute(2, 0, 1)
  90. x = F.pad(x, (0, -n_w % r, 0, -n_h % r))
  91. x = F.unfold(x.unsqueeze(0), r, stride=r).squeeze(0).transpose(0, 1)
  92. return self.w2(F.gelu(self.w1(x)))