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,202 @@
|
|
|
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
|
+
# Credits: architecture adapted from "Rewrite the Stars" (https://github.com/ma-xu/Rewrite-the-Stars) as
|
|
7
|
+
# used by TableCenterNet (https://github.com/dreamy-xay/TableCenterNet).
|
|
8
|
+
|
|
9
|
+
from copy import deepcopy
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
from torch import nn
|
|
14
|
+
from torch.nn.init import trunc_normal_
|
|
15
|
+
|
|
16
|
+
from doctr.datasets import VOCABS
|
|
17
|
+
|
|
18
|
+
from ...modules.layers import DropPath
|
|
19
|
+
from ...utils import load_pretrained_params
|
|
20
|
+
|
|
21
|
+
__all__ = ["StarNet", "starnet_s3"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
default_cfgs: dict[str, dict[str, Any]] = {
|
|
25
|
+
"starnet_s3": {
|
|
26
|
+
"mean": (0.694, 0.695, 0.693),
|
|
27
|
+
"std": (0.299, 0.296, 0.301),
|
|
28
|
+
"input_shape": (3, 32, 32),
|
|
29
|
+
"classes": list(VOCABS["french"]),
|
|
30
|
+
"url": "https://github.com/mindee/doctr/releases/download/v1.0.1/starnet_s3-a413415c.pt",
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ConvBN(nn.Sequential):
|
|
36
|
+
"""A convolution optionally followed by batch-norm (the conv keeps its bias, as in the reference)."""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
in_planes: int,
|
|
41
|
+
out_planes: int,
|
|
42
|
+
kernel_size: int = 1,
|
|
43
|
+
stride: int = 1,
|
|
44
|
+
padding: int = 0,
|
|
45
|
+
dilation: int = 1,
|
|
46
|
+
groups: int = 1,
|
|
47
|
+
with_bn: bool = True,
|
|
48
|
+
):
|
|
49
|
+
super().__init__()
|
|
50
|
+
self.add_module("conv", nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, dilation, groups))
|
|
51
|
+
if with_bn:
|
|
52
|
+
bn = nn.BatchNorm2d(out_planes, momentum=0.1)
|
|
53
|
+
nn.init.constant_(bn.weight, 1)
|
|
54
|
+
nn.init.constant_(bn.bias, 0)
|
|
55
|
+
self.add_module("bn", bn)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Block(nn.Module):
|
|
59
|
+
"""StarNet block: depth-wise conv, the element-wise "star" multiplication of two linear branches,
|
|
60
|
+
a projection and a residual connection."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, dim: int, mlp_ratio: int = 4, drop_path: float = 0.0):
|
|
63
|
+
super().__init__()
|
|
64
|
+
self.dwconv = ConvBN(dim, dim, 7, 1, 3, groups=dim, with_bn=True)
|
|
65
|
+
self.f1 = ConvBN(dim, mlp_ratio * dim, 1, with_bn=False)
|
|
66
|
+
self.f2 = ConvBN(dim, mlp_ratio * dim, 1, with_bn=False)
|
|
67
|
+
self.g = ConvBN(mlp_ratio * dim, dim, 1, with_bn=True)
|
|
68
|
+
self.dwconv2 = ConvBN(dim, dim, 7, 1, 3, groups=dim, with_bn=False)
|
|
69
|
+
self.act = nn.ReLU6()
|
|
70
|
+
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
|
71
|
+
|
|
72
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
73
|
+
identity = x
|
|
74
|
+
x = self.dwconv(x)
|
|
75
|
+
x1, x2 = self.f1(x), self.f2(x)
|
|
76
|
+
x = self.act(x1) * x2
|
|
77
|
+
x = self.dwconv2(self.g(x))
|
|
78
|
+
return identity + self.drop_path(x)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class StarNet(nn.Sequential):
|
|
82
|
+
"""Implements the StarNet architecture from `"Rewrite the Stars" <https://arxiv.org/abs/2403.19967>`_.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
base_dim: channel width of the first stage (doubles every stage)
|
|
86
|
+
depths: number of blocks in each of the four stages
|
|
87
|
+
mlp_ratio: expansion ratio of the star-multiplication branches
|
|
88
|
+
drop_path_rate: maximum stochastic-depth rate (linearly scaled across blocks)
|
|
89
|
+
stem_dim: number of channels produced by the stem
|
|
90
|
+
num_classes: number of output classes of the classification head
|
|
91
|
+
include_top: whether to add the classification head
|
|
92
|
+
cfg: the configuration dict of the model
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(
|
|
96
|
+
self,
|
|
97
|
+
base_dim: int = 32,
|
|
98
|
+
depths: tuple[int, int, int, int] = (2, 2, 8, 4),
|
|
99
|
+
mlp_ratio: int = 4,
|
|
100
|
+
drop_path_rate: float = 0.0,
|
|
101
|
+
stem_dim: int = 32,
|
|
102
|
+
num_classes: int = 1000,
|
|
103
|
+
include_top: bool = True,
|
|
104
|
+
cfg: dict[str, Any] | None = None,
|
|
105
|
+
) -> None:
|
|
106
|
+
stem = nn.Sequential(ConvBN(3, stem_dim, kernel_size=3, stride=2, padding=1), nn.ReLU6())
|
|
107
|
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
|
|
108
|
+
|
|
109
|
+
channels = [stem_dim]
|
|
110
|
+
stages: list[nn.Module] = []
|
|
111
|
+
in_channel = stem_dim
|
|
112
|
+
cur = 0
|
|
113
|
+
for i_layer, depth in enumerate(depths):
|
|
114
|
+
embed_dim = base_dim * 2**i_layer
|
|
115
|
+
channels.append(embed_dim)
|
|
116
|
+
down_sampler = ConvBN(in_channel, embed_dim, 3, 2, 1)
|
|
117
|
+
in_channel = embed_dim
|
|
118
|
+
blocks = [Block(in_channel, mlp_ratio, dpr[cur + i]) for i in range(depth)]
|
|
119
|
+
cur += depth
|
|
120
|
+
stages.append(nn.Sequential(down_sampler, *blocks))
|
|
121
|
+
|
|
122
|
+
_layers: list[nn.Module] = [stem, *stages]
|
|
123
|
+
if include_top:
|
|
124
|
+
_layers.append(
|
|
125
|
+
nn.Sequential(
|
|
126
|
+
nn.BatchNorm2d(in_channel, momentum=0.1),
|
|
127
|
+
nn.AdaptiveAvgPool2d(1),
|
|
128
|
+
nn.Flatten(1),
|
|
129
|
+
nn.Linear(in_channel, num_classes),
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
super().__init__(*_layers)
|
|
134
|
+
self.channels = channels # [stem_dim, base_dim, base_dim*2, base_dim*4, base_dim*8]
|
|
135
|
+
self.cfg = cfg
|
|
136
|
+
|
|
137
|
+
self.apply(self._init_weights)
|
|
138
|
+
|
|
139
|
+
@staticmethod
|
|
140
|
+
def _init_weights(m: nn.Module) -> None:
|
|
141
|
+
if isinstance(m, (nn.Linear, nn.Conv2d)):
|
|
142
|
+
trunc_normal_(m.weight, std=0.02)
|
|
143
|
+
if m.bias is not None:
|
|
144
|
+
nn.init.constant_(m.bias, 0)
|
|
145
|
+
elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)):
|
|
146
|
+
nn.init.constant_(m.bias, 0)
|
|
147
|
+
nn.init.constant_(m.weight, 1.0)
|
|
148
|
+
|
|
149
|
+
def from_pretrained(self, path_or_url: str, **kwargs: Any) -> None:
|
|
150
|
+
"""Load pretrained parameters onto the model
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
path_or_url: the path or URL to the model parameters (checkpoint)
|
|
154
|
+
**kwargs: additional arguments to be passed to `doctr.models.utils.load_pretrained_params`
|
|
155
|
+
"""
|
|
156
|
+
load_pretrained_params(self, path_or_url, **kwargs)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _starnet(
|
|
160
|
+
arch: str,
|
|
161
|
+
pretrained: bool,
|
|
162
|
+
ignore_keys: list[str] | None = None,
|
|
163
|
+
**kwargs: Any,
|
|
164
|
+
) -> StarNet:
|
|
165
|
+
kwargs["num_classes"] = kwargs.get("num_classes", len(default_cfgs[arch]["classes"]))
|
|
166
|
+
kwargs["classes"] = kwargs.get("classes", default_cfgs[arch]["classes"])
|
|
167
|
+
|
|
168
|
+
_cfg = deepcopy(default_cfgs[arch])
|
|
169
|
+
_cfg["num_classes"] = kwargs["num_classes"]
|
|
170
|
+
_cfg["classes"] = kwargs["classes"]
|
|
171
|
+
kwargs.pop("classes")
|
|
172
|
+
|
|
173
|
+
# Build the model
|
|
174
|
+
model = StarNet(**kwargs)
|
|
175
|
+
# Load pretrained parameters
|
|
176
|
+
if pretrained:
|
|
177
|
+
# The number of classes is not the same as the number of classes in the pretrained model =>
|
|
178
|
+
# remove the last layer weights
|
|
179
|
+
_ignore_keys = ignore_keys if kwargs["num_classes"] != len(default_cfgs[arch]["classes"]) else None
|
|
180
|
+
model.from_pretrained(default_cfgs[arch]["url"], ignore_keys=_ignore_keys)
|
|
181
|
+
|
|
182
|
+
model.cfg = _cfg
|
|
183
|
+
|
|
184
|
+
return model
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def starnet_s3(pretrained: bool = False, **kwargs: Any) -> StarNet:
|
|
188
|
+
"""StarNet-S3 from `"Rewrite the Stars" <https://arxiv.org/abs/2403.19967>`_.
|
|
189
|
+
|
|
190
|
+
>>> import torch
|
|
191
|
+
>>> from doctr.models import starnet_s3
|
|
192
|
+
>>> model = starnet_s3(pretrained=False)
|
|
193
|
+
>>> out = model(torch.rand((1, 3, 32, 32), dtype=torch.float32))
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
pretrained: boolean, True if model is pretrained
|
|
197
|
+
**kwargs: keyword arguments of the StarNet architecture
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
A StarNet-S3 model
|
|
201
|
+
"""
|
|
202
|
+
return _starnet("starnet_s3", pretrained, ignore_keys=["5.3.weight", "5.3.bias"], **kwargs)
|
|
@@ -14,7 +14,7 @@ from doctr.datasets import VOCABS
|
|
|
14
14
|
from ...modules.layers import FASTConvLayer
|
|
15
15
|
from ...utils import conv_sequence_pt, load_pretrained_params
|
|
16
16
|
|
|
17
|
-
__all__ = ["textnet_tiny", "textnet_small", "textnet_base"]
|
|
17
|
+
__all__ = ["TextNet", "textnet_tiny", "textnet_small", "textnet_base"]
|
|
18
18
|
|
|
19
19
|
default_cfgs: dict[str, dict[str, Any]] = {
|
|
20
20
|
"textnet_tiny": {
|
|
@@ -48,6 +48,7 @@ class TextNet(nn.Sequential):
|
|
|
48
48
|
|
|
49
49
|
Args:
|
|
50
50
|
stages (list[dict[str, list[int]]]): list of dictionaries containing the parameters of each stage.
|
|
51
|
+
input_shape (tuple[int, int, int], optional): Input shape of the model. Defaults to (3, 32, 32).
|
|
51
52
|
include_top (bool, optional): Whether to include the classifier head. Defaults to True.
|
|
52
53
|
num_classes (int, optional): Number of output classes. Defaults to 1000.
|
|
53
54
|
cfg (dict[str, Any], optional): Additional configuration. Defaults to None.
|
|
@@ -63,7 +64,7 @@ class TextNet(nn.Sequential):
|
|
|
63
64
|
) -> None:
|
|
64
65
|
_layers: list[nn.Module] = [
|
|
65
66
|
*conv_sequence_pt(
|
|
66
|
-
in_channels=3, out_channels=64,
|
|
67
|
+
in_channels=3, out_channels=64, act=True, bn=True, kernel_size=3, stride=2, padding=(1, 1)
|
|
67
68
|
),
|
|
68
69
|
*[
|
|
69
70
|
nn.Sequential(*[
|
|
@@ -143,7 +144,7 @@ def textnet_tiny(pretrained: bool = False, **kwargs: Any) -> TextNet:
|
|
|
143
144
|
>>> out = model(input_tensor)
|
|
144
145
|
|
|
145
146
|
Args:
|
|
146
|
-
pretrained:
|
|
147
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
147
148
|
**kwargs: keyword arguments of the TextNet architecture
|
|
148
149
|
|
|
149
150
|
Returns:
|
|
@@ -190,7 +191,7 @@ def textnet_small(pretrained: bool = False, **kwargs: Any) -> TextNet:
|
|
|
190
191
|
>>> out = model(input_tensor)
|
|
191
192
|
|
|
192
193
|
Args:
|
|
193
|
-
pretrained:
|
|
194
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
194
195
|
**kwargs: keyword arguments of the TextNet architecture
|
|
195
196
|
|
|
196
197
|
Returns:
|
|
@@ -237,7 +238,7 @@ def textnet_base(pretrained: bool = False, **kwargs: Any) -> TextNet:
|
|
|
237
238
|
>>> out = model(input_tensor)
|
|
238
239
|
|
|
239
240
|
Args:
|
|
240
|
-
pretrained:
|
|
241
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
241
242
|
**kwargs: keyword arguments of the TextNet architecture
|
|
242
243
|
|
|
243
244
|
Returns:
|
|
@@ -9,12 +9,13 @@ from typing import Any
|
|
|
9
9
|
|
|
10
10
|
from torch import nn
|
|
11
11
|
from torchvision.models import vgg as tv_vgg
|
|
12
|
+
from torchvision.models.vgg import VGG
|
|
12
13
|
|
|
13
14
|
from doctr.datasets import VOCABS
|
|
14
15
|
|
|
15
16
|
from ...utils import load_pretrained_params
|
|
16
17
|
|
|
17
|
-
__all__ = ["vgg16_bn_r"]
|
|
18
|
+
__all__ = ["VGG", "vgg16_bn_r"]
|
|
18
19
|
|
|
19
20
|
|
|
20
21
|
default_cfgs: dict[str, dict[str, Any]] = {
|
|
@@ -92,7 +93,7 @@ def vgg16_bn_r(pretrained: bool = False, **kwargs: Any) -> tv_vgg.VGG:
|
|
|
92
93
|
>>> out = model(input_tensor)
|
|
93
94
|
|
|
94
95
|
Args:
|
|
95
|
-
pretrained
|
|
96
|
+
pretrained: If True, returns a model pre-trained on ImageNet
|
|
96
97
|
**kwargs: keyword arguments of the VGG architecture
|
|
97
98
|
|
|
98
99
|
Returns:
|
|
@@ -63,11 +63,11 @@ class PatchEmbed(nn.Module):
|
|
|
63
63
|
self.embed_dim = embed_dim
|
|
64
64
|
self.proj = nn.Sequential(
|
|
65
65
|
*conv_sequence_pt(
|
|
66
|
-
in_channels, embed_dim // 2, kernel_size=3, stride=2, padding=1, bias=False, bn=True,
|
|
66
|
+
in_channels, embed_dim // 2, kernel_size=3, stride=2, padding=1, bias=False, bn=True, act=False
|
|
67
67
|
),
|
|
68
68
|
nn.GELU(),
|
|
69
69
|
*conv_sequence_pt(
|
|
70
|
-
embed_dim // 2, embed_dim, kernel_size=3, stride=2, padding=1, bias=False, bn=True,
|
|
70
|
+
embed_dim // 2, embed_dim, kernel_size=3, stride=2, padding=1, bias=False, bn=True, act=False
|
|
71
71
|
),
|
|
72
72
|
nn.GELU(),
|
|
73
73
|
)
|
|
@@ -240,10 +240,10 @@ class OverlappedSpatialReductionAttention(nn.Module):
|
|
|
240
240
|
groups=dim,
|
|
241
241
|
bias=False,
|
|
242
242
|
bn=True,
|
|
243
|
-
|
|
243
|
+
act=False,
|
|
244
244
|
),
|
|
245
245
|
nn.GELU(),
|
|
246
|
-
*conv_sequence_pt(dim, dim, kernel_size=1, groups=dim, bias=False, bn=True,
|
|
246
|
+
*conv_sequence_pt(dim, dim, kernel_size=1, groups=dim, bias=False, bn=True, act=False),
|
|
247
247
|
)
|
|
248
248
|
else:
|
|
249
249
|
self.sr = nn.Identity() # type: ignore[assignment]
|
|
@@ -23,7 +23,7 @@ from .layers import (
|
|
|
23
23
|
SqueezeLayer,
|
|
24
24
|
)
|
|
25
25
|
|
|
26
|
-
__all__ = ["vip_tiny", "vip_base"]
|
|
26
|
+
__all__ = ["VIPNet", "vip_tiny", "vip_base"]
|
|
27
27
|
|
|
28
28
|
default_cfgs: dict[str, dict[str, Any]] = {
|
|
29
29
|
"vip_tiny": {
|
|
@@ -247,7 +247,7 @@ def vip_tiny(pretrained: bool = False, **kwargs: Any) -> VIPNet:
|
|
|
247
247
|
https://github.com/cxfyxl/VIPTR/blob/main/modules/VIPTRv2.py)
|
|
248
248
|
|
|
249
249
|
Args:
|
|
250
|
-
pretrained:
|
|
250
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
251
251
|
**kwargs: optional arguments
|
|
252
252
|
|
|
253
253
|
Returns:
|
|
@@ -276,7 +276,7 @@ def vip_base(pretrained: bool = False, **kwargs: Any) -> VIPNet:
|
|
|
276
276
|
https://github.com/cxfyxl/VIPTR/blob/main/modules/VIPTRv2.py)
|
|
277
277
|
|
|
278
278
|
Args:
|
|
279
|
-
pretrained:
|
|
279
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
280
280
|
**kwargs: optional arguments
|
|
281
281
|
|
|
282
282
|
Returns:
|
|
@@ -309,7 +309,7 @@ def _vip(
|
|
|
309
309
|
|
|
310
310
|
Args:
|
|
311
311
|
arch: architecture key
|
|
312
|
-
pretrained:
|
|
312
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
313
313
|
ignore_keys: layer keys to ignore
|
|
314
314
|
**kwargs: arguments passed to VIPNet
|
|
315
315
|
|
|
@@ -15,7 +15,7 @@ from doctr.models.modules.vision_transformer import PatchEmbedding
|
|
|
15
15
|
|
|
16
16
|
from ...utils import load_pretrained_params
|
|
17
17
|
|
|
18
|
-
__all__ = ["vit_s", "vit_b"]
|
|
18
|
+
__all__ = ["VisionTransformer", "vit_s", "vit_b"]
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
default_cfgs: dict[str, dict[str, Any]] = {
|
|
@@ -150,7 +150,7 @@ def vit_s(pretrained: bool = False, **kwargs: Any) -> VisionTransformer:
|
|
|
150
150
|
>>> out = model(input_tensor)
|
|
151
151
|
|
|
152
152
|
Args:
|
|
153
|
-
pretrained:
|
|
153
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
154
154
|
**kwargs: keyword arguments of the VisionTransformer architecture
|
|
155
155
|
|
|
156
156
|
Returns:
|
|
@@ -180,7 +180,7 @@ def vit_b(pretrained: bool = False, **kwargs: Any) -> VisionTransformer:
|
|
|
180
180
|
>>> out = model(input_tensor)
|
|
181
181
|
|
|
182
182
|
Args:
|
|
183
|
-
pretrained:
|
|
183
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
184
184
|
**kwargs: keyword arguments of the VisionTransformer architecture
|
|
185
185
|
|
|
186
186
|
Returns:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|
|
@@ -0,0 +1,215 @@
|
|
|
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 torch
|
|
7
|
+
import torch.nn as nn
|
|
8
|
+
import torch.nn.functional as F
|
|
9
|
+
|
|
10
|
+
from doctr.models.modules import DropPath
|
|
11
|
+
|
|
12
|
+
__all__ = ["PatchEmbed", "MLP", "AttentionWithCAE", "WindowedCAETransformerBlock"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PatchEmbed(nn.Module):
|
|
16
|
+
"""Simple 2D convolutional patch embedding layer for ViT Det
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
kernel_size: kernel size of the projection layer.
|
|
20
|
+
stride: stride of the projection layer.
|
|
21
|
+
padding: padding size of the projection layer.
|
|
22
|
+
in_chans: Number of input image channels.
|
|
23
|
+
embed_dim: embed_dim (int): Patch embedding dimension.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
kernel_size: tuple[int, int] = (16, 16),
|
|
29
|
+
stride: tuple[int, int] = (16, 16),
|
|
30
|
+
padding: tuple[int, int] = (0, 0),
|
|
31
|
+
in_chans: int = 3,
|
|
32
|
+
embed_dim: int = 768,
|
|
33
|
+
):
|
|
34
|
+
super().__init__()
|
|
35
|
+
|
|
36
|
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding)
|
|
37
|
+
|
|
38
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
39
|
+
# B C H W -> B H W C
|
|
40
|
+
return self.proj(x).permute(0, 2, 3, 1)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class MLP(nn.Module):
|
|
44
|
+
"""Simple Multilayer Perceptron (MLP)
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
in_features: number of input features
|
|
48
|
+
hidden_features: number of hidden features (default: in_features)
|
|
49
|
+
out_features: number of output features (default: in_features)
|
|
50
|
+
act_layer: activation layer (default: nn.GELU)
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
in_features: int,
|
|
56
|
+
hidden_features: int | None = None,
|
|
57
|
+
out_features: int | None = None,
|
|
58
|
+
act_layer=nn.GELU,
|
|
59
|
+
):
|
|
60
|
+
super().__init__()
|
|
61
|
+
|
|
62
|
+
hidden_features = hidden_features or in_features
|
|
63
|
+
out_features = out_features or in_features
|
|
64
|
+
|
|
65
|
+
self.net = nn.Sequential(
|
|
66
|
+
nn.Linear(in_features, hidden_features),
|
|
67
|
+
act_layer(),
|
|
68
|
+
nn.Linear(hidden_features, out_features),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
72
|
+
return self.net(x)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AttentionWithCAE(nn.Module):
|
|
76
|
+
"""Multi-head Attention block with CAE bias construction.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
dim: Number of input channels.
|
|
80
|
+
num_heads: Number of attention heads.
|
|
81
|
+
qkv_bias: If True, add a learnable bias to query, key, value.
|
|
82
|
+
use_cae: If True, use CAE bias construction (separate q and v bias).
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_cae: bool = False):
|
|
86
|
+
super().__init__()
|
|
87
|
+
|
|
88
|
+
self.num_heads = num_heads
|
|
89
|
+
self.head_dim = dim // num_heads
|
|
90
|
+
self.scale = self.head_dim**-0.5
|
|
91
|
+
self.use_cae = use_cae
|
|
92
|
+
|
|
93
|
+
self.qkv = nn.Linear(dim, dim * 3, bias=(qkv_bias and not use_cae))
|
|
94
|
+
|
|
95
|
+
# CAE bias
|
|
96
|
+
if use_cae:
|
|
97
|
+
self.q_bias = nn.Parameter(torch.zeros(dim))
|
|
98
|
+
self.v_bias = nn.Parameter(torch.zeros(dim))
|
|
99
|
+
|
|
100
|
+
self.proj = nn.Linear(dim, dim)
|
|
101
|
+
|
|
102
|
+
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
|
103
|
+
B, N, C = x.shape
|
|
104
|
+
|
|
105
|
+
# QKV projection
|
|
106
|
+
if self.use_cae:
|
|
107
|
+
zeros = torch.zeros_like(self.v_bias, requires_grad=False)
|
|
108
|
+
qkv_bias = torch.cat([self.q_bias, zeros, self.v_bias])
|
|
109
|
+
qkv = F.linear(x, weight=self.qkv.weight, bias=qkv_bias)
|
|
110
|
+
else: # pragma: no cover
|
|
111
|
+
qkv = self.qkv(x)
|
|
112
|
+
|
|
113
|
+
# Reshape to multi-head
|
|
114
|
+
qkv = qkv.view(B, N, 3, self.num_heads, self.head_dim)
|
|
115
|
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
|
116
|
+
|
|
117
|
+
# Attention
|
|
118
|
+
attn = (q * self.scale) @ k.transpose(-2, -1)
|
|
119
|
+
|
|
120
|
+
if mask is not None:
|
|
121
|
+
attn = attn.masked_fill(mask.view(B, 1, 1, N).expand_as(attn), float("-inf"))
|
|
122
|
+
|
|
123
|
+
attn = attn.softmax(dim=-1)
|
|
124
|
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
|
125
|
+
return self.proj(x)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class WindowedCAETransformerBlock(nn.Module):
|
|
129
|
+
"""Transformer blocks with support of window attention and residual propagation blocks
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
dim (int): Number of input channels.
|
|
133
|
+
num_heads (int): Number of attention heads in each ViT block.
|
|
134
|
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
|
135
|
+
qkv_bias (bool): If True, add a learnable bias to query, key, value.
|
|
136
|
+
drop_prob (float): Stochastic depth rate.
|
|
137
|
+
norm_layer (nn.Module): Normalization layer.
|
|
138
|
+
act_layer (nn.Module): Activation layer.
|
|
139
|
+
window (bool): If True, use window attention. Otherwise, use global attention.
|
|
140
|
+
use_cae (bool): If True, use CAE bias construction (separate q and v bias).
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
def __init__(
|
|
144
|
+
self,
|
|
145
|
+
dim,
|
|
146
|
+
num_heads,
|
|
147
|
+
mlp_ratio=4.0,
|
|
148
|
+
qkv_bias=True,
|
|
149
|
+
drop_prob=0.0,
|
|
150
|
+
norm_layer=nn.LayerNorm,
|
|
151
|
+
act_layer=nn.GELU,
|
|
152
|
+
window=False,
|
|
153
|
+
use_cae=False,
|
|
154
|
+
):
|
|
155
|
+
super().__init__()
|
|
156
|
+
|
|
157
|
+
self.norm1 = norm_layer(dim)
|
|
158
|
+
self.norm2 = norm_layer(dim)
|
|
159
|
+
|
|
160
|
+
self.attn = AttentionWithCAE(
|
|
161
|
+
dim,
|
|
162
|
+
num_heads=num_heads,
|
|
163
|
+
qkv_bias=qkv_bias,
|
|
164
|
+
use_cae=use_cae,
|
|
165
|
+
)
|
|
166
|
+
self.mlp = MLP(
|
|
167
|
+
in_features=dim,
|
|
168
|
+
hidden_features=int(dim * mlp_ratio),
|
|
169
|
+
act_layer=act_layer,
|
|
170
|
+
)
|
|
171
|
+
self.drop_path = DropPath(drop_prob) if drop_prob > 0.0 else nn.Identity()
|
|
172
|
+
|
|
173
|
+
self.window = window
|
|
174
|
+
self.use_cae = use_cae
|
|
175
|
+
|
|
176
|
+
if use_cae:
|
|
177
|
+
self.gamma_1 = nn.Parameter(0.1 * torch.ones(dim), requires_grad=True)
|
|
178
|
+
self.gamma_2 = nn.Parameter(0.1 * torch.ones(dim), requires_grad=True)
|
|
179
|
+
|
|
180
|
+
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
|
181
|
+
B, HW, C = x.shape
|
|
182
|
+
shortcut = x
|
|
183
|
+
|
|
184
|
+
x = self.norm1(x)
|
|
185
|
+
mask_r = mask
|
|
186
|
+
|
|
187
|
+
# Window partitioning logic
|
|
188
|
+
if not self.window:
|
|
189
|
+
x = x.reshape(B // 16, 16 * HW, C)
|
|
190
|
+
shortcut_r = shortcut.reshape(B // 16, 16 * HW, C)
|
|
191
|
+
|
|
192
|
+
if mask is not None: # pragma: no cover
|
|
193
|
+
mask_r = mask.reshape(B // 16, 16 * HW)
|
|
194
|
+
else:
|
|
195
|
+
mask_r = None
|
|
196
|
+
else:
|
|
197
|
+
shortcut_r = shortcut
|
|
198
|
+
|
|
199
|
+
# Attention
|
|
200
|
+
attn_out = self.attn(x, mask_r)
|
|
201
|
+
|
|
202
|
+
if self.use_cae:
|
|
203
|
+
attn_out = self.gamma_1 * attn_out
|
|
204
|
+
|
|
205
|
+
x = shortcut_r + self.drop_path(attn_out)
|
|
206
|
+
|
|
207
|
+
# Reshape back if needed
|
|
208
|
+
if not self.window:
|
|
209
|
+
x = x.reshape(B, HW, C)
|
|
210
|
+
if mask is not None: # pragma: no cover
|
|
211
|
+
mask = mask.reshape(B, HW)
|
|
212
|
+
|
|
213
|
+
x = x + self.drop_path((self.gamma_2 * self.mlp(self.norm2(x))) if self.use_cae else self.mlp(self.norm2(x)))
|
|
214
|
+
|
|
215
|
+
return x
|