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.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +669 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +14 -3
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +121 -37
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +9 -7
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +129 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +5 -4
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +10 -8
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +104 -21
- doctr/datasets/vocabs.py +320 -148
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +3 -0
- doctr/io/elements.py +381 -271
- doctr/io/exporters.py +1915 -0
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -7
- doctr/io/image/pytorch.py +13 -5
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +3 -0
- doctr/models/_utils.py +206 -13
- doctr/models/builder.py +590 -137
- doctr/models/classification/__init__.py +3 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +34 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +14 -2
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +32 -18
- doctr/models/detection/differentiable_binarization/base.py +23 -9
- doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
- doctr/models/detection/fast/base.py +22 -6
- doctr/models/detection/fast/pytorch.py +24 -11
- doctr/models/detection/linknet/base.py +22 -6
- doctr/models/detection/linknet/pytorch.py +10 -3
- doctr/models/detection/predictor/pytorch.py +43 -2
- doctr/models/detection/zoo.py +6 -2
- doctr/models/factory/hub.py +59 -41
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +23 -1
- doctr/models/kie_predictor/pytorch.py +87 -15
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +895 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +114 -0
- doctr/models/layout/zoo.py +94 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +415 -17
- doctr/models/predictor/pytorch.py +109 -12
- doctr/models/preprocessor/pytorch.py +82 -25
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +1127 -0
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +40 -16
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +84 -22
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +126 -25
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +68 -12
- doctr/models/recognition/sar/pytorch.py +21 -7
- doctr/models/recognition/utils.py +80 -50
- doctr/models/recognition/viptr/pytorch.py +38 -14
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +11 -7
- doctr/models/recognition/zoo.py +36 -9
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +231 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +675 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
- doctr/models/table_structure/zoo.py +87 -0
- doctr/models/utils/pytorch.py +381 -25
- doctr/models/zoo.py +141 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +261 -82
- doctr/transforms/modules/pytorch.py +396 -76
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +24 -11
- doctr/utils/fonts.py +64 -17
- doctr/utils/geometry.py +167 -28
- doctr/utils/metrics.py +481 -19
- doctr/utils/multithreading.py +127 -4
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +73 -10
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
- python_doctr-1.2.0.dist-info/RECORD +191 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
|
@@ -0,0 +1,895 @@
|
|
|
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
|
+
from collections.abc import Callable
|
|
8
|
+
from copy import deepcopy
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import torch
|
|
13
|
+
from scipy.optimize import linear_sum_assignment
|
|
14
|
+
from torch import nn
|
|
15
|
+
from torch.nn import functional as F
|
|
16
|
+
|
|
17
|
+
from doctr.models.classification import vit_det_m, vit_det_s
|
|
18
|
+
|
|
19
|
+
from ...utils import _bf16_to_float32, load_pretrained_params
|
|
20
|
+
from .base import _LWDETR, LWDETRPostProcessor
|
|
21
|
+
from .layers import (
|
|
22
|
+
LWDETRDecoder,
|
|
23
|
+
LWDETRHead,
|
|
24
|
+
MultiScaleProjector,
|
|
25
|
+
refine_obb_boxes,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = ["LWDETR", "lw_detr_s", "lw_detr_m"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
default_cfgs: dict[str, dict[str, Any]] = {
|
|
32
|
+
"lw_detr_s": {
|
|
33
|
+
"input_shape": (3, 1024, 1024),
|
|
34
|
+
"mean": (0.798, 0.785, 0.772),
|
|
35
|
+
"std": (0.264, 0.2749, 0.287),
|
|
36
|
+
"class_names": [
|
|
37
|
+
"Caption",
|
|
38
|
+
"Footnote",
|
|
39
|
+
"Formula",
|
|
40
|
+
"List-item",
|
|
41
|
+
"Page-footer",
|
|
42
|
+
"Page-header",
|
|
43
|
+
"Picture",
|
|
44
|
+
"Section-header",
|
|
45
|
+
"Table",
|
|
46
|
+
"Text",
|
|
47
|
+
"Title",
|
|
48
|
+
],
|
|
49
|
+
"url": "https://github.com/mindee/doctr/releases/download/v1.0.1/lw_detr_s-ebbd6ab9.pt",
|
|
50
|
+
},
|
|
51
|
+
"lw_detr_m": {
|
|
52
|
+
"input_shape": (3, 1024, 1024),
|
|
53
|
+
"mean": (0.798, 0.785, 0.772),
|
|
54
|
+
"std": (0.264, 0.2749, 0.287),
|
|
55
|
+
"class_names": [
|
|
56
|
+
"Caption",
|
|
57
|
+
"Footnote",
|
|
58
|
+
"Formula",
|
|
59
|
+
"List-item",
|
|
60
|
+
"Page-footer",
|
|
61
|
+
"Page-header",
|
|
62
|
+
"Picture",
|
|
63
|
+
"Section-header",
|
|
64
|
+
"Table",
|
|
65
|
+
"Text",
|
|
66
|
+
"Title",
|
|
67
|
+
],
|
|
68
|
+
"url": "https://github.com/mindee/doctr/releases/download/v1.1.0/lw_detr_m-12c799e1.pt",
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _obb_covariance_components(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
74
|
+
"""Compute the components (a, b, c) of the Gaussian covariance matrix [[a, c], [c, b]] associated with
|
|
75
|
+
oriented boxes in (cx, cy, w, h, sinθ, cosθ) format, following ProbIoU (https://arxiv.org/abs/2106.06072).
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
boxes: (..., 6) tensor of oriented boxes
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
a, b, c: (...,) tensors of covariance components
|
|
82
|
+
"""
|
|
83
|
+
w = boxes[..., 2].clamp(min=1e-6)
|
|
84
|
+
h = boxes[..., 3].clamp(min=1e-6)
|
|
85
|
+
rot = F.normalize(boxes[..., 4:6], dim=-1, eps=1e-6)
|
|
86
|
+
sin, cos = rot[..., 0], rot[..., 1]
|
|
87
|
+
|
|
88
|
+
var_w = w.pow(2) / 12.0
|
|
89
|
+
var_h = h.pow(2) / 12.0
|
|
90
|
+
cos2 = cos.pow(2)
|
|
91
|
+
sin2 = sin.pow(2)
|
|
92
|
+
|
|
93
|
+
a = var_w * cos2 + var_h * sin2
|
|
94
|
+
b = var_w * sin2 + var_h * cos2
|
|
95
|
+
c = (var_w - var_h) * cos * sin
|
|
96
|
+
return a, b, c
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _probiou(
|
|
100
|
+
boxes1: torch.Tensor,
|
|
101
|
+
boxes2: torch.Tensor,
|
|
102
|
+
pairwise: bool = False,
|
|
103
|
+
scale: float = 1.0,
|
|
104
|
+
eps: float = 1e-7,
|
|
105
|
+
) -> torch.Tensor:
|
|
106
|
+
"""Compute the probabilistic IoU between oriented boxes in (cx, cy, w, h, sinθ, cosθ) format,
|
|
107
|
+
as described in `"Gaussian Bounding Boxes and Probabilistic IoU" <https://arxiv.org/abs/2106.06072>`_.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
boxes1: (N, 6) tensor of oriented boxes
|
|
111
|
+
boxes2: (M, 6) tensor of oriented boxes (M = N if `pairwise` is False)
|
|
112
|
+
pairwise: if True, return the (N, M) matrix of IoUs, otherwise the element-wise (N,) IoUs
|
|
113
|
+
scale: factor applied to the spatial components (cx, cy, w, h) before computing the IoU.
|
|
114
|
+
ProbIoU is mathematically scale-invariant, but the stabilizing `eps` terms are not: in
|
|
115
|
+
normalized [0, 1] coordinates the covariance terms of small boxes (e.g. checkboxes) fall
|
|
116
|
+
below `eps` and the result degenerates (non-overlapping small boxes can score ~1).
|
|
117
|
+
eps: small value for numerical stability
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
probiou: (N,) or (N, M) tensor of IoU-like similarities in [0, 1]
|
|
121
|
+
"""
|
|
122
|
+
# AMP safe-guard
|
|
123
|
+
boxes1 = boxes1.float()
|
|
124
|
+
boxes2 = boxes2.float()
|
|
125
|
+
|
|
126
|
+
if scale != 1.0:
|
|
127
|
+
boxes1 = torch.cat([boxes1[..., :4] * scale, boxes1[..., 4:]], dim=-1)
|
|
128
|
+
boxes2 = torch.cat([boxes2[..., :4] * scale, boxes2[..., 4:]], dim=-1)
|
|
129
|
+
|
|
130
|
+
x1, y1 = boxes1[..., 0], boxes1[..., 1]
|
|
131
|
+
x2, y2 = boxes2[..., 0], boxes2[..., 1]
|
|
132
|
+
a1, b1, c1 = _obb_covariance_components(boxes1)
|
|
133
|
+
a2, b2, c2 = _obb_covariance_components(boxes2)
|
|
134
|
+
|
|
135
|
+
if pairwise:
|
|
136
|
+
x1, y1, a1, b1, c1 = (t.unsqueeze(-1) for t in (x1, y1, a1, b1, c1)) # (N, 1)
|
|
137
|
+
x2, y2, a2, b2, c2 = (t.unsqueeze(-2) for t in (x2, y2, a2, b2, c2)) # (1, M)
|
|
138
|
+
|
|
139
|
+
denom = (a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps
|
|
140
|
+
t1 = ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / denom * 0.25
|
|
141
|
+
t2 = ((c1 + c2) * (x2 - x1) * (y1 - y2)) / denom * 0.5
|
|
142
|
+
t3 = (
|
|
143
|
+
((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2)).clamp(min=eps)
|
|
144
|
+
/ (4 * ((a1 * b1 - c1.pow(2)).clamp(min=eps) * (a2 * b2 - c2.pow(2)).clamp(min=eps)).sqrt() + eps)
|
|
145
|
+
+ eps
|
|
146
|
+
).log() * 0.5
|
|
147
|
+
|
|
148
|
+
bhattacharyya = (t1 + t2 + t3).clamp(min=eps, max=100.0)
|
|
149
|
+
hellinger = (1.0 - (-bhattacharyya).exp() + eps).sqrt()
|
|
150
|
+
return 1.0 - hellinger
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class LWDETRBackbone(nn.Module):
|
|
154
|
+
"""Backbone of LW-DETR, based on a ViT Det architecture. The backbone is used as feature extractor.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
encoder_fn: the function to build the encoder of the backbone, which is a ViT Det architecture
|
|
158
|
+
out_channels: number of channels in the output feature maps of the backbone.
|
|
159
|
+
num_blocks: number of blocks in the C2fBottleneck of the projector.
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
def __init__(
|
|
163
|
+
self,
|
|
164
|
+
encoder_fn: nn.Module,
|
|
165
|
+
out_channels: int = 256,
|
|
166
|
+
num_blocks: int = 3,
|
|
167
|
+
) -> None:
|
|
168
|
+
super().__init__()
|
|
169
|
+
self.encoder = encoder_fn
|
|
170
|
+
|
|
171
|
+
_is_training = self.encoder.training
|
|
172
|
+
|
|
173
|
+
self.encoder.eval()
|
|
174
|
+
with torch.no_grad():
|
|
175
|
+
in_shape = (3, 512, 512)
|
|
176
|
+
out = self.encoder(torch.zeros((1, *in_shape)))
|
|
177
|
+
# Get the number of channels for each feature map output by the backbone
|
|
178
|
+
_shapes = [feat.shape[1] for feat in out]
|
|
179
|
+
self.encoder.train(_is_training)
|
|
180
|
+
|
|
181
|
+
self.projector = MultiScaleProjector(
|
|
182
|
+
in_channels=_shapes,
|
|
183
|
+
out_channels=out_channels,
|
|
184
|
+
num_blocks=num_blocks,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def _resize_valid_mask(self, mask: torch.Tensor, size: tuple[int, int]) -> torch.Tensor:
|
|
188
|
+
"""Resize the valid-pixel mask to feature-map size
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
mask: a binary mask of shape [batch_size x H x W], containing True on valid (non-padded) pixels
|
|
192
|
+
size: the target size (H', W') for the resized mask
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
resized_mask: a binary mask of shape [batch_size x H' x W'], containing True on valid positions
|
|
196
|
+
"""
|
|
197
|
+
if mask.dtype != torch.bool:
|
|
198
|
+
mask = mask.bool()
|
|
199
|
+
|
|
200
|
+
valid = mask.float().unsqueeze(1) # True/1 = valid pixels
|
|
201
|
+
|
|
202
|
+
# Data-dependent sanity checks
|
|
203
|
+
if self.training: # pragma: no cover
|
|
204
|
+
if (valid.flatten(1).sum(dim=1) == 0).any():
|
|
205
|
+
bad = torch.where(valid.flatten(1).sum(dim=1) == 0)[0].tolist()
|
|
206
|
+
raise RuntimeError(f"Input masks are fully padded before resizing: {bad}")
|
|
207
|
+
|
|
208
|
+
# Use max pooling to resize the valid mask:
|
|
209
|
+
# a pixel in the resized mask is valid if at least one pixel
|
|
210
|
+
# in the corresponding window in the input mask is valid
|
|
211
|
+
h_in, w_in = int(mask.shape[-2]), int(mask.shape[-1])
|
|
212
|
+
h_out, w_out = int(size[0]), int(size[1])
|
|
213
|
+
kh, kw = h_in // h_out, w_in // w_out
|
|
214
|
+
resized_mask = (F.max_pool2d(valid, kernel_size=(kh, kw), stride=(kh, kw)) > 0).squeeze(1)
|
|
215
|
+
|
|
216
|
+
# Data-dependent sanity checks
|
|
217
|
+
if self.training: # pragma: no cover
|
|
218
|
+
if (~resized_mask).flatten(1).all(dim=1).any():
|
|
219
|
+
bad = torch.where((~resized_mask).flatten(1).all(dim=1))[0].tolist()
|
|
220
|
+
raise RuntimeError(f"Feature masks became fully padded after resizing: {bad}")
|
|
221
|
+
|
|
222
|
+
return resized_mask
|
|
223
|
+
|
|
224
|
+
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> list[tuple[torch.Tensor, torch.Tensor]]:
|
|
225
|
+
"""Forward pass of the backbone.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
x: batched images, of shape [batch_size x 3 x H x W]
|
|
229
|
+
mask: a binary mask of shape [batch_size x H x W], containing True on valid (non-padded) pixels
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
A list of tuples (feat, mask) for each feature map, where:
|
|
233
|
+
- feat is the feature map of shape [batch_size x out_channels x H' x W']
|
|
234
|
+
- mask is the corresponding valid mask of shape [batch_size x H' x W'], True on valid positions
|
|
235
|
+
"""
|
|
236
|
+
# (H, W, B, C)
|
|
237
|
+
feats = self.encoder(x)
|
|
238
|
+
feats = self.projector(feats)
|
|
239
|
+
# [(B, C, H, W)]
|
|
240
|
+
if mask is None: # pragma: no cover
|
|
241
|
+
# No mask provided: consider every pixel as valid image content
|
|
242
|
+
mask = torch.ones((x.shape[0], x.shape[2], x.shape[3]), dtype=torch.bool, device=x.device)
|
|
243
|
+
return [(feat, self._resize_valid_mask(mask, feat.shape[2:])) for feat in feats]
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class LWDETR(nn.Module, _LWDETR):
|
|
247
|
+
"""LW-DETR as described in `"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection"
|
|
248
|
+
<https://arxiv.org/pdf/2406.03459v1>`_.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
feat_extractor: the backbone of the model, used as feature extractor
|
|
252
|
+
class_names: list of class names to be detected by the model
|
|
253
|
+
score_thresh: the score threshold for post-processing the model outputs
|
|
254
|
+
iou_thresh: the IoU threshold for post-processing the model outputs
|
|
255
|
+
d_model: the dimension of the model
|
|
256
|
+
num_queries: the number of object queries
|
|
257
|
+
group_detr: the number of groups in the group DETR architecture
|
|
258
|
+
dec_layers: the number of decoder layers
|
|
259
|
+
sa_num_heads: the number of heads in the self-attention of the decoder
|
|
260
|
+
ca_num_heads: the number of heads in the cross-attention of the decoder
|
|
261
|
+
ff_dim: the dimension of the feedforward network in the decoder
|
|
262
|
+
dec_n_points: the number of sampling points in the deformable attention of the decoder
|
|
263
|
+
dropout_prob: the dropout probability in the decoder
|
|
264
|
+
assume_straight_pages: if True, fit straight bounding boxes only
|
|
265
|
+
exportable: onnx exportable returns only logits
|
|
266
|
+
cfg: the configuration dict of the model
|
|
267
|
+
"""
|
|
268
|
+
|
|
269
|
+
def __init__(
|
|
270
|
+
self,
|
|
271
|
+
feat_extractor: LWDETRBackbone,
|
|
272
|
+
class_names: list[str],
|
|
273
|
+
score_thresh: float = 0.5,
|
|
274
|
+
iou_thresh: float = 0.5,
|
|
275
|
+
d_model: int = 256,
|
|
276
|
+
num_queries: int = 195,
|
|
277
|
+
group_detr: int = 13,
|
|
278
|
+
dec_layers: int = 3,
|
|
279
|
+
sa_num_heads: int = 8,
|
|
280
|
+
ca_num_heads: int = 16,
|
|
281
|
+
ff_dim: int = 2048,
|
|
282
|
+
dec_n_points: int = 2,
|
|
283
|
+
dropout_prob: float = 0.0,
|
|
284
|
+
assume_straight_pages: bool = True,
|
|
285
|
+
exportable: bool = False,
|
|
286
|
+
cfg: dict[str, Any] | None = None,
|
|
287
|
+
) -> None:
|
|
288
|
+
super().__init__()
|
|
289
|
+
|
|
290
|
+
self.class_names: list[str] = class_names
|
|
291
|
+
# No background class: the model is trained with a sigmoid-based (IA-BCE) loss
|
|
292
|
+
self.num_classes = len(self.class_names)
|
|
293
|
+
self.cfg = cfg
|
|
294
|
+
self.exportable = exportable
|
|
295
|
+
self.assume_straight_pages = assume_straight_pages
|
|
296
|
+
|
|
297
|
+
self.feat_extractor = feat_extractor
|
|
298
|
+
|
|
299
|
+
self.group_detr = group_detr
|
|
300
|
+
self.num_queries = num_queries
|
|
301
|
+
self.d_model = d_model
|
|
302
|
+
|
|
303
|
+
self.reference_point_embed = nn.Embedding(self.num_queries * self.group_detr, 6)
|
|
304
|
+
|
|
305
|
+
self.query_feat = nn.Embedding(self.num_queries * self.group_detr, self.d_model)
|
|
306
|
+
|
|
307
|
+
self.class_embed = nn.Linear(self.d_model, self.num_classes)
|
|
308
|
+
self.bbox_embed = LWDETRHead(self.d_model, self.d_model, 6, num_layers=3)
|
|
309
|
+
|
|
310
|
+
self.decoder = LWDETRDecoder(
|
|
311
|
+
num_layers=dec_layers,
|
|
312
|
+
d_model=d_model,
|
|
313
|
+
sa_num_heads=sa_num_heads,
|
|
314
|
+
ca_num_heads=ca_num_heads,
|
|
315
|
+
ff_dim=ff_dim,
|
|
316
|
+
dec_n_points=dec_n_points,
|
|
317
|
+
group_detr=group_detr,
|
|
318
|
+
dropout_prob=dropout_prob,
|
|
319
|
+
bbox_embed=self.bbox_embed,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
self.enc_output = nn.ModuleList([nn.Linear(self.d_model, self.d_model) for _ in range(self.group_detr)])
|
|
323
|
+
self.enc_output_norm = nn.ModuleList([nn.LayerNorm(self.d_model) for _ in range(self.group_detr)])
|
|
324
|
+
|
|
325
|
+
self.enc_out_bbox_embed = nn.ModuleList([
|
|
326
|
+
LWDETRHead(self.d_model, self.d_model, 6, num_layers=3) for _ in range(self.group_detr)
|
|
327
|
+
])
|
|
328
|
+
self.enc_out_class_embed = nn.ModuleList([
|
|
329
|
+
nn.Linear(self.d_model, self.num_classes) for _ in range(self.group_detr)
|
|
330
|
+
])
|
|
331
|
+
|
|
332
|
+
self.postprocessor = LWDETRPostProcessor(
|
|
333
|
+
num_classes=self.num_classes,
|
|
334
|
+
score_thresh=score_thresh,
|
|
335
|
+
iou_thresh=iou_thresh,
|
|
336
|
+
assume_straight_pages=self.assume_straight_pages,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
for n, m in self.named_modules():
|
|
340
|
+
# Don't override the initialization of the backbone
|
|
341
|
+
if n.startswith("feat_extractor."):
|
|
342
|
+
continue
|
|
343
|
+
|
|
344
|
+
if isinstance(m, nn.Linear):
|
|
345
|
+
nn.init.trunc_normal_(m.weight, mean=0.0, std=0.02)
|
|
346
|
+
if m.bias is not None:
|
|
347
|
+
nn.init.zeros_(m.bias)
|
|
348
|
+
elif isinstance(m, nn.Conv2d):
|
|
349
|
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
|
350
|
+
if m.bias is not None:
|
|
351
|
+
nn.init.zeros_(m.bias)
|
|
352
|
+
elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)):
|
|
353
|
+
if hasattr(m, "weight") and m.weight is not None:
|
|
354
|
+
nn.init.ones_(m.weight)
|
|
355
|
+
if hasattr(m, "bias") and m.bias is not None:
|
|
356
|
+
nn.init.zeros_(m.bias)
|
|
357
|
+
elif isinstance(m, nn.Embedding):
|
|
358
|
+
nn.init.normal_(m.weight, std=0.02)
|
|
359
|
+
|
|
360
|
+
if isinstance(m, nn.Linear) and m.out_features == self.num_classes:
|
|
361
|
+
prior_prob = 0.01
|
|
362
|
+
bias_value = -math.log((1 - prior_prob) / prior_prob)
|
|
363
|
+
if m.bias is not None:
|
|
364
|
+
nn.init.constant_(m.bias, bias_value)
|
|
365
|
+
|
|
366
|
+
# Initialize the iterative refinement heads to predict zero deltas (i.e. identity refinement)
|
|
367
|
+
# at the start of training, to stabilize training in the early stages when the encoder proposals are still noisy
|
|
368
|
+
with torch.no_grad():
|
|
369
|
+
for head in [self.bbox_embed, *self.enc_out_bbox_embed]:
|
|
370
|
+
last = head.layers[-1]
|
|
371
|
+
last.weight.zero_()
|
|
372
|
+
last.bias.zero_()
|
|
373
|
+
last.bias[5] = 1.0 # cosθ of the rotation delta -> identity rotation
|
|
374
|
+
|
|
375
|
+
# The reference point embedding acts as a learned delta composed with the encoder proposals
|
|
376
|
+
self.reference_point_embed.weight.zero_()
|
|
377
|
+
self.reference_point_embed.weight[:, 5] = 1.0 # cosθ
|
|
378
|
+
|
|
379
|
+
def from_pretrained(self, path_or_url: str, **kwargs: Any) -> None:
|
|
380
|
+
"""Load pretrained parameters onto the model
|
|
381
|
+
|
|
382
|
+
Args:
|
|
383
|
+
path_or_url: the path or URL to the model parameters (checkpoint)
|
|
384
|
+
**kwargs: additional arguments to be passed to `doctr.models.utils.load_pretrained_params`
|
|
385
|
+
"""
|
|
386
|
+
load_pretrained_params(self, path_or_url, **kwargs)
|
|
387
|
+
|
|
388
|
+
def gen_encoder_output_proposals(
|
|
389
|
+
self, enc_output: torch.Tensor, valid_mask: torch.Tensor, spatial_shapes: list[tuple[int, int]]
|
|
390
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
391
|
+
"""Generate the encoder output proposals from encoded enc_output.
|
|
392
|
+
|
|
393
|
+
Args:
|
|
394
|
+
enc_output: Output of the encoder
|
|
395
|
+
valid_mask: Valid-position mask for `enc_output` (True on valid, non-padded positions)
|
|
396
|
+
spatial_shapes: Spatial shapes of the feature maps
|
|
397
|
+
|
|
398
|
+
Returns:
|
|
399
|
+
A tuple of feature map and bbox prediction.
|
|
400
|
+
- object_query: Object query features. Later used to directly predict a bounding box.
|
|
401
|
+
- output_proposals: Normalized proposals in [0, 1] space.
|
|
402
|
+
Invalid positions (padding or out-of-bounds) are filled with 0.
|
|
403
|
+
- invalid_mask: Boolean mask that is True for invalid positions
|
|
404
|
+
(padded pixels or proposals whose coordinates fall outside (0.01, 0.99)).
|
|
405
|
+
"""
|
|
406
|
+
batch_size = enc_output.shape[0]
|
|
407
|
+
proposals = []
|
|
408
|
+
_cur = 0
|
|
409
|
+
|
|
410
|
+
for level, (height, width) in enumerate(spatial_shapes):
|
|
411
|
+
grid_y, grid_x = torch.meshgrid(
|
|
412
|
+
torch.arange(height, dtype=enc_output.dtype, device=enc_output.device),
|
|
413
|
+
torch.arange(width, dtype=enc_output.dtype, device=enc_output.device),
|
|
414
|
+
indexing="ij",
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
grid = torch.stack([grid_x, grid_y], dim=-1)
|
|
418
|
+
grid = grid.unsqueeze(0).expand(batch_size, -1, -1, -1)
|
|
419
|
+
|
|
420
|
+
scale = torch.tensor(
|
|
421
|
+
[width, height],
|
|
422
|
+
dtype=enc_output.dtype,
|
|
423
|
+
device=enc_output.device,
|
|
424
|
+
).view(1, 1, 1, 2)
|
|
425
|
+
|
|
426
|
+
# Canvas-normalized center coordinates
|
|
427
|
+
grid = (grid + 0.5) / scale
|
|
428
|
+
width_height = torch.ones_like(grid) * 0.05 * (2.0**level)
|
|
429
|
+
sin = torch.zeros_like(grid[..., :1])
|
|
430
|
+
cos = torch.ones_like(grid[..., :1])
|
|
431
|
+
proposal = torch.cat((grid, width_height, sin, cos), dim=-1).view(batch_size, -1, 6)
|
|
432
|
+
proposals.append(proposal)
|
|
433
|
+
_cur += height * width
|
|
434
|
+
|
|
435
|
+
output_proposals = torch.cat(proposals, dim=1)
|
|
436
|
+
|
|
437
|
+
spatial_valid = ((output_proposals[..., :4] > 0.01) & (output_proposals[..., :4] < 0.99)).all(
|
|
438
|
+
dim=-1, keepdim=True
|
|
439
|
+
)
|
|
440
|
+
invalid_mask = ~valid_mask.unsqueeze(-1) | ~spatial_valid
|
|
441
|
+
|
|
442
|
+
output_proposals = output_proposals.masked_fill(invalid_mask, 0.0)
|
|
443
|
+
object_query = enc_output.masked_fill(invalid_mask, 0.0)
|
|
444
|
+
|
|
445
|
+
return object_query, output_proposals, invalid_mask
|
|
446
|
+
|
|
447
|
+
def forward(
|
|
448
|
+
self,
|
|
449
|
+
input: torch.Tensor,
|
|
450
|
+
masks: torch.Tensor | None = None,
|
|
451
|
+
target: list[dict[str, np.ndarray]] | None = None,
|
|
452
|
+
return_model_output: bool = False,
|
|
453
|
+
return_preds: bool = False,
|
|
454
|
+
**kwargs: Any,
|
|
455
|
+
) -> dict[str, Any]:
|
|
456
|
+
feats = self.feat_extractor(input, masks)
|
|
457
|
+
|
|
458
|
+
sources: list[torch.Tensor] = []
|
|
459
|
+
feats_masks: list[torch.Tensor] = []
|
|
460
|
+
|
|
461
|
+
for source, mask in feats:
|
|
462
|
+
sources.append(source)
|
|
463
|
+
feats_masks.append(mask)
|
|
464
|
+
if mask is None: # pragma: no cover
|
|
465
|
+
raise ValueError("No attention mask was provided")
|
|
466
|
+
|
|
467
|
+
if self.training:
|
|
468
|
+
reference_points = self.reference_point_embed.weight
|
|
469
|
+
query_feat = self.query_feat.weight
|
|
470
|
+
else:
|
|
471
|
+
# only use one group in inference
|
|
472
|
+
reference_points = self.reference_point_embed.weight[: self.num_queries]
|
|
473
|
+
query_feat = self.query_feat.weight[: self.num_queries]
|
|
474
|
+
|
|
475
|
+
# Prepare encoder inputs (by flattening)
|
|
476
|
+
source_flatten_list: list[torch.Tensor] = []
|
|
477
|
+
mask_flatten_list: list[torch.Tensor] = []
|
|
478
|
+
spatial_shapes_list: list[tuple[int, int]] = []
|
|
479
|
+
for source, mask in zip(sources, feats_masks):
|
|
480
|
+
batch_size, num_channels, height, width = source.shape
|
|
481
|
+
spatial_shape = (height, width)
|
|
482
|
+
spatial_shapes_list.append(spatial_shape)
|
|
483
|
+
source = source.flatten(2).transpose(1, 2)
|
|
484
|
+
mask = mask.flatten(1)
|
|
485
|
+
source_flatten_list.append(source)
|
|
486
|
+
mask_flatten_list.append(mask)
|
|
487
|
+
source_flatten = torch.cat(source_flatten_list, 1)
|
|
488
|
+
mask_flatten = torch.cat(mask_flatten_list, 1)
|
|
489
|
+
|
|
490
|
+
tgt = query_feat.unsqueeze(0).expand(batch_size, -1, -1)
|
|
491
|
+
reference_points = reference_points.unsqueeze(0).expand(batch_size, -1, -1)
|
|
492
|
+
|
|
493
|
+
object_query_embedding, output_proposals, invalid_mask = self.gen_encoder_output_proposals(
|
|
494
|
+
source_flatten, mask_flatten, spatial_shapes_list
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
group_detr = self.group_detr if self.training else 1
|
|
498
|
+
topk = self.num_queries
|
|
499
|
+
|
|
500
|
+
topk_coords_logits_list: list[torch.Tensor] = []
|
|
501
|
+
|
|
502
|
+
# encoder predictions on the selected top-k proposals, kept undetached for the auxiliary loss
|
|
503
|
+
all_group_enc_logits: list[torch.Tensor] = []
|
|
504
|
+
all_group_enc_coords: list[torch.Tensor] = []
|
|
505
|
+
|
|
506
|
+
for group_id in range(group_detr):
|
|
507
|
+
group_object_query = self.enc_output[group_id](object_query_embedding)
|
|
508
|
+
group_object_query = self.enc_output_norm[group_id](group_object_query)
|
|
509
|
+
|
|
510
|
+
group_enc_outputs_class = self.enc_out_class_embed[group_id](group_object_query)
|
|
511
|
+
|
|
512
|
+
group_enc_outputs_class_masked = group_enc_outputs_class.masked_fill(invalid_mask, float("-inf"))
|
|
513
|
+
|
|
514
|
+
group_delta_bbox = self.enc_out_bbox_embed[group_id](group_object_query)
|
|
515
|
+
group_enc_outputs_coord = refine_obb_boxes(output_proposals, group_delta_bbox)
|
|
516
|
+
|
|
517
|
+
group_topk_proposals = torch.topk(group_enc_outputs_class_masked.max(-1)[0], topk, dim=1)[1]
|
|
518
|
+
|
|
519
|
+
group_topk_coords_logits_undetach = torch.gather(
|
|
520
|
+
group_enc_outputs_coord,
|
|
521
|
+
1,
|
|
522
|
+
group_topk_proposals.unsqueeze(-1).repeat(1, 1, 6),
|
|
523
|
+
)
|
|
524
|
+
# the auxiliary loss supervises only the selected proposals,
|
|
525
|
+
# so gather the matching class logits as well
|
|
526
|
+
group_topk_logits_undetach = torch.gather(
|
|
527
|
+
group_enc_outputs_class,
|
|
528
|
+
1,
|
|
529
|
+
group_topk_proposals.unsqueeze(-1).repeat(1, 1, self.num_classes),
|
|
530
|
+
)
|
|
531
|
+
all_group_enc_logits.append(group_topk_logits_undetach)
|
|
532
|
+
all_group_enc_coords.append(group_topk_coords_logits_undetach)
|
|
533
|
+
|
|
534
|
+
# the decoder consumes detached proposals as initial reference points
|
|
535
|
+
topk_coords_logits_list.append(group_topk_coords_logits_undetach.detach())
|
|
536
|
+
|
|
537
|
+
topk_coords_logits = torch.cat(topk_coords_logits_list, 1)
|
|
538
|
+
reference_points = refine_obb_boxes(topk_coords_logits, reference_points)
|
|
539
|
+
|
|
540
|
+
last_hidden_states, intermediate, intermediate_reference_points = self.decoder(
|
|
541
|
+
inputs_embeds=tgt,
|
|
542
|
+
reference_points=reference_points,
|
|
543
|
+
spatial_shapes_list=spatial_shapes_list,
|
|
544
|
+
encoder_hidden_states=source_flatten,
|
|
545
|
+
encoder_attention_mask=mask_flatten,
|
|
546
|
+
)
|
|
547
|
+
|
|
548
|
+
logits = self.class_embed(last_hidden_states)
|
|
549
|
+
pred_boxes_delta = self.bbox_embed(last_hidden_states)
|
|
550
|
+
pred_boxes = refine_obb_boxes(intermediate_reference_points[-1], pred_boxes_delta)
|
|
551
|
+
|
|
552
|
+
out: dict[str, Any] = {}
|
|
553
|
+
|
|
554
|
+
logits = _bf16_to_float32(logits)
|
|
555
|
+
pred_boxes = _bf16_to_float32(pred_boxes)
|
|
556
|
+
|
|
557
|
+
if self.exportable:
|
|
558
|
+
out["logits"] = logits
|
|
559
|
+
out["pred_boxes"] = pred_boxes
|
|
560
|
+
return out
|
|
561
|
+
|
|
562
|
+
if return_model_output or target is None or return_preds:
|
|
563
|
+
out["logits"] = logits
|
|
564
|
+
|
|
565
|
+
if target is None or return_preds:
|
|
566
|
+
# Disable for torch.compile compatibility
|
|
567
|
+
@torch.compiler.disable
|
|
568
|
+
def _postprocess(logits, boxes):
|
|
569
|
+
return self.postprocessor(logits, boxes)
|
|
570
|
+
|
|
571
|
+
out["preds"] = _postprocess(logits.detach().cpu().numpy(), pred_boxes.detach().cpu().numpy())
|
|
572
|
+
|
|
573
|
+
if target is not None:
|
|
574
|
+
# Build target
|
|
575
|
+
processed_targets = self.build_target(target, self.class_names)
|
|
576
|
+
|
|
577
|
+
# ProbIoU is computed in pixel coordinates
|
|
578
|
+
box_scale = float(max(input.shape[-2], input.shape[-1]))
|
|
579
|
+
|
|
580
|
+
# Every prediction set supervised by the loss, each holding (B, num_queries, ...) tensors:
|
|
581
|
+
# the final decoder layer split by group, the intermediate decoder layers split by group
|
|
582
|
+
# (`intermediate_reference_points[i]` is the reference INPUT to decoder layer i) and the selected
|
|
583
|
+
# encoder proposals of every group. They are all weighted 1 / group_detr, so they can be matched and
|
|
584
|
+
# scored in one batched pass instead of one Hungarian matching per (set, sample).
|
|
585
|
+
logits_sets = list(logits.chunk(group_detr, dim=1))
|
|
586
|
+
boxes_sets = list(pred_boxes.chunk(group_detr, dim=1))
|
|
587
|
+
for i in range(intermediate.shape[0] - 1):
|
|
588
|
+
aux_logits = self.class_embed(intermediate[i])
|
|
589
|
+
aux_boxes_delta = self.bbox_embed(intermediate[i])
|
|
590
|
+
aux_boxes = refine_obb_boxes(intermediate_reference_points[i], aux_boxes_delta)
|
|
591
|
+
logits_sets.extend(aux_logits.chunk(group_detr, dim=1))
|
|
592
|
+
boxes_sets.extend(aux_boxes.chunk(group_detr, dim=1))
|
|
593
|
+
logits_sets.extend(all_group_enc_logits)
|
|
594
|
+
boxes_sets.extend(all_group_enc_coords)
|
|
595
|
+
|
|
596
|
+
out["loss"] = self._compute_sets_loss(
|
|
597
|
+
torch.stack([t.float() for t in logits_sets]),
|
|
598
|
+
torch.stack([t.float() for t in boxes_sets]),
|
|
599
|
+
processed_targets,
|
|
600
|
+
box_scale=box_scale,
|
|
601
|
+
set_weight=1.0 / group_detr,
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
return out
|
|
605
|
+
|
|
606
|
+
def compute_loss(
|
|
607
|
+
self,
|
|
608
|
+
logits: torch.Tensor,
|
|
609
|
+
pred_boxes: torch.Tensor,
|
|
610
|
+
targets: list[dict[str, np.ndarray]],
|
|
611
|
+
cls_loss_weight: float = 1.0,
|
|
612
|
+
l1_loss_weight: float = 5.0,
|
|
613
|
+
iou_loss_weight: float = 2.0,
|
|
614
|
+
box_scale: float = 1024.0,
|
|
615
|
+
) -> torch.Tensor:
|
|
616
|
+
"""Compute the LW-DETR loss for oriented bounding boxes.
|
|
617
|
+
|
|
618
|
+
Predictions are matched one-to-one to the ground truth boxes with Hungarian matching,
|
|
619
|
+
using a cost combining a focal-style classification cost, an L1 box cost
|
|
620
|
+
and a (negated) ProbIoU cost. The loss then consists of:
|
|
621
|
+
|
|
622
|
+
- an IoU-aware binary cross-entropy (IA-BCE) classification loss, as described in the LW-DETR paper,
|
|
623
|
+
where the target of a matched (query, class) pair is `p**alpha * IoU**(1 - alpha)` and the rotated
|
|
624
|
+
ProbIoU is used as IoU measure
|
|
625
|
+
- an L1 regression loss on the normalized (cx, cy, w, h) of the matched pairs
|
|
626
|
+
- a ProbIoU loss (1 - ProbIoU) on the matched oriented boxes, computed in absolute pixel
|
|
627
|
+
coordinates (as in O2-RT-DETR). The box rotation is supervised solely through this term:
|
|
628
|
+
ProbIoU is differentiable w.r.t. the angle even for non-overlapping boxes.
|
|
629
|
+
|
|
630
|
+
All terms are normalized by the number of ground truth boxes in the batch.
|
|
631
|
+
|
|
632
|
+
Args:
|
|
633
|
+
logits: (B, Q, C) tensor containing the predicted class logits for each query
|
|
634
|
+
pred_boxes: (B, Q, 6) tensor containing the predicted boxes (cx, cy, w, h, sinθ, cosθ) for each query
|
|
635
|
+
targets: list of B dictionaries with keys "boxes" ((N, 6) array in OBB format)
|
|
636
|
+
and "labels" ((N,) array of class indices)
|
|
637
|
+
cls_loss_weight: weight of the classification loss
|
|
638
|
+
l1_loss_weight: weight of the L1 box regression loss
|
|
639
|
+
iou_loss_weight: weight of the ProbIoU loss
|
|
640
|
+
box_scale: image size used to rescale normalized boxes to pixel coordinates for ProbIoU computation
|
|
641
|
+
|
|
642
|
+
Returns:
|
|
643
|
+
loss: the computed loss value
|
|
644
|
+
"""
|
|
645
|
+
return self._compute_sets_loss(
|
|
646
|
+
logits.float().unsqueeze(0),
|
|
647
|
+
pred_boxes.float().unsqueeze(0),
|
|
648
|
+
targets,
|
|
649
|
+
cls_loss_weight=cls_loss_weight,
|
|
650
|
+
l1_loss_weight=l1_loss_weight,
|
|
651
|
+
iou_loss_weight=iou_loss_weight,
|
|
652
|
+
box_scale=box_scale,
|
|
653
|
+
)
|
|
654
|
+
|
|
655
|
+
@staticmethod
|
|
656
|
+
def _pad_targets(
|
|
657
|
+
targets: list[dict[str, np.ndarray]], device: torch.device
|
|
658
|
+
) -> tuple[torch.Tensor, torch.Tensor, list[int]]:
|
|
659
|
+
"""Stack the per-sample targets into padded tensors with a single host-to-device transfer.
|
|
660
|
+
|
|
661
|
+
Returns:
|
|
662
|
+
boxes: (B, Nmax, 6) float tensor (zero padded), labels: (B, Nmax) long tensor (zero padded),
|
|
663
|
+
counts: number of real boxes of every sample
|
|
664
|
+
"""
|
|
665
|
+
counts = [int(np.asarray(sample["labels"]).size) for sample in targets]
|
|
666
|
+
n_max = max(max(counts), 1)
|
|
667
|
+
boxes = np.zeros((len(targets), n_max, 6), dtype=np.float32)
|
|
668
|
+
labels = np.zeros((len(targets), n_max), dtype=np.int64)
|
|
669
|
+
for b, (sample, n) in enumerate(zip(targets, counts)):
|
|
670
|
+
if n:
|
|
671
|
+
boxes[b, :n] = np.asarray(sample["boxes"], dtype=np.float32).reshape(-1, 6)
|
|
672
|
+
labels[b, :n] = np.asarray(sample["labels"], dtype=np.int64).reshape(-1)
|
|
673
|
+
packed = torch.from_numpy(np.concatenate([boxes.reshape(len(targets), -1), labels.astype(np.float32)], 1))
|
|
674
|
+
packed = packed.to(device) # one transfer for boxes and labels
|
|
675
|
+
boxes_t = packed[:, : n_max * 6].reshape(len(targets), n_max, 6)
|
|
676
|
+
labels_t = packed[:, n_max * 6 :].long()
|
|
677
|
+
return boxes_t, labels_t, counts
|
|
678
|
+
|
|
679
|
+
def _compute_sets_loss(
|
|
680
|
+
self,
|
|
681
|
+
logits: torch.Tensor,
|
|
682
|
+
pred_boxes: torch.Tensor,
|
|
683
|
+
targets: list[dict[str, np.ndarray]],
|
|
684
|
+
cls_loss_weight: float = 1.0,
|
|
685
|
+
l1_loss_weight: float = 5.0,
|
|
686
|
+
iou_loss_weight: float = 2.0,
|
|
687
|
+
box_scale: float = 1024.0,
|
|
688
|
+
set_weight: float = 1.0,
|
|
689
|
+
) -> torch.Tensor:
|
|
690
|
+
"""Batched version of `compute_loss` over S prediction sets sharing the same targets.
|
|
691
|
+
|
|
692
|
+
The Hungarian costs of every (set, sample) pair are computed on the device in one go and copied to the
|
|
693
|
+
host once; the matched pairs are then scored with a handful of vectorized operations. The result equals
|
|
694
|
+
`set_weight * sum(compute_loss(logits[s], pred_boxes[s], targets) for s in range(S))` up to float
|
|
695
|
+
summation order, without the S * B device synchronizations of the per-set formulation.
|
|
696
|
+
|
|
697
|
+
Args:
|
|
698
|
+
logits: (S, B, Q, C) class logits of every prediction set
|
|
699
|
+
pred_boxes: (S, B, Q, 6) oriented boxes of every prediction set
|
|
700
|
+
targets: list of B dictionaries with keys "boxes" ((N, 6) OBB) and "labels" ((N,) class indices)
|
|
701
|
+
cls_loss_weight: weight of the classification loss
|
|
702
|
+
l1_loss_weight: weight of the L1 box regression loss
|
|
703
|
+
iou_loss_weight: weight of the ProbIoU loss
|
|
704
|
+
box_scale: image size used to rescale normalized boxes to pixel coordinates for ProbIoU computation
|
|
705
|
+
set_weight: factor applied to the sum of the per-set losses
|
|
706
|
+
|
|
707
|
+
Returns:
|
|
708
|
+
the loss value
|
|
709
|
+
"""
|
|
710
|
+
alpha, gamma, eps = 0.25, 2.0, 1e-8
|
|
711
|
+
device = logits.device
|
|
712
|
+
n_sets, batch_size, _num_queries, _num_classes = logits.shape
|
|
713
|
+
|
|
714
|
+
tgt_boxes, tgt_labels, counts = self._pad_targets(targets, device)
|
|
715
|
+
# Number of target boxes in the batch, for loss normalization
|
|
716
|
+
num_boxes = max(sum(counts), 1)
|
|
717
|
+
|
|
718
|
+
prob = logits.sigmoid()
|
|
719
|
+
|
|
720
|
+
# Hungarian matching (one-to-one), independent for every (set, sample) pair but computed together
|
|
721
|
+
with torch.no_grad():
|
|
722
|
+
# Focal-style classification cost, gathered for the (padded) target labels: (S, B, Q, Nmax)
|
|
723
|
+
neg_cost = (1 - alpha) * prob.pow(gamma) * (-(1 - prob + eps).log())
|
|
724
|
+
pos_cost = alpha * (1 - prob).pow(gamma) * (-(prob + eps).log())
|
|
725
|
+
label_idx = tgt_labels[None, :, None, :].expand(n_sets, -1, prob.shape[2], -1)
|
|
726
|
+
cost_class = pos_cost.gather(-1, label_idx) - neg_cost.gather(-1, label_idx)
|
|
727
|
+
|
|
728
|
+
# L1 cost on normalized (cx, cy, w, h)
|
|
729
|
+
cost_bbox = torch.cdist(
|
|
730
|
+
pred_boxes[..., :4].reshape(n_sets * batch_size, -1, 4),
|
|
731
|
+
tgt_boxes[None, :, :, :4].expand(n_sets, -1, -1, -1).reshape(n_sets * batch_size, -1, 4),
|
|
732
|
+
p=1,
|
|
733
|
+
).reshape(n_sets, batch_size, -1, tgt_boxes.shape[1])
|
|
734
|
+
|
|
735
|
+
# Rotated IoU cost, computed in pixel coordinates (also carries the angle signal for the matching)
|
|
736
|
+
cost_iou = -_probiou(
|
|
737
|
+
pred_boxes, tgt_boxes.unsqueeze(0).expand(n_sets, -1, -1, -1), pairwise=True, scale=box_scale
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
cost = (2.0 * cost_class + 5.0 * cost_bbox + 2.0 * cost_iou).cpu().numpy() # the only sync
|
|
741
|
+
|
|
742
|
+
# Solve the (small) assignment problems on the host and gather the matched (set, sample, query, target)
|
|
743
|
+
# quadruplets, then send them back to the device in a single transfer
|
|
744
|
+
matched_set_ids: list[np.ndarray] = []
|
|
745
|
+
matched_sample_ids: list[np.ndarray] = []
|
|
746
|
+
matched_query_ids: list[np.ndarray] = []
|
|
747
|
+
matched_target_ids: list[np.ndarray] = []
|
|
748
|
+
for sample_id, num_targets in enumerate(counts):
|
|
749
|
+
if num_targets == 0:
|
|
750
|
+
continue
|
|
751
|
+
for set_id in range(n_sets):
|
|
752
|
+
query_ids, target_ids = linear_sum_assignment(cost[set_id, sample_id, :, :num_targets])
|
|
753
|
+
matched_set_ids.append(np.full_like(query_ids, set_id))
|
|
754
|
+
matched_sample_ids.append(np.full_like(query_ids, sample_id))
|
|
755
|
+
matched_query_ids.append(query_ids)
|
|
756
|
+
matched_target_ids.append(target_ids)
|
|
757
|
+
if matched_set_ids:
|
|
758
|
+
matched = torch.from_numpy(
|
|
759
|
+
np.stack([
|
|
760
|
+
np.concatenate(ids)
|
|
761
|
+
for ids in (matched_set_ids, matched_sample_ids, matched_query_ids, matched_target_ids)
|
|
762
|
+
])
|
|
763
|
+
).to(device, dtype=torch.long)
|
|
764
|
+
set_ids, sample_ids, query_ids_t, target_ids_t = matched
|
|
765
|
+
else:
|
|
766
|
+
set_ids = sample_ids = query_ids_t = target_ids_t = torch.empty(0, dtype=torch.long, device=device)
|
|
767
|
+
|
|
768
|
+
matched_pred_boxes = pred_boxes[set_ids, sample_ids, query_ids_t]
|
|
769
|
+
matched_tgt_boxes = tgt_boxes[sample_ids, target_ids_t]
|
|
770
|
+
matched_tgt_labels = tgt_labels[sample_ids, target_ids_t]
|
|
771
|
+
|
|
772
|
+
# IoU-aware BCE classification loss (IA-BCE)
|
|
773
|
+
pos_weights = torch.zeros_like(logits)
|
|
774
|
+
neg_weights = prob.pow(gamma)
|
|
775
|
+
if len(set_ids) > 0:
|
|
776
|
+
with torch.no_grad():
|
|
777
|
+
ious = _probiou(matched_pred_boxes, matched_tgt_boxes, scale=box_scale).clamp(min=0.0, max=1.0)
|
|
778
|
+
t = prob[set_ids, sample_ids, query_ids_t, matched_tgt_labels].pow(alpha) * ious.pow(1 - alpha)
|
|
779
|
+
t = t.clamp(min=0.01)
|
|
780
|
+
pos_weights[set_ids, sample_ids, query_ids_t, matched_tgt_labels] = t
|
|
781
|
+
neg_weights[set_ids, sample_ids, query_ids_t, matched_tgt_labels] = 1 - t
|
|
782
|
+
|
|
783
|
+
cls_loss = -(pos_weights * (prob + eps).log() + neg_weights * (1 - prob + eps).log())
|
|
784
|
+
loss = cls_loss_weight * cls_loss.sum() / num_boxes
|
|
785
|
+
|
|
786
|
+
if len(set_ids) > 0:
|
|
787
|
+
# L1 loss on normalized (cx, cy, w, h)
|
|
788
|
+
l1_loss = F.l1_loss(matched_pred_boxes[:, :4], matched_tgt_boxes[:, :4], reduction="sum") / num_boxes
|
|
789
|
+
# ProbIoU loss on the whole oriented box (position, size and rotation), in pixel coordinates
|
|
790
|
+
probiou_loss = (1 - _probiou(matched_pred_boxes, matched_tgt_boxes, scale=box_scale)).sum() / num_boxes
|
|
791
|
+
loss = loss + l1_loss_weight * l1_loss + iou_loss_weight * probiou_loss
|
|
792
|
+
|
|
793
|
+
return loss * set_weight
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def _lw_detr(
|
|
797
|
+
arch: str,
|
|
798
|
+
pretrained: bool,
|
|
799
|
+
backbone_fn: Callable[[bool], nn.Module],
|
|
800
|
+
ignore_keys: list[str] | None = None,
|
|
801
|
+
**kwargs: Any,
|
|
802
|
+
) -> LWDETR:
|
|
803
|
+
# Patch the config
|
|
804
|
+
kwargs["class_names"] = kwargs.get("class_names", default_cfgs[arch].get("class_names", []))
|
|
805
|
+
|
|
806
|
+
_cfg = deepcopy(default_cfgs[arch])
|
|
807
|
+
_cfg["class_names"] = sorted(kwargs["class_names"])
|
|
808
|
+
kwargs.pop("class_names")
|
|
809
|
+
|
|
810
|
+
# Build the feature extractor
|
|
811
|
+
backbone = backbone_fn( # type: ignore[call-arg]
|
|
812
|
+
False,
|
|
813
|
+
include_top=False,
|
|
814
|
+
input_shape=default_cfgs[arch]["input_shape"],
|
|
815
|
+
patch_size=kwargs.pop("patch_size", (16, 16)),
|
|
816
|
+
)
|
|
817
|
+
feat_extractor = LWDETRBackbone(encoder_fn=backbone)
|
|
818
|
+
|
|
819
|
+
# Build the model
|
|
820
|
+
model = LWDETR(
|
|
821
|
+
feat_extractor,
|
|
822
|
+
cfg=_cfg,
|
|
823
|
+
class_names=_cfg["class_names"],
|
|
824
|
+
**kwargs,
|
|
825
|
+
)
|
|
826
|
+
# Load pretrained parameters
|
|
827
|
+
if pretrained:
|
|
828
|
+
# The number of class_names is not the same as the number of classes in the pretrained model =>
|
|
829
|
+
# remove the layer weights
|
|
830
|
+
_ignore_keys = ignore_keys if _cfg["class_names"] != sorted(default_cfgs[arch].get("class_names", [])) else None
|
|
831
|
+
model.from_pretrained(default_cfgs[arch]["url"], ignore_keys=_ignore_keys)
|
|
832
|
+
|
|
833
|
+
return model
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def lw_detr_s(pretrained: bool = False, **kwargs: Any) -> LWDETR:
|
|
837
|
+
"""LW-DETR as described in `"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection"
|
|
838
|
+
<https://arxiv.org/pdf/2406.03459v1>`_.
|
|
839
|
+
|
|
840
|
+
>>> import torch
|
|
841
|
+
>>> from doctr.models import lw_detr_s
|
|
842
|
+
>>> model = lw_detr_s(pretrained=True).eval()
|
|
843
|
+
>>> input_tensor = torch.rand((1, 3, 1024, 1024), dtype=torch.float32)
|
|
844
|
+
>>> out = model(input_tensor)
|
|
845
|
+
|
|
846
|
+
Args:
|
|
847
|
+
pretrained: If True, returns a model pre-trained on our text detection dataset
|
|
848
|
+
**kwargs: keyword arguments of the LinkNet architecture
|
|
849
|
+
|
|
850
|
+
Returns:
|
|
851
|
+
text detection architecture
|
|
852
|
+
"""
|
|
853
|
+
return _lw_detr(
|
|
854
|
+
"lw_detr_s",
|
|
855
|
+
pretrained,
|
|
856
|
+
vit_det_s,
|
|
857
|
+
ignore_keys=[
|
|
858
|
+
"class_embed.weight",
|
|
859
|
+
"class_embed.bias",
|
|
860
|
+
*[f"enc_out_class_embed.{i}.weight" for i in range(kwargs.get("group_detr", 13))],
|
|
861
|
+
*[f"enc_out_class_embed.{i}.bias" for i in range(kwargs.get("group_detr", 13))],
|
|
862
|
+
],
|
|
863
|
+
**kwargs,
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def lw_detr_m(pretrained: bool = False, **kwargs: Any) -> LWDETR:
|
|
868
|
+
"""LW-DETR as described in `"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection"
|
|
869
|
+
<https://arxiv.org/pdf/2406.03459v1>`_.
|
|
870
|
+
|
|
871
|
+
>>> import torch
|
|
872
|
+
>>> from doctr.models import lw_detr_m
|
|
873
|
+
>>> model = lw_detr_m(pretrained=True).eval()
|
|
874
|
+
>>> input_tensor = torch.rand((1, 3, 1024, 1024), dtype=torch.float32)
|
|
875
|
+
>>> out = model(input_tensor)
|
|
876
|
+
|
|
877
|
+
Args:
|
|
878
|
+
pretrained: If True, returns a model pre-trained on our text detection dataset
|
|
879
|
+
**kwargs: keyword arguments of the LinkNet architecture
|
|
880
|
+
|
|
881
|
+
Returns:
|
|
882
|
+
text detection architecture
|
|
883
|
+
"""
|
|
884
|
+
return _lw_detr(
|
|
885
|
+
"lw_detr_m",
|
|
886
|
+
pretrained,
|
|
887
|
+
vit_det_m,
|
|
888
|
+
ignore_keys=[
|
|
889
|
+
"class_embed.weight",
|
|
890
|
+
"class_embed.bias",
|
|
891
|
+
*[f"enc_out_class_embed.{i}.weight" for i in range(kwargs.get("group_detr", 13))],
|
|
892
|
+
*[f"enc_out_class_embed.{i}.bias" for i in range(kwargs.get("group_detr", 13))],
|
|
893
|
+
],
|
|
894
|
+
**kwargs,
|
|
895
|
+
)
|