Reference for ultralytics/nn/modules/transformer.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/nn/modules/transformer.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.nn.modules.transformer.TransformerEncoderLayer
TransformerEncoderLayer(
c1, cm=2048, num_heads=8, dropout=0.0, act=nn.GELU(), normalize_before=False
)
Bases: Module
Defines a single layer of the transformer encoder.
Attributes:
Name | Type | Description |
---|---|---|
ma |
MultiheadAttention
|
Multi-head attention module. |
fc1 |
Linear
|
First linear layer in the feedforward network. |
fc2 |
Linear
|
Second linear layer in the feedforward network. |
norm1 |
LayerNorm
|
Layer normalization after attention. |
norm2 |
LayerNorm
|
Layer normalization after feedforward network. |
dropout |
Dropout
|
Dropout layer for the feedforward network. |
dropout1 |
Dropout
|
Dropout layer after attention. |
dropout2 |
Dropout
|
Dropout layer after feedforward network. |
act |
Module
|
Activation function. |
normalize_before |
bool
|
Whether to apply normalization before attention and feedforward. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
c1
|
int
|
Input dimension. |
required |
cm
|
int
|
Hidden dimension in the feedforward network. |
2048
|
num_heads
|
int
|
Number of attention heads. |
8
|
dropout
|
float
|
Dropout probability. |
0.0
|
act
|
Module
|
Activation function. |
GELU()
|
normalize_before
|
bool
|
Whether to apply normalization before attention and feedforward. |
False
|
Source code in ultralytics/nn/modules/transformer.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
|
forward
forward(src, src_mask=None, src_key_padding_mask=None, pos=None)
Forward propagates the input through the encoder module.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
Tensor
|
Input tensor. |
required |
src_mask
|
Tensor
|
Mask for the src sequence. |
None
|
src_key_padding_mask
|
Tensor
|
Mask for the src keys per batch. |
None
|
pos
|
Tensor
|
Positional encoding. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after transformer encoder layer. |
Source code in ultralytics/nn/modules/transformer.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
|
forward_post
forward_post(src, src_mask=None, src_key_padding_mask=None, pos=None)
Perform forward pass with post-normalization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
Tensor
|
Input tensor. |
required |
src_mask
|
Tensor
|
Mask for the src sequence. |
None
|
src_key_padding_mask
|
Tensor
|
Mask for the src keys per batch. |
None
|
pos
|
Tensor
|
Positional encoding. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after attention and feedforward. |
Source code in ultralytics/nn/modules/transformer.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
|
forward_pre
forward_pre(src, src_mask=None, src_key_padding_mask=None, pos=None)
Perform forward pass with pre-normalization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
Tensor
|
Input tensor. |
required |
src_mask
|
Tensor
|
Mask for the src sequence. |
None
|
src_key_padding_mask
|
Tensor
|
Mask for the src keys per batch. |
None
|
pos
|
Tensor
|
Positional encoding. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after attention and feedforward. |
Source code in ultralytics/nn/modules/transformer.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
|
with_pos_embed
staticmethod
with_pos_embed(tensor, pos=None)
Add position embeddings to the tensor if provided.
Source code in ultralytics/nn/modules/transformer.py
78 79 80 81 |
|
ultralytics.nn.modules.transformer.AIFI
AIFI(
c1, cm=2048, num_heads=8, dropout=0, act=nn.GELU(), normalize_before=False
)
Bases: TransformerEncoderLayer
Defines the AIFI transformer layer.
This class extends TransformerEncoderLayer to work with 2D data by adding positional embeddings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
c1
|
int
|
Input dimension. |
required |
cm
|
int
|
Hidden dimension in the feedforward network. |
2048
|
num_heads
|
int
|
Number of attention heads. |
8
|
dropout
|
float
|
Dropout probability. |
0
|
act
|
Module
|
Activation function. |
GELU()
|
normalize_before
|
bool
|
Whether to apply normalization before attention and feedforward. |
False
|
Source code in ultralytics/nn/modules/transformer.py
150 151 152 153 154 155 156 157 158 159 160 161 162 |
|
build_2d_sincos_position_embedding
staticmethod
build_2d_sincos_position_embedding(w, h, embed_dim=256, temperature=10000.0)
Build 2D sine-cosine position embedding.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
w
|
int
|
Width of the feature map. |
required |
h
|
int
|
Height of the feature map. |
required |
embed_dim
|
int
|
Embedding dimension. |
256
|
temperature
|
float
|
Temperature for the sine/cosine functions. |
10000.0
|
Returns:
Type | Description |
---|---|
Tensor
|
Position embedding with shape [1, embed_dim, h*w]. |
Source code in ultralytics/nn/modules/transformer.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
forward
forward(x)
Forward pass for the AIFI transformer layer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor with shape [B, C, H, W]. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor with shape [B, C, H, W]. |
Source code in ultralytics/nn/modules/transformer.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
|
ultralytics.nn.modules.transformer.TransformerLayer
TransformerLayer(c, num_heads)
Bases: Module
Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
c
|
int
|
Input and output channel dimension. |
required |
num_heads
|
int
|
Number of attention heads. |
required |
Source code in ultralytics/nn/modules/transformer.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
|
forward
forward(x)
Apply a transformer block to the input x and return the output.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after transformer layer. |
Source code in ultralytics/nn/modules/transformer.py
227 228 229 230 231 232 233 234 235 236 237 238 |
|
ultralytics.nn.modules.transformer.TransformerBlock
TransformerBlock(c1, c2, num_heads, num_layers)
Bases: Module
Vision Transformer https://arxiv.org/abs/2010.11929.
Attributes:
Name | Type | Description |
---|---|---|
conv |
Conv
|
Convolution layer if input and output channels differ. |
linear |
Linear
|
Learnable position embedding. |
tr |
Sequential
|
Sequential container of transformer layers. |
c2 |
int
|
Output channel dimension. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
c1
|
int
|
Input channel dimension. |
required |
c2
|
int
|
Output channel dimension. |
required |
num_heads
|
int
|
Number of attention heads. |
required |
num_layers
|
int
|
Number of transformer layers. |
required |
Source code in ultralytics/nn/modules/transformer.py
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
|
forward
forward(x)
Forward propagates the input through the bottleneck module.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor with shape [b, c1, w, h]. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor with shape [b, c2, w, h]. |
Source code in ultralytics/nn/modules/transformer.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
|
ultralytics.nn.modules.transformer.MLPBlock
MLPBlock(embedding_dim, mlp_dim, act=nn.GELU)
Bases: Module
Implements a single block of a multi-layer perceptron.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
embedding_dim
|
int
|
Input and output dimension. |
required |
mlp_dim
|
int
|
Hidden dimension. |
required |
act
|
Module
|
Activation function. |
GELU
|
Source code in ultralytics/nn/modules/transformer.py
290 291 292 293 294 295 296 297 298 299 300 301 302 |
|
forward
forward(x: Tensor) -> torch.Tensor
Forward pass for the MLPBlock.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after MLP block. |
Source code in ultralytics/nn/modules/transformer.py
304 305 306 307 308 309 310 311 312 313 314 |
|
ultralytics.nn.modules.transformer.MLP
MLP(input_dim, hidden_dim, output_dim, num_layers, act=nn.ReLU, sigmoid=False)
Bases: Module
Implements a simple multi-layer perceptron (also called FFN).
Attributes:
Name | Type | Description |
---|---|---|
num_layers |
int
|
Number of layers in the MLP. |
layers |
ModuleList
|
List of linear layers. |
sigmoid |
bool
|
Whether to apply sigmoid to the output. |
act |
Module
|
Activation function. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_dim
|
int
|
Input dimension. |
required |
hidden_dim
|
int
|
Hidden dimension. |
required |
output_dim
|
int
|
Output dimension. |
required |
num_layers
|
int
|
Number of layers. |
required |
act
|
Module
|
Activation function. |
ReLU
|
sigmoid
|
bool
|
Whether to apply sigmoid to the output. |
False
|
Source code in ultralytics/nn/modules/transformer.py
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
|
forward
forward(x)
Forward pass for the entire MLP.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after MLP. |
Source code in ultralytics/nn/modules/transformer.py
347 348 349 350 351 352 353 354 355 356 357 358 359 |
|
ultralytics.nn.modules.transformer.LayerNorm2d
LayerNorm2d(num_channels, eps=1e-06)
Bases: Module
2D Layer Normalization module inspired by Detectron2 and ConvNeXt implementations.
Original implementations in https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py and https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py.
Attributes:
Name | Type | Description |
---|---|---|
weight |
Parameter
|
Learnable scale parameter. |
bias |
Parameter
|
Learnable bias parameter. |
eps |
float
|
Small constant for numerical stability. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_channels
|
int
|
Number of channels in the input. |
required |
eps
|
float
|
Small constant for numerical stability. |
1e-06
|
Source code in ultralytics/nn/modules/transformer.py
377 378 379 380 381 382 383 384 385 386 387 388 |
|
forward
forward(x)
Perform forward pass for 2D layer normalization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Normalized output tensor. |
Source code in ultralytics/nn/modules/transformer.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
|
ultralytics.nn.modules.transformer.MSDeformAttn
MSDeformAttn(d_model=256, n_levels=4, n_heads=8, n_points=4)
Bases: Module
Multiscale Deformable Attention Module based on Deformable-DETR and PaddleDetection implementations.
https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py
Attributes:
Name | Type | Description |
---|---|---|
im2col_step |
int
|
Step size for im2col operations. |
d_model |
int
|
Model dimension. |
n_levels |
int
|
Number of feature levels. |
n_heads |
int
|
Number of attention heads. |
n_points |
int
|
Number of sampling points per attention head per feature level. |
sampling_offsets |
Linear
|
Linear layer for generating sampling offsets. |
attention_weights |
Linear
|
Linear layer for generating attention weights. |
value_proj |
Linear
|
Linear layer for projecting values. |
output_proj |
Linear
|
Linear layer for projecting output. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
d_model
|
int
|
Model dimension. |
256
|
n_levels
|
int
|
Number of feature levels. |
4
|
n_heads
|
int
|
Number of attention heads. |
8
|
n_points
|
int
|
Number of sampling points per attention head per feature level. |
4
|
Source code in ultralytics/nn/modules/transformer.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
|
forward
forward(query, refer_bbox, value, value_shapes, value_mask=None)
Perform forward pass for multiscale deformable attention.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query
|
Tensor
|
Tensor with shape [bs, query_length, C]. |
required |
refer_bbox
|
Tensor
|
Tensor with shape [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0), bottom-right (1, 1), including padding area. |
required |
value
|
Tensor
|
Tensor with shape [bs, value_length, C]. |
required |
value_shapes
|
list
|
List with shape [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]. |
required |
value_mask
|
Tensor
|
Tensor with shape [bs, value_length], True for non-padding elements, False for padding elements. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor with shape [bs, Length_{query}, C]. |
Source code in ultralytics/nn/modules/transformer.py
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
|
ultralytics.nn.modules.transformer.DeformableTransformerDecoderLayer
DeformableTransformerDecoderLayer(
d_model=256,
n_heads=8,
d_ffn=1024,
dropout=0.0,
act=nn.ReLU(),
n_levels=4,
n_points=4,
)
Bases: Module
Deformable Transformer Decoder Layer inspired by PaddleDetection and Deformable-DETR implementations.
https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py
Attributes:
Name | Type | Description |
---|---|---|
self_attn |
MultiheadAttention
|
Self-attention module. |
dropout1 |
Dropout
|
Dropout after self-attention. |
norm1 |
LayerNorm
|
Layer normalization after self-attention. |
cross_attn |
MSDeformAttn
|
Cross-attention module. |
dropout2 |
Dropout
|
Dropout after cross-attention. |
norm2 |
LayerNorm
|
Layer normalization after cross-attention. |
linear1 |
Linear
|
First linear layer in the feedforward network. |
act |
Module
|
Activation function. |
dropout3 |
Dropout
|
Dropout in the feedforward network. |
linear2 |
Linear
|
Second linear layer in the feedforward network. |
dropout4 |
Dropout
|
Dropout after the feedforward network. |
norm3 |
LayerNorm
|
Layer normalization after the feedforward network. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
d_model
|
int
|
Model dimension. |
256
|
n_heads
|
int
|
Number of attention heads. |
8
|
d_ffn
|
int
|
Dimension of the feedforward network. |
1024
|
dropout
|
float
|
Dropout probability. |
0.0
|
act
|
Module
|
Activation function. |
ReLU()
|
n_levels
|
int
|
Number of feature levels. |
4
|
n_points
|
int
|
Number of sampling points. |
4
|
Source code in ultralytics/nn/modules/transformer.py
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 |
|
forward
forward(
embed,
refer_bbox,
feats,
shapes,
padding_mask=None,
attn_mask=None,
query_pos=None,
)
Perform the forward pass through the entire decoder layer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
embed
|
Tensor
|
Input embeddings. |
required |
refer_bbox
|
Tensor
|
Reference bounding boxes. |
required |
feats
|
Tensor
|
Feature maps. |
required |
shapes
|
list
|
Feature shapes. |
required |
padding_mask
|
Tensor
|
Padding mask. |
None
|
attn_mask
|
Tensor
|
Attention mask. |
None
|
query_pos
|
Tensor
|
Query position embeddings. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after decoder layer. |
Source code in ultralytics/nn/modules/transformer.py
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 |
|
forward_ffn
forward_ffn(tgt)
Perform forward pass through the Feed-Forward Network part of the layer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tgt
|
Tensor
|
Input tensor. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor after FFN. |
Source code in ultralytics/nn/modules/transformer.py
580 581 582 583 584 585 586 587 588 589 590 591 592 |
|
with_pos_embed
staticmethod
with_pos_embed(tensor, pos)
Add positional embeddings to the input tensor, if provided.
Source code in ultralytics/nn/modules/transformer.py
575 576 577 578 |
|
ultralytics.nn.modules.transformer.DeformableTransformerDecoder
DeformableTransformerDecoder(
hidden_dim, decoder_layer, num_layers, eval_idx=-1
)
Bases: Module
Implementation of Deformable Transformer Decoder based on PaddleDetection.
Attributes:
Name | Type | Description |
---|---|---|
layers |
ModuleList
|
List of decoder layers. |
num_layers |
int
|
Number of decoder layers. |
hidden_dim |
int
|
Hidden dimension. |
eval_idx |
int
|
Index of the layer to use during evaluation. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hidden_dim
|
int
|
Hidden dimension. |
required |
decoder_layer
|
Module
|
Decoder layer module. |
required |
num_layers
|
int
|
Number of decoder layers. |
required |
eval_idx
|
int
|
Index of the layer to use during evaluation. |
-1
|
Source code in ultralytics/nn/modules/transformer.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 |
|
forward
forward(
embed,
refer_bbox,
feats,
shapes,
bbox_head,
score_head,
pos_mlp,
attn_mask=None,
padding_mask=None,
)
Perform the forward pass through the entire decoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
embed
|
Tensor
|
Decoder embeddings. |
required |
refer_bbox
|
Tensor
|
Reference bounding boxes. |
required |
feats
|
Tensor
|
Image features. |
required |
shapes
|
list
|
Feature shapes. |
required |
bbox_head
|
Module
|
Bounding box prediction head. |
required |
score_head
|
Module
|
Score prediction head. |
required |
pos_mlp
|
Module
|
Position MLP. |
required |
attn_mask
|
Tensor
|
Attention mask. |
None
|
padding_mask
|
Tensor
|
Padding mask. |
None
|
Returns:
Name | Type | Description |
---|---|---|
dec_bboxes |
Tensor
|
Decoded bounding boxes. |
dec_cls |
Tensor
|
Decoded classification scores. |
Source code in ultralytics/nn/modules/transformer.py
658 659 660 661 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 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 |
|