dgenerate-ultralytics-headless 8.3.134__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
- tests/__init__.py +22 -0
- tests/conftest.py +83 -0
- tests/test_cli.py +138 -0
- tests/test_cuda.py +215 -0
- tests/test_engine.py +131 -0
- tests/test_exports.py +236 -0
- tests/test_integrations.py +154 -0
- tests/test_python.py +694 -0
- tests/test_solutions.py +187 -0
- ultralytics/__init__.py +30 -0
- ultralytics/assets/bus.jpg +0 -0
- ultralytics/assets/zidane.jpg +0 -0
- ultralytics/cfg/__init__.py +1023 -0
- ultralytics/cfg/datasets/Argoverse.yaml +77 -0
- ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
- ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
- ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
- ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
- ultralytics/cfg/datasets/Objects365.yaml +443 -0
- ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
- ultralytics/cfg/datasets/VOC.yaml +106 -0
- ultralytics/cfg/datasets/VisDrone.yaml +77 -0
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
- ultralytics/cfg/datasets/coco-pose.yaml +42 -0
- ultralytics/cfg/datasets/coco.yaml +118 -0
- ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco128.yaml +101 -0
- ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
- ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
- ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco8.yaml +101 -0
- ultralytics/cfg/datasets/crack-seg.yaml +22 -0
- ultralytics/cfg/datasets/dog-pose.yaml +24 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
- ultralytics/cfg/datasets/dota8.yaml +35 -0
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
- ultralytics/cfg/datasets/lvis.yaml +1240 -0
- ultralytics/cfg/datasets/medical-pills.yaml +22 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
- ultralytics/cfg/datasets/package-seg.yaml +22 -0
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
- ultralytics/cfg/datasets/xView.yaml +155 -0
- ultralytics/cfg/default.yaml +127 -0
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
- ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
- ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
- ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
- ultralytics/cfg/models/12/yolo12.yaml +48 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
- ultralytics/cfg/models/v3/yolov3.yaml +49 -0
- ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
- ultralytics/cfg/models/v5/yolov5.yaml +51 -0
- ultralytics/cfg/models/v6/yolov6.yaml +56 -0
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
- ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8.yaml +49 -0
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/trackers/botsort.yaml +22 -0
- ultralytics/cfg/trackers/bytetrack.yaml +14 -0
- ultralytics/data/__init__.py +26 -0
- ultralytics/data/annotator.py +66 -0
- ultralytics/data/augment.py +2945 -0
- ultralytics/data/base.py +438 -0
- ultralytics/data/build.py +258 -0
- ultralytics/data/converter.py +754 -0
- ultralytics/data/dataset.py +834 -0
- ultralytics/data/loaders.py +676 -0
- ultralytics/data/scripts/download_weights.sh +18 -0
- ultralytics/data/scripts/get_coco.sh +61 -0
- ultralytics/data/scripts/get_coco128.sh +18 -0
- ultralytics/data/scripts/get_imagenet.sh +52 -0
- ultralytics/data/split.py +125 -0
- ultralytics/data/split_dota.py +325 -0
- ultralytics/data/utils.py +777 -0
- ultralytics/engine/__init__.py +1 -0
- ultralytics/engine/exporter.py +1519 -0
- ultralytics/engine/model.py +1156 -0
- ultralytics/engine/predictor.py +502 -0
- ultralytics/engine/results.py +1840 -0
- ultralytics/engine/trainer.py +853 -0
- ultralytics/engine/tuner.py +243 -0
- ultralytics/engine/validator.py +377 -0
- ultralytics/hub/__init__.py +168 -0
- ultralytics/hub/auth.py +137 -0
- ultralytics/hub/google/__init__.py +176 -0
- ultralytics/hub/session.py +446 -0
- ultralytics/hub/utils.py +248 -0
- ultralytics/models/__init__.py +9 -0
- ultralytics/models/fastsam/__init__.py +7 -0
- ultralytics/models/fastsam/model.py +61 -0
- ultralytics/models/fastsam/predict.py +181 -0
- ultralytics/models/fastsam/utils.py +24 -0
- ultralytics/models/fastsam/val.py +40 -0
- ultralytics/models/nas/__init__.py +7 -0
- ultralytics/models/nas/model.py +102 -0
- ultralytics/models/nas/predict.py +58 -0
- ultralytics/models/nas/val.py +39 -0
- ultralytics/models/rtdetr/__init__.py +7 -0
- ultralytics/models/rtdetr/model.py +63 -0
- ultralytics/models/rtdetr/predict.py +84 -0
- ultralytics/models/rtdetr/train.py +85 -0
- ultralytics/models/rtdetr/val.py +191 -0
- ultralytics/models/sam/__init__.py +6 -0
- ultralytics/models/sam/amg.py +260 -0
- ultralytics/models/sam/build.py +358 -0
- ultralytics/models/sam/model.py +170 -0
- ultralytics/models/sam/modules/__init__.py +1 -0
- ultralytics/models/sam/modules/blocks.py +1129 -0
- ultralytics/models/sam/modules/decoders.py +515 -0
- ultralytics/models/sam/modules/encoders.py +854 -0
- ultralytics/models/sam/modules/memory_attention.py +299 -0
- ultralytics/models/sam/modules/sam.py +1006 -0
- ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
- ultralytics/models/sam/modules/transformer.py +351 -0
- ultralytics/models/sam/modules/utils.py +394 -0
- ultralytics/models/sam/predict.py +1605 -0
- ultralytics/models/utils/__init__.py +1 -0
- ultralytics/models/utils/loss.py +455 -0
- ultralytics/models/utils/ops.py +268 -0
- ultralytics/models/yolo/__init__.py +7 -0
- ultralytics/models/yolo/classify/__init__.py +7 -0
- ultralytics/models/yolo/classify/predict.py +88 -0
- ultralytics/models/yolo/classify/train.py +233 -0
- ultralytics/models/yolo/classify/val.py +215 -0
- ultralytics/models/yolo/detect/__init__.py +7 -0
- ultralytics/models/yolo/detect/predict.py +124 -0
- ultralytics/models/yolo/detect/train.py +217 -0
- ultralytics/models/yolo/detect/val.py +451 -0
- ultralytics/models/yolo/model.py +354 -0
- ultralytics/models/yolo/obb/__init__.py +7 -0
- ultralytics/models/yolo/obb/predict.py +66 -0
- ultralytics/models/yolo/obb/train.py +81 -0
- ultralytics/models/yolo/obb/val.py +283 -0
- ultralytics/models/yolo/pose/__init__.py +7 -0
- ultralytics/models/yolo/pose/predict.py +79 -0
- ultralytics/models/yolo/pose/train.py +154 -0
- ultralytics/models/yolo/pose/val.py +394 -0
- ultralytics/models/yolo/segment/__init__.py +7 -0
- ultralytics/models/yolo/segment/predict.py +113 -0
- ultralytics/models/yolo/segment/train.py +123 -0
- ultralytics/models/yolo/segment/val.py +428 -0
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +119 -0
- ultralytics/models/yolo/world/train_world.py +176 -0
- ultralytics/models/yolo/yoloe/__init__.py +22 -0
- ultralytics/models/yolo/yoloe/predict.py +169 -0
- ultralytics/models/yolo/yoloe/train.py +298 -0
- ultralytics/models/yolo/yoloe/train_seg.py +124 -0
- ultralytics/models/yolo/yoloe/val.py +191 -0
- ultralytics/nn/__init__.py +29 -0
- ultralytics/nn/autobackend.py +842 -0
- ultralytics/nn/modules/__init__.py +182 -0
- ultralytics/nn/modules/activation.py +53 -0
- ultralytics/nn/modules/block.py +1966 -0
- ultralytics/nn/modules/conv.py +712 -0
- ultralytics/nn/modules/head.py +880 -0
- ultralytics/nn/modules/transformer.py +713 -0
- ultralytics/nn/modules/utils.py +164 -0
- ultralytics/nn/tasks.py +1627 -0
- ultralytics/nn/text_model.py +351 -0
- ultralytics/solutions/__init__.py +41 -0
- ultralytics/solutions/ai_gym.py +116 -0
- ultralytics/solutions/analytics.py +252 -0
- ultralytics/solutions/config.py +106 -0
- ultralytics/solutions/distance_calculation.py +124 -0
- ultralytics/solutions/heatmap.py +127 -0
- ultralytics/solutions/instance_segmentation.py +84 -0
- ultralytics/solutions/object_blurrer.py +90 -0
- ultralytics/solutions/object_counter.py +195 -0
- ultralytics/solutions/object_cropper.py +84 -0
- ultralytics/solutions/parking_management.py +273 -0
- ultralytics/solutions/queue_management.py +93 -0
- ultralytics/solutions/region_counter.py +120 -0
- ultralytics/solutions/security_alarm.py +154 -0
- ultralytics/solutions/similarity_search.py +172 -0
- ultralytics/solutions/solutions.py +724 -0
- ultralytics/solutions/speed_estimation.py +110 -0
- ultralytics/solutions/streamlit_inference.py +196 -0
- ultralytics/solutions/templates/similarity-search.html +160 -0
- ultralytics/solutions/trackzone.py +88 -0
- ultralytics/solutions/vision_eye.py +68 -0
- ultralytics/trackers/__init__.py +7 -0
- ultralytics/trackers/basetrack.py +124 -0
- ultralytics/trackers/bot_sort.py +260 -0
- ultralytics/trackers/byte_tracker.py +480 -0
- ultralytics/trackers/track.py +125 -0
- ultralytics/trackers/utils/__init__.py +1 -0
- ultralytics/trackers/utils/gmc.py +376 -0
- ultralytics/trackers/utils/kalman_filter.py +493 -0
- ultralytics/trackers/utils/matching.py +157 -0
- ultralytics/utils/__init__.py +1435 -0
- ultralytics/utils/autobatch.py +106 -0
- ultralytics/utils/autodevice.py +174 -0
- ultralytics/utils/benchmarks.py +695 -0
- ultralytics/utils/callbacks/__init__.py +5 -0
- ultralytics/utils/callbacks/base.py +234 -0
- ultralytics/utils/callbacks/clearml.py +153 -0
- ultralytics/utils/callbacks/comet.py +552 -0
- ultralytics/utils/callbacks/dvc.py +205 -0
- ultralytics/utils/callbacks/hub.py +108 -0
- ultralytics/utils/callbacks/mlflow.py +138 -0
- ultralytics/utils/callbacks/neptune.py +140 -0
- ultralytics/utils/callbacks/raytune.py +43 -0
- ultralytics/utils/callbacks/tensorboard.py +132 -0
- ultralytics/utils/callbacks/wb.py +185 -0
- ultralytics/utils/checks.py +897 -0
- ultralytics/utils/dist.py +119 -0
- ultralytics/utils/downloads.py +499 -0
- ultralytics/utils/errors.py +43 -0
- ultralytics/utils/export.py +219 -0
- ultralytics/utils/files.py +221 -0
- ultralytics/utils/instance.py +499 -0
- ultralytics/utils/loss.py +813 -0
- ultralytics/utils/metrics.py +1356 -0
- ultralytics/utils/ops.py +885 -0
- ultralytics/utils/patches.py +143 -0
- ultralytics/utils/plotting.py +1011 -0
- ultralytics/utils/tal.py +416 -0
- ultralytics/utils/torch_utils.py +990 -0
- ultralytics/utils/triton.py +116 -0
- ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,351 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
|
3
|
+
import math
|
4
|
+
from typing import Tuple, Type
|
5
|
+
|
6
|
+
import torch
|
7
|
+
from torch import Tensor, nn
|
8
|
+
|
9
|
+
from ultralytics.nn.modules import MLPBlock
|
10
|
+
|
11
|
+
|
12
|
+
class TwoWayTransformer(nn.Module):
|
13
|
+
"""
|
14
|
+
A Two-Way Transformer module for simultaneous attention to image and query points.
|
15
|
+
|
16
|
+
This class implements a specialized transformer decoder that attends to an input image using queries with
|
17
|
+
supplied positional embeddings. It's useful for tasks like object detection, image segmentation, and point
|
18
|
+
cloud processing.
|
19
|
+
|
20
|
+
Attributes:
|
21
|
+
depth (int): Number of layers in the transformer.
|
22
|
+
embedding_dim (int): Channel dimension for input embeddings.
|
23
|
+
num_heads (int): Number of heads for multihead attention.
|
24
|
+
mlp_dim (int): Internal channel dimension for the MLP block.
|
25
|
+
layers (nn.ModuleList): List of TwoWayAttentionBlock layers composing the transformer.
|
26
|
+
final_attn_token_to_image (Attention): Final attention layer from queries to image.
|
27
|
+
norm_final_attn (nn.LayerNorm): Layer normalization applied to final queries.
|
28
|
+
|
29
|
+
Methods:
|
30
|
+
forward: Processes image and point embeddings through the transformer.
|
31
|
+
|
32
|
+
Examples:
|
33
|
+
>>> transformer = TwoWayTransformer(depth=6, embedding_dim=256, num_heads=8, mlp_dim=2048)
|
34
|
+
>>> image_embedding = torch.randn(1, 256, 32, 32)
|
35
|
+
>>> image_pe = torch.randn(1, 256, 32, 32)
|
36
|
+
>>> point_embedding = torch.randn(1, 100, 256)
|
37
|
+
>>> output_queries, output_image = transformer(image_embedding, image_pe, point_embedding)
|
38
|
+
>>> print(output_queries.shape, output_image.shape)
|
39
|
+
"""
|
40
|
+
|
41
|
+
def __init__(
|
42
|
+
self,
|
43
|
+
depth: int,
|
44
|
+
embedding_dim: int,
|
45
|
+
num_heads: int,
|
46
|
+
mlp_dim: int,
|
47
|
+
activation: Type[nn.Module] = nn.ReLU,
|
48
|
+
attention_downsample_rate: int = 2,
|
49
|
+
) -> None:
|
50
|
+
"""
|
51
|
+
Initialize a Two-Way Transformer for simultaneous attention to image and query points.
|
52
|
+
|
53
|
+
Args:
|
54
|
+
depth (int): Number of layers in the transformer.
|
55
|
+
embedding_dim (int): Channel dimension for input embeddings.
|
56
|
+
num_heads (int): Number of heads for multihead attention. Must divide embedding_dim.
|
57
|
+
mlp_dim (int): Internal channel dimension for the MLP block.
|
58
|
+
activation (Type[nn.Module]): Activation function to use in the MLP block.
|
59
|
+
attention_downsample_rate (int): Downsampling rate for attention mechanism.
|
60
|
+
"""
|
61
|
+
super().__init__()
|
62
|
+
self.depth = depth
|
63
|
+
self.embedding_dim = embedding_dim
|
64
|
+
self.num_heads = num_heads
|
65
|
+
self.mlp_dim = mlp_dim
|
66
|
+
self.layers = nn.ModuleList()
|
67
|
+
|
68
|
+
for i in range(depth):
|
69
|
+
self.layers.append(
|
70
|
+
TwoWayAttentionBlock(
|
71
|
+
embedding_dim=embedding_dim,
|
72
|
+
num_heads=num_heads,
|
73
|
+
mlp_dim=mlp_dim,
|
74
|
+
activation=activation,
|
75
|
+
attention_downsample_rate=attention_downsample_rate,
|
76
|
+
skip_first_layer_pe=(i == 0),
|
77
|
+
)
|
78
|
+
)
|
79
|
+
|
80
|
+
self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
|
81
|
+
self.norm_final_attn = nn.LayerNorm(embedding_dim)
|
82
|
+
|
83
|
+
def forward(
|
84
|
+
self,
|
85
|
+
image_embedding: Tensor,
|
86
|
+
image_pe: Tensor,
|
87
|
+
point_embedding: Tensor,
|
88
|
+
) -> Tuple[Tensor, Tensor]:
|
89
|
+
"""
|
90
|
+
Process image and point embeddings through the Two-Way Transformer.
|
91
|
+
|
92
|
+
Args:
|
93
|
+
image_embedding (Tensor): Image to attend to, with shape (B, embedding_dim, H, W).
|
94
|
+
image_pe (Tensor): Positional encoding to add to the image, with same shape as image_embedding.
|
95
|
+
point_embedding (Tensor): Embedding to add to query points, with shape (B, N_points, embedding_dim).
|
96
|
+
|
97
|
+
Returns:
|
98
|
+
queries (Tensor): Processed point embeddings with shape (B, N_points, embedding_dim).
|
99
|
+
keys (Tensor): Processed image embeddings with shape (B, H*W, embedding_dim).
|
100
|
+
"""
|
101
|
+
# BxCxHxW -> BxHWxC == B x N_image_tokens x C
|
102
|
+
image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
|
103
|
+
image_pe = image_pe.flatten(2).permute(0, 2, 1)
|
104
|
+
|
105
|
+
# Prepare queries
|
106
|
+
queries = point_embedding
|
107
|
+
keys = image_embedding
|
108
|
+
|
109
|
+
# Apply transformer blocks and final layernorm
|
110
|
+
for layer in self.layers:
|
111
|
+
queries, keys = layer(
|
112
|
+
queries=queries,
|
113
|
+
keys=keys,
|
114
|
+
query_pe=point_embedding,
|
115
|
+
key_pe=image_pe,
|
116
|
+
)
|
117
|
+
|
118
|
+
# Apply the final attention layer from the points to the image
|
119
|
+
q = queries + point_embedding
|
120
|
+
k = keys + image_pe
|
121
|
+
attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
|
122
|
+
queries = queries + attn_out
|
123
|
+
queries = self.norm_final_attn(queries)
|
124
|
+
|
125
|
+
return queries, keys
|
126
|
+
|
127
|
+
|
128
|
+
class TwoWayAttentionBlock(nn.Module):
|
129
|
+
"""
|
130
|
+
A two-way attention block for simultaneous attention to image and query points.
|
131
|
+
|
132
|
+
This class implements a specialized transformer block with four main layers: self-attention on sparse inputs,
|
133
|
+
cross-attention of sparse inputs to dense inputs, MLP block on sparse inputs, and cross-attention of dense
|
134
|
+
inputs to sparse inputs.
|
135
|
+
|
136
|
+
Attributes:
|
137
|
+
self_attn (Attention): Self-attention layer for queries.
|
138
|
+
norm1 (nn.LayerNorm): Layer normalization after self-attention.
|
139
|
+
cross_attn_token_to_image (Attention): Cross-attention layer from queries to keys.
|
140
|
+
norm2 (nn.LayerNorm): Layer normalization after token-to-image attention.
|
141
|
+
mlp (MLPBlock): MLP block for transforming query embeddings.
|
142
|
+
norm3 (nn.LayerNorm): Layer normalization after MLP block.
|
143
|
+
norm4 (nn.LayerNorm): Layer normalization after image-to-token attention.
|
144
|
+
cross_attn_image_to_token (Attention): Cross-attention layer from keys to queries.
|
145
|
+
skip_first_layer_pe (bool): Whether to skip positional encoding in the first layer.
|
146
|
+
|
147
|
+
Methods:
|
148
|
+
forward: Applies self-attention and cross-attention to queries and keys.
|
149
|
+
|
150
|
+
Examples:
|
151
|
+
>>> embedding_dim, num_heads = 256, 8
|
152
|
+
>>> block = TwoWayAttentionBlock(embedding_dim, num_heads)
|
153
|
+
>>> queries = torch.randn(1, 100, embedding_dim)
|
154
|
+
>>> keys = torch.randn(1, 1000, embedding_dim)
|
155
|
+
>>> query_pe = torch.randn(1, 100, embedding_dim)
|
156
|
+
>>> key_pe = torch.randn(1, 1000, embedding_dim)
|
157
|
+
>>> processed_queries, processed_keys = block(queries, keys, query_pe, key_pe)
|
158
|
+
"""
|
159
|
+
|
160
|
+
def __init__(
|
161
|
+
self,
|
162
|
+
embedding_dim: int,
|
163
|
+
num_heads: int,
|
164
|
+
mlp_dim: int = 2048,
|
165
|
+
activation: Type[nn.Module] = nn.ReLU,
|
166
|
+
attention_downsample_rate: int = 2,
|
167
|
+
skip_first_layer_pe: bool = False,
|
168
|
+
) -> None:
|
169
|
+
"""
|
170
|
+
Initialize a TwoWayAttentionBlock for simultaneous attention to image and query points.
|
171
|
+
|
172
|
+
This block implements a specialized transformer layer with four main components: self-attention on sparse
|
173
|
+
inputs, cross-attention of sparse inputs to dense inputs, MLP block on sparse inputs, and cross-attention
|
174
|
+
of dense inputs to sparse inputs.
|
175
|
+
|
176
|
+
Args:
|
177
|
+
embedding_dim (int): Channel dimension of the embeddings.
|
178
|
+
num_heads (int): Number of attention heads in the attention layers.
|
179
|
+
mlp_dim (int): Hidden dimension of the MLP block.
|
180
|
+
activation (Type[nn.Module]): Activation function for the MLP block.
|
181
|
+
attention_downsample_rate (int): Downsampling rate for the attention mechanism.
|
182
|
+
skip_first_layer_pe (bool): Whether to skip positional encoding in the first layer.
|
183
|
+
"""
|
184
|
+
super().__init__()
|
185
|
+
self.self_attn = Attention(embedding_dim, num_heads)
|
186
|
+
self.norm1 = nn.LayerNorm(embedding_dim)
|
187
|
+
|
188
|
+
self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
|
189
|
+
self.norm2 = nn.LayerNorm(embedding_dim)
|
190
|
+
|
191
|
+
self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
|
192
|
+
self.norm3 = nn.LayerNorm(embedding_dim)
|
193
|
+
|
194
|
+
self.norm4 = nn.LayerNorm(embedding_dim)
|
195
|
+
self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
|
196
|
+
|
197
|
+
self.skip_first_layer_pe = skip_first_layer_pe
|
198
|
+
|
199
|
+
def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> Tuple[Tensor, Tensor]:
|
200
|
+
"""
|
201
|
+
Apply two-way attention to process query and key embeddings in a transformer block.
|
202
|
+
|
203
|
+
Args:
|
204
|
+
queries (Tensor): Query embeddings with shape (B, N_queries, embedding_dim).
|
205
|
+
keys (Tensor): Key embeddings with shape (B, N_keys, embedding_dim).
|
206
|
+
query_pe (Tensor): Positional encodings for queries with same shape as queries.
|
207
|
+
key_pe (Tensor): Positional encodings for keys with same shape as keys.
|
208
|
+
|
209
|
+
Returns:
|
210
|
+
queries (Tensor): Processed query embeddings with shape (B, N_queries, embedding_dim).
|
211
|
+
keys (Tensor): Processed key embeddings with shape (B, N_keys, embedding_dim).
|
212
|
+
"""
|
213
|
+
# Self attention block
|
214
|
+
if self.skip_first_layer_pe:
|
215
|
+
queries = self.self_attn(q=queries, k=queries, v=queries)
|
216
|
+
else:
|
217
|
+
q = queries + query_pe
|
218
|
+
attn_out = self.self_attn(q=q, k=q, v=queries)
|
219
|
+
queries = queries + attn_out
|
220
|
+
queries = self.norm1(queries)
|
221
|
+
|
222
|
+
# Cross attention block, tokens attending to image embedding
|
223
|
+
q = queries + query_pe
|
224
|
+
k = keys + key_pe
|
225
|
+
attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
|
226
|
+
queries = queries + attn_out
|
227
|
+
queries = self.norm2(queries)
|
228
|
+
|
229
|
+
# MLP block
|
230
|
+
mlp_out = self.mlp(queries)
|
231
|
+
queries = queries + mlp_out
|
232
|
+
queries = self.norm3(queries)
|
233
|
+
|
234
|
+
# Cross attention block, image embedding attending to tokens
|
235
|
+
q = queries + query_pe
|
236
|
+
k = keys + key_pe
|
237
|
+
attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
|
238
|
+
keys = keys + attn_out
|
239
|
+
keys = self.norm4(keys)
|
240
|
+
|
241
|
+
return queries, keys
|
242
|
+
|
243
|
+
|
244
|
+
class Attention(nn.Module):
|
245
|
+
"""
|
246
|
+
An attention layer with downscaling capability for embedding size after projection.
|
247
|
+
|
248
|
+
This class implements a multi-head attention mechanism with the option to downsample the internal
|
249
|
+
dimension of queries, keys, and values.
|
250
|
+
|
251
|
+
Attributes:
|
252
|
+
embedding_dim (int): Dimensionality of input embeddings.
|
253
|
+
kv_in_dim (int): Dimensionality of key and value inputs.
|
254
|
+
internal_dim (int): Internal dimension after downsampling.
|
255
|
+
num_heads (int): Number of attention heads.
|
256
|
+
q_proj (nn.Linear): Linear projection for queries.
|
257
|
+
k_proj (nn.Linear): Linear projection for keys.
|
258
|
+
v_proj (nn.Linear): Linear projection for values.
|
259
|
+
out_proj (nn.Linear): Linear projection for output.
|
260
|
+
|
261
|
+
Methods:
|
262
|
+
_separate_heads: Separates input tensor into attention heads.
|
263
|
+
_recombine_heads: Recombines separated attention heads.
|
264
|
+
forward: Computes attention output for given query, key, and value tensors.
|
265
|
+
|
266
|
+
Examples:
|
267
|
+
>>> attn = Attention(embedding_dim=256, num_heads=8, downsample_rate=2)
|
268
|
+
>>> q = torch.randn(1, 100, 256)
|
269
|
+
>>> k = v = torch.randn(1, 50, 256)
|
270
|
+
>>> output = attn(q, k, v)
|
271
|
+
>>> print(output.shape)
|
272
|
+
torch.Size([1, 100, 256])
|
273
|
+
"""
|
274
|
+
|
275
|
+
def __init__(
|
276
|
+
self,
|
277
|
+
embedding_dim: int,
|
278
|
+
num_heads: int,
|
279
|
+
downsample_rate: int = 1,
|
280
|
+
kv_in_dim: int = None,
|
281
|
+
) -> None:
|
282
|
+
"""
|
283
|
+
Initialize the Attention module with specified dimensions and settings.
|
284
|
+
|
285
|
+
Args:
|
286
|
+
embedding_dim (int): Dimensionality of input embeddings.
|
287
|
+
num_heads (int): Number of attention heads.
|
288
|
+
downsample_rate (int): Factor by which internal dimensions are downsampled.
|
289
|
+
kv_in_dim (int | None): Dimensionality of key and value inputs. If None, uses embedding_dim.
|
290
|
+
|
291
|
+
Raises:
|
292
|
+
AssertionError: If num_heads does not evenly divide the internal dim (embedding_dim / downsample_rate).
|
293
|
+
"""
|
294
|
+
super().__init__()
|
295
|
+
self.embedding_dim = embedding_dim
|
296
|
+
self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim
|
297
|
+
self.internal_dim = embedding_dim // downsample_rate
|
298
|
+
self.num_heads = num_heads
|
299
|
+
assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."
|
300
|
+
|
301
|
+
self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
|
302
|
+
self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
303
|
+
self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
304
|
+
self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
|
305
|
+
|
306
|
+
@staticmethod
|
307
|
+
def _separate_heads(x: Tensor, num_heads: int) -> Tensor:
|
308
|
+
"""Separate the input tensor into the specified number of attention heads."""
|
309
|
+
b, n, c = x.shape
|
310
|
+
x = x.reshape(b, n, num_heads, c // num_heads)
|
311
|
+
return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
|
312
|
+
|
313
|
+
@staticmethod
|
314
|
+
def _recombine_heads(x: Tensor) -> Tensor:
|
315
|
+
"""Recombine separated attention heads into a single tensor."""
|
316
|
+
b, n_heads, n_tokens, c_per_head = x.shape
|
317
|
+
x = x.transpose(1, 2)
|
318
|
+
return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
|
319
|
+
|
320
|
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
|
321
|
+
"""
|
322
|
+
Apply multi-head attention to query, key, and value tensors with optional downsampling.
|
323
|
+
|
324
|
+
Args:
|
325
|
+
q (Tensor): Query tensor with shape (B, N_q, embedding_dim).
|
326
|
+
k (Tensor): Key tensor with shape (B, N_k, embedding_dim).
|
327
|
+
v (Tensor): Value tensor with shape (B, N_k, embedding_dim).
|
328
|
+
|
329
|
+
Returns:
|
330
|
+
(Tensor): Output tensor after attention with shape (B, N_q, embedding_dim).
|
331
|
+
"""
|
332
|
+
# Input projections
|
333
|
+
q = self.q_proj(q)
|
334
|
+
k = self.k_proj(k)
|
335
|
+
v = self.v_proj(v)
|
336
|
+
|
337
|
+
# Separate into heads
|
338
|
+
q = self._separate_heads(q, self.num_heads)
|
339
|
+
k = self._separate_heads(k, self.num_heads)
|
340
|
+
v = self._separate_heads(v, self.num_heads)
|
341
|
+
|
342
|
+
# Attention
|
343
|
+
_, _, _, c_per_head = q.shape
|
344
|
+
attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens
|
345
|
+
attn = attn / math.sqrt(c_per_head)
|
346
|
+
attn = torch.softmax(attn, dim=-1)
|
347
|
+
|
348
|
+
# Get output
|
349
|
+
out = attn @ v
|
350
|
+
out = self._recombine_heads(out)
|
351
|
+
return self.out_proj(out)
|