์ฝ˜ํ…์ธ ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

์ฐธ์กฐ ultralytics/models/sam/modules/transformer.py

์ฐธ๊ณ 

์ด ํŒŒ์ผ์€ https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/models/ sam/modules/transformer .py์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฌธ์ œ๋ฅผ ๋ฐœ๊ฒฌํ•˜๋ฉด ํ’€ ๋ฆฌํ€˜์ŠคํŠธ (๐Ÿ› ๏ธ) ๋ฅผ ํ†ตํ•ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋„๋ก ๋„์™€์ฃผ์„ธ์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ™!



ultralytics.models.sam.modules.transformer.TwoWayTransformer

๋ฒ ์ด์Šค: Module

์ด๋ฏธ์ง€์™€ ์ฟผ๋ฆฌ ํฌ์ธํŠธ์— ๋™์‹œ์— ์ฃผ์˜๋ฅผ ๊ธฐ์šธ์ผ ์ˆ˜ ์žˆ๋Š” ์–‘๋ฐฉํ–ฅ ํŠธ๋žœ์Šคํฌ๋จธ ๋ชจ๋“ˆ์ž…๋‹ˆ๋‹ค. ์ด ํด๋ž˜์Šค ๋Š” ์œ„์น˜ ์ž„๋ฒ ๋”ฉ์ด ์ œ๊ณต๋˜๋Š” ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ž…๋ ฅ ์ด๋ฏธ์ง€๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ํŠน์ˆ˜ํ•œ ํŠธ๋žœ์Šคํฌ๋จธ ๋””์ฝ”๋” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ€ ์ œ๊ณต๋˜๋Š” ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ž…๋ ฅ ์ด๋ฏธ์ง€์— ๋Œ€์‘ํ•ฉ๋‹ˆ๋‹ค. ๋ฌผ์ฒด ๊ฐ์ง€, ์ด๋ฏธ์ง€ ๋ถ„ํ• , ํฌ์ธํŠธ ํด๋ผ์šฐ๋“œ ์ฒ˜๋ฆฌ์™€ ๊ฐ™์€ ์ž‘์—…์— ํŠนํžˆ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ฒ˜๋ฆฌ์™€ ๊ฐ™์€ ์ž‘์—…์— ํŠนํžˆ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

์†์„ฑ:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช…
depth int

ํŠธ๋žœ์Šคํฌ๋จธ์˜ ๋ ˆ์ด์–ด ์ˆ˜์ž…๋‹ˆ๋‹ค.

embedding_dim int

์ž…๋ ฅ ์ž„๋ฒ ๋”ฉ์˜ ์ฑ„๋„ ํฌ๊ธฐ์ž…๋‹ˆ๋‹ค.

num_heads int

๋ฉ€ํ‹ฐํ—ค๋“œ ์ฃผ์˜์— ๋Œ€ํ•œ ํ—ค๋“œ ์ˆ˜์ž…๋‹ˆ๋‹ค.

mlp_dim int

MLP ๋ธ”๋ก์˜ ๋‚ด๋ถ€ ์ฑ„๋„ ์น˜์ˆ˜์ž…๋‹ˆ๋‹ค.

layers ModuleList

ํŠธ๋žœ์Šคํฌ๋จธ๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” TwoWayAttentionBlock ๋ ˆ์ด์–ด ๋ชฉ๋ก์ž…๋‹ˆ๋‹ค.

final_attn_token_to_image Attention

์ฟผ๋ฆฌ์—์„œ ์ด๋ฏธ์ง€์— ์ ์šฉ๋˜๋Š” ์ตœ์ข… ๊ด€์‹ฌ ๋ ˆ์ด์–ด์ž…๋‹ˆ๋‹ค.

norm_final_attn LayerNorm

์ตœ์ข… ์ฟผ๋ฆฌ์— ์ ์šฉ๋œ ๋ ˆ์ด์–ด ์ •๊ทœํ™”์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
class TwoWayTransformer(nn.Module):
    """
    A Two-Way Transformer module that enables the simultaneous attention to both image and query points. This class
    serves as a specialized transformer decoder that attends to an input image using queries whose positional embedding
    is supplied. This is particularly useful for tasks like object detection, image segmentation, and point cloud
    processing.

    Attributes:
        depth (int): The number of layers in the transformer.
        embedding_dim (int): The channel dimension for the input embeddings.
        num_heads (int): The number of heads for multihead attention.
        mlp_dim (int): The internal channel dimension for the MLP block.
        layers (nn.ModuleList): The list of TwoWayAttentionBlock layers that make up the transformer.
        final_attn_token_to_image (Attention): The final attention layer applied from the queries to the image.
        norm_final_attn (nn.LayerNorm): The layer normalization applied to the final queries.
    """

    def __init__(
        self,
        depth: int,
        embedding_dim: int,
        num_heads: int,
        mlp_dim: int,
        activation: Type[nn.Module] = nn.ReLU,
        attention_downsample_rate: int = 2,
    ) -> None:
        """
        A transformer decoder that attends to an input image using queries whose positional embedding is supplied.

        Args:
          depth (int): number of layers in the transformer
          embedding_dim (int): the channel dimension for the input embeddings
          num_heads (int): the number of heads for multihead attention. Must
            divide embedding_dim
          mlp_dim (int): the channel dimension internal to the MLP block
          activation (nn.Module): the activation to use in the MLP block
        """
        super().__init__()
        self.depth = depth
        self.embedding_dim = embedding_dim
        self.num_heads = num_heads
        self.mlp_dim = mlp_dim
        self.layers = nn.ModuleList()

        for i in range(depth):
            self.layers.append(
                TwoWayAttentionBlock(
                    embedding_dim=embedding_dim,
                    num_heads=num_heads,
                    mlp_dim=mlp_dim,
                    activation=activation,
                    attention_downsample_rate=attention_downsample_rate,
                    skip_first_layer_pe=(i == 0),
                )
            )

        self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
        self.norm_final_attn = nn.LayerNorm(embedding_dim)

    def forward(
        self,
        image_embedding: Tensor,
        image_pe: Tensor,
        point_embedding: Tensor,
    ) -> Tuple[Tensor, Tensor]:
        """
        Args:
          image_embedding (torch.Tensor): image to attend to. Should be shape B x embedding_dim x h x w for any h and w.
          image_pe (torch.Tensor): the positional encoding to add to the image. Must have same shape as image_embedding.
          point_embedding (torch.Tensor): the embedding to add to the query points.
            Must have shape B x N_points x embedding_dim for any N_points.

        Returns:
          (torch.Tensor): the processed point_embedding
          (torch.Tensor): the processed image_embedding
        """
        # BxCxHxW -> BxHWxC == B x N_image_tokens x C
        bs, c, h, w = image_embedding.shape
        image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
        image_pe = image_pe.flatten(2).permute(0, 2, 1)

        # Prepare queries
        queries = point_embedding
        keys = image_embedding

        # Apply transformer blocks and final layernorm
        for layer in self.layers:
            queries, keys = layer(
                queries=queries,
                keys=keys,
                query_pe=point_embedding,
                key_pe=image_pe,
            )

        # Apply the final attention layer from the points to the image
        q = queries + point_embedding
        k = keys + image_pe
        attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
        queries = queries + attn_out
        queries = self.norm_final_attn(queries)

        return queries, keys

__init__(depth, embedding_dim, num_heads, mlp_dim, activation=nn.ReLU, attention_downsample_rate=2)

์œ„์น˜ ์ž„๋ฒ ๋”ฉ์ด ์ œ๊ณต๋œ ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ž…๋ ฅ ์ด๋ฏธ์ง€๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ํŠธ๋žœ์Šคํฌ๋จธ ๋””์ฝ”๋”์ž…๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
depth int

๋ณ€์••๊ธฐ์˜ ๋ ˆ์ด์–ด ์ˆ˜

ํ•„์ˆ˜
embedding_dim int

์ž…๋ ฅ ์ž„๋ฒ ๋”ฉ์˜ ์ฑ„๋„ ์น˜์ˆ˜

ํ•„์ˆ˜
num_heads int

๋ฉ€ํ‹ฐํ—ค๋“œ ์ฃผ์˜์— ๋Œ€ํ•œ ํ—ค๋“œ ์ˆ˜์ž…๋‹ˆ๋‹ค. ํ•„์ˆ˜ DIVIDE ์ž„๋ฒ ๋”ฉ_๋”ค

ํ•„์ˆ˜
mlp_dim int

MLP ๋ธ”๋ก ๋‚ด๋ถ€์˜ ์ฑ„๋„ ์น˜์ˆ˜

ํ•„์ˆ˜
activation Module

MLP ๋ธ”๋ก์—์„œ ์‚ฌ์šฉํ•  ํ™œ์„ฑํ™”

ReLU
์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
def __init__(
    self,
    depth: int,
    embedding_dim: int,
    num_heads: int,
    mlp_dim: int,
    activation: Type[nn.Module] = nn.ReLU,
    attention_downsample_rate: int = 2,
) -> None:
    """
    A transformer decoder that attends to an input image using queries whose positional embedding is supplied.

    Args:
      depth (int): number of layers in the transformer
      embedding_dim (int): the channel dimension for the input embeddings
      num_heads (int): the number of heads for multihead attention. Must
        divide embedding_dim
      mlp_dim (int): the channel dimension internal to the MLP block
      activation (nn.Module): the activation to use in the MLP block
    """
    super().__init__()
    self.depth = depth
    self.embedding_dim = embedding_dim
    self.num_heads = num_heads
    self.mlp_dim = mlp_dim
    self.layers = nn.ModuleList()

    for i in range(depth):
        self.layers.append(
            TwoWayAttentionBlock(
                embedding_dim=embedding_dim,
                num_heads=num_heads,
                mlp_dim=mlp_dim,
                activation=activation,
                attention_downsample_rate=attention_downsample_rate,
                skip_first_layer_pe=(i == 0),
            )
        )

    self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
    self.norm_final_attn = nn.LayerNorm(embedding_dim)

forward(image_embedding, image_pe, point_embedding)

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
image_embedding Tensor

์ด๋ฏธ์ง€๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋“  h์™€ w์— ๋Œ€ํ•ด B x embedding_dim x h x w ๋ชจ์–‘์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

ํ•„์ˆ˜
image_pe Tensor

์ด๋ฏธ์ง€์— ์ถ”๊ฐ€ํ•  ์œ„์น˜ ์ธ์ฝ”๋”ฉ์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. ์ด๋ฏธ์ง€_์ž„๋ฒ ๋”ฉ๊ณผ ๊ฐ™์€ ๋ชจ์–‘์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

ํ•„์ˆ˜
point_embedding Tensor

์ฟผ๋ฆฌ ํฌ์ธํŠธ์— ์ถ”๊ฐ€ํ•  ์ž„๋ฒ ๋”ฉ์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋“  N_ํฌ์ธํŠธ์— ๋Œ€ํ•ด B x N_ํฌ์ธํŠธ x embedding_dim ๋ชจ์–‘์„ ๊ฐ€์ ธ์•ผ ํ•ฉ๋‹ˆ๋‹ค.

ํ•„์ˆ˜

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
Tensor

์ฒ˜๋ฆฌ๋œ ํฌ์ธํŠธ_์ž„๋ฒ ๋”ฉ

Tensor

์ฒ˜๋ฆฌ๋œ ์ด๋ฏธ์ง€_์ž„๋ฒ ๋”ฉ

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
def forward(
    self,
    image_embedding: Tensor,
    image_pe: Tensor,
    point_embedding: Tensor,
) -> Tuple[Tensor, Tensor]:
    """
    Args:
      image_embedding (torch.Tensor): image to attend to. Should be shape B x embedding_dim x h x w for any h and w.
      image_pe (torch.Tensor): the positional encoding to add to the image. Must have same shape as image_embedding.
      point_embedding (torch.Tensor): the embedding to add to the query points.
        Must have shape B x N_points x embedding_dim for any N_points.

    Returns:
      (torch.Tensor): the processed point_embedding
      (torch.Tensor): the processed image_embedding
    """
    # BxCxHxW -> BxHWxC == B x N_image_tokens x C
    bs, c, h, w = image_embedding.shape
    image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
    image_pe = image_pe.flatten(2).permute(0, 2, 1)

    # Prepare queries
    queries = point_embedding
    keys = image_embedding

    # Apply transformer blocks and final layernorm
    for layer in self.layers:
        queries, keys = layer(
            queries=queries,
            keys=keys,
            query_pe=point_embedding,
            key_pe=image_pe,
        )

    # Apply the final attention layer from the points to the image
    q = queries + point_embedding
    k = keys + image_pe
    attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
    queries = queries + attn_out
    queries = self.norm_final_attn(queries)

    return queries, keys



ultralytics.models.sam.modules.transformer.TwoWayAttentionBlock

๋ฒ ์ด์Šค: Module

์ฟผ๋ฆฌ์—์„œ ํ‚ค๋กœ, ํ‚ค์—์„œ ์ฟผ๋ฆฌ๋กœ ๋‘ ๋ฐฉํ–ฅ์œผ๋กœ ์ž์ฒด ์ฃผ์˜์™€ ๊ต์ฐจ ์ฃผ์˜๋ฅผ ๋ชจ๋‘ ์ˆ˜ํ–‰ํ•˜๋Š” ์ฃผ์˜ ๋ธ”๋ก์ž…๋‹ˆ๋‹ค. ํ‚ค์—์„œ ์ฟผ๋ฆฌ๋กœ. ์ด ๋ธ”๋ก์€ ๋„ค ๊ฐ€์ง€ ์ฃผ์š” ๊ณ„์ธต์œผ๋กœ ๊ตฌ์„ฑ๋ฉ๋‹ˆ๋‹ค. (1) ํฌ์†Œ ์ž…๋ ฅ์— ๋Œ€ํ•œ ์ž์ฒด ์ฃผ์˜, (2) ํฌ์†Œ ์ž…๋ ฅ์—์„œ ๋ฐ€์ง‘ ์ž…๋ ฅ์œผ๋กœ์˜ ๊ต์ฐจ ์ฃผ์˜ (2) ํฌ์†Œ ์ž…๋ ฅ์—์„œ ๊ณ ๋ฐ€๋„ ์ž…๋ ฅ์œผ๋กœ์˜ ๊ต์ฐจ ์ฃผ์˜, (3) ํฌ์†Œ ์ž…๋ ฅ์— ๋Œ€ํ•œ MLP ๋ธ”๋ก, (4) ๊ณ ๋ฐ€๋„ ์ž…๋ ฅ์—์„œ ํฌ์†Œ ์ž…๋ ฅ์œผ๋กœ์˜ ์ŠคํŒŒ์Šค ์ž…๋ ฅ.

์†์„ฑ:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช…
self_attn Attention

์ฟผ๋ฆฌ์— ๋Œ€ํ•œ ์…€ํ”„ ์–ดํ…์…˜ ๋ ˆ์ด์–ด์ž…๋‹ˆ๋‹ค.

norm1 LayerNorm

์ฒซ ๋ฒˆ์งธ ๊ด€์‹ฌ ๋ธ”๋ก์— ๋”ฐ๋ฅธ ๋ ˆ์ด์–ด ์ •๊ทœํ™”.

cross_attn_token_to_image Attention

์ฟผ๋ฆฌ์—์„œ ํ‚ค๊นŒ์ง€ ๊ต์ฐจ ์ฃผ์˜ ๊ณ„์ธต.

norm2 LayerNorm

๋‘ ๋ฒˆ์งธ ๊ด€์‹ฌ ๋ธ”๋ก์— ๋”ฐ๋ฅธ ๋ ˆ์ด์–ด ์ •๊ทœํ™”.

mlp MLPBlock

์ฟผ๋ฆฌ ์ž„๋ฒ ๋”ฉ์„ ๋ณ€ํ™˜ํ•˜๋Š” MLP ๋ธ”๋ก์ž…๋‹ˆ๋‹ค.

norm3 LayerNorm

MLP ๋ธ”๋ก์— ๋”ฐ๋ฅธ ๋ ˆ์ด์–ด ์ •๊ทœํ™”.

norm4 LayerNorm

์„ธ ๋ฒˆ์งธ ์ฃผ์˜ ๋ธ”๋ก์— ๋”ฐ๋ฅธ ๋ ˆ์ด์–ด ์ •๊ทœํ™”.

cross_attn_image_to_token Attention

ํ‚ค์—์„œ ์ฟผ๋ฆฌ๊นŒ์ง€ ๊ต์ฐจ ์ฃผ์˜ ๊ณ„์ธต.

skip_first_layer_pe bool

์ฒซ ๋ฒˆ์งธ ๋ ˆ์ด์–ด์—์„œ ์œ„์น˜ ์ธ์ฝ”๋”ฉ์„ ๊ฑด๋„ˆ๋›ธ์ง€ ์—ฌ๋ถ€์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
class TwoWayAttentionBlock(nn.Module):
    """
    An attention block that performs both self-attention and cross-attention in two directions: queries to keys and
    keys to queries. This block consists of four main layers: (1) self-attention on sparse inputs, (2) cross-attention
    of sparse inputs to dense inputs, (3) an MLP block on sparse inputs, and (4) cross-attention of dense inputs to
    sparse inputs.

    Attributes:
        self_attn (Attention): The self-attention layer for the queries.
        norm1 (nn.LayerNorm): Layer normalization following the first attention block.
        cross_attn_token_to_image (Attention): Cross-attention layer from queries to keys.
        norm2 (nn.LayerNorm): Layer normalization following the second attention block.
        mlp (MLPBlock): MLP block that transforms the query embeddings.
        norm3 (nn.LayerNorm): Layer normalization following the MLP block.
        norm4 (nn.LayerNorm): Layer normalization following the third attention block.
        cross_attn_image_to_token (Attention): Cross-attention layer from keys to queries.
        skip_first_layer_pe (bool): Whether to skip the positional encoding in the first layer.
    """

    def __init__(
        self,
        embedding_dim: int,
        num_heads: int,
        mlp_dim: int = 2048,
        activation: Type[nn.Module] = nn.ReLU,
        attention_downsample_rate: int = 2,
        skip_first_layer_pe: bool = False,
    ) -> None:
        """
        A transformer block with four layers: (1) self-attention of sparse inputs, (2) cross attention of sparse
        inputs to dense inputs, (3) mlp block on sparse inputs, and (4) cross attention of dense inputs to sparse
        inputs.

        Args:
          embedding_dim (int): the channel dimension of the embeddings
          num_heads (int): the number of heads in the attention layers
          mlp_dim (int): the hidden dimension of the mlp block
          activation (nn.Module): the activation of the mlp block
          skip_first_layer_pe (bool): skip the PE on the first layer
        """
        super().__init__()
        self.self_attn = Attention(embedding_dim, num_heads)
        self.norm1 = nn.LayerNorm(embedding_dim)

        self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
        self.norm2 = nn.LayerNorm(embedding_dim)

        self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
        self.norm3 = nn.LayerNorm(embedding_dim)

        self.norm4 = nn.LayerNorm(embedding_dim)
        self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)

        self.skip_first_layer_pe = skip_first_layer_pe

    def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> Tuple[Tensor, Tensor]:
        """Apply self-attention and cross-attention to queries and keys and return the processed embeddings."""

        # Self attention block
        if self.skip_first_layer_pe:
            queries = self.self_attn(q=queries, k=queries, v=queries)
        else:
            q = queries + query_pe
            attn_out = self.self_attn(q=q, k=q, v=queries)
            queries = queries + attn_out
        queries = self.norm1(queries)

        # Cross attention block, tokens attending to image embedding
        q = queries + query_pe
        k = keys + key_pe
        attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
        queries = queries + attn_out
        queries = self.norm2(queries)

        # MLP block
        mlp_out = self.mlp(queries)
        queries = queries + mlp_out
        queries = self.norm3(queries)

        # Cross attention block, image embedding attending to tokens
        q = queries + query_pe
        k = keys + key_pe
        attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
        keys = keys + attn_out
        keys = self.norm4(keys)

        return queries, keys

__init__(embedding_dim, num_heads, mlp_dim=2048, activation=nn.ReLU, attention_downsample_rate=2, skip_first_layer_pe=False)

๋„ค ๊ฐœ์˜ ๋ ˆ์ด์–ด๋กœ ๊ตฌ์„ฑ๋œ ํŠธ๋žœ์Šคํฌ๋จธ ๋ธ”๋ก: (1) ํฌ์†Œ ์ž…๋ ฅ์˜ ์ž์ฒด ์ฃผ์˜, (2) ํฌ์†Œ ์ž…๋ ฅ์—์„œ ๊ณ ๋ฐ€๋„ ์ž…๋ ฅ์œผ๋กœ์˜ ๊ต์ฐจ ์ฃผ์˜ ์ž…๋ ฅ, (3) ํฌ์†Œ ์ž…๋ ฅ์— ๋Œ€ํ•œ MLP ๋ธ”๋ก, (4) ํฌ์†Œ ์ž…๋ ฅ์— ๋Œ€ํ•œ ๊ณ ๋ฐ€๋„ ์ž…๋ ฅ์˜ ๊ต์ฐจ ์ฃผ์˜. ์ž…๋ ฅ์— ๋Œ€ํ•œ ๊ต์ฐจ ์ฃผ์˜.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
embedding_dim int

์ž„๋ฒ ๋”ฉ์˜ ์ฑ„๋„ ํฌ๊ธฐ

ํ•„์ˆ˜
num_heads int

๊ด€์‹ฌ ๊ณ„์ธต์˜ ํ—ค๋“œ ์ˆ˜

ํ•„์ˆ˜
mlp_dim int

MLP ๋ธ”๋ก์˜ ์ˆจ๊ฒจ์ง„ ์น˜์ˆ˜

2048
activation Module

MLP ๋ธ”๋ก์˜ ํ™œ์„ฑํ™”

ReLU
skip_first_layer_pe bool

์ฒซ ๋ฒˆ์งธ ๋ ˆ์ด์–ด์—์„œ PE ๊ฑด๋„ˆ๋›ฐ๊ธฐ

False
์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
def __init__(
    self,
    embedding_dim: int,
    num_heads: int,
    mlp_dim: int = 2048,
    activation: Type[nn.Module] = nn.ReLU,
    attention_downsample_rate: int = 2,
    skip_first_layer_pe: bool = False,
) -> None:
    """
    A transformer block with four layers: (1) self-attention of sparse inputs, (2) cross attention of sparse
    inputs to dense inputs, (3) mlp block on sparse inputs, and (4) cross attention of dense inputs to sparse
    inputs.

    Args:
      embedding_dim (int): the channel dimension of the embeddings
      num_heads (int): the number of heads in the attention layers
      mlp_dim (int): the hidden dimension of the mlp block
      activation (nn.Module): the activation of the mlp block
      skip_first_layer_pe (bool): skip the PE on the first layer
    """
    super().__init__()
    self.self_attn = Attention(embedding_dim, num_heads)
    self.norm1 = nn.LayerNorm(embedding_dim)

    self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
    self.norm2 = nn.LayerNorm(embedding_dim)

    self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
    self.norm3 = nn.LayerNorm(embedding_dim)

    self.norm4 = nn.LayerNorm(embedding_dim)
    self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)

    self.skip_first_layer_pe = skip_first_layer_pe

forward(queries, keys, query_pe, key_pe)

์ฟผ๋ฆฌ์™€ ํ‚ค์— ์ž์ฒด ์ฃผ์˜ ๋ฐ ๊ต์ฐจ ์ฃผ์˜๋ฅผ ์ ์šฉํ•˜๊ณ  ์ฒ˜๋ฆฌ๋œ ์ž„๋ฒ ๋”ฉ์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> Tuple[Tensor, Tensor]:
    """Apply self-attention and cross-attention to queries and keys and return the processed embeddings."""

    # Self attention block
    if self.skip_first_layer_pe:
        queries = self.self_attn(q=queries, k=queries, v=queries)
    else:
        q = queries + query_pe
        attn_out = self.self_attn(q=q, k=q, v=queries)
        queries = queries + attn_out
    queries = self.norm1(queries)

    # Cross attention block, tokens attending to image embedding
    q = queries + query_pe
    k = keys + key_pe
    attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
    queries = queries + attn_out
    queries = self.norm2(queries)

    # MLP block
    mlp_out = self.mlp(queries)
    queries = queries + mlp_out
    queries = self.norm3(queries)

    # Cross attention block, image embedding attending to tokens
    q = queries + query_pe
    k = keys + key_pe
    attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
    keys = keys + attn_out
    keys = self.norm4(keys)

    return queries, keys



ultralytics.models.sam.modules.transformer.Attention

๋ฒ ์ด์Šค: Module

์ฟผ๋ฆฌ, ํ‚ค, ๊ฐ’์œผ๋กœ ํˆฌ์˜ํ•œ ํ›„ ์ž„๋ฒ ๋”ฉ ํฌ๊ธฐ๋ฅผ ์ถ•์†Œํ•  ์ˆ˜ ์žˆ๋Š” ๊ด€์‹ฌ ๋ ˆ์ด์–ด์ž…๋‹ˆ๋‹ค. ๊ฐ’์œผ๋กœ ํฌ๊ธฐ๋ฅผ ์ถ•์†Œํ•  ์ˆ˜ ์žˆ๋Š” ์ฃผ์˜ ๋ ˆ์ด์–ด์ž…๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
class Attention(nn.Module):
    """An attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
    values.
    """

    def __init__(
        self,
        embedding_dim: int,
        num_heads: int,
        downsample_rate: int = 1,
    ) -> None:
        """
        Initializes the Attention model with the given dimensions and settings.

        Args:
            embedding_dim (int): The dimensionality of the input embeddings.
            num_heads (int): The number of attention heads.
            downsample_rate (int, optional): The factor by which the internal dimensions are downsampled. Defaults to 1.

        Raises:
            AssertionError: If 'num_heads' does not evenly divide the internal dim (embedding_dim / downsample_rate).
        """
        super().__init__()
        self.embedding_dim = embedding_dim
        self.internal_dim = embedding_dim // downsample_rate
        self.num_heads = num_heads
        assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."

        self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
        self.k_proj = nn.Linear(embedding_dim, self.internal_dim)
        self.v_proj = nn.Linear(embedding_dim, self.internal_dim)
        self.out_proj = nn.Linear(self.internal_dim, embedding_dim)

    @staticmethod
    def _separate_heads(x: Tensor, num_heads: int) -> Tensor:
        """Separate the input tensor into the specified number of attention heads."""
        b, n, c = x.shape
        x = x.reshape(b, n, num_heads, c // num_heads)
        return x.transpose(1, 2)  # B x N_heads x N_tokens x C_per_head

    @staticmethod
    def _recombine_heads(x: Tensor) -> Tensor:
        """Recombine the separated attention heads into a single tensor."""
        b, n_heads, n_tokens, c_per_head = x.shape
        x = x.transpose(1, 2)
        return x.reshape(b, n_tokens, n_heads * c_per_head)  # B x N_tokens x C

    def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
        """Compute the attention output given the input query, key, and value tensors."""

        # Input projections
        q = self.q_proj(q)
        k = self.k_proj(k)
        v = self.v_proj(v)

        # Separate into heads
        q = self._separate_heads(q, self.num_heads)
        k = self._separate_heads(k, self.num_heads)
        v = self._separate_heads(v, self.num_heads)

        # Attention
        _, _, _, c_per_head = q.shape
        attn = q @ k.permute(0, 1, 3, 2)  # B x N_heads x N_tokens x N_tokens
        attn = attn / math.sqrt(c_per_head)
        attn = torch.softmax(attn, dim=-1)

        # Get output
        out = attn @ v
        out = self._recombine_heads(out)
        return self.out_proj(out)

__init__(embedding_dim, num_heads, downsample_rate=1)

์ง€์ •๋œ ์ฐจ์›๊ณผ ์„ค์ •์œผ๋กœ ๊ด€์‹ฌ๋„ ๋ชจ๋ธ์„ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
embedding_dim int

์ž…๋ ฅ ์ž„๋ฒ ๋”ฉ์˜ ์ฐจ์›์ž…๋‹ˆ๋‹ค.

ํ•„์ˆ˜
num_heads int

๊ด€์‹ฌ ํ—ค๋“œ ์ˆ˜์ž…๋‹ˆ๋‹ค.

ํ•„์ˆ˜
downsample_rate int

๋‚ด๋ถ€ ์น˜์ˆ˜๊ฐ€ ๋‹ค์šด์ƒ˜ํ”Œ๋ง๋˜๋Š” ๊ณ„์ˆ˜์ž…๋‹ˆ๋‹ค. ๊ธฐ๋ณธ๊ฐ’์€ 1์ž…๋‹ˆ๋‹ค.

1

์˜ฌ๋ฆฌ๋‹ค:

์œ ํ˜• ์„ค๋ช…
AssertionError

'num_heads'๊ฐ€ ๋‚ด๋ถ€ ๋”ค(embedding_dim / downsample_rate)์„ ๊ท ๋“ฑํ•˜๊ฒŒ ๋‚˜๋ˆ„์ง€ ์•Š๋Š” ๊ฒฝ์šฐ.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
def __init__(
    self,
    embedding_dim: int,
    num_heads: int,
    downsample_rate: int = 1,
) -> None:
    """
    Initializes the Attention model with the given dimensions and settings.

    Args:
        embedding_dim (int): The dimensionality of the input embeddings.
        num_heads (int): The number of attention heads.
        downsample_rate (int, optional): The factor by which the internal dimensions are downsampled. Defaults to 1.

    Raises:
        AssertionError: If 'num_heads' does not evenly divide the internal dim (embedding_dim / downsample_rate).
    """
    super().__init__()
    self.embedding_dim = embedding_dim
    self.internal_dim = embedding_dim // downsample_rate
    self.num_heads = num_heads
    assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."

    self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
    self.k_proj = nn.Linear(embedding_dim, self.internal_dim)
    self.v_proj = nn.Linear(embedding_dim, self.internal_dim)
    self.out_proj = nn.Linear(self.internal_dim, embedding_dim)

forward(q, k, v)

์ž…๋ ฅ ์ฟผ๋ฆฌ, ํ‚ค, ๊ฐ’ ํ…์„œ๊ฐ€ ์ฃผ์–ด์ง€๋ฉด ๊ด€์‹ฌ๋„ ์ถœ๋ ฅ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/sam/modules/transformer.py
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
    """Compute the attention output given the input query, key, and value tensors."""

    # Input projections
    q = self.q_proj(q)
    k = self.k_proj(k)
    v = self.v_proj(v)

    # Separate into heads
    q = self._separate_heads(q, self.num_heads)
    k = self._separate_heads(k, self.num_heads)
    v = self._separate_heads(v, self.num_heads)

    # Attention
    _, _, _, c_per_head = q.shape
    attn = q @ k.permute(0, 1, 3, 2)  # B x N_heads x N_tokens x N_tokens
    attn = attn / math.sqrt(c_per_head)
    attn = torch.softmax(attn, dim=-1)

    # Get output
    out = attn @ v
    out = self._recombine_heads(out)
    return self.out_proj(out)





Created 2023-11-12, Updated 2024-06-02
Authors: glenn-jocher (5), Burhan-Q (1), Laughing-q (1)