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
DropPath(drop_prob=0.0, scale_by_keep=True)
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
36 37 38 39 40 |
|
forward
forward(x)
Applies stochastic depth to input tensor during training, with optional scaling.
Source code in ultralytics/models/sam/modules/blocks.py
42 43 44 45 46 47 48 49 50 51 |
|
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
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
|
forward
forward(x)
Downsamples and encodes input mask to embed_dim channels using convolutional layers and LayerNorm2d.
Source code in ultralytics/models/sam/modules/blocks.py
109 110 111 |
|
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
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
|
forward
forward(x)
Applies ConvNeXt block operations to input tensor, including convolutions and residual connection.
Source code in ultralytics/models/sam/modules/blocks.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
ultralytics.models.sam.modules.blocks.Fuser
Fuser(layer, num_layers, dim=None, input_projection=False)
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
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
forward
forward(x)
Applies a series of layers to the input tensor, optionally projecting it first.
Source code in ultralytics/models/sam/modules/blocks.py
256 257 258 259 260 261 |
|
ultralytics.models.sam.modules.blocks.SAM2TwoWayAttentionBlock
SAM2TwoWayAttentionBlock(
embedding_dim: int,
num_heads: int,
mlp_dim: int = 2048,
activation: Type[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
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
|
ultralytics.models.sam.modules.blocks.SAM2TwoWayTransformer
SAM2TwoWayTransformer(
depth: int,
embedding_dim: int,
num_heads: int,
mlp_dim: int,
activation: Type[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
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
|
ultralytics.models.sam.modules.blocks.RoPEAttention
RoPEAttention(
*args,
rope_theta=10000.0,
rope_k_repeat=False,
feat_sizes=(32, 32),
**kwargs
)
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
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 |
|
forward
forward(q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0) -> Tensor
Applies rotary position encoding and computes attention between query, key, and value tensors.
Source code in ultralytics/models/sam/modules/blocks.py
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
|
ultralytics.models.sam.modules.blocks.MultiScaleAttention
MultiScaleAttention(
dim: int, dim_out: int, num_heads: int, q_pool: Module = None
)
Bases: Module
Implements multiscale self-attention with optional query pooling for efficient feature extraction.
This class provides a flexible implementation of multiscale attention, allowing for optional downsampling of query features through pooling. It's designed to enhance the model's ability to capture multiscale 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 multiscale 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
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
|
forward
forward(x: Tensor) -> torch.Tensor
Applies multiscale attention with optional query pooling to extract multiscale features.
Source code in ultralytics/models/sam/modules/blocks.py
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 |
|
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[Module, str] = "LayerNorm",
q_stride: Tuple[int, int] = None,
act_layer: Module = nn.GELU,
window_size: int = 0,
)
Bases: Module
A multiscale attention block with window partitioning and query pooling for efficient vision transformers.
This class implements a multiscale 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 multiscale 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
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 |
|
forward
forward(x: Tensor) -> torch.Tensor
Processes input through multiscale attention and MLP, with optional windowing and downsampling.
Source code in ultralytics/models/sam/modules/blocks.py
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 |
|
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
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
|
encode_boxes
encode_boxes(x, y, w, h)
Encodes box coordinates and dimensions into positional embeddings for detection.
Source code in ultralytics/models/sam/modules/blocks.py
762 763 764 765 766 |
|
encode_points
encode_points(x, y, labels)
Encodes 2D points with sinusoidal embeddings and appends labels.
Source code in ultralytics/models/sam/modules/blocks.py
770 771 772 773 774 775 776 777 |
|
forward
forward(x: Tensor)
Generates sinusoidal position embeddings for 2D inputs like images.
Source code in ultralytics/models/sam/modules/blocks.py
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 |
|
ultralytics.models.sam.modules.blocks.PositionEmbeddingRandom
PositionEmbeddingRandom(num_pos_feats: int = 64, scale: Optional[float] = None)
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
836 837 838 839 840 841 842 843 844 845 |
|
forward
forward(size: Tuple[int, int]) -> torch.Tensor
Generates positional encoding for a grid using random spatial frequencies.
Source code in ultralytics/models/sam/modules/blocks.py
856 857 858 859 860 861 862 863 864 865 866 867 |
|
forward_with_coords
forward_with_coords(
coords_input: Tensor, image_size: Tuple[int, int]
) -> torch.Tensor
Positionally encodes input coordinates, normalizing them to [0,1] based on the given image size.
Source code in ultralytics/models/sam/modules/blocks.py
869 870 871 872 873 874 |
|
ultralytics.models.sam.modules.blocks.Block
Block(
dim: int,
num_heads: int,
mlp_ratio: float = 4.0,
qkv_bias: bool = True,
norm_layer: Type[Module] = nn.LayerNorm,
act_layer: Type[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
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 |
|
forward
forward(x: Tensor) -> torch.Tensor
Processes input through transformer block with optional windowed self-attention and residual connection.
Source code in ultralytics/models/sam/modules/blocks.py
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 |
|
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
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 |
|
forward
forward(x: Tensor) -> torch.Tensor
Applies multi-head attention with optional relative positional encoding to input tensor.
Source code in ultralytics/models/sam/modules/blocks.py
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 |
|
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
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 |
|
forward
forward(x: Tensor) -> torch.Tensor
Computes patch embedding by applying convolution and transposing resulting tensor.
Source code in ultralytics/models/sam/modules/blocks.py
1127 1128 1129 |
|
ultralytics.models.sam.modules.blocks.do_pool
do_pool(x: Tensor, pool: Module, norm: Module = None) -> torch.Tensor
Applies pooling and optional normalization to a tensor, handling spatial dimension permutations.
Source code in ultralytics/models/sam/modules/blocks.py
488 489 490 491 492 493 494 495 496 497 498 499 500 |
|