Reference for ultralytics/models/sam/modules/blocks.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/models/sam/modules/blocks.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.models.sam.modules.blocks.DropPath
Bases: Module
Implements stochastic depth regularization for neural networks during training.
Attributes:
Name | Type | Description |
---|---|---|
drop_prob |
float
|
Probability of dropping a path during training. |
scale_by_keep |
bool
|
Whether to scale the output by the keep probability. |
Methods:
Name | Description |
---|---|
forward |
Applies stochastic depth to input tensor during training, with optional scaling. |
Examples:
>>> drop_path = DropPath(drop_prob=0.2, scale_by_keep=True)
>>> x = torch.randn(32, 64, 224, 224)
>>> output = drop_path(x)
Source code in ultralytics/models/sam/modules/blocks.py
forward
Applies stochastic depth to input tensor during training, with optional scaling.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.MaskDownSampler
MaskDownSampler(
embed_dim=256,
kernel_size=4,
stride=4,
padding=0,
total_stride=16,
activation=nn.GELU,
)
Bases: Module
A mask downsampling and embedding module for efficient processing of input masks.
This class implements a mask downsampler that progressively reduces the spatial dimensions of input masks while expanding their channel dimensions using convolutional layers, layer normalization, and activation functions.
Attributes:
Name | Type | Description |
---|---|---|
encoder |
Sequential
|
A sequential container of convolutional layers, layer normalization, and activation functions for downsampling and embedding masks. |
Methods:
Name | Description |
---|---|
forward |
Downsamples and encodes input mask to embed_dim channels. |
Examples:
>>> mask_downsampler = MaskDownSampler(embed_dim=256, kernel_size=4, stride=4, padding=0, total_stride=16)
>>> input_mask = torch.randn(1, 1, 256, 256)
>>> output = mask_downsampler(input_mask)
>>> print(output.shape)
torch.Size([1, 256, 16, 16])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Downsamples and encodes input mask to embed_dim channels using convolutional layers and LayerNorm2d.
ultralytics.models.sam.modules.blocks.CXBlock
CXBlock(
dim,
kernel_size=7,
padding=3,
drop_path=0.0,
layer_scale_init_value=1e-06,
use_dwconv=True,
)
Bases: Module
ConvNeXt Block for efficient feature extraction in convolutional neural networks.
This block implements a modified version of the ConvNeXt architecture, offering improved performance and flexibility in feature extraction.
Attributes:
Name | Type | Description |
---|---|---|
dwconv |
Conv2d
|
Depthwise or standard 2D convolution layer. |
norm |
LayerNorm2d
|
Layer normalization applied to channels. |
pwconv1 |
Linear
|
First pointwise convolution implemented as a linear layer. |
act |
GELU
|
GELU activation function. |
pwconv2 |
Linear
|
Second pointwise convolution implemented as a linear layer. |
gamma |
Parameter | None
|
Learnable scale parameter for layer scaling. |
drop_path |
Module
|
DropPath layer for stochastic depth regularization. |
Methods:
Name | Description |
---|---|
forward |
Processes the input tensor through the ConvNeXt block. |
Examples:
>>> import torch
>>> x = torch.randn(1, 64, 56, 56)
>>> block = CXBlock(dim=64, kernel_size=7, padding=3)
>>> output = block(x)
>>> print(output.shape)
torch.Size([1, 64, 56, 56])
This block implements a modified version of the ConvNeXt architecture, offering improved performance and flexibility in feature extraction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dim
|
int
|
Number of input channels. |
required |
kernel_size
|
int
|
Size of the convolutional kernel. |
7
|
padding
|
int
|
Padding size for the convolution. |
3
|
drop_path
|
float
|
Stochastic depth rate. |
0.0
|
layer_scale_init_value
|
float
|
Initial value for Layer Scale. |
1e-06
|
use_dwconv
|
bool
|
Whether to use depthwise convolution. |
True
|
Examples:
>>> block = CXBlock(dim=64, kernel_size=7, padding=3)
>>> x = torch.randn(1, 64, 32, 32)
>>> output = block(x)
>>> print(output.shape)
torch.Size([1, 64, 32, 32])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Applies ConvNeXt block operations to input tensor, including convolutions and residual connection.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.Fuser
Bases: Module
A module for fusing features through multiple layers of a neural network.
This class applies a series of identical layers to an input tensor, optionally projecting the input first.
Attributes:
Name | Type | Description |
---|---|---|
proj |
Module
|
An optional input projection layer. Identity if no projection is needed. |
layers |
ModuleList
|
A list of identical layers to be applied sequentially. |
Methods:
Name | Description |
---|---|
forward |
Applies the fuser to an input tensor. |
Examples:
>>> layer = CXBlock(dim=256)
>>> fuser = Fuser(layer, num_layers=3, dim=256, input_projection=True)
>>> x = torch.randn(1, 256, 32, 32)
>>> output = fuser(x)
>>> print(output.shape)
torch.Size([1, 256, 32, 32])
This module creates a sequence of identical layers and optionally applies an input projection.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
layer
|
Module
|
The layer to be replicated in the fuser. |
required |
num_layers
|
int
|
The number of times to replicate the layer. |
required |
dim
|
int | None
|
The dimension for input projection, if used. |
None
|
input_projection
|
bool
|
Whether to use input projection. |
False
|
Examples:
>>> layer = nn.Linear(64, 64)
>>> fuser = Fuser(layer, num_layers=3, dim=64, input_projection=True)
>>> input_tensor = torch.randn(1, 64)
>>> output = fuser(input_tensor)
Source code in ultralytics/models/sam/modules/blocks.py
forward
Applies a series of layers to the input tensor, optionally projecting it first.
ultralytics.models.sam.modules.blocks.SAM2TwoWayAttentionBlock
SAM2TwoWayAttentionBlock(
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,
)
Bases: TwoWayAttentionBlock
A two-way attention block for performing self-attention and cross-attention in both directions.
This block extends the TwoWayAttentionBlock and consists of four main components: self-attention on sparse inputs, cross-attention from sparse to dense inputs, an MLP block on sparse inputs, and cross-attention from dense to sparse inputs.
Attributes:
Name | Type | Description |
---|---|---|
self_attn |
Attention
|
Self-attention layer for queries. |
norm1 |
LayerNorm
|
Layer normalization after the first attention block. |
cross_attn_token_to_image |
Attention
|
Cross-attention layer from queries to keys. |
norm2 |
LayerNorm
|
Layer normalization after the second attention block. |
mlp |
MLP
|
MLP block for transforming query embeddings. |
norm3 |
LayerNorm
|
Layer normalization after the MLP block. |
norm4 |
LayerNorm
|
Layer normalization after the third attention block. |
cross_attn_image_to_token |
Attention
|
Cross-attention layer from keys to queries. |
skip_first_layer_pe |
bool
|
Flag to skip positional encoding in the first layer. |
Methods:
Name | Description |
---|---|
forward |
Processes input through the attention blocks and MLP. |
Examples:
>>> block = SAM2TwoWayAttentionBlock(embedding_dim=256, num_heads=8)
>>> sparse_input = torch.randn(1, 100, 256)
>>> dense_input = torch.randn(1, 256, 16, 16)
>>> sparse_output, dense_output = block(sparse_input, dense_input)
This block extends the TwoWayAttentionBlock and consists of four main components: self-attention on sparse inputs, cross-attention from sparse to dense inputs, an MLP block on sparse inputs, and cross-attention from dense to sparse inputs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
embedding_dim
|
int
|
The channel dimension of the embeddings. |
required |
num_heads
|
int
|
The number of heads in the attention layers. |
required |
mlp_dim
|
int
|
The hidden dimension of the MLP block. |
2048
|
activation
|
Type[Module]
|
The activation function of the MLP block. |
ReLU
|
attention_downsample_rate
|
int
|
The downsample rate for attention computations. |
2
|
skip_first_layer_pe
|
bool
|
Whether to skip the positional encoding in the first layer. |
False
|
Examples:
>>> block = SAM2TwoWayAttentionBlock(embedding_dim=256, num_heads=8, mlp_dim=2048)
>>> sparse_inputs = torch.randn(1, 100, 256)
>>> dense_inputs = torch.randn(1, 256, 32, 32)
>>> sparse_outputs, dense_outputs = block(sparse_inputs, dense_inputs)
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.SAM2TwoWayTransformer
SAM2TwoWayTransformer(
depth: int,
embedding_dim: int,
num_heads: int,
mlp_dim: int,
activation: Type[nn.Module] = nn.ReLU,
attention_downsample_rate: int = 2,
)
Bases: TwoWayTransformer
A Two-Way Transformer module for simultaneous attention to image and query points.
This class extends the TwoWayTransformer, implementing a specialized transformer decoder that attends to an input image using queries with supplied positional embeddings. It is particularly useful for tasks like object detection, image segmentation, and point cloud processing.
Attributes:
Name | Type | Description |
---|---|---|
depth |
int
|
Number of layers in the transformer. |
embedding_dim |
int
|
Channel dimension for input embeddings. |
num_heads |
int
|
Number of heads for multihead attention. |
mlp_dim |
int
|
Internal channel dimension for the MLP block. |
layers |
ModuleList
|
List of SAM2TwoWayAttentionBlock layers comprising the transformer. |
final_attn_token_to_image |
Attention
|
Final attention layer from queries to image. |
norm_final_attn |
LayerNorm
|
Layer normalization applied to final queries. |
Methods:
Name | Description |
---|---|
forward |
Processes input image embeddings and query embeddings through the transformer. |
Examples:
>>> transformer = SAM2TwoWayTransformer(depth=5, embedding_dim=256, num_heads=8, mlp_dim=2048)
>>> image_embedding = torch.randn(1, 256, 64, 64)
>>> query_embedding = torch.randn(1, 100, 256)
>>> output = transformer(image_embedding, query_embedding)
>>> print(output[0].shape, output[1].shape)
torch.Size([1, 100, 256]) torch.Size([1, 256, 64, 64])
This transformer decoder attends to an input image using queries with supplied positional embeddings. It is designed for tasks like object detection, image segmentation, and point cloud processing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
depth
|
int
|
Number of layers in the transformer. |
required |
embedding_dim
|
int
|
Channel dimension for the input embeddings. |
required |
num_heads
|
int
|
Number of heads for multihead attention. Must divide embedding_dim. |
required |
mlp_dim
|
int
|
Channel dimension internal to the MLP block. |
required |
activation
|
Type[Module]
|
Activation function to use in the MLP block. |
ReLU
|
attention_downsample_rate
|
int
|
Downsampling rate for attention computations. |
2
|
Examples:
>>> transformer = SAM2TwoWayTransformer(depth=5, embedding_dim=256, num_heads=8, mlp_dim=2048)
>>> transformer
SAM2TwoWayTransformer(
(layers): ModuleList(
(0-4): 5 x SAM2TwoWayAttentionBlock(...)
)
(final_attn_token_to_image): Attention(...)
(norm_final_attn): LayerNorm(...)
)
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.RoPEAttention
Bases: Attention
Implements rotary position encoding for attention mechanisms in transformer architectures.
This class extends the base Attention class by incorporating Rotary Position Encoding (RoPE) to enhance the positional awareness of the attention mechanism.
Attributes:
Name | Type | Description |
---|---|---|
compute_cis |
Callable
|
Function to compute axial complex numbers for rotary encoding. |
freqs_cis |
Tensor
|
Precomputed frequency tensor for rotary encoding. |
rope_k_repeat |
bool
|
Flag to repeat query RoPE to match key length for cross-attention to memories. |
Methods:
Name | Description |
---|---|
forward |
Applies rotary position encoding and computes attention between query, key, and value tensors. |
Examples:
>>> rope_attn = RoPEAttention(embedding_dim=256, num_heads=8, rope_theta=10000.0, feat_sizes=(32, 32))
>>> q = torch.randn(1, 1024, 256)
>>> k = torch.randn(1, 1024, 256)
>>> v = torch.randn(1, 1024, 256)
>>> output = rope_attn(q, k, v)
>>> print(output.shape)
torch.Size([1, 1024, 256])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Applies rotary position encoding and computes attention between query, key, and value tensors.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.MultiScaleAttention
Bases: Module
Implements multi-scale self-attention with optional query pooling for efficient feature extraction.
This class provides a flexible implementation of multi-scale attention, allowing for optional downsampling of query features through pooling. It's designed to enhance the model's ability to capture multi-scale information in visual tasks.
Attributes:
Name | Type | Description |
---|---|---|
dim |
int
|
Input dimension of the feature map. |
dim_out |
int
|
Output dimension of the attention module. |
num_heads |
int
|
Number of attention heads. |
scale |
float
|
Scaling factor for dot-product attention. |
q_pool |
Module | None
|
Optional pooling module for query features. |
qkv |
Linear
|
Linear projection for query, key, and value. |
proj |
Linear
|
Output projection. |
Methods:
Name | Description |
---|---|
forward |
Applies multi-scale attention to the input tensor. |
Examples:
>>> import torch
>>> from torch import nn
>>> x = torch.randn(1, 64, 64, 256)
>>> msa = MultiScaleAttention(dim=256, dim_out=256, num_heads=8)
>>> output = msa(x)
>>> print(output.shape)
torch.Size([1, 64, 64, 256])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Applies multi-scale attention with optional query pooling to extract multi-scale features.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.MultiScaleBlock
MultiScaleBlock(
dim: int,
dim_out: int,
num_heads: int,
mlp_ratio: float = 4.0,
drop_path: float = 0.0,
norm_layer: Union[nn.Module, str] = "LayerNorm",
q_stride: Tuple[int, int] = None,
act_layer: nn.Module = nn.GELU,
window_size: int = 0,
)
Bases: Module
A multi-scale attention block with window partitioning and query pooling for efficient vision transformers.
This class implements a multi-scale attention mechanism with optional window partitioning and downsampling, designed for use in vision transformer architectures.
Attributes:
Name | Type | Description |
---|---|---|
dim |
int
|
Input dimension of the block. |
dim_out |
int
|
Output dimension of the block. |
norm1 |
Module
|
First normalization layer. |
window_size |
int
|
Size of the window for partitioning. |
pool |
Module | None
|
Pooling layer for query downsampling. |
q_stride |
Tuple[int, int] | None
|
Stride for query pooling. |
attn |
MultiScaleAttention
|
Multi-scale attention module. |
drop_path |
Module
|
Drop path layer for regularization. |
norm2 |
Module
|
Second normalization layer. |
mlp |
MLP
|
Multi-layer perceptron module. |
proj |
Linear | None
|
Projection layer for dimension mismatch. |
Methods:
Name | Description |
---|---|
forward |
Processes input tensor through the multi-scale block. |
Examples:
>>> block = MultiScaleBlock(dim=256, dim_out=512, num_heads=8, window_size=7)
>>> x = torch.randn(1, 56, 56, 256)
>>> output = block(x)
>>> print(output.shape)
torch.Size([1, 28, 28, 512])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Processes input through multi-scale attention and MLP, with optional windowing and downsampling.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.PositionEmbeddingSine
PositionEmbeddingSine(
num_pos_feats,
temperature: int = 10000,
normalize: bool = True,
scale: Optional[float] = None,
)
Bases: Module
A module for generating sinusoidal positional embeddings for 2D inputs like images.
This class implements sinusoidal position encoding for 2D spatial positions, which can be used in transformer-based models for computer vision tasks.
Attributes:
Name | Type | Description |
---|---|---|
num_pos_feats |
int
|
Number of positional features (half of the embedding dimension). |
temperature |
int
|
Temperature parameter for the sinusoidal functions. |
normalize |
bool
|
Whether to normalize the positional embeddings. |
scale |
float
|
Scaling factor for the embeddings when normalize is True. |
cache |
Dict
|
Cache for storing precomputed embeddings. |
Methods:
Name | Description |
---|---|
_encode_xy |
Encodes 2D positions using sine and cosine functions. |
encode_boxes |
Encodes box coordinates and dimensions into positional embeddings. |
encode_points |
Encodes 2D point coordinates with sinusoidal positional embeddings. |
forward |
Generates sinusoidal position embeddings for 2D inputs. |
Examples:
>>> pos_emb = PositionEmbeddingSine(num_pos_feats=128)
>>> x = torch.randn(1, 3, 224, 224)
>>> embeddings = pos_emb(x)
>>> print(embeddings.shape)
torch.Size([1, 256, 224, 224])
Source code in ultralytics/models/sam/modules/blocks.py
encode_boxes
Encodes box coordinates and dimensions into positional embeddings for detection.
Source code in ultralytics/models/sam/modules/blocks.py
encode_points
Encodes 2D points with sinusoidal embeddings and appends labels.
Source code in ultralytics/models/sam/modules/blocks.py
forward
Generates sinusoidal position embeddings for 2D inputs like images.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.PositionEmbeddingRandom
Bases: Module
Positional encoding using random spatial frequencies.
This class generates positional embeddings for input coordinates using random spatial frequencies. It is particularly useful for transformer-based models that require position information.
Attributes:
Name | Type | Description |
---|---|---|
positional_encoding_gaussian_matrix |
Tensor
|
A buffer containing random values for encoding. |
Methods:
Name | Description |
---|---|
_pe_encoding |
Positionally encodes points that are normalized to [0,1]. |
forward |
Generates positional encoding for a grid of the specified size. |
forward_with_coords |
Positionally encodes points that are not normalized to [0,1]. |
Examples:
>>> pe = PositionEmbeddingRandom(num_pos_feats=64)
>>> size = (32, 32)
>>> encoding = pe(size)
>>> print(encoding.shape)
torch.Size([128, 32, 32])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Generates positional encoding for a grid using random spatial frequencies.
Source code in ultralytics/models/sam/modules/blocks.py
forward_with_coords
Positionally encodes input coordinates, normalizing them to [0,1] based on the given image size.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.Block
Block(
dim: int,
num_heads: int,
mlp_ratio: float = 4.0,
qkv_bias: bool = True,
norm_layer: Type[nn.Module] = nn.LayerNorm,
act_layer: Type[nn.Module] = nn.GELU,
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
window_size: int = 0,
input_size: Optional[Tuple[int, int]] = None,
)
Bases: Module
Transformer block with support for window attention and residual propagation.
This class implements a transformer block that can use either global or windowed self-attention, followed by a feed-forward network. It supports relative positional embeddings and is designed for use in vision transformer architectures.
Attributes:
Name | Type | Description |
---|---|---|
norm1 |
Module
|
First normalization layer. |
attn |
REAttention
|
Self-attention layer with optional relative positional encoding. |
norm2 |
Module
|
Second normalization layer. |
mlp |
MLPBlock
|
Multi-layer perceptron block. |
window_size |
int
|
Size of attention window. If 0, global attention is used. |
Methods:
Name | Description |
---|---|
forward |
Processes input through the transformer block. |
Examples:
>>> import torch
>>> block = Block(dim=256, num_heads=8, window_size=7)
>>> x = torch.randn(1, 56, 56, 256)
>>> output = block(x)
>>> print(output.shape)
torch.Size([1, 56, 56, 256])
This constructor sets up a transformer block that can use either global or windowed self-attention, followed by a feed-forward network. It supports relative positional embeddings and is designed for use in vision transformer architectures.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dim
|
int
|
Number of input channels. |
required |
num_heads
|
int
|
Number of attention heads in the self-attention layer. |
required |
mlp_ratio
|
float
|
Ratio of mlp hidden dimension to embedding dimension. |
4.0
|
qkv_bias
|
bool
|
If True, adds a learnable bias to query, key, value projections. |
True
|
norm_layer
|
Type[Module]
|
Type of normalization layer to use. |
LayerNorm
|
act_layer
|
Type[Module]
|
Type of activation function to use in the MLP block. |
GELU
|
use_rel_pos
|
bool
|
If True, uses relative positional embeddings in attention. |
False
|
rel_pos_zero_init
|
bool
|
If True, initializes relative positional parameters to zero. |
True
|
window_size
|
int
|
Size of attention window. If 0, uses global attention. |
0
|
input_size
|
Optional[Tuple[int, int]]
|
Input resolution for calculating relative positional parameter size. |
None
|
Examples:
>>> block = Block(dim=256, num_heads=8, window_size=7)
>>> x = torch.randn(1, 56, 56, 256)
>>> output = block(x)
>>> print(output.shape)
torch.Size([1, 56, 56, 256])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Processes input through transformer block with optional windowed self-attention and residual connection.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.REAttention
REAttention(
dim: int,
num_heads: int = 8,
qkv_bias: bool = True,
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
input_size: Optional[Tuple[int, int]] = None,
)
Bases: Module
Rotary Embedding Attention module for efficient self-attention in transformer architectures.
This class implements a multi-head attention mechanism with rotary positional embeddings, designed for use in vision transformer models. It supports optional query pooling and window partitioning for efficient processing of large inputs.
Attributes:
Name | Type | Description |
---|---|---|
compute_cis |
Callable
|
Function to compute axial complex numbers for rotary encoding. |
freqs_cis |
Tensor
|
Precomputed frequency tensor for rotary encoding. |
rope_k_repeat |
bool
|
Flag to repeat query RoPE to match key length for cross-attention to memories. |
q_proj |
Linear
|
Linear projection for query. |
k_proj |
Linear
|
Linear projection for key. |
v_proj |
Linear
|
Linear projection for value. |
out_proj |
Linear
|
Output projection. |
num_heads |
int
|
Number of attention heads. |
internal_dim |
int
|
Internal dimension for attention computation. |
Methods:
Name | Description |
---|---|
forward |
Applies rotary position encoding and computes attention between query, key, and value tensors. |
Examples:
>>> rope_attn = REAttention(embedding_dim=256, num_heads=8, rope_theta=10000.0, feat_sizes=(32, 32))
>>> q = torch.randn(1, 1024, 256)
>>> k = torch.randn(1, 1024, 256)
>>> v = torch.randn(1, 1024, 256)
>>> output = rope_attn(q, k, v)
>>> print(output.shape)
torch.Size([1, 1024, 256])
This module implements multi-head attention with optional relative positional encodings, designed specifically for vision tasks in transformer models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dim
|
int
|
Number of input channels. |
required |
num_heads
|
int
|
Number of attention heads. Default is 8. |
8
|
qkv_bias
|
bool
|
If True, adds a learnable bias to query, key, value projections. Default is True. |
True
|
use_rel_pos
|
bool
|
If True, uses relative positional encodings. Default is False. |
False
|
rel_pos_zero_init
|
bool
|
If True, initializes relative positional parameters to zero. Default is True. |
True
|
input_size
|
Tuple[int, int] | None
|
Input resolution for calculating relative positional parameter size. Required if use_rel_pos is True. Default is None. |
None
|
Examples:
>>> attention = REAttention(dim=256, num_heads=8, input_size=(32, 32))
>>> x = torch.randn(1, 32, 32, 256)
>>> output = attention(x)
>>> print(output.shape)
torch.Size([1, 32, 32, 256])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Applies multi-head attention with optional relative positional encoding to input tensor.
Source code in ultralytics/models/sam/modules/blocks.py
ultralytics.models.sam.modules.blocks.PatchEmbed
PatchEmbed(
kernel_size: Tuple[int, int] = (16, 16),
stride: Tuple[int, int] = (16, 16),
padding: Tuple[int, int] = (0, 0),
in_chans: int = 3,
embed_dim: int = 768,
)
Bases: Module
Image to Patch Embedding module for vision transformer architectures.
This module converts an input image into a sequence of patch embeddings using a convolutional layer. It is commonly used as the first layer in vision transformer architectures to transform image data into a suitable format for subsequent transformer blocks.
Attributes:
Name | Type | Description |
---|---|---|
proj |
Conv2d
|
Convolutional layer for projecting image patches to embeddings. |
Methods:
Name | Description |
---|---|
forward |
Applies patch embedding to the input tensor. |
Examples:
>>> patch_embed = PatchEmbed(kernel_size=(16, 16), stride=(16, 16), in_chans=3, embed_dim=768)
>>> x = torch.randn(1, 3, 224, 224)
>>> output = patch_embed(x)
>>> print(output.shape)
torch.Size([1, 768, 14, 14])
This module is typically used as the first layer in vision transformer architectures to transform image data into a suitable format for subsequent transformer blocks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kernel_size
|
Tuple[int, int]
|
Size of the convolutional kernel for patch extraction. |
(16, 16)
|
stride
|
Tuple[int, int]
|
Stride of the convolutional operation. |
(16, 16)
|
padding
|
Tuple[int, int]
|
Padding applied to the input before convolution. |
(0, 0)
|
in_chans
|
int
|
Number of input image channels. |
3
|
embed_dim
|
int
|
Dimensionality of the output patch embeddings. |
768
|
Examples:
>>> patch_embed = PatchEmbed(kernel_size=(16, 16), stride=(16, 16), in_chans=3, embed_dim=768)
>>> x = torch.randn(1, 3, 224, 224)
>>> output = patch_embed(x)
>>> print(output.shape)
torch.Size([1, 768, 14, 14])
Source code in ultralytics/models/sam/modules/blocks.py
forward
Computes patch embedding by applying convolution and transposing resulting tensor.
ultralytics.models.sam.modules.blocks.do_pool
Applies pooling and optional normalization to a tensor, handling spatial dimension permutations.