Pyramid Vision Transformer Code#

import torch
import torch.nn as nn
import torch.nn.functional as F

import numpy as np

MLP#

class MLP(nn.Module):
  def __init__(self, in_channel, hidden_features):
    super().__init__()
    hidden_features = hidden_features if hidden_features is not None else in_channel
    self.fc1 = nn.Linear(in_channel, hidden_features)
    self.act = nn.GELU()
    self.fc2 = nn.Linear(hidden_features, in_channel)
    
  def forward(self, x):
    x = self.fc1(x)
    x = self.act(x)
    x = self.fc2(x)
    return x

Attention#

class Attention(nn.Module):
  def __init__(self, input_dim, num_heads=8, qk_scale=None, attn_drop=0, proj_drop=0, sr_scale=1):
    super().__init__()

    self.dim = input_dim
    self.num_heads = num_heads
    head_dim = input_dim // num_heads # dimension of each head
    
    self.scale = qk_scale if qk_scale is not None else np.math.sqrt(head_dim)

    self.q = nn.Linear(self.dim, self.dim)
    self.kv = nn.Linear(self.dim, self.dim * 2)

    self.proj = nn.Linear(self.dim, self.dim)

    self.sr_scale = sr_scale
    if sr_scale > 1:
      self.sr = nn.Conv2d(self.dim, self.dim, kernel_size=sr_scale, stride=sr_scale)
      self.norm = nn.LayerNorm(self.dim)
    
  def forward(self, x, H, W):
      B, N, C = x.shape
      q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
      
      if self.sr_scale > 1:
        x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
        x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
        x_ = self.norm(x_)
        kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
      else:
        kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
      k, v = kv[0], kv[1]

      attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
      attn = attn.softmax(dim=-1)
      x = torch.matmul(attn, v).reshape(B, N, C)
      x = self.proj(x)

      return x
class PatchEmbed(nn.Module):
  def __init__(self, img_size=224, patch_size=16, in_channel=3, embed_dim=768):
    super().__init__()
    self.img_size = (img_size, img_size)
    self.patch_size = (patch_size, patch_size)

    self.H, self.W = self.img_size[0] // self.patch_size[0], self.img_size[1] // self.patch_size[1] # number of patch(width, height)
    self.num_patches = self.H * self.W # number of patches
    self.proj = nn.Conv2d(in_channel, embed_dim, kernel_size=self.patch_size, stride=self.patch_size)
    self.norm = nn.LayerNorm(embed_dim)

  def forward(self, x):
    """
    input : x -> feature map of image
    output : x -> output feature map, (H, W) -> number of patch(height, weight)
    """
    B, C, H, W = x.shape
    x = self.proj(x).flatten(2).transpose(1, 2)
    x = self.norm(x)
    H, W = H // self.patch_size[0], W // self.patch_size[1]

    return x, (H, W)

Block#

class Block(nn.Module):
  def __init__(self, dim, num_heads, mlp_ratio = 4, qk_scale = None, sr_scale=1):
    super().__init__()
    self.dim = dim
    self.norm1 = nn.LayerNorm(dim)
    self.attn = Attention(dim, num_heads = num_heads, qk_scale=qk_scale, sr_scale=sr_scale)
    self.norm2 = nn.LayerNorm(dim)

    mlp_hidden_dim = int(dim * mlp_ratio)
    self.mlp = MLP(in_channel=dim, hidden_features=mlp_hidden_dim)

  def forward(self, x, H, W):
    x = self.norm1(x)
    x = x + self.attn(x, H, W)

    x = self.norm2(x)
    x = x + self.mlp(x)
    return x

PyramidVisionTransformer#

class PyramidVisionTransformer(nn.Module):
  def __init__(self, img_size=224, patch_size=16, in_channel=3, num_classes=1000, embed_dims=[64, 128, 256, 512], num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qk_scale=None, depths=[3, 4, 6, 3], sr_scales=[8, 4, 2, 1]):
    super().__init__()
    self.num_classes = num_classes
    self.depths = depths

    # patch embedding
    self.patch_embed1 = PatchEmbed(img_size=img_size, patch_size=patch_size, in_channel=in_channel, embed_dim=embed_dims[0])
    self.patch_embed2 = PatchEmbed(img_size=img_size // 4, patch_size=2, in_channel=embed_dims[0], embed_dim=embed_dims[1])
    self.patch_embed3 = PatchEmbed(img_size=img_size // 8, patch_size=2, in_channel=embed_dims[1], embed_dim=embed_dims[2])
    self.patch_embed4 = PatchEmbed(img_size=img_size // 16, patch_size=2, in_channel=embed_dims[2], embed_dim=embed_dims[3])

    # position embedding
    self.pos_embed1 = nn.Parameter(torch.randn(1, self.patch_embed1.num_patches, embed_dims[0]))
    self.pos_embed2 = nn.Parameter(torch.randn(1, self.patch_embed2.num_patches, embed_dims[1]))
    self.pos_embed3 = nn.Parameter(torch.randn(1, self.patch_embed3.num_patches, embed_dims[2]))
    self.pos_embed4 = nn.Parameter(torch.randn(1, self.patch_embed4.num_patches + 1, embed_dims[3]))

    self.block1 = nn.ModuleList([Block(
        dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qk_scale=qk_scale, sr_scale=sr_scales[0]
    ) for _ in range(depths[0])])

    self.block2 = nn.ModuleList([Block(
        dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qk_scale=qk_scale, sr_scale=sr_scales[1]   
    ) for _ in range(depths[1])])
    
    self.block3 = nn.ModuleList([Block(
        dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qk_scale=qk_scale, sr_scale=sr_scales[2]   
    ) for _ in range(depths[2])])
    
    self.block4 = nn.ModuleList([Block(
        dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qk_scale=qk_scale, sr_scale=sr_scales[3]   
    ) for _ in range(depths[3])])

    self.norm = nn.LayerNorm(embed_dims[3])
    
    self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dims[3]))
    
    self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()

  def forward(self, x):
    # STEP1 - embedding
    B = x.shape[0]

    #stage 1
    print('stage1 :', x.shape)
    x, (H, W) = self.patch_embed1(x)
    x = x + self.pos_embed1
    for blk in self.block1:
      x = blk(x, H, W)
    x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()

    # stage 2
    print('stage2 :', x.shape)
    x, (H, W) = self.patch_embed2(x)
    x = x + self.pos_embed2
    for blk in self.block2:
      x = blk(x, H, W)
    x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()


    # stage 3
    print('stage3 :', x.shape)
    x, (H, W) = self.patch_embed3(x)
    x = x + self.pos_embed3
    for blk in self.block3:
      x = blk(x, H, W)
    x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()

    # stage 4
    print('stage4 :', x.shape)
    x, (H, W) = self.patch_embed4(x)
    cls_tokens = self.cls_token.expand(B, -1, -1)
    x = torch.cat((cls_tokens, x), dim=1)
    x = x + self.pos_embed4
    for blk in self.block4:
      x = blk(x, H, W)
    x = self.norm(x)
    x = x[:, 0]

    x = self.head(x)
    return x

PvT-Tiny#

def PVT_Tiny():
  model = PyramidVisionTransformer(
      patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], depths=[2, 2, 2, 2]
      , sr_scales=[8, 4, 2, 1])
  return model

Author by 지승환
Edit by 김주영