dgenerate-ultralytics-headless 8.3.236__py3-none-any.whl → 8.3.239__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.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/METADATA +1 -1
- {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/RECORD +117 -105
- tests/test_exports.py +3 -1
- tests/test_python.py +2 -2
- tests/test_solutions.py +6 -6
- ultralytics/__init__.py +1 -1
- ultralytics/cfg/__init__.py +4 -4
- ultralytics/cfg/datasets/Argoverse.yaml +7 -6
- ultralytics/cfg/datasets/DOTAv1.5.yaml +1 -1
- ultralytics/cfg/datasets/DOTAv1.yaml +1 -1
- ultralytics/cfg/datasets/VOC.yaml +15 -16
- ultralytics/cfg/datasets/african-wildlife.yaml +1 -1
- ultralytics/cfg/datasets/coco128-seg.yaml +1 -1
- ultralytics/cfg/datasets/dota8-multispectral.yaml +1 -1
- ultralytics/cfg/datasets/dota8.yaml +2 -2
- ultralytics/cfg/datasets/kitti.yaml +1 -1
- ultralytics/cfg/datasets/xView.yaml +16 -16
- ultralytics/cfg/models/11/yolo11-pose.yaml +1 -1
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +2 -2
- ultralytics/cfg/models/11/yoloe-11.yaml +2 -2
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +9 -6
- ultralytics/cfg/models/v8/yoloe-v8.yaml +9 -6
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +2 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +2 -2
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +2 -2
- ultralytics/cfg/models/v8/yolov8-obb.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-p2.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-world.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +6 -6
- ultralytics/data/augment.py +1 -1
- ultralytics/data/base.py +4 -2
- ultralytics/data/build.py +4 -4
- ultralytics/data/loaders.py +17 -12
- ultralytics/data/utils.py +4 -4
- ultralytics/engine/exporter.py +40 -25
- ultralytics/engine/predictor.py +8 -6
- ultralytics/engine/results.py +12 -13
- ultralytics/engine/trainer.py +10 -2
- ultralytics/engine/tuner.py +2 -3
- ultralytics/engine/validator.py +2 -2
- ultralytics/models/fastsam/model.py +2 -2
- ultralytics/models/fastsam/predict.py +2 -3
- ultralytics/models/fastsam/val.py +4 -4
- ultralytics/models/rtdetr/predict.py +2 -3
- ultralytics/models/rtdetr/val.py +10 -5
- ultralytics/models/sam/__init__.py +14 -1
- ultralytics/models/sam/build.py +22 -13
- ultralytics/models/sam/build_sam3.py +377 -0
- ultralytics/models/sam/model.py +13 -5
- ultralytics/models/sam/modules/blocks.py +20 -8
- ultralytics/models/sam/modules/decoders.py +2 -3
- ultralytics/models/sam/modules/encoders.py +4 -1
- ultralytics/models/sam/modules/memory_attention.py +6 -2
- ultralytics/models/sam/modules/sam.py +159 -10
- ultralytics/models/sam/modules/utils.py +134 -4
- ultralytics/models/sam/predict.py +2073 -139
- ultralytics/models/sam/sam3/__init__.py +3 -0
- ultralytics/models/sam/sam3/decoder.py +546 -0
- ultralytics/models/sam/sam3/encoder.py +535 -0
- ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
- ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
- ultralytics/models/sam/sam3/model_misc.py +198 -0
- ultralytics/models/sam/sam3/necks.py +129 -0
- ultralytics/models/sam/sam3/sam3_image.py +339 -0
- ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
- ultralytics/models/sam/sam3/vitdet.py +546 -0
- ultralytics/models/sam/sam3/vl_combiner.py +160 -0
- ultralytics/models/yolo/classify/val.py +1 -1
- ultralytics/models/yolo/detect/train.py +1 -1
- ultralytics/models/yolo/detect/val.py +7 -7
- ultralytics/models/yolo/obb/val.py +19 -8
- ultralytics/models/yolo/pose/val.py +1 -1
- ultralytics/models/yolo/segment/val.py +1 -1
- ultralytics/nn/autobackend.py +9 -9
- ultralytics/nn/modules/block.py +1 -1
- ultralytics/nn/modules/transformer.py +21 -1
- ultralytics/nn/tasks.py +3 -3
- ultralytics/nn/text_model.py +2 -7
- ultralytics/solutions/ai_gym.py +1 -1
- ultralytics/solutions/analytics.py +6 -6
- ultralytics/solutions/config.py +1 -1
- ultralytics/solutions/distance_calculation.py +1 -1
- ultralytics/solutions/object_counter.py +1 -1
- ultralytics/solutions/object_cropper.py +3 -6
- ultralytics/solutions/parking_management.py +21 -17
- ultralytics/solutions/queue_management.py +5 -5
- ultralytics/solutions/region_counter.py +2 -2
- ultralytics/solutions/security_alarm.py +1 -1
- ultralytics/solutions/solutions.py +45 -22
- ultralytics/solutions/speed_estimation.py +1 -1
- ultralytics/trackers/basetrack.py +1 -1
- ultralytics/trackers/bot_sort.py +4 -3
- ultralytics/trackers/byte_tracker.py +4 -4
- ultralytics/trackers/utils/gmc.py +6 -7
- ultralytics/trackers/utils/kalman_filter.py +2 -1
- ultralytics/trackers/utils/matching.py +4 -3
- ultralytics/utils/__init__.py +12 -3
- ultralytics/utils/benchmarks.py +2 -2
- ultralytics/utils/callbacks/tensorboard.py +19 -25
- ultralytics/utils/checks.py +4 -3
- ultralytics/utils/downloads.py +1 -1
- ultralytics/utils/export/tensorflow.py +16 -2
- ultralytics/utils/files.py +13 -12
- ultralytics/utils/logger.py +62 -27
- ultralytics/utils/metrics.py +1 -1
- ultralytics/utils/ops.py +7 -9
- ultralytics/utils/patches.py +3 -3
- ultralytics/utils/plotting.py +7 -12
- ultralytics/utils/tuner.py +1 -1
- {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/WHEEL +0 -0
- {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/entry_points.txt +0 -0
- {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/licenses/LICENSE +0 -0
- {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections import OrderedDict
|
|
8
|
+
from typing import Callable
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
import torch.nn as nn
|
|
12
|
+
from torch.utils.checkpoint import checkpoint
|
|
13
|
+
|
|
14
|
+
from .model_misc import LayerScale
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ResidualAttentionBlock(nn.Module):
|
|
18
|
+
"""Transformer block with multi-head attention, layer normalization, and MLP feed-forward network."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
d_model: int,
|
|
23
|
+
n_head: int,
|
|
24
|
+
mlp_ratio: float = 4.0,
|
|
25
|
+
ls_init_value: float | None = None,
|
|
26
|
+
act_layer: Callable[[], nn.Module] = nn.GELU,
|
|
27
|
+
norm_layer: Callable[[int], nn.Module] = nn.LayerNorm,
|
|
28
|
+
):
|
|
29
|
+
"""Initialize residual attention block with configurable dimensions and normalization."""
|
|
30
|
+
super().__init__()
|
|
31
|
+
# Attention
|
|
32
|
+
self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True)
|
|
33
|
+
|
|
34
|
+
# LayerNorm, LayerScale
|
|
35
|
+
self.ln_1 = norm_layer(d_model)
|
|
36
|
+
self.ln_2 = norm_layer(d_model)
|
|
37
|
+
|
|
38
|
+
self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
|
|
39
|
+
self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
|
|
40
|
+
|
|
41
|
+
# MLP
|
|
42
|
+
mlp_width = int(d_model * mlp_ratio)
|
|
43
|
+
self.mlp = nn.Sequential(
|
|
44
|
+
OrderedDict(
|
|
45
|
+
[
|
|
46
|
+
("c_fc", nn.Linear(d_model, mlp_width)),
|
|
47
|
+
("gelu", act_layer()),
|
|
48
|
+
("c_proj", nn.Linear(mlp_width, d_model)),
|
|
49
|
+
]
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def attention(
|
|
54
|
+
self, q_x: torch.Tensor, k_x: torch.Tensor = None, v_x: torch.Tensor = None, attn_mask: torch.Tensor = None
|
|
55
|
+
) -> torch.Tensor:
|
|
56
|
+
"""Compute multi-head attention with optional cross-attention support and masking."""
|
|
57
|
+
k_x = k_x if k_x is not None else q_x
|
|
58
|
+
v_x = v_x if v_x is not None else q_x
|
|
59
|
+
if attn_mask is not None:
|
|
60
|
+
# Leave boolean masks as is
|
|
61
|
+
if not attn_mask.dtype == torch.bool:
|
|
62
|
+
attn_mask = attn_mask.to(q_x.dtype)
|
|
63
|
+
|
|
64
|
+
return self.attn(q_x, k_x, v_x, need_weights=False, attn_mask=attn_mask)[0]
|
|
65
|
+
|
|
66
|
+
def forward(
|
|
67
|
+
self, q_x: torch.Tensor, k_x: torch.Tensor = None, v_x: torch.Tensor = None, attn_mask: torch.Tensor = None
|
|
68
|
+
) -> torch.Tensor:
|
|
69
|
+
"""Apply residual attention with layer normalization and MLP, supporting optional cross-attention."""
|
|
70
|
+
k_x = self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None
|
|
71
|
+
v_x = self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None
|
|
72
|
+
x = q_x + self.ls_1(self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask))
|
|
73
|
+
x = x + self.ls_2(self.mlp(self.ln_2(x)))
|
|
74
|
+
return x
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Transformer(nn.Module):
|
|
78
|
+
"""Stack of residual attention blocks forming a transformer encoder with optional gradient checkpointing."""
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
width: int,
|
|
83
|
+
layers: int,
|
|
84
|
+
heads: int,
|
|
85
|
+
mlp_ratio: float = 4.0,
|
|
86
|
+
ls_init_value: float | None = None,
|
|
87
|
+
act_layer: Callable[[], nn.Module] = nn.GELU,
|
|
88
|
+
norm_layer: Callable[[int], nn.Module] = nn.LayerNorm,
|
|
89
|
+
compile_mode: str | None = None,
|
|
90
|
+
use_act_checkpoint: bool = False,
|
|
91
|
+
):
|
|
92
|
+
"""Initialize transformer with configurable depth, width, and optional compilation/checkpointing."""
|
|
93
|
+
super().__init__()
|
|
94
|
+
self.width = width
|
|
95
|
+
self.layers = layers
|
|
96
|
+
self.grad_checkpointing = use_act_checkpoint
|
|
97
|
+
self.resblocks = nn.ModuleList(
|
|
98
|
+
[
|
|
99
|
+
ResidualAttentionBlock(
|
|
100
|
+
width,
|
|
101
|
+
heads,
|
|
102
|
+
mlp_ratio,
|
|
103
|
+
ls_init_value=ls_init_value,
|
|
104
|
+
act_layer=act_layer,
|
|
105
|
+
norm_layer=norm_layer,
|
|
106
|
+
)
|
|
107
|
+
for _ in range(layers)
|
|
108
|
+
]
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
if compile_mode is not None:
|
|
112
|
+
self.forward = torch.compile(self.forward, mode=compile_mode, fullgraph=True)
|
|
113
|
+
if self.grad_checkpointing:
|
|
114
|
+
torch._dynamo.config.optimize_ddp = False
|
|
115
|
+
|
|
116
|
+
def forward(self, x: torch.Tensor, attn_mask: torch.Tensor = None) -> torch.Tensor:
|
|
117
|
+
"""Process input through all transformer blocks with optional gradient checkpointing during training."""
|
|
118
|
+
for _, r in enumerate(self.resblocks):
|
|
119
|
+
if self.grad_checkpointing and not torch.jit.is_scripting() and self.training:
|
|
120
|
+
x = checkpoint(r, x, None, None, attn_mask, use_reentrant=False)
|
|
121
|
+
else:
|
|
122
|
+
x = r(x, attn_mask=attn_mask)
|
|
123
|
+
return x
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def text_global_pool(
|
|
127
|
+
x: torch.Tensor, text: torch.Tensor = None, pool_type: str = "argmax"
|
|
128
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
129
|
+
"""Extract pooled representation and tokens from text embeddings using specified pooling strategy
|
|
130
|
+
(first/last/argmax/none).
|
|
131
|
+
"""
|
|
132
|
+
if pool_type == "first":
|
|
133
|
+
pooled, tokens = x[:, 0], x[:, 1:]
|
|
134
|
+
elif pool_type == "last":
|
|
135
|
+
pooled, tokens = x[:, -1], x[:, :-1]
|
|
136
|
+
elif pool_type == "argmax":
|
|
137
|
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
|
138
|
+
assert text is not None
|
|
139
|
+
pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x
|
|
140
|
+
else:
|
|
141
|
+
pooled = tokens = x
|
|
142
|
+
return pooled, tokens
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class TextTransformer(nn.Module):
|
|
146
|
+
"""Text transformer encoder with causal masking and flexible pooling strategies."""
|
|
147
|
+
|
|
148
|
+
def __init__(
|
|
149
|
+
self,
|
|
150
|
+
context_length: int = 77,
|
|
151
|
+
vocab_size: int = 49408,
|
|
152
|
+
width: int = 512,
|
|
153
|
+
heads: int = 8,
|
|
154
|
+
layers: int = 12,
|
|
155
|
+
mlp_ratio: float = 4.0,
|
|
156
|
+
ls_init_value: float | None = None,
|
|
157
|
+
output_dim: int = 512,
|
|
158
|
+
no_causal_mask: bool = False,
|
|
159
|
+
pool_type: str = "none", # no pooling
|
|
160
|
+
proj_bias: bool = False,
|
|
161
|
+
act_layer: Callable = nn.GELU,
|
|
162
|
+
norm_layer: Callable = nn.LayerNorm,
|
|
163
|
+
output_tokens: bool = False,
|
|
164
|
+
use_ln_post: bool = True,
|
|
165
|
+
compile_mode: str | None = None,
|
|
166
|
+
use_act_checkpoint: bool = False,
|
|
167
|
+
):
|
|
168
|
+
"""Initialize text transformer with embedding layers, transformer blocks, and pooling options."""
|
|
169
|
+
super().__init__()
|
|
170
|
+
assert pool_type in ("first", "last", "argmax", "none")
|
|
171
|
+
self.output_tokens = output_tokens
|
|
172
|
+
self.num_pos = self.context_length = context_length
|
|
173
|
+
self.vocab_size = vocab_size
|
|
174
|
+
self.width = width
|
|
175
|
+
self.output_dim = output_dim
|
|
176
|
+
self.heads = heads
|
|
177
|
+
self.pool_type = pool_type
|
|
178
|
+
|
|
179
|
+
self.token_embedding = nn.Embedding(self.vocab_size, width)
|
|
180
|
+
self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width))
|
|
181
|
+
self.transformer = Transformer(
|
|
182
|
+
width=width,
|
|
183
|
+
layers=layers,
|
|
184
|
+
heads=heads,
|
|
185
|
+
mlp_ratio=mlp_ratio,
|
|
186
|
+
ls_init_value=ls_init_value,
|
|
187
|
+
act_layer=act_layer,
|
|
188
|
+
norm_layer=norm_layer,
|
|
189
|
+
compile_mode=compile_mode,
|
|
190
|
+
use_act_checkpoint=use_act_checkpoint,
|
|
191
|
+
)
|
|
192
|
+
self.ln_final = norm_layer(width) if use_ln_post else nn.Identity()
|
|
193
|
+
if no_causal_mask:
|
|
194
|
+
self.attn_mask = None
|
|
195
|
+
else:
|
|
196
|
+
self.register_buffer("attn_mask", self.build_causal_mask(), persistent=False)
|
|
197
|
+
if proj_bias:
|
|
198
|
+
self.text_projection = nn.Linear(width, output_dim)
|
|
199
|
+
else:
|
|
200
|
+
self.text_projection = nn.Parameter(torch.empty(width, output_dim))
|
|
201
|
+
|
|
202
|
+
def build_causal_mask(self) -> torch.Tensor:
|
|
203
|
+
"""Create a causal attention mask to prevent attention to future tokens."""
|
|
204
|
+
# lazily create causal attention mask, with full attention between the tokens
|
|
205
|
+
# pytorch uses additive attention mask; fill with -inf
|
|
206
|
+
mask = torch.empty(self.num_pos, self.num_pos)
|
|
207
|
+
mask.fill_(float("-inf"))
|
|
208
|
+
mask.triu_(1) # zero out the lower diagonal
|
|
209
|
+
return mask
|
|
210
|
+
|
|
211
|
+
def forward(self, text: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
|
212
|
+
"""Forward pass through the text transformer, returning pooled output and optionally token embeddings."""
|
|
213
|
+
seq_len = text.shape[1]
|
|
214
|
+
x = self.token_embedding(text) # [batch_size, n_ctx, d_model]
|
|
215
|
+
|
|
216
|
+
attn_mask = self.attn_mask
|
|
217
|
+
if attn_mask is not None:
|
|
218
|
+
attn_mask = attn_mask[:seq_len, :seq_len]
|
|
219
|
+
|
|
220
|
+
x = x + self.positional_embedding[:seq_len]
|
|
221
|
+
x = self.transformer(x, attn_mask=attn_mask)
|
|
222
|
+
|
|
223
|
+
x = self.ln_final(x)
|
|
224
|
+
pooled, tokens = text_global_pool(x, text, pool_type=self.pool_type)
|
|
225
|
+
if self.text_projection is not None:
|
|
226
|
+
if isinstance(self.text_projection, nn.Linear):
|
|
227
|
+
pooled = self.text_projection(pooled)
|
|
228
|
+
else:
|
|
229
|
+
pooled = pooled @ self.text_projection
|
|
230
|
+
if self.output_tokens:
|
|
231
|
+
return pooled, tokens
|
|
232
|
+
return pooled
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class VETextEncoder(nn.Module):
|
|
236
|
+
"""Text encoder for Vision Encoder (VE) models, combining a text transformer and a linear resizer."""
|
|
237
|
+
|
|
238
|
+
def __init__(
|
|
239
|
+
self,
|
|
240
|
+
d_model: int,
|
|
241
|
+
tokenizer: Callable,
|
|
242
|
+
width: int = 1024,
|
|
243
|
+
heads: int = 16,
|
|
244
|
+
layers: int = 24,
|
|
245
|
+
context_length: int = 32,
|
|
246
|
+
vocab_size: int = 49408,
|
|
247
|
+
use_ln_post: bool = True,
|
|
248
|
+
compile_mode: str | None = None,
|
|
249
|
+
use_act_checkpoint: bool = True,
|
|
250
|
+
):
|
|
251
|
+
"""Initialize VE text encoder with a text transformer and a linear resizer to match decoder dimensions."""
|
|
252
|
+
super().__init__()
|
|
253
|
+
self.context_length = context_length
|
|
254
|
+
self.use_ln_post = use_ln_post
|
|
255
|
+
self.tokenizer = tokenizer
|
|
256
|
+
|
|
257
|
+
self.encoder = TextTransformer(
|
|
258
|
+
context_length=self.context_length,
|
|
259
|
+
vocab_size=vocab_size,
|
|
260
|
+
width=width,
|
|
261
|
+
heads=heads,
|
|
262
|
+
layers=layers,
|
|
263
|
+
# we want the tokens, not just the pooled output
|
|
264
|
+
output_tokens=True,
|
|
265
|
+
use_ln_post=use_ln_post,
|
|
266
|
+
compile_mode=compile_mode,
|
|
267
|
+
use_act_checkpoint=use_act_checkpoint,
|
|
268
|
+
)
|
|
269
|
+
self.resizer = nn.Linear(self.encoder.width, d_model)
|
|
270
|
+
|
|
271
|
+
def forward(
|
|
272
|
+
self, text: list[str] | tuple[torch.Tensor, torch.Tensor, dict], input_boxes: list | None = None
|
|
273
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
274
|
+
"""Encode text input, either raw strings or pre-encoded tensors, and resize to match decoder dimensions."""
|
|
275
|
+
if isinstance(text[0], str):
|
|
276
|
+
# no use case for this
|
|
277
|
+
assert input_boxes is None or len(input_boxes) == 0, "not supported"
|
|
278
|
+
|
|
279
|
+
# Encode the text
|
|
280
|
+
tokenized = self.tokenizer(text, context_length=self.context_length).to(
|
|
281
|
+
self.resizer.weight.device
|
|
282
|
+
) # [b, seq_len]
|
|
283
|
+
text_attention_mask = (tokenized != 0).bool()
|
|
284
|
+
|
|
285
|
+
# manually embed the tokens
|
|
286
|
+
inputs_embeds = self.encoder.token_embedding(tokenized) # [b, seq_len, d=1024]
|
|
287
|
+
_, text_memory = self.encoder(tokenized) # [b, seq_len, d=1024]
|
|
288
|
+
|
|
289
|
+
assert text_memory.shape[1] == inputs_embeds.shape[1]
|
|
290
|
+
# Invert attention mask because its the opposite in pytorch transformer
|
|
291
|
+
text_attention_mask = text_attention_mask.ne(1)
|
|
292
|
+
# Transpose memory because pytorch's attention expects sequence first
|
|
293
|
+
text_memory = text_memory.transpose(0, 1)
|
|
294
|
+
# Resize the encoder hidden states to be of the same d_model as the decoder
|
|
295
|
+
text_memory_resized = self.resizer(text_memory)
|
|
296
|
+
else:
|
|
297
|
+
# The text is already encoded, use as is.
|
|
298
|
+
text_attention_mask, text_memory_resized, tokenized = text
|
|
299
|
+
inputs_embeds = tokenized["inputs_embeds"]
|
|
300
|
+
assert input_boxes is None or len(input_boxes) == 0, "Can't replace boxes in text if it's already encoded"
|
|
301
|
+
|
|
302
|
+
# Note that the input_embeds are returned in pytorch's convention (sequence first)
|
|
303
|
+
return (
|
|
304
|
+
text_attention_mask,
|
|
305
|
+
text_memory_resized,
|
|
306
|
+
inputs_embeds.transpose(0, 1),
|
|
307
|
+
)
|