python-doctr 1.0.0__py3-none-any.whl → 1.1.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 +506 -0
- doctr/contrib/artefacts.py +1 -1
- doctr/contrib/base.py +1 -1
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +5 -3
- doctr/datasets/cord.py +3 -2
- doctr/datasets/datasets/base.py +13 -25
- doctr/datasets/datasets/pytorch.py +15 -5
- doctr/datasets/detection.py +3 -2
- doctr/datasets/doc_artefacts.py +3 -2
- doctr/datasets/funsd.py +3 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +4 -3
- doctr/datasets/ic13.py +5 -3
- doctr/datasets/iiit5k.py +3 -2
- doctr/datasets/iiithws.py +5 -3
- doctr/datasets/imgur5k.py +5 -3
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +5 -3
- doctr/datasets/ocr.py +3 -2
- doctr/datasets/orientation.py +3 -2
- doctr/datasets/recognition.py +3 -2
- doctr/datasets/sroie.py +3 -2
- doctr/datasets/svhn.py +3 -2
- doctr/datasets/svt.py +4 -3
- doctr/datasets/synthtext.py +3 -2
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +15 -6
- doctr/datasets/vocabs.py +3 -1
- doctr/datasets/wildreceipt.py +5 -3
- doctr/file_utils.py +4 -2
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +253 -261
- doctr/io/exporters.py +1275 -0
- doctr/io/html.py +1 -1
- doctr/io/image/base.py +4 -3
- doctr/io/image/pytorch.py +6 -4
- doctr/io/pdf.py +1 -1
- doctr/io/reader.py +1 -1
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +111 -25
- doctr/models/builder.py +533 -62
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +2 -2
- doctr/models/classification/mobilenet/pytorch.py +7 -7
- doctr/models/classification/predictor/pytorch.py +7 -3
- doctr/models/classification/resnet/pytorch.py +6 -6
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +7 -6
- doctr/models/classification/vgg/pytorch.py +4 -3
- doctr/models/classification/vip/layers/pytorch.py +5 -5
- doctr/models/classification/vip/pytorch.py +5 -5
- doctr/models/classification/vit/pytorch.py +4 -4
- 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 +4 -1
- doctr/models/core.py +1 -1
- doctr/models/detection/_utils/base.py +24 -8
- doctr/models/detection/_utils/pytorch.py +1 -1
- doctr/models/detection/core.py +34 -19
- doctr/models/detection/differentiable_binarization/base.py +7 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
- doctr/models/detection/fast/base.py +6 -2
- doctr/models/detection/fast/pytorch.py +4 -4
- doctr/models/detection/linknet/base.py +6 -2
- doctr/models/detection/linknet/pytorch.py +4 -4
- doctr/models/detection/predictor/pytorch.py +4 -3
- doctr/models/detection/zoo.py +3 -3
- doctr/models/factory/hub.py +72 -52
- doctr/models/kie_predictor/base.py +17 -2
- doctr/models/kie_predictor/pytorch.py +42 -11
- 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 +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +140 -4
- doctr/models/modules/transformer/pytorch.py +1 -1
- doctr/models/modules/vision_transformer/pytorch.py +1 -1
- doctr/models/predictor/base.py +138 -16
- doctr/models/predictor/pytorch.py +151 -9
- doctr/models/preprocessor/pytorch.py +78 -23
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/core.py +1 -1
- doctr/models/recognition/crnn/pytorch.py +6 -8
- doctr/models/recognition/master/base.py +1 -1
- doctr/models/recognition/master/pytorch.py +7 -8
- doctr/models/recognition/parseq/base.py +1 -1
- doctr/models/recognition/parseq/pytorch.py +5 -5
- doctr/models/recognition/predictor/_utils.py +1 -1
- doctr/models/recognition/predictor/pytorch.py +2 -2
- doctr/models/recognition/sar/pytorch.py +2 -2
- doctr/models/recognition/utils.py +9 -11
- doctr/models/recognition/viptr/pytorch.py +4 -6
- doctr/models/recognition/vitstr/base.py +1 -1
- doctr/models/recognition/vitstr/pytorch.py +6 -6
- doctr/models/recognition/zoo.py +6 -7
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +316 -16
- doctr/models/zoo.py +91 -3
- doctr/transforms/functional/base.py +3 -2
- doctr/transforms/functional/pytorch.py +1 -1
- doctr/transforms/modules/base.py +248 -83
- doctr/transforms/modules/pytorch.py +213 -74
- doctr/utils/common_types.py +22 -2
- doctr/utils/data.py +5 -4
- doctr/utils/fonts.py +56 -17
- doctr/utils/geometry.py +136 -19
- doctr/utils/metrics.py +351 -19
- doctr/utils/multithreading.py +6 -3
- doctr/utils/reconstitution.py +697 -133
- doctr/utils/repr.py +1 -1
- doctr/utils/visualization.py +63 -4
- doctr/version.py +1 -1
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.0.dist-info/RECORD +0 -149
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
|
@@ -0,0 +1,838 @@
|
|
|
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": None,
|
|
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
|
+
# Main loss from final decoder layer (group DETR: each group is matched independently)
|
|
581
|
+
split_logits = logits.chunk(group_detr, dim=1)
|
|
582
|
+
split_boxes = pred_boxes.chunk(group_detr, dim=1)
|
|
583
|
+
|
|
584
|
+
main_loss: float | torch.Tensor = 0.0
|
|
585
|
+
for g_logits, g_boxes in zip(split_logits, split_boxes):
|
|
586
|
+
main_loss += self.compute_loss(g_logits, g_boxes, processed_targets, box_scale=box_scale)
|
|
587
|
+
loss = main_loss / group_detr
|
|
588
|
+
|
|
589
|
+
# Auxiliary losses from intermediate decoder layers
|
|
590
|
+
# (`intermediate_reference_points[i]` is the reference INPUT to decoder layer i)
|
|
591
|
+
for i in range(intermediate.shape[0] - 1):
|
|
592
|
+
aux_logits = self.class_embed(intermediate[i])
|
|
593
|
+
aux_boxes_delta = self.bbox_embed(intermediate[i])
|
|
594
|
+
aux_boxes = refine_obb_boxes(intermediate_reference_points[i], aux_boxes_delta)
|
|
595
|
+
|
|
596
|
+
split_aux_logits = aux_logits.chunk(group_detr, dim=1)
|
|
597
|
+
split_aux_boxes = aux_boxes.chunk(group_detr, dim=1)
|
|
598
|
+
|
|
599
|
+
aux_loss: float | torch.Tensor = 0.0
|
|
600
|
+
for g_logits, g_boxes in zip(split_aux_logits, split_aux_boxes):
|
|
601
|
+
aux_loss += self.compute_loss(g_logits, g_boxes, processed_targets, box_scale=box_scale)
|
|
602
|
+
loss += aux_loss / group_detr
|
|
603
|
+
|
|
604
|
+
# Auxiliary losses for the selected encoder proposals
|
|
605
|
+
enc_loss: float | torch.Tensor = 0.0
|
|
606
|
+
for group_logits, group_coords in zip(all_group_enc_logits, all_group_enc_coords):
|
|
607
|
+
enc_loss += self.compute_loss(group_logits, group_coords, processed_targets, box_scale=box_scale)
|
|
608
|
+
loss += enc_loss / group_detr
|
|
609
|
+
|
|
610
|
+
out["loss"] = loss
|
|
611
|
+
|
|
612
|
+
return out
|
|
613
|
+
|
|
614
|
+
def compute_loss(
|
|
615
|
+
self,
|
|
616
|
+
logits: torch.Tensor,
|
|
617
|
+
pred_boxes: torch.Tensor,
|
|
618
|
+
targets: list[dict[str, np.ndarray]],
|
|
619
|
+
cls_loss_weight: float = 1.0,
|
|
620
|
+
l1_loss_weight: float = 5.0,
|
|
621
|
+
iou_loss_weight: float = 2.0,
|
|
622
|
+
box_scale: float = 1024.0,
|
|
623
|
+
) -> torch.Tensor:
|
|
624
|
+
"""Compute the LW-DETR loss for oriented bounding boxes.
|
|
625
|
+
|
|
626
|
+
Predictions are matched one-to-one to the ground truth boxes with Hungarian matching,
|
|
627
|
+
using a cost combining a focal-style classification cost, an L1 box cost
|
|
628
|
+
and a (negated) ProbIoU cost. The loss then consists of:
|
|
629
|
+
|
|
630
|
+
- an IoU-aware binary cross-entropy (IA-BCE) classification loss, as described in the LW-DETR paper,
|
|
631
|
+
where the target of a matched (query, class) pair is `p**alpha * IoU**(1 - alpha)` and the rotated
|
|
632
|
+
ProbIoU is used as IoU measure
|
|
633
|
+
- an L1 regression loss on the normalized (cx, cy, w, h) of the matched pairs
|
|
634
|
+
- a ProbIoU loss (1 - ProbIoU) on the matched oriented boxes, computed in absolute pixel
|
|
635
|
+
coordinates (as in O2-RT-DETR). The box rotation is supervised solely through this term:
|
|
636
|
+
ProbIoU is differentiable w.r.t. the angle even for non-overlapping boxes.
|
|
637
|
+
|
|
638
|
+
All terms are normalized by the number of ground truth boxes in the batch.
|
|
639
|
+
|
|
640
|
+
Args:
|
|
641
|
+
logits: (B, Q, C) tensor containing the predicted class logits for each query
|
|
642
|
+
pred_boxes: (B, Q, 6) tensor containing the predicted boxes (cx, cy, w, h, sinθ, cosθ) for each query
|
|
643
|
+
targets: list of B dictionaries with keys "boxes" ((N, 6) array in OBB format)
|
|
644
|
+
and "labels" ((N,) array of class indices)
|
|
645
|
+
cls_loss_weight: weight of the classification loss
|
|
646
|
+
l1_loss_weight: weight of the L1 box regression loss
|
|
647
|
+
iou_loss_weight: weight of the ProbIoU loss
|
|
648
|
+
box_scale: image size used to rescale normalized boxes to pixel coordinates for ProbIoU computation
|
|
649
|
+
|
|
650
|
+
Returns:
|
|
651
|
+
loss: the computed loss value
|
|
652
|
+
"""
|
|
653
|
+
alpha, gamma, eps = 0.25, 2.0, 1e-8
|
|
654
|
+
# AMP safe-guard
|
|
655
|
+
logits = logits.float()
|
|
656
|
+
pred_boxes = pred_boxes.float()
|
|
657
|
+
device = logits.device
|
|
658
|
+
batch_size = logits.shape[0]
|
|
659
|
+
|
|
660
|
+
tgt_boxes_list: list[torch.Tensor] = []
|
|
661
|
+
tgt_labels_list: list[torch.Tensor] = []
|
|
662
|
+
for sample in targets:
|
|
663
|
+
tgt_boxes_list.append(
|
|
664
|
+
torch.as_tensor(sample["boxes"], device=device, dtype=pred_boxes.dtype).reshape(-1, 6)
|
|
665
|
+
)
|
|
666
|
+
tgt_labels_list.append(torch.as_tensor(sample["labels"], device=device, dtype=torch.long).reshape(-1))
|
|
667
|
+
|
|
668
|
+
# Number of target boxes in the batch, for loss normalization
|
|
669
|
+
num_boxes = max(sum(int(labels.numel()) for labels in tgt_labels_list), 1)
|
|
670
|
+
|
|
671
|
+
# Hungarian matching (one-to-one), performed independently for each sample
|
|
672
|
+
indices: list[tuple[torch.Tensor, torch.Tensor]] = []
|
|
673
|
+
with torch.no_grad():
|
|
674
|
+
prob = logits.sigmoid()
|
|
675
|
+
for b in range(batch_size):
|
|
676
|
+
tgt_boxes, tgt_labels = tgt_boxes_list[b], tgt_labels_list[b]
|
|
677
|
+
if tgt_labels.numel() == 0:
|
|
678
|
+
empty = torch.empty(0, dtype=torch.long, device=device)
|
|
679
|
+
indices.append((empty, empty))
|
|
680
|
+
continue
|
|
681
|
+
|
|
682
|
+
out_prob = prob[b]
|
|
683
|
+
out_boxes = pred_boxes[b]
|
|
684
|
+
|
|
685
|
+
# Focal-style classification cost
|
|
686
|
+
neg_cost = (1 - alpha) * out_prob.pow(gamma) * (-(1 - out_prob + eps).log())
|
|
687
|
+
pos_cost = alpha * (1 - out_prob).pow(gamma) * (-(out_prob + eps).log())
|
|
688
|
+
cost_class = pos_cost[:, tgt_labels] - neg_cost[:, tgt_labels]
|
|
689
|
+
|
|
690
|
+
# L1 cost on normalized (cx, cy, w, h)
|
|
691
|
+
cost_bbox = torch.cdist(out_boxes[:, :4].float(), tgt_boxes[:, :4].float(), p=1)
|
|
692
|
+
|
|
693
|
+
# Rotated IoU cost, computed in pixel coordinates
|
|
694
|
+
# this term also carries the angle signal for the matching
|
|
695
|
+
cost_iou = -_probiou(out_boxes, tgt_boxes, pairwise=True, scale=box_scale)
|
|
696
|
+
|
|
697
|
+
cost = 2.0 * cost_class + 5.0 * cost_bbox + 2.0 * cost_iou
|
|
698
|
+
|
|
699
|
+
query_idx, tgt_idx = linear_sum_assignment(cost.detach().cpu().numpy())
|
|
700
|
+
indices.append((
|
|
701
|
+
torch.as_tensor(query_idx, dtype=torch.long, device=device),
|
|
702
|
+
torch.as_tensor(tgt_idx, dtype=torch.long, device=device),
|
|
703
|
+
))
|
|
704
|
+
|
|
705
|
+
# Flatten the matched pairs across the batch
|
|
706
|
+
batch_idx = torch.cat([torch.full_like(src, b) for b, (src, _) in enumerate(indices)])
|
|
707
|
+
query_idx = torch.cat([src for (src, _) in indices])
|
|
708
|
+
matched_tgt_boxes = torch.cat([tgt_boxes_list[b][tgt] for b, (_, tgt) in enumerate(indices)])
|
|
709
|
+
matched_tgt_labels = torch.cat([tgt_labels_list[b][tgt] for b, (_, tgt) in enumerate(indices)])
|
|
710
|
+
matched_pred_boxes = pred_boxes[batch_idx, query_idx]
|
|
711
|
+
|
|
712
|
+
prob = logits.sigmoid()
|
|
713
|
+
|
|
714
|
+
# IoU-aware BCE classification loss (IA-BCE)
|
|
715
|
+
pos_weights = torch.zeros_like(logits)
|
|
716
|
+
neg_weights = prob.pow(gamma)
|
|
717
|
+
if len(batch_idx) > 0:
|
|
718
|
+
with torch.no_grad():
|
|
719
|
+
ious = _probiou(matched_pred_boxes, matched_tgt_boxes, scale=box_scale).clamp(min=0.0, max=1.0)
|
|
720
|
+
t = prob[batch_idx, query_idx, matched_tgt_labels].pow(alpha) * ious.pow(1 - alpha)
|
|
721
|
+
t = t.clamp(min=0.01)
|
|
722
|
+
pos_weights[batch_idx, query_idx, matched_tgt_labels] = t
|
|
723
|
+
neg_weights[batch_idx, query_idx, matched_tgt_labels] = 1 - t
|
|
724
|
+
|
|
725
|
+
cls_loss = -(pos_weights * (prob + eps).log() + neg_weights * (1 - prob + eps).log())
|
|
726
|
+
loss = cls_loss_weight * cls_loss.sum() / num_boxes
|
|
727
|
+
|
|
728
|
+
if len(batch_idx) == 0:
|
|
729
|
+
return loss
|
|
730
|
+
|
|
731
|
+
# L1 loss on normalized (cx, cy, w, h)
|
|
732
|
+
l1_loss = F.l1_loss(matched_pred_boxes[:, :4], matched_tgt_boxes[:, :4], reduction="sum") / num_boxes
|
|
733
|
+
# ProbIoU loss on the whole oriented box (position, size and rotation), in pixel coordinates
|
|
734
|
+
probiou_loss = (1 - _probiou(matched_pred_boxes, matched_tgt_boxes, scale=box_scale)).sum() / num_boxes
|
|
735
|
+
|
|
736
|
+
return loss + l1_loss_weight * l1_loss + iou_loss_weight * probiou_loss
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def _lw_detr(
|
|
740
|
+
arch: str,
|
|
741
|
+
pretrained: bool,
|
|
742
|
+
backbone_fn: Callable[[bool], nn.Module],
|
|
743
|
+
ignore_keys: list[str] | None = None,
|
|
744
|
+
**kwargs: Any,
|
|
745
|
+
) -> LWDETR:
|
|
746
|
+
# Patch the config
|
|
747
|
+
kwargs["class_names"] = kwargs.get("class_names", default_cfgs[arch].get("class_names", []))
|
|
748
|
+
|
|
749
|
+
_cfg = deepcopy(default_cfgs[arch])
|
|
750
|
+
_cfg["class_names"] = sorted(kwargs["class_names"])
|
|
751
|
+
kwargs.pop("class_names")
|
|
752
|
+
|
|
753
|
+
# Build the feature extractor
|
|
754
|
+
backbone = backbone_fn( # type: ignore[call-arg]
|
|
755
|
+
False,
|
|
756
|
+
include_top=False,
|
|
757
|
+
input_shape=default_cfgs[arch]["input_shape"],
|
|
758
|
+
patch_size=kwargs.pop("patch_size", (16, 16)),
|
|
759
|
+
)
|
|
760
|
+
feat_extractor = LWDETRBackbone(encoder_fn=backbone)
|
|
761
|
+
|
|
762
|
+
# Build the model
|
|
763
|
+
model = LWDETR(
|
|
764
|
+
feat_extractor,
|
|
765
|
+
cfg=_cfg,
|
|
766
|
+
class_names=_cfg["class_names"],
|
|
767
|
+
**kwargs,
|
|
768
|
+
)
|
|
769
|
+
# Load pretrained parameters
|
|
770
|
+
if pretrained:
|
|
771
|
+
# The number of class_names is not the same as the number of classes in the pretrained model =>
|
|
772
|
+
# remove the layer weights
|
|
773
|
+
_ignore_keys = ignore_keys if _cfg["class_names"] != sorted(default_cfgs[arch].get("class_names", [])) else None
|
|
774
|
+
model.from_pretrained(default_cfgs[arch]["url"], ignore_keys=_ignore_keys)
|
|
775
|
+
|
|
776
|
+
return model
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def lw_detr_s(pretrained: bool = False, **kwargs: Any) -> LWDETR:
|
|
780
|
+
"""LW-DETR as described in `"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection"
|
|
781
|
+
<https://arxiv.org/pdf/2406.03459v1>`_.
|
|
782
|
+
|
|
783
|
+
>>> import torch
|
|
784
|
+
>>> from doctr.models import lw_detr_s
|
|
785
|
+
>>> model = lw_detr_s(pretrained=True).eval()
|
|
786
|
+
>>> input_tensor = torch.rand((1, 3, 1024, 1024), dtype=torch.float32)
|
|
787
|
+
>>> out = model(input_tensor)
|
|
788
|
+
|
|
789
|
+
Args:
|
|
790
|
+
pretrained: If True, returns a model pre-trained on our text detection dataset
|
|
791
|
+
**kwargs: keyword arguments of the LinkNet architecture
|
|
792
|
+
|
|
793
|
+
Returns:
|
|
794
|
+
text detection architecture
|
|
795
|
+
"""
|
|
796
|
+
return _lw_detr(
|
|
797
|
+
"lw_detr_s",
|
|
798
|
+
pretrained,
|
|
799
|
+
vit_det_s,
|
|
800
|
+
ignore_keys=[
|
|
801
|
+
"class_embed.weight",
|
|
802
|
+
"class_embed.bias",
|
|
803
|
+
*[f"enc_out_class_embed.{i}.weight" for i in range(kwargs.get("group_detr", 13))],
|
|
804
|
+
*[f"enc_out_class_embed.{i}.bias" for i in range(kwargs.get("group_detr", 13))],
|
|
805
|
+
],
|
|
806
|
+
**kwargs,
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def lw_detr_m(pretrained: bool = False, **kwargs: Any) -> LWDETR:
|
|
811
|
+
"""LW-DETR as described in `"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection"
|
|
812
|
+
<https://arxiv.org/pdf/2406.03459v1>`_.
|
|
813
|
+
|
|
814
|
+
>>> import torch
|
|
815
|
+
>>> from doctr.models import lw_detr_m
|
|
816
|
+
>>> model = lw_detr_m(pretrained=True).eval()
|
|
817
|
+
>>> input_tensor = torch.rand((1, 3, 1024, 1024), dtype=torch.float32)
|
|
818
|
+
>>> out = model(input_tensor)
|
|
819
|
+
|
|
820
|
+
Args:
|
|
821
|
+
pretrained: If True, returns a model pre-trained on our text detection dataset
|
|
822
|
+
**kwargs: keyword arguments of the LinkNet architecture
|
|
823
|
+
|
|
824
|
+
Returns:
|
|
825
|
+
text detection architecture
|
|
826
|
+
"""
|
|
827
|
+
return _lw_detr(
|
|
828
|
+
"lw_detr_m",
|
|
829
|
+
pretrained,
|
|
830
|
+
vit_det_m,
|
|
831
|
+
ignore_keys=[
|
|
832
|
+
"class_embed.weight",
|
|
833
|
+
"class_embed.bias",
|
|
834
|
+
*[f"enc_out_class_embed.{i}.weight" for i in range(kwargs.get("group_detr", 13))],
|
|
835
|
+
*[f"enc_out_class_embed.{i}.bias" for i in range(kwargs.get("group_detr", 13))],
|
|
836
|
+
],
|
|
837
|
+
**kwargs,
|
|
838
|
+
)
|