파이톨치

CLIP 코드 뜯어보기 - ModifiedResNet Class 본문

카테고리 없음

CLIP 코드 뜯어보기 - ModifiedResNet Class

파이톨치 2025. 1. 18. 18:01
728x90

https://github.com/openai/CLIP/blob/main/clip/model.py

 

CLIP/clip/model.py at main · openai/CLIP

CLIP (Contrastive Language-Image Pretraining), Predict the most relevant text snippet given an image - openai/CLIP

github.com

 

CLIP 코드를 대충 머리 속에 넣어두려고 한다. 

CLIP에 들어가는 인코더와 디코더의 구조, 그리고 학습하는 방법을 머리 속에 넣어둔다면 이를 응용할 일이 생길 때 유용할 것이라고 기대하기 때문이다. 그리고 이 정도 되는 코드를 머리 속에 넣어두어야 어디가서 쫄지 않고 코드를 잘 짤 수 있을 것 같기 때문이다. 

스스로 이 코드를 모른다면, 부끄러울 것 같아 이 코드를 정리 해 보려고 한다. 

 

우선 깃허브에 들어가서, model.py를 열어보면 파이토치 코드가 보인다. 처음에 보려고 하는 코드는 ResNet 구조이다. 하지만, openai에서 현대에 맞는 기법들을 사용해서 resnet을 변형한 구조이다. 기존의 resent과 주요한 차이점은 ma

x pool 을 썼던 자리에 average pool을 사용했고, 마지막에 사용된 pooling 층은 QKV를 사용한 attention으로 대체 되었다.

처음 시작은 Bottleneck 클래스이다. 벌써부터 숨이 턱 막하지만 천천히 천천히 하나하나 뜯어봐야겠다. 

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1):
        super().__init__()

        # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
        self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu1 = nn.ReLU(inplace=True)

        self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.relu2 = nn.ReLU(inplace=True)

        self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()

        self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion)
        self.relu3 = nn.ReLU(inplace=True)

        self.downsample = None
        self.stride = stride

        if stride > 1 or inplanes != planes * Bottleneck.expansion:
            # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
            self.downsample = nn.Sequential(OrderedDict([
                ("-1", nn.AvgPool2d(stride)),
                ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
                ("1", nn.BatchNorm2d(planes * self.expansion))
            ]))

    def forward(self, x: torch.Tensor):
        identity = x

        out = self.relu1(self.bn1(self.conv1(x)))
        out = self.relu2(self.bn2(self.conv2(out)))
        out = self.avgpool(out)
        out = self.bn3(self.conv3(out))

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu3(out)
        return out

 

이 코드를 보고 처음 드는 생각은 이게 어디 쓰일까? 이다. GPT 한테 물어보고 알았다. 이건 res-net에 쓰이는 구조이다. 

처음에 nn.Conv2d가 등장한다. 이 함수는 in_channels, out_channels, kernel_size 순으로 인자가 들어간다. 그리고 현재 strid는 주석대로 디폴트값인 1을 사용하고 있다. 

 

예를 들어, (B, C_in, H, W)인 입력이 들어간다면, (B, C_out, H_out, W_out)인 출력이 나올 것이다. 생각해보면 커널사이즈가 1이기 때문에 H_out, W_out은 H, W와 같은 것이다. 단순한 스칼라 값이 곱해진다고 생각하면 되는 것이다.  

수학적으로는 아래와 같은데, 그림으로 보는게 더 이해하기 편하다. 보통 입력이 RGB이기 때문에, 저렇게 곱했을 때 채널이 2개 생기는 것이고 각 채널마다 커널을 곱해서 더하는 것이다. 

이를 확장해서 생각해보면 커널 사이즈가 3일 때는 다음과 같을 것이다. 이게 참 헷갈렸는데, 그림으로 보니까 바로 이해가 된다!! 

이게 이해한 것을 합쳐서 이 bottle neck이라는 클래스가 뭘 하는 클래스인지 이해해보자. 우선 입력이 들어왔을 때, 1x1x1 사이즈의 커널을 지나서 원하는 채널 수로 만들어 준다. 그 뒤에는 batch_norm 2d를 해준다. 그림으로는 요렇게 생겼는데 배치 단위로 정규화를 해주는 것이다. 이 때 각 채널별로 평균과 분산이 계산되어 정규화가 된다. 

그 다음에 활성화 함수를 지나고 이걸 다시 다음층에 넘겨주는데 이 때 커널 사이즈는 3이고, 패딩은 1이다. 이렇게 하면 h, w의 사이즈 변화 없이 합성곱 연산을 할 수 있다. 그 뒤에 avgpool2d 연산을 통해서 stride가 1보다 크면 작동하고 아니면, 항등 연산을 한다. 그 뒤로 3번째 합성 곱 연산은 self.expansion의 값 만큼 채널 수를 곱해서 반환하게 된다. 그 뒤에 out에 처음에 들어왔던 x를 곱한다. 의문점은 이 때 차원 수가 안 맞지 않나? 왜냐면 3번째에서 4배 만큼 불렸기 떄문이다. 아! 모델을 설계할 때, inplanes == planes * BottleBeck.expansion이면 문제가 안 생긴다. 만약 그렇지 않은 경우에는 이를 맞춰주기 위해서 self.downsample 함수가 동작하는 것이다. 지금 Bottleneck 함수는 residual 연산을 하고 있는 것이다. 전체적인 그림은 아래와 같이 되는 것읻. 

 

이 다음에는 유명한 self-attention 매너니즘이 나온다. 이 층은 modified resnet의 마지막 pooling layer 역할을 한다.

길을 헤매기 쉬운 코드이지만 집중해서 잃어보자. 우선 init 함수에서는 posisional_embedding을 nn.Parameter로 구성해서 학습가능하게 만들었다. torch.randn은 평균이 0이고 표준편차가 1인 정규분포에서 난수를 생성한다. 이 난수를 생성하는 코드를 이용해서 초기화를 해주는 것이다. 공간적인 차원 정보의 제곱이 의미하는 것은 잘려진 패치의 가로와 세로 길이이다. 이를 1차원으로 펼쳤을 때, spacial_dim의 제곱만큼 공간이 필요한 것이고, +1 은 cls 토큰을 위한 것이다. embed_dim은 각 픽셀에 대한 임베딩의 차원을 의미한다. 그리고 embed_dim의 루트를 씌워 나누어 주는데, 이건 초기값의 분포를 안정적으로 만들기 위함이다. (초기화 관련은 따로 찾아보시길)

 

내 멋대로 그림으로 정리해보자면 이렇게 될 것이다. strid가 2라면 입력 해상도는 줄어들 것이다. 

채널 수는 그만큼 늘어날 것이다. BottleNeck 클래스를 연속적으로 붙이긴 위해선 planes * self.exapnsion이 다음 층의 입력으로 들어가야 할 것이다. 

 

그 다음에 선형층을 넣어서 입력을 서로 다른 공간에 투영시킨다. 그렇게 서로 다른 k, q, v를 만들어낸다. 

class AttentionPool2d(nn.Module):
    def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
        super().__init__()
        self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
        self.k_proj = nn.Linear(embed_dim, embed_dim)
        self.q_proj = nn.Linear(embed_dim, embed_dim)
        self.v_proj = nn.Linear(embed_dim, embed_dim)
        self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
        self.num_heads = num_heads

    def forward(self, x):
        x = x.flatten(start_dim=2).permute(2, 0, 1)  # NCHW -> (HW)NC
        x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0)  # (HW+1)NC
        x = x + self.positional_embedding[:, None, :].to(x.dtype)  # (HW+1)NC
        x, _ = F.multi_head_attention_forward(
            query=x[:1], key=x, value=x,
            embed_dim_to_check=x.shape[-1],
            num_heads=self.num_heads,
            q_proj_weight=self.q_proj.weight,
            k_proj_weight=self.k_proj.weight,
            v_proj_weight=self.v_proj.weight,
            in_proj_weight=None,
            in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
            bias_k=None,
            bias_v=None,
            add_zero_attn=False,
            dropout_p=0,
            out_proj_weight=self.c_proj.weight,
            out_proj_bias=self.c_proj.bias,
            use_separate_proj_weight=True,
            training=self.training,
            need_weights=False
        )
        return x.squeeze(0)

 

일단 flatten을 통해서 펴주는데, start_dim = 2니까 뒤에 2개를 펴준다. N, C, H*W가 되고 이를 permute로 순서를 바꾸어 준다. 

그렇게 하면 H*W, N, C 순서로 바뀐다. 여기에 cls 토큰을 앞에 추가해준다. 그거기에 다시 positional embedding을 추가해준다.

이거 해주는거다. 

그 뒤에 transformer에 넣어주게 된다. 저기 저 multi-head-attention 함수는 조금 복잡하기 때문에 머릿 속에 넣어두긴 힘들고, 그냥 필요할 때 검색해서 사용해야 겠다. 

이제 해줘야 하는 것은 만들어둔 클래스를 활용해서 modified resnet 구조를 만드는 것이다. 

이렇게 보면 난해할 수 있는데, 지금 보니까 이 코드는 기존에 있던 층을 변형하는 것이다. 입력을 layers 정보가 있는데, 이것은 사전에 학습된 층들인 것 같다. 

class ModifiedResNet(nn.Module):
    """
    A ResNet class that is similar to torchvision's but contains the following changes:
    - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
    - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
    - The final pooling layer is a QKV attention instead of an average pool
    """

    def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
        super().__init__()
        self.output_dim = output_dim
        self.input_resolution = input_resolution

        # the 3-layer stem
        self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(width // 2)
        self.relu1 = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(width // 2)
        self.relu2 = nn.ReLU(inplace=True)
        self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
        self.bn3 = nn.BatchNorm2d(width)
        self.relu3 = nn.ReLU(inplace=True)
        self.avgpool = nn.AvgPool2d(2)

        # residual layers
        self._inplanes = width  # this is a *mutable* variable used during construction
        self.layer1 = self._make_layer(width, layers[0])
        self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
        self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
        self.layer4 = self._make_layer(width * 8, layers[3], stride=2)

        embed_dim = width * 32  # the ResNet feature dimension
        self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
        
    def _make_layer(self, planes, blocks, stride=1):
        layers = [Bottleneck(self._inplanes, planes, stride)]

        self._inplanes = planes * Bottleneck.expansion
        for _ in range(1, blocks):
            layers.append(Bottleneck(self._inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        def stem(x):
            x = self.relu1(self.bn1(self.conv1(x)))
            x = self.relu2(self.bn2(self.conv2(x)))
            x = self.relu3(self.bn3(self.conv3(x)))
            x = self.avgpool(x)
            return x

        x = x.type(self.conv1.weight.dtype)
        x = stem(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.attnpool(x)

        return x

 

처음에 stem 연산을 하면 아래와 같이 차원이 변한다. 3차원이었던 0번째 차원이 width 만큼으로 변하게 되고, 

w * w 였던 해상도가 stride=2, avgpool(2)를 거치게 되면서 w/4 * w/4로 줄어들게 된다. 

그 뒤로는 더 깊고, 좁아진다. 해상도는 다시 stride를 3번 거치게 되면서 1/8을 하게 되고,  0 차원은 깊이는 더 깊어져서 width * 8 * Bottleneck.expansion을 하게 된다. 그 다음에 저 벡터를 flatten 해서 multiheadattion에 넣으면 원하는 output_dim 크기의 벡터가 나오는 것이다. 이렇게 이미지가 들어갔을 때, 그에 맞는 이미지 벡터를 얻을 수 있게 되는 것이다. 중간에 multiheadattention 함수는 나도 잘 모르겠다. 암튼 저런 형태로 입출력이 된다는건 이해가 된다. 

728x90