python-doctr 1.0.1__py3-none-any.whl → 1.2.0__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.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -0,0 +1,785 @@
1
+ # Copyright (C) 2021-2026, Mindee.
2
+
3
+ # This program is licensed under the Apache License 2.0.
4
+ # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
+
6
+ import math
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from torch import nn
11
+
12
+ from doctr.models.modules import ChannelLayerNorm
13
+ from doctr.models.utils import conv_sequence_pt
14
+
15
+ __all__ = [
16
+ "MultiScaleProjector",
17
+ "C2fBottleneck",
18
+ "LWDETRHead",
19
+ "LWDETRDecoder",
20
+ "LWDETRMultiscaleDeformableAttention",
21
+ "refine_obb_boxes",
22
+ ]
23
+
24
+
25
+ def refine_obb_boxes(reference_points: torch.Tensor, deltas: torch.Tensor) -> torch.Tensor:
26
+ """Refine oriented bounding boxes by applying predicted deltas to reference points.
27
+ Both reference points and deltas are in the format (cx, cy, w, h, sinθ, cosθ).
28
+
29
+ cx' = cx + delta_cx * w
30
+ cy' = cy + delta_cy * h
31
+ w' = w * exp(delta_w)
32
+ h' = h * exp(delta_h)
33
+ (sinθ', cosθ') = rotation composition of (sinθ, cosθ) with the normalized delta rotation
34
+
35
+ Args:
36
+ reference_points: (..., 6) tensor containing the reference points
37
+ deltas: (..., 6) tensor containing the predicted deltas
38
+
39
+ Returns:
40
+ refined_boxes: (..., 6) tensor containing the refined bounding boxes
41
+ """
42
+ reference_points = reference_points.to(deltas.device)
43
+ # center
44
+ cxcy = deltas[..., :2] * reference_points[..., 2:4] + reference_points[..., :2]
45
+ # size: clamp deltas to prevent exp() from overflowing during early training.
46
+ # NOTE: the upper bound must allow the encoder proposals (w = h = 0.05) to reach full-page boxes
47
+ # in a single refinement step: exp(3.5) * 0.05 ~= 1.66, so boxes up to (and beyond) the full canvas
48
+ # remain reachable. A tighter bound (e.g. 2.0 -> 0.05 * exp(2) ~= 0.37) silently caps the size of the
49
+ # encoder proposals and creates an irreducible loss floor for large layout items (tables, pictures).
50
+ wh = torch.clamp(deltas[..., 2:4], min=-5.0, max=3.5).exp() * reference_points[..., 2:4]
51
+ # rotation (eps avoids division-by-zero NaN creation)
52
+ delta_rot = F.normalize(deltas[..., 4:6], dim=-1, eps=1e-6)
53
+ sin_delta = delta_rot[..., 0:1]
54
+ cos_delta = delta_rot[..., 1:2]
55
+ sin_ref = reference_points[..., 4:5]
56
+ cos_ref = reference_points[..., 5:6]
57
+
58
+ # compose rotations
59
+ sin_new = sin_ref * cos_delta + cos_ref * sin_delta
60
+ cos_new = cos_ref * cos_delta - sin_ref * sin_delta
61
+ rot = F.normalize(torch.cat([sin_new, cos_new], dim=-1), dim=-1, eps=1e-6)
62
+
63
+ return torch.cat((cxcy, wh, rot), dim=-1)
64
+
65
+
66
+ class LWDETRHead(nn.Module):
67
+ """
68
+ Simple MLP used as the reference point head in LW-DETR.
69
+
70
+ Args:
71
+ input_dim: number of input features
72
+ hidden_dim: number of hidden features
73
+ output_dim: number of output features
74
+ num_layers: number of layers in the MLP
75
+ """
76
+
77
+ def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int):
78
+ super().__init__()
79
+ self.num_layers = num_layers
80
+ h = [hidden_dim] * (num_layers - 1)
81
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
82
+
83
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
84
+ for i, layer in enumerate(self.layers):
85
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
86
+ return x
87
+
88
+
89
+ class LWDETRMLP(nn.Module):
90
+ """Simple MLP used in the decoder layers of LW-DETR.
91
+
92
+ Args:
93
+ d_model: number of input and output features
94
+ ff_dim: number of hidden features
95
+ dropout_prob: dropout probability
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ d_model: int,
101
+ ff_dim: int,
102
+ dropout_prob: float = 0.1,
103
+ ):
104
+ super().__init__()
105
+ self.act = nn.ReLU()
106
+ self.dropout_1 = nn.Dropout(dropout_prob)
107
+ self.dropout_2 = nn.Dropout(dropout_prob)
108
+ self.fc1 = nn.Linear(d_model, ff_dim)
109
+ self.fc2 = nn.Linear(ff_dim, d_model)
110
+
111
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
112
+ return x + self.dropout_2(self.fc2(self.dropout_1(self.act(self.fc1(x)))))
113
+
114
+
115
+ class LWDETRAttention(nn.Module):
116
+ """This module implements the self-attention mechanism used in LW-DETR.
117
+ It performs multi-head self-attention on the input hidden states.
118
+ The group detr technique is used during training to add more supervision by
119
+ using multiple weight-sharing decoders at once for faster convergence.
120
+
121
+ Args:
122
+ sa_num_heads: number of attention heads for self-attention
123
+ d_model: number of input and output features
124
+ dropout_prob: dropout probability for attention weights
125
+ group_detr: number of weight-sharing decoders to use during training
126
+ layer_idx: index of the decoder layer (used for group detr)
127
+ """
128
+
129
+ def __init__(
130
+ self,
131
+ sa_num_heads: int = 8,
132
+ d_model: int = 256,
133
+ dropout_prob: float = 0.0,
134
+ group_detr: int = 13,
135
+ layer_idx: int = 0,
136
+ ):
137
+ super().__init__()
138
+ self.layer_idx = layer_idx
139
+ self.head_dim = d_model // sa_num_heads
140
+ self.scaling = self.head_dim**-0.5
141
+ self.dropout = dropout_prob
142
+ self.group_detr = group_detr
143
+
144
+ self.q_proj = nn.Linear(d_model, sa_num_heads * self.head_dim, bias=True)
145
+ self.k_proj = nn.Linear(d_model, sa_num_heads * self.head_dim, bias=True)
146
+ self.v_proj = nn.Linear(d_model, sa_num_heads * self.head_dim, bias=True)
147
+ self.o_proj = nn.Linear(sa_num_heads * self.head_dim, d_model, bias=True)
148
+
149
+ def forward(
150
+ self,
151
+ hidden_states: torch.Tensor,
152
+ position_embeddings: torch.Tensor | None = None,
153
+ ) -> tuple[torch.Tensor, torch.Tensor]:
154
+ batch_size, seq_len, _ = hidden_states.shape
155
+
156
+ if self.training:
157
+ # Crash prevention: ensure seq_len is perfectly divisible
158
+ assert seq_len % self.group_detr == 0, (
159
+ f"Seq len {seq_len} must be divisible by group_detr {self.group_detr}"
160
+ )
161
+
162
+ hidden_states_original = hidden_states
163
+ if position_embeddings is not None:
164
+ hidden_states = hidden_states if position_embeddings is None else hidden_states + position_embeddings
165
+
166
+ if self.training:
167
+ # at training, we use group detr technique to
168
+ # add more supervision by using multiple weight-sharing decoders at once for faster convergence
169
+ # at inference, we only use one decoder
170
+ hidden_states_original = torch.cat(hidden_states_original.split(seq_len // self.group_detr, dim=1), dim=0)
171
+ hidden_states = torch.cat(hidden_states.split(seq_len // self.group_detr, dim=1), dim=0)
172
+
173
+ attention_input_shape = hidden_states.shape[:-1]
174
+ hidden_shape = (*attention_input_shape, -1, self.head_dim)
175
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
176
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
177
+ value_states = self.v_proj(hidden_states_original).view(hidden_shape).transpose(1, 2)
178
+
179
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
180
+
181
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
182
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
183
+ attn_output = torch.matmul(attn_weights, value_states)
184
+ attn_output = attn_output.transpose(1, 2).contiguous()
185
+
186
+ attn_output = attn_output.reshape(*attention_input_shape, -1).contiguous()
187
+ attn_output = self.o_proj(attn_output)
188
+
189
+ if self.training:
190
+ attn_output = torch.cat(torch.split(attn_output, batch_size, dim=0), dim=1)
191
+
192
+ return attn_output, attn_weights
193
+
194
+
195
+ class MultiScaleDeformableAttention(nn.Module):
196
+ """This module implements MultiScaleDeformableAttention from Deformable DETR.
197
+ It performs multi-scale deformable attention on the input feature maps.
198
+ Borrowed from:
199
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/deformable_detr/modeling_deformable_detr.py
200
+ """
201
+
202
+ def forward(
203
+ self,
204
+ value: torch.Tensor,
205
+ value_spatial_shapes_list: list[tuple],
206
+ sampling_locations: torch.Tensor,
207
+ attention_weights: torch.Tensor,
208
+ ) -> torch.Tensor:
209
+ batch_size, _, num_heads, hidden_dim = value.shape
210
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
211
+ value_list = value.split([height * width for height, width in value_spatial_shapes_list], dim=1)
212
+ sampling_grids = 2 * sampling_locations - 1
213
+ sampling_value_list = []
214
+ for level_id, (height, width) in enumerate(value_spatial_shapes_list):
215
+ # batch_size, height*width, num_heads, hidden_dim
216
+ # -> batch_size, height*width, num_heads*hidden_dim
217
+ # -> batch_size, num_heads*hidden_dim, height*width
218
+ # -> batch_size*num_heads, hidden_dim, height, width
219
+ value_l_ = (
220
+ value_list[level_id]
221
+ .flatten(2)
222
+ .transpose(1, 2)
223
+ .reshape(batch_size * num_heads, hidden_dim, height, width)
224
+ .contiguous()
225
+ )
226
+ # batch_size, num_queries, num_heads, num_points, 2
227
+ # -> batch_size, num_heads, num_queries, num_points, 2
228
+ # -> batch_size*num_heads, num_queries, num_points, 2
229
+ sampling_grid_l_ = sampling_grids[:, :, :, level_id].transpose(1, 2).flatten(0, 1).contiguous()
230
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
231
+ sampling_value_l_ = nn.functional.grid_sample(
232
+ value_l_,
233
+ sampling_grid_l_,
234
+ mode="bilinear",
235
+ padding_mode="zeros",
236
+ align_corners=False,
237
+ )
238
+ sampling_value_list.append(sampling_value_l_)
239
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
240
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
241
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
242
+ attention_weights = attention_weights.transpose(1, 2).reshape(
243
+ batch_size * num_heads, 1, num_queries, num_levels * num_points
244
+ )
245
+ output = (
246
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
247
+ .sum(-1)
248
+ .view(batch_size, num_heads * hidden_dim, num_queries)
249
+ )
250
+ return output.transpose(1, 2).contiguous()
251
+
252
+
253
+ class LWDETRMultiscaleDeformableAttention(nn.Module):
254
+ """
255
+ Multiscale deformable attention as proposed in Deformable DETR.
256
+
257
+ Args:
258
+ d_model: number of input and output features
259
+ ca_num_heads: number of attention heads for cross-attention
260
+ dec_n_points: number of sampling points for each attention head
261
+ """
262
+
263
+ def __init__(
264
+ self,
265
+ d_model: int = 256,
266
+ ca_num_heads: int = 16,
267
+ dec_n_points: int = 2,
268
+ ):
269
+ super().__init__()
270
+
271
+ self.attn = MultiScaleDeformableAttention()
272
+
273
+ self.d_model = d_model
274
+ self.n_levels = 1
275
+ self.n_heads = ca_num_heads
276
+ self.n_points = dec_n_points
277
+
278
+ self.sampling_offsets = nn.Linear(d_model, self.n_heads * self.n_levels * dec_n_points * 2)
279
+ self.attention_weights = nn.Linear(d_model, self.n_heads * self.n_levels * dec_n_points)
280
+ self.value_proj = nn.Linear(d_model, d_model)
281
+ self.output_proj = nn.Linear(d_model, d_model)
282
+
283
+ def forward(
284
+ self,
285
+ hidden_states: torch.Tensor,
286
+ attention_mask: torch.Tensor | None = None,
287
+ encoder_hidden_states=None,
288
+ position_embeddings: torch.Tensor | None = None,
289
+ reference_points=None,
290
+ spatial_shapes_list=None,
291
+ ) -> tuple[torch.Tensor, torch.Tensor]:
292
+ # add position embeddings to the hidden states before projecting to queries and keys
293
+ if position_embeddings is not None:
294
+ hidden_states = hidden_states + position_embeddings
295
+
296
+ batch_size, num_queries, _ = hidden_states.shape
297
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
298
+
299
+ value = self.value_proj(encoder_hidden_states)
300
+ if attention_mask is not None:
301
+ # attention_mask contains True on valid positions -> zero-out the padded (invalid) values
302
+ value = value.masked_fill(~attention_mask[..., None], float(0))
303
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
304
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
305
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
306
+ )
307
+ attention_weights = self.attention_weights(hidden_states).view(
308
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
309
+ )
310
+ attention_weights = F.softmax(attention_weights, -1).view(
311
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
312
+ )
313
+ # batch_size, num_queries, n_heads, n_levels, n_points, 2
314
+ num_coordinates = reference_points.shape[-1]
315
+
316
+ if num_coordinates == 4:
317
+ sampling_locations = (
318
+ reference_points[:, :, None, :, None, :2]
319
+ + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
320
+ )
321
+ elif num_coordinates == 6:
322
+ ref = reference_points[:, :, None, :, None, :] # (..., 6)
323
+
324
+ center = ref[..., :2] # (cx, cy)
325
+ wh = ref[..., 2:4] # (w, h)
326
+ sin = ref[..., 4:5] # sinθ
327
+ cos = ref[..., 5:6] # cosθ
328
+
329
+ # normalize offsets
330
+ offsets = sampling_offsets / self.n_points * wh * 0.5
331
+
332
+ dx = offsets[..., 0:1]
333
+ dy = offsets[..., 1:2]
334
+
335
+ # rotate offsets
336
+ dx_rot = dx * cos - dy * sin
337
+ dy_rot = dx * sin + dy * cos
338
+
339
+ rotated_offsets = torch.cat([dx_rot, dy_rot], dim=-1)
340
+
341
+ sampling_locations = center + rotated_offsets
342
+ else:
343
+ raise ValueError(f"Last dim of reference_points must be 4 or 6, but got {reference_points.shape[-1]}")
344
+
345
+ output = self.attn(
346
+ value,
347
+ spatial_shapes_list,
348
+ sampling_locations,
349
+ attention_weights,
350
+ )
351
+
352
+ output = self.output_proj(output)
353
+
354
+ return output, attention_weights
355
+
356
+
357
+ class LWDETRDecoderLayer(nn.Module):
358
+ """This module implements a single decoder layer of LW-DETR,
359
+ which consists of self-attention, cross-attention and an MLP.
360
+
361
+ Args:
362
+ d_model: number of input and output features
363
+ ff_dim: number of hidden features in the MLP
364
+ dropout_prob: dropout probability for the attention and MLP layers
365
+ ca_num_heads: number of attention heads for cross-attention
366
+ dec_n_points: number of sampling points for each attention head in cross-attention
367
+ sa_num_heads: number of attention heads for self-attention
368
+ group_detr: number of weight-sharing decoders to use during training for the group detr technique
369
+ layer_idx: index of the decoder layer (used for group detr)
370
+ """
371
+
372
+ def __init__(
373
+ self,
374
+ d_model: int = 256,
375
+ ff_dim: int = 2048,
376
+ dropout_prob: float = 0.0,
377
+ ca_num_heads: int = 16,
378
+ dec_n_points: int = 2,
379
+ sa_num_heads: int = 8,
380
+ group_detr: int = 13,
381
+ layer_idx: int = 0,
382
+ ):
383
+ super().__init__()
384
+ self.dropout = dropout_prob
385
+
386
+ # self-attention
387
+ self.self_attn = LWDETRAttention(
388
+ sa_num_heads=sa_num_heads,
389
+ d_model=d_model,
390
+ dropout_prob=dropout_prob,
391
+ group_detr=group_detr,
392
+ layer_idx=layer_idx,
393
+ )
394
+ self.self_attn_layer_norm = nn.LayerNorm(d_model)
395
+
396
+ # cross-attention
397
+ self.cross_attn = LWDETRMultiscaleDeformableAttention(
398
+ d_model=d_model,
399
+ ca_num_heads=ca_num_heads,
400
+ dec_n_points=dec_n_points,
401
+ )
402
+ self.cross_attn_layer_norm = nn.LayerNorm(d_model)
403
+
404
+ # mlp
405
+ self.mlp = LWDETRMLP(d_model, ff_dim, dropout_prob)
406
+ self.layer_norm = nn.LayerNorm(d_model)
407
+
408
+ def forward(
409
+ self,
410
+ hidden_states: torch.Tensor,
411
+ position_embeddings: torch.Tensor | None = None,
412
+ reference_points: torch.Tensor | None = None,
413
+ spatial_shapes_list: list[tuple] | None = None,
414
+ encoder_hidden_states: torch.Tensor | None = None,
415
+ encoder_attention_mask: torch.Tensor | None = None,
416
+ ) -> torch.Tensor:
417
+ self_attention_output, self_attn_weights = self.self_attn(
418
+ hidden_states, position_embeddings=position_embeddings
419
+ )
420
+
421
+ self_attention_output = F.dropout(self_attention_output, p=self.dropout, training=self.training)
422
+ hidden_states = hidden_states + self_attention_output
423
+ hidden_states = self.self_attn_layer_norm(hidden_states)
424
+
425
+ cross_attention_output, cross_attn_weights = self.cross_attn(
426
+ hidden_states=hidden_states,
427
+ attention_mask=encoder_attention_mask,
428
+ encoder_hidden_states=encoder_hidden_states,
429
+ position_embeddings=position_embeddings,
430
+ reference_points=reference_points,
431
+ spatial_shapes_list=spatial_shapes_list,
432
+ )
433
+ cross_attention_output = F.dropout(cross_attention_output, p=self.dropout, training=self.training)
434
+ hidden_states = hidden_states + cross_attention_output
435
+ hidden_states = self.cross_attn_layer_norm(hidden_states)
436
+
437
+ hidden_states = self.mlp(hidden_states)
438
+ hidden_states = self.layer_norm(hidden_states)
439
+
440
+ return hidden_states
441
+
442
+
443
+ # function to generate sine positional embedding for 4d coordinates
444
+ # Borrowed from: https://github.com/Atten4Vis/LW-DETR/blob/main/models/transformer.py
445
+ def gen_sine_position_embeddings(pos_tensor: torch.Tensor, hidden_size: int = 256) -> torch.Tensor:
446
+ """
447
+ This function computes position embeddings using sine and cosine functions from the input positional tensor,
448
+ which has a shape of (batch_size, num_queries, 4).
449
+ The last dimension of `pos_tensor` represents the following coordinates:
450
+ - 0: x-coord
451
+ - 1: y-coord
452
+ - 2: width
453
+ - 3: height
454
+
455
+ The output shape is (batch_size, num_queries, 512),
456
+ where final dim (hidden_size*2 = 512) is the total embedding dimension
457
+ achieved by concatenating the sine and cosine values for each coordinate.
458
+ """
459
+ scale = 2 * math.pi
460
+ dim = hidden_size // 2
461
+ dim_t = torch.arange(dim, dtype=torch.float32, device=pos_tensor.device)
462
+ dim_t = 10000 ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / dim)
463
+ x_embed = pos_tensor[:, :, 0] * scale
464
+ y_embed = pos_tensor[:, :, 1] * scale
465
+ pos_x = x_embed[:, :, None] / dim_t
466
+ pos_y = y_embed[:, :, None] / dim_t
467
+ pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
468
+ pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
469
+ if pos_tensor.size(-1) == 4:
470
+ w_embed = pos_tensor[:, :, 2] * scale
471
+ pos_w = w_embed[:, :, None] / dim_t
472
+ pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2)
473
+
474
+ h_embed = pos_tensor[:, :, 3] * scale
475
+ pos_h = h_embed[:, :, None] / dim_t
476
+ pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2)
477
+
478
+ pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2)
479
+ else:
480
+ raise ValueError(f"Unknown pos_tensor shape(-1):{pos_tensor.size(-1)}")
481
+ return pos.to(pos_tensor.dtype)
482
+
483
+
484
+ class LWDETRDecoder(nn.Module):
485
+ """This module implements the decoder of LW-DETR,
486
+ which consists of multiple decoder layers and a reference point head.
487
+
488
+ Args:
489
+ num_layers: number of decoder layers
490
+ d_model: number of input and output features for each decoder layer
491
+ sa_num_heads: number of attention heads for self-attention in each decoder layer
492
+ ca_num_heads: number of attention heads for cross-attention in each decoder layer
493
+ ff_dim: number of hidden features in the MLP of each decoder layer
494
+ dec_n_points: number of sampling points for each attention head in cross-attention of each decoder layer
495
+ group_detr: number of weight-sharing decoders to use during training for the group detr technique
496
+ dropout_prob: dropout probability for the attention and MLP layers in each decoder layer
497
+ bbox_embed: module to predict bounding box deltas for iterative refinement of reference points
498
+ """
499
+
500
+ def __init__(
501
+ self,
502
+ num_layers: int = 3,
503
+ d_model: int = 256,
504
+ sa_num_heads: int = 8,
505
+ ca_num_heads: int = 16,
506
+ ff_dim: int = 2048,
507
+ dec_n_points: int = 2,
508
+ group_detr: int = 13,
509
+ dropout_prob: float = 0.0,
510
+ bbox_embed: nn.Module | None = None,
511
+ ):
512
+ super().__init__()
513
+ self.dropout_prob = dropout_prob
514
+ self.d_model = d_model
515
+ self.layers = nn.ModuleList([
516
+ LWDETRDecoderLayer(
517
+ d_model=self.d_model,
518
+ sa_num_heads=sa_num_heads,
519
+ ca_num_heads=ca_num_heads,
520
+ ff_dim=ff_dim,
521
+ dec_n_points=dec_n_points,
522
+ group_detr=group_detr,
523
+ dropout_prob=dropout_prob,
524
+ layer_idx=i,
525
+ )
526
+ for i in range(num_layers)
527
+ ])
528
+ self.layernorm = nn.LayerNorm(self.d_model)
529
+ self.bbox_embed = bbox_embed
530
+
531
+ self.ref_point_head = LWDETRHead(2 * self.d_model, self.d_model, self.d_model, num_layers=2)
532
+ self.angle_proj = nn.Sequential(
533
+ nn.Linear(4, self.d_model),
534
+ nn.ReLU(),
535
+ nn.Linear(self.d_model, self.d_model),
536
+ )
537
+
538
+ def get_reference(
539
+ self,
540
+ reference_points: torch.Tensor,
541
+ num_levels: int,
542
+ ) -> tuple[torch.Tensor, torch.Tensor]:
543
+ """This function computes the reference point inputs and positional embeddings for the decoder layers.
544
+
545
+ Args:
546
+ reference_points: (batch_size, num_queries, 6)
547
+ tensor containing the current reference points in the format (cx, cy, w, h, sinθ, cosθ)
548
+ num_levels: number of feature levels used in the decoder (1 for LW-DETR small and medium)
549
+
550
+ Returns:
551
+ reference_points_inputs: (batch_size, num_queries, num_levels, 6)
552
+ tensor containing the reference point inputs for the decoder layers
553
+ query_pos: (batch_size, num_queries, d_model)
554
+ tensor containing the positional embeddings for the decoder layers,
555
+ which are computed from the reference points using sine and cosine functions and a linear projection
556
+ """
557
+ ref_xywh = reference_points[..., :4]
558
+ angle = reference_points[..., 4:6]
559
+
560
+ spatial_inputs = ref_xywh[:, :, None].expand(-1, -1, num_levels, -1)
561
+ angle_expanded = angle[:, :, None].expand(-1, -1, num_levels, -1)
562
+
563
+ reference_points_inputs = torch.cat([spatial_inputs, angle_expanded], dim=-1)
564
+ # generate sine positional embeddings from the reference points and
565
+ # project them to get the final query positional embeddings
566
+ query_sine_embed = gen_sine_position_embeddings(ref_xywh, self.d_model)
567
+ base_query_pos = self.ref_point_head(query_sine_embed)
568
+ # Angle embedding: use the same sine/cosine encoding scheme as for the spatial coordinates,
569
+ # but with a separate linear projection.
570
+ sin_t = angle[..., 0:1]
571
+ cos_t = angle[..., 1:2]
572
+ angle_feat = torch.cat(
573
+ [
574
+ sin_t,
575
+ cos_t,
576
+ 2 * sin_t * cos_t,
577
+ cos_t**2 - sin_t**2,
578
+ ],
579
+ dim=-1,
580
+ )
581
+ angle_emb = self.angle_proj(angle_feat)
582
+ # Combine
583
+ query_pos = base_query_pos + angle_emb
584
+ return reference_points_inputs, query_pos
585
+
586
+ def forward(
587
+ self,
588
+ inputs_embeds: torch.Tensor | None,
589
+ reference_points: torch.Tensor,
590
+ spatial_shapes_list: list[tuple[int, int]],
591
+ encoder_hidden_states: torch.Tensor,
592
+ encoder_attention_mask: torch.Tensor | None = None,
593
+ ):
594
+ """Forward pass of the decoder with iterative (per-layer) box refinement.
595
+
596
+ Returns:
597
+ last_hidden_state: (B, Q, d_model) normalized hidden states of the last decoder layer
598
+ intermediate: (num_layers, B, Q, d_model) normalized hidden states of every decoder layer
599
+ intermediate_reference_points: (num_layers, B, Q, 6) the reference points used as INPUT to each
600
+ decoder layer. Box predictions for layer i must be computed as
601
+ `refine_obb_boxes(intermediate_reference_points[i], bbox_embed(intermediate[i]))`.
602
+ Following LW-DETR, the refined reference points are detached before being fed to the next
603
+ layer, while the undetached versions are kept in the returned stack so that gradients can
604
+ flow one extra refinement step when computing the auxiliary losses.
605
+ """
606
+ intermediate: list[torch.Tensor] = []
607
+
608
+ # reference points fed to each decoder layer (input of layer i at index i)
609
+ intermediate_reference_points: list[torch.Tensor] = [reference_points]
610
+
611
+ if inputs_embeds is not None:
612
+ hidden_states = inputs_embeds
613
+
614
+ num_levels = len(spatial_shapes_list)
615
+
616
+ reference_points_inputs, query_pos = self.get_reference(
617
+ reference_points,
618
+ num_levels=num_levels,
619
+ )
620
+
621
+ for lid, decoder_layer in enumerate(self.layers):
622
+ hidden_states = decoder_layer(
623
+ hidden_states,
624
+ encoder_hidden_states=encoder_hidden_states,
625
+ encoder_attention_mask=encoder_attention_mask,
626
+ position_embeddings=query_pos,
627
+ reference_points=reference_points_inputs,
628
+ spatial_shapes_list=spatial_shapes_list,
629
+ )
630
+
631
+ hidden_states_norm = self.layernorm(hidden_states)
632
+ intermediate.append(hidden_states_norm)
633
+
634
+ # iterative refinement
635
+ if self.bbox_embed is not None and lid < len(self.layers) - 1:
636
+ delta = self.bbox_embed(hidden_states_norm)
637
+ new_reference_points = refine_obb_boxes(reference_points, delta)
638
+
639
+ # keep the undetached version for the auxiliary losses ("look forward" supervision)
640
+ intermediate_reference_points.append(new_reference_points)
641
+
642
+ # the next layer consumes detached reference points
643
+ reference_points = new_reference_points.detach()
644
+ reference_points_inputs, query_pos = self.get_reference(
645
+ reference_points,
646
+ num_levels=num_levels,
647
+ )
648
+
649
+ intermediate_stack = torch.stack(intermediate)
650
+ last_hidden_state = intermediate_stack[-1]
651
+
652
+ intermediate_reference_points_stack = torch.stack(intermediate_reference_points)
653
+
654
+ return last_hidden_state, intermediate_stack, intermediate_reference_points_stack
655
+
656
+
657
+ class MultiScaleProjector(nn.Module):
658
+ """
659
+ This module implements MultiScaleProjector in :paper:`lwdetr`.
660
+ It creates pyramid features built on top of the input feature map.
661
+ This is modified from the original MultiScaleProjector to use only the levels used in LW-DETR small and medium.
662
+
663
+ Args:
664
+ in_channels (list[int]): list of input channels for each level of the input feature maps.
665
+ out_channels (int): number of channels in the output feature maps.
666
+ num_blocks (int): number of blocks in the C2fBottleneck.
667
+ """
668
+
669
+ def __init__(self, in_channels: list[int], out_channels: int, num_blocks: int = 3):
670
+ super().__init__()
671
+
672
+ self.use_extra_pool = False
673
+
674
+ self.stages_sampling = nn.ModuleList()
675
+ self.stages = nn.ModuleList()
676
+
677
+ sampling_layers = nn.ModuleList()
678
+ out_dim: int = 0
679
+
680
+ for in_dim in in_channels:
681
+ layers, out_dim = [nn.Identity()], in_dim
682
+ sampling_layers.append(nn.Sequential(*layers))
683
+
684
+ self.stages_sampling.append(sampling_layers)
685
+
686
+ fusion_in_dim = out_dim * len(in_channels)
687
+
688
+ self.stages.append(
689
+ nn.Sequential(
690
+ C2fBottleneck(fusion_in_dim, out_channels, num_blocks),
691
+ ChannelLayerNorm(out_channels),
692
+ )
693
+ )
694
+
695
+ def forward(self, x: torch.Tensor) -> list[tuple[torch.Tensor, torch.Tensor]]:
696
+ feats = [layer(xi) for layer, xi in zip(self.stages_sampling[0], x)] # type: ignore[call-overload]
697
+ fused = torch.cat(feats, dim=1)
698
+ return [self.stages[0](fused)]
699
+
700
+
701
+ class C2fBottleneck(nn.Module):
702
+ """Faster implementation of CSP bottleneck with 2 convolutions and 1 residual connection.
703
+
704
+ Args:
705
+ input_dim: number of input channels
706
+ out_channels: number of output channels
707
+ num_blocks: number of bottleneck blocks
708
+ """
709
+
710
+ def __init__(self, input_dim: int, out_channels: int, num_blocks: int):
711
+ super().__init__()
712
+
713
+ self.c = int(out_channels * 0.5)
714
+
715
+ self.conv_seq_1 = nn.Sequential(
716
+ *conv_sequence_pt(
717
+ in_channels=input_dim,
718
+ out_channels=2 * self.c,
719
+ kernel_size=1,
720
+ stride=1,
721
+ padding=0,
722
+ groups=1,
723
+ dilation=1,
724
+ act=True,
725
+ bias=False,
726
+ bn=True,
727
+ activation=nn.SiLU(inplace=True),
728
+ )
729
+ )
730
+
731
+ self.blocks = nn.ModuleList([
732
+ nn.Sequential(
733
+ *conv_sequence_pt(
734
+ in_channels=self.c,
735
+ out_channels=self.c,
736
+ kernel_size=3,
737
+ stride=1,
738
+ padding=1,
739
+ groups=1,
740
+ dilation=1,
741
+ act=True,
742
+ bias=False,
743
+ bn=True,
744
+ activation=nn.SiLU(inplace=True),
745
+ ),
746
+ *conv_sequence_pt(
747
+ in_channels=self.c,
748
+ out_channels=self.c,
749
+ kernel_size=3,
750
+ stride=1,
751
+ padding=1,
752
+ groups=1,
753
+ dilation=1,
754
+ act=True,
755
+ bias=False,
756
+ bn=True,
757
+ activation=nn.SiLU(inplace=True),
758
+ ),
759
+ )
760
+ for _ in range(num_blocks)
761
+ ])
762
+
763
+ self.conv_seq_2 = nn.Sequential(
764
+ *conv_sequence_pt(
765
+ in_channels=(2 + num_blocks) * self.c,
766
+ out_channels=out_channels,
767
+ kernel_size=1,
768
+ stride=1,
769
+ padding=0,
770
+ groups=1,
771
+ dilation=1,
772
+ act=True,
773
+ bias=False,
774
+ bn=True,
775
+ activation=nn.SiLU(inplace=True),
776
+ )
777
+ )
778
+
779
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
780
+ y = list(self.conv_seq_1(x).split((self.c, self.c), dim=1))
781
+
782
+ for block in self.blocks:
783
+ y.append(block(y[-1]))
784
+
785
+ return self.conv_seq_2(torch.cat(y, dim=1))