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 @@
|
|
|
1
|
+
from .pytorch import *
|
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
from collections.abc import Iterable, Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import torch
|
|
11
|
+
from torch import nn
|
|
12
|
+
|
|
13
|
+
from doctr.models._utils import predict_by_chunks
|
|
14
|
+
from doctr.models.detection._utils import _remove_padding
|
|
15
|
+
from doctr.models.preprocessor import PreProcessor
|
|
16
|
+
from doctr.models.utils import set_device_and_dtype
|
|
17
|
+
|
|
18
|
+
__all__ = ["LayoutPredictor"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LayoutPredictor(nn.Module):
|
|
22
|
+
"""Implements an object able to localize layout elements in a document
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
pre_processor: transform inputs for easier batched model inference
|
|
26
|
+
model: core layout architecture
|
|
27
|
+
chunk_size: the maximum number of pages decoded and processed at once (32 by default). Longer
|
|
28
|
+
inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
|
|
29
|
+
chunk by chunk, with a memory footprint that does not grow with the number of pages. It is rounded
|
|
30
|
+
up to a multiple of the batch size, so that the predictions are the same as in a single pass.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
pre_processor: PreProcessor,
|
|
36
|
+
model: nn.Module,
|
|
37
|
+
chunk_size: int = 32,
|
|
38
|
+
) -> None:
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.pre_processor = pre_processor
|
|
41
|
+
self.model = model.eval()
|
|
42
|
+
if chunk_size < 1:
|
|
43
|
+
raise ValueError("`chunk_size` must be a positive integer")
|
|
44
|
+
self.chunk_size = chunk_size
|
|
45
|
+
|
|
46
|
+
@torch.inference_mode()
|
|
47
|
+
def forward(
|
|
48
|
+
self,
|
|
49
|
+
pages: Sequence[np.ndarray] | Iterable[np.ndarray],
|
|
50
|
+
**kwargs: Any,
|
|
51
|
+
) -> list[dict[str, np.ndarray]]:
|
|
52
|
+
"""Detect the layout regions of pages
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
pages: a list of pages (numpy arrays of shape H x W x C), a lazy page source
|
|
56
|
+
(cf. `DocumentFile.from_pdf(..., lazy=True)`) or any iterable of pages
|
|
57
|
+
**kwargs: keyword arguments forwarded to the model
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
the regions of each page: `{"class_names", "boxes", "scores"}`
|
|
61
|
+
"""
|
|
62
|
+
return predict_by_chunks(
|
|
63
|
+
lambda chunk: self._predict(chunk, **kwargs), pages, self.chunk_size, self.pre_processor.batch_size
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
@torch.inference_mode()
|
|
67
|
+
def _predict(
|
|
68
|
+
self,
|
|
69
|
+
pages: list[np.ndarray],
|
|
70
|
+
**kwargs: Any,
|
|
71
|
+
) -> list[dict[str, np.ndarray]]:
|
|
72
|
+
if len(pages) == 0:
|
|
73
|
+
return []
|
|
74
|
+
# Extract parameters from the preprocessor
|
|
75
|
+
preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
|
|
76
|
+
symmetric_pad = self.pre_processor.resize.symmetric_pad
|
|
77
|
+
assume_straight_pages = self.model.assume_straight_pages
|
|
78
|
+
# This flag is needed to return the padding mask from the preprocessor
|
|
79
|
+
self.pre_processor.resize.return_padding_mask = True
|
|
80
|
+
|
|
81
|
+
# Dimension check
|
|
82
|
+
if any(page.ndim != 3 for page in pages):
|
|
83
|
+
raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
|
|
84
|
+
|
|
85
|
+
processed_batches = self.pre_processor(pages)
|
|
86
|
+
_params = next(self.model.parameters())
|
|
87
|
+
self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
|
|
88
|
+
self.model, processed_batches, _params.device, _params.dtype
|
|
89
|
+
)
|
|
90
|
+
predicted_batches = [
|
|
91
|
+
self.model(batch[0], batch[1], return_preds=True, return_model_output=True, **kwargs)
|
|
92
|
+
for batch in processed_batches
|
|
93
|
+
]
|
|
94
|
+
# remap idx to class names
|
|
95
|
+
class_names = [
|
|
96
|
+
[self.model.class_names[int(i)] for i in pred[0]] # type: ignore[index]
|
|
97
|
+
for batch in predicted_batches
|
|
98
|
+
for pred in batch["preds"]
|
|
99
|
+
]
|
|
100
|
+
boxes = [pred[1] for batch in predicted_batches for pred in batch["preds"]]
|
|
101
|
+
scores = [pred[2] for batch in predicted_batches for pred in batch["preds"]]
|
|
102
|
+
|
|
103
|
+
# Remove padding from loc predictions
|
|
104
|
+
preds = _remove_padding(
|
|
105
|
+
pages,
|
|
106
|
+
[{"pred": box} for box in boxes],
|
|
107
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
108
|
+
symmetric_pad=symmetric_pad,
|
|
109
|
+
assume_straight_pages=assume_straight_pages, # type: ignore[arg-type]
|
|
110
|
+
)
|
|
111
|
+
return [
|
|
112
|
+
{"class_names": class_name, "boxes": pred["pred"], "scores": score} # type: ignore[dict-item]
|
|
113
|
+
for class_name, pred, score in zip(class_names, preds, scores)
|
|
114
|
+
]
|
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from doctr.models.utils import _CompiledModule
|
|
9
|
+
|
|
10
|
+
from .. import layout
|
|
11
|
+
from ..preprocessor import PreProcessor
|
|
12
|
+
from .predictor import LayoutPredictor
|
|
13
|
+
|
|
14
|
+
__all__ = ["layout_predictor"]
|
|
15
|
+
|
|
16
|
+
ARCHS: list[str]
|
|
17
|
+
|
|
18
|
+
ARCHS = ["lw_detr_s", "lw_detr_m"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = True, **kwargs: Any) -> LayoutPredictor:
|
|
22
|
+
if isinstance(arch, str):
|
|
23
|
+
if arch not in ARCHS:
|
|
24
|
+
raise ValueError(f"unknown architecture '{arch}'")
|
|
25
|
+
|
|
26
|
+
_model = layout.__dict__[arch](
|
|
27
|
+
pretrained=pretrained,
|
|
28
|
+
assume_straight_pages=assume_straight_pages,
|
|
29
|
+
)
|
|
30
|
+
else:
|
|
31
|
+
# Adding the type for torch compiled models to the allowed architectures
|
|
32
|
+
allowed_archs = [layout.LWDETR, _CompiledModule]
|
|
33
|
+
|
|
34
|
+
if not isinstance(arch, tuple(allowed_archs)):
|
|
35
|
+
raise ValueError(f"unknown architecture: {type(arch)}")
|
|
36
|
+
_model = arch
|
|
37
|
+
_model.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
|
|
38
|
+
_model.postprocessor.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
|
|
39
|
+
|
|
40
|
+
kwargs.pop("pretrained_backbone", None)
|
|
41
|
+
|
|
42
|
+
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
43
|
+
kwargs["std"] = kwargs.get("std", _model.cfg["std"])
|
|
44
|
+
kwargs["batch_size"] = kwargs.get("batch_size", 2)
|
|
45
|
+
chunk_size = kwargs.pop("chunk_size", 32)
|
|
46
|
+
predictor = LayoutPredictor(
|
|
47
|
+
PreProcessor(_model.cfg["input_shape"][1:], **kwargs),
|
|
48
|
+
_model,
|
|
49
|
+
chunk_size=chunk_size,
|
|
50
|
+
)
|
|
51
|
+
return predictor
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def layout_predictor(
|
|
55
|
+
arch: Any = "lw_detr_s",
|
|
56
|
+
pretrained: bool = False,
|
|
57
|
+
assume_straight_pages: bool = True,
|
|
58
|
+
preserve_aspect_ratio: bool = True,
|
|
59
|
+
symmetric_pad: bool = True,
|
|
60
|
+
batch_size: int = 2,
|
|
61
|
+
**kwargs: Any,
|
|
62
|
+
) -> LayoutPredictor:
|
|
63
|
+
"""Layout prediction architecture.
|
|
64
|
+
|
|
65
|
+
>>> import numpy as np
|
|
66
|
+
>>> from doctr.models import layout_predictor
|
|
67
|
+
>>> model = layout_predictor(arch='lw_detr_s', pretrained=True)
|
|
68
|
+
>>> input_page = (255 * np.random.rand(600, 800, 3)).astype(np.uint8)
|
|
69
|
+
>>> out = model([input_page])
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
arch: name of the architecture or model itself to use (e.g. 'lw_detr_s')
|
|
73
|
+
pretrained: If True, returns a model pre-trained on our layout prediction dataset
|
|
74
|
+
assume_straight_pages: If True, fit straight boxes to the page
|
|
75
|
+
preserve_aspect_ratio: If True, pad the input document image to preserve the aspect ratio before
|
|
76
|
+
running the detection model on it
|
|
77
|
+
symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
|
|
78
|
+
batch_size: number of samples the model processes in parallel
|
|
79
|
+
chunk_size: maximum number of pages decoded and processed at once (32 by default): longer inputs and
|
|
80
|
+
lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
|
|
81
|
+
**kwargs: optional keyword arguments passed to the architecture
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
Layout predictor
|
|
85
|
+
"""
|
|
86
|
+
return _predictor(
|
|
87
|
+
arch=arch,
|
|
88
|
+
pretrained=pretrained,
|
|
89
|
+
assume_straight_pages=assume_straight_pages,
|
|
90
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
91
|
+
symmetric_pad=symmetric_pad,
|
|
92
|
+
batch_size=batch_size,
|
|
93
|
+
**kwargs,
|
|
94
|
+
)
|
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
|
-
|
|
7
6
|
import numpy as np
|
|
8
7
|
import torch
|
|
9
8
|
import torch.nn as nn
|
|
9
|
+
import torch.nn.functional as F
|
|
10
10
|
|
|
11
|
-
__all__ = ["FASTConvLayer", "DropPath", "AdaptiveAvgPool2d"]
|
|
11
|
+
__all__ = ["FASTConvLayer", "DropPath", "AdaptiveAvgPool2d", "ChannelLayerNorm", "DCNv2"]
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
class DropPath(nn.Module):
|
|
@@ -36,7 +36,6 @@ class DropPath(nn.Module):
|
|
|
36
36
|
class AdaptiveAvgPool2d(nn.Module):
|
|
37
37
|
"""
|
|
38
38
|
Custom AdaptiveAvgPool2d implementation which is ONNX and `torch.compile` compatible.
|
|
39
|
-
|
|
40
39
|
"""
|
|
41
40
|
|
|
42
41
|
def __init__(self, output_size):
|
|
@@ -59,6 +58,143 @@ class AdaptiveAvgPool2d(nn.Module):
|
|
|
59
58
|
return out
|
|
60
59
|
|
|
61
60
|
|
|
61
|
+
class ChannelLayerNorm(nn.Module):
|
|
62
|
+
"""
|
|
63
|
+
A LayerNorm variant, popularized by Transformers, that performs point-wise mean and
|
|
64
|
+
variance normalization over the channel dimension for inputs that have shape
|
|
65
|
+
(batch_size, channels, height, width).
|
|
66
|
+
https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(self, normalized_shape: int, eps: float = 1e-6):
|
|
70
|
+
super().__init__()
|
|
71
|
+
self.weight = nn.Parameter(torch.ones(normalized_shape))
|
|
72
|
+
self.bias = nn.Parameter(torch.zeros(normalized_shape))
|
|
73
|
+
self.eps = eps
|
|
74
|
+
self.normalized_shape = (normalized_shape,)
|
|
75
|
+
|
|
76
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
77
|
+
u = x.mean(1, keepdim=True)
|
|
78
|
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
|
79
|
+
x = (x - u) / torch.sqrt(s + self.eps)
|
|
80
|
+
x = self.weight[:, None, None] * x + self.bias[:, None, None]
|
|
81
|
+
return x
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _deform_conv2d(
|
|
85
|
+
x: torch.Tensor,
|
|
86
|
+
offset: torch.Tensor,
|
|
87
|
+
weight: torch.Tensor,
|
|
88
|
+
bias: torch.Tensor,
|
|
89
|
+
stride: tuple[int, int],
|
|
90
|
+
padding: tuple[int, int],
|
|
91
|
+
dilation: tuple[int, int],
|
|
92
|
+
mask: torch.Tensor,
|
|
93
|
+
) -> torch.Tensor:
|
|
94
|
+
"""Modulated deformable convolution (DCNv2).
|
|
95
|
+
|
|
96
|
+
Numerically equivalent to `torchvision.ops.deform_conv2d` (same offset/mask channel layout and bilinear
|
|
97
|
+
convention) but built only from `grid_sample` + `conv2d`, so the model is ONNX-exportable (the
|
|
98
|
+
`torchvision::deform_conv2d` operator has no ONNX symbolic). `offset` is laid out as torchvision
|
|
99
|
+
expects: for kernel position `k = kh * Kw + kw`, `offset[:, 2 * k]` is the vertical offset and
|
|
100
|
+
`offset[:, 2 * k + 1]` the horizontal one; `mask[:, k]` is the modulation.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
x: input feature map, shape (N, C, H, W)
|
|
104
|
+
offset: sampling offsets, shape (N, 2 * Kh * Kw, Ho, Wo)
|
|
105
|
+
weight: convolution weight, shape (Cout, C, Kh, Kw)
|
|
106
|
+
bias: convolution bias, shape (Cout,)
|
|
107
|
+
stride: convolution stride (sh, sw)
|
|
108
|
+
padding: convolution padding (ph, pw)
|
|
109
|
+
dilation: convolution dilation (dh, dw)
|
|
110
|
+
mask: modulation mask, shape (N, Kh * Kw, Ho, Wo)
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
the output feature map, shape (N, Cout, Ho, Wo)
|
|
114
|
+
"""
|
|
115
|
+
_, _, h, w = x.shape
|
|
116
|
+
cout, _, kh, kw = weight.shape
|
|
117
|
+
sh, sw = stride
|
|
118
|
+
ph, pw = padding
|
|
119
|
+
dh, dw = dilation
|
|
120
|
+
ho, wo = offset.shape[-2], offset.shape[-1]
|
|
121
|
+
|
|
122
|
+
# Base sampling location of each output position in the input plane (before kernel/dilation and offset)
|
|
123
|
+
base_y = (torch.arange(ho, device=x.device, dtype=x.dtype) * sh - ph).view(1, ho, 1)
|
|
124
|
+
base_x = (torch.arange(wo, device=x.device, dtype=x.dtype) * sw - pw).view(1, 1, wo)
|
|
125
|
+
norm_y, norm_x = max(h - 1, 1), max(w - 1, 1)
|
|
126
|
+
|
|
127
|
+
out = x.new_zeros((x.shape[0], cout, ho, wo))
|
|
128
|
+
for kh_i in range(kh):
|
|
129
|
+
for kw_i in range(kw):
|
|
130
|
+
k = kh_i * kw + kw_i
|
|
131
|
+
sample_y = base_y + kh_i * dh + offset[:, 2 * k, :, :]
|
|
132
|
+
sample_x = base_x + kw_i * dw + offset[:, 2 * k + 1, :, :]
|
|
133
|
+
# Normalize to [-1, 1] for grid_sample with align_corners=True (zero padding out of bounds)
|
|
134
|
+
grid = torch.stack((2.0 * sample_x / norm_x - 1.0, 2.0 * sample_y / norm_y - 1.0), dim=-1)
|
|
135
|
+
sampled = F.grid_sample(x, grid, mode="bilinear", padding_mode="zeros", align_corners=True)
|
|
136
|
+
sampled = sampled * mask[:, k : k + 1, :, :]
|
|
137
|
+
out = out + F.conv2d(sampled, weight[:, :, kh_i, kw_i].unsqueeze(-1).unsqueeze(-1))
|
|
138
|
+
return out + bias.view(1, -1, 1, 1)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class DCNv2(nn.Module):
|
|
142
|
+
"""Modulated deformable convolution (v2).
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
in_channels: number of channels in the input feature map
|
|
146
|
+
out_channels: number of channels produced by the convolution
|
|
147
|
+
kernel_size: size of the convolving kernel
|
|
148
|
+
stride: stride of the convolution
|
|
149
|
+
padding: zero-padding added to both sides of the input
|
|
150
|
+
dilation: spacing between kernel elements
|
|
151
|
+
deformable_groups: number of deformable group partitions
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(
|
|
155
|
+
self,
|
|
156
|
+
in_channels: int,
|
|
157
|
+
out_channels: int,
|
|
158
|
+
kernel_size: int | tuple[int, int],
|
|
159
|
+
stride: int,
|
|
160
|
+
padding: int,
|
|
161
|
+
dilation: int = 1,
|
|
162
|
+
deformable_groups: int = 1,
|
|
163
|
+
):
|
|
164
|
+
super().__init__()
|
|
165
|
+
self.stride = (stride, stride)
|
|
166
|
+
self.padding = (padding, padding)
|
|
167
|
+
self.dilation = (dilation, dilation)
|
|
168
|
+
if isinstance(kernel_size, int):
|
|
169
|
+
kernel_size = (kernel_size, kernel_size)
|
|
170
|
+
self.weight = nn.Parameter(torch.empty(out_channels, in_channels, *kernel_size))
|
|
171
|
+
self.bias = nn.Parameter(torch.empty(out_channels))
|
|
172
|
+
channels_ = deformable_groups * 3 * kernel_size[0] * kernel_size[1]
|
|
173
|
+
self.conv_offset_mask = nn.Conv2d(in_channels, channels_, kernel_size, stride, padding, bias=True)
|
|
174
|
+
self.reset_parameters()
|
|
175
|
+
|
|
176
|
+
def reset_parameters(self) -> None:
|
|
177
|
+
# Standard DCN initialization: the regular conv weight is initialized like a vanilla conv, while
|
|
178
|
+
# the offset/mask predictor is zero-initialized so the layer starts as a plain convolution
|
|
179
|
+
# (offsets = 0, modulation = 0.5). Without this, weight/bias keep their uninitialized
|
|
180
|
+
# torch.empty values, which makes the deformable conv explode and the loss diverge to NaN.
|
|
181
|
+
n = self.weight.shape[1]
|
|
182
|
+
for k in self.weight.shape[2:]:
|
|
183
|
+
n *= k
|
|
184
|
+
stdv = 1.0 / (n**0.5)
|
|
185
|
+
nn.init.uniform_(self.weight, -stdv, stdv)
|
|
186
|
+
nn.init.zeros_(self.bias)
|
|
187
|
+
nn.init.zeros_(self.conv_offset_mask.weight)
|
|
188
|
+
nn.init.zeros_(self.conv_offset_mask.bias) # type: ignore[arg-type]
|
|
189
|
+
|
|
190
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
191
|
+
out = self.conv_offset_mask(x)
|
|
192
|
+
o1, o2, mask = torch.chunk(out, 3, dim=1)
|
|
193
|
+
offset = torch.cat((o1, o2), dim=1)
|
|
194
|
+
mask = torch.sigmoid(mask)
|
|
195
|
+
return _deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding, self.dilation, mask)
|
|
196
|
+
|
|
197
|
+
|
|
62
198
|
class FASTConvLayer(nn.Module):
|
|
63
199
|
"""Convolutional layer used in the TextNet and FAST architectures"""
|
|
64
200
|
|
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
# This module 'transformer.py' is inspired by https://github.com/wenwenyu/MASTER-pytorch and Decoder is borrowed
|
|
7
7
|
|
|
8
8
|
import math
|
|
9
|
-
from collections.abc import Callable
|
|
10
|
-
from
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
10
|
+
from copy import deepcopy
|
|
11
|
+
from typing import Any, cast
|
|
11
12
|
|
|
12
13
|
import torch
|
|
14
|
+
import torch.nn.functional as F
|
|
13
15
|
from torch import nn
|
|
14
16
|
|
|
15
17
|
__all__ = ["Decoder", "PositionalEncoding", "EncoderBlock", "MultiHeadAttention", "PositionwiseFeedForward"]
|
|
@@ -30,40 +32,49 @@ class PositionalEncoding(nn.Module):
|
|
|
30
32
|
pe[:, 1::2] = torch.cos(position * div_term)
|
|
31
33
|
self.register_buffer("pe", pe.unsqueeze(0))
|
|
32
34
|
|
|
33
|
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
35
|
+
def forward(self, x: torch.Tensor, start: int = 0) -> torch.Tensor:
|
|
34
36
|
"""Forward pass
|
|
35
37
|
|
|
36
38
|
Args:
|
|
37
39
|
x: embeddings (batch, max_len, d_model)
|
|
40
|
+
start: position of the first embedding in the sequence (e.g. for incremental decoding)
|
|
38
41
|
|
|
39
42
|
Returns:
|
|
40
43
|
positional embeddings (batch, max_len, d_model)
|
|
41
44
|
"""
|
|
42
|
-
x = x + self.pe[:, : x.size(1)] # type: ignore[index]
|
|
45
|
+
x = x + self.pe[:, start : start + x.size(1)] # type: ignore[index]
|
|
43
46
|
return self.dropout(x)
|
|
44
47
|
|
|
45
48
|
|
|
46
49
|
def scaled_dot_product_attention(
|
|
47
50
|
query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None = None
|
|
48
|
-
) -> tuple[torch.Tensor,
|
|
49
|
-
"""Scaled Dot-Product Attention
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
51
|
+
) -> tuple[torch.Tensor, None]:
|
|
52
|
+
"""Scaled Dot-Product Attention, with the fused kernels of PyTorch (the attention weights are not materialized)
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
query: queries of shape (*, L, E)
|
|
56
|
+
key: keys of shape (*, S, E)
|
|
57
|
+
value: values of shape (*, S, E)
|
|
58
|
+
mask: optional mask broadcastable to (*, L, S), where 0 marks the keys a query must not attend to
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
the attention output of shape (*, L, E), and None in place of the attention weights
|
|
62
|
+
"""
|
|
63
|
+
# NOTE: the boolean mask is derived with an int comparison, to ensure the ONNX compatibility
|
|
64
|
+
attn_mask = None if mask is None else mask != 0
|
|
65
|
+
return F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask), None
|
|
56
66
|
|
|
57
67
|
|
|
58
68
|
class PositionwiseFeedForward(nn.Sequential):
|
|
59
69
|
"""Position-wise Feed-Forward Network"""
|
|
60
70
|
|
|
61
71
|
def __init__(
|
|
62
|
-
self, d_model: int, ffd: int, dropout: float = 0.1, activation_fct: Callable[[Any], Any] =
|
|
72
|
+
self, d_model: int, ffd: int, dropout: float = 0.1, activation_fct: Callable[[Any], Any] | None = None
|
|
63
73
|
) -> None:
|
|
64
74
|
super().__init__( # type: ignore[call-overload]
|
|
65
75
|
nn.Linear(d_model, ffd),
|
|
66
|
-
|
|
76
|
+
# A new module per instance: a default instance would be shared by every layer of every model
|
|
77
|
+
nn.ReLU() if activation_fct is None else activation_fct,
|
|
67
78
|
nn.Dropout(p=dropout),
|
|
68
79
|
nn.Linear(ffd, d_model),
|
|
69
80
|
nn.Dropout(p=dropout),
|
|
@@ -83,23 +94,55 @@ class MultiHeadAttention(nn.Module):
|
|
|
83
94
|
self.linear_layers = nn.ModuleList([nn.Linear(d_model, d_model) for _ in range(3)])
|
|
84
95
|
self.output_linear = nn.Linear(d_model, d_model)
|
|
85
96
|
|
|
86
|
-
def
|
|
87
|
-
|
|
97
|
+
def _split_heads(self, x: torch.Tensor) -> torch.Tensor:
|
|
98
|
+
# (N, L, d_model) --> (N, num_heads, L, d_k)
|
|
99
|
+
return x.view(x.size(0), -1, self.num_heads, self.d_k).transpose(1, 2)
|
|
88
100
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
linear(x).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
|
|
92
|
-
for linear, x in zip(self.linear_layers, (query, key, value))
|
|
93
|
-
]
|
|
101
|
+
def project_kv(self, key: torch.Tensor, value: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
|
102
|
+
"""Project the keys and values, e.g. once for the steps of an incremental decoding
|
|
94
103
|
|
|
95
|
-
|
|
96
|
-
|
|
104
|
+
Args:
|
|
105
|
+
key: keys of shape (N, S, d_model)
|
|
106
|
+
value: values of shape (N, S, d_model)
|
|
97
107
|
|
|
98
|
-
|
|
99
|
-
|
|
108
|
+
Returns:
|
|
109
|
+
the projected keys and values, of shape (N, num_heads, S, d_k)
|
|
110
|
+
"""
|
|
111
|
+
return self._split_heads(self.linear_layers[1](key)), self._split_heads(self.linear_layers[2](value))
|
|
112
|
+
|
|
113
|
+
def attend(
|
|
114
|
+
self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None = None
|
|
115
|
+
) -> torch.Tensor:
|
|
116
|
+
"""Attention of the queries over keys and values projected with `project_kv`
|
|
100
117
|
|
|
118
|
+
Args:
|
|
119
|
+
query: queries of shape (N, L, d_model)
|
|
120
|
+
key: projected keys of shape (N, num_heads, S, d_k)
|
|
121
|
+
value: projected values of shape (N, num_heads, S, d_k)
|
|
122
|
+
mask: optional mask broadcastable to (N, num_heads, L, S), where 0 marks the masked keys
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
the attention output of shape (N, L, d_model)
|
|
126
|
+
"""
|
|
127
|
+
x, _ = scaled_dot_product_attention(self._split_heads(self.linear_layers[0](query)), key, value, mask=mask)
|
|
128
|
+
# Concat attention heads
|
|
129
|
+
x = x.transpose(1, 2).contiguous().view(query.size(0), -1, self.num_heads * self.d_k)
|
|
101
130
|
return self.output_linear(x)
|
|
102
131
|
|
|
132
|
+
def attend_transposed(
|
|
133
|
+
self, query: torch.Tensor, key_t: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None = None
|
|
134
|
+
) -> torch.Tensor:
|
|
135
|
+
"""Attention (inference) over keys transposed beforehand, of shape (N, num_heads, d_k, S): an exported decoding
|
|
136
|
+
loop then has no transpose of the keys at each step (cf. `attend` for the other arguments)"""
|
|
137
|
+
scores = torch.matmul(self._split_heads(self.linear_layers[0](query)), key_t) * self.d_k**-0.5
|
|
138
|
+
if mask is not None:
|
|
139
|
+
scores = scores.masked_fill(mask == 0, float("-inf"))
|
|
140
|
+
x = torch.matmul(scores.softmax(-1), value)
|
|
141
|
+
return self.output_linear(x.transpose(1, 2).flatten(2))
|
|
142
|
+
|
|
143
|
+
def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask=None) -> torch.Tensor:
|
|
144
|
+
return self.attend(query, *self.project_kv(key, value), mask=mask)
|
|
145
|
+
|
|
103
146
|
|
|
104
147
|
class EncoderBlock(nn.Module):
|
|
105
148
|
"""Transformer Encoder Block"""
|
|
@@ -111,7 +154,7 @@ class EncoderBlock(nn.Module):
|
|
|
111
154
|
d_model: int,
|
|
112
155
|
dff: int, # hidden dimension of the feedforward network
|
|
113
156
|
dropout: float,
|
|
114
|
-
activation_fct: Callable[[Any], Any] =
|
|
157
|
+
activation_fct: Callable[[Any], Any] | None = None,
|
|
115
158
|
) -> None:
|
|
116
159
|
super().__init__()
|
|
117
160
|
|
|
@@ -126,7 +169,9 @@ class EncoderBlock(nn.Module):
|
|
|
126
169
|
MultiHeadAttention(num_heads, d_model, dropout) for _ in range(self.num_layers)
|
|
127
170
|
])
|
|
128
171
|
self.position_feed_forward = nn.ModuleList([
|
|
129
|
-
|
|
172
|
+
# deepcopy: one activation module per layer instead of one shared by all of them
|
|
173
|
+
PositionwiseFeedForward(d_model, dff, dropout, deepcopy(activation_fct))
|
|
174
|
+
for _ in range(self.num_layers)
|
|
130
175
|
])
|
|
131
176
|
|
|
132
177
|
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
|
@@ -184,18 +229,93 @@ class Decoder(nn.Module):
|
|
|
184
229
|
memory: torch.Tensor,
|
|
185
230
|
source_mask: torch.Tensor | None = None,
|
|
186
231
|
target_mask: torch.Tensor | None = None,
|
|
232
|
+
cache: list[dict[str, tuple[torch.Tensor, torch.Tensor]]] | None = None,
|
|
187
233
|
) -> torch.Tensor:
|
|
234
|
+
"""Decode the target tokens
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
tgt: target tokens of shape (N, L)
|
|
238
|
+
memory: encoded source of shape (N, S, d_model)
|
|
239
|
+
source_mask: optional mask of the source
|
|
240
|
+
target_mask: optional mask of the target
|
|
241
|
+
cache: for incremental decoding, an initially empty list that keeps the keys and values of every layer
|
|
242
|
+
between the calls: `tgt` then only holds the new tokens, which follow the ones of the previous calls
|
|
243
|
+
and attend to all of them (the source is projected once, at the first call)
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
the decoded features of shape (N, L, d_model)
|
|
247
|
+
"""
|
|
248
|
+
start = 0 if not cache else cache[0]["self"][0].size(2)
|
|
188
249
|
tgt = self.embed(tgt) * math.sqrt(self.d_model)
|
|
189
|
-
|
|
190
|
-
output = pos_enc_tgt
|
|
250
|
+
output = self.positional_encoding(tgt, start)
|
|
191
251
|
|
|
192
252
|
for i in range(self.num_layers):
|
|
253
|
+
self_attention = cast(MultiHeadAttention, self.attention[i])
|
|
254
|
+
source_attention = cast(MultiHeadAttention, self.source_attention[i])
|
|
193
255
|
normed_output = self.layer_norm_input(output)
|
|
194
|
-
|
|
256
|
+
if cache is None:
|
|
257
|
+
attended = self_attention(normed_output, normed_output, normed_output, target_mask)
|
|
258
|
+
else:
|
|
259
|
+
if len(cache) <= i:
|
|
260
|
+
cache.append({"source": source_attention.project_kv(memory, memory)})
|
|
261
|
+
key, value = self_attention.project_kv(normed_output, normed_output)
|
|
262
|
+
if "self" in cache[i]:
|
|
263
|
+
key = torch.cat([cache[i]["self"][0], key], dim=2)
|
|
264
|
+
value = torch.cat([cache[i]["self"][1], value], dim=2)
|
|
265
|
+
cache[i]["self"] = (key, value)
|
|
266
|
+
attended = self_attention.attend(normed_output, key, value, target_mask)
|
|
267
|
+
output = output + self.dropout(attended)
|
|
268
|
+
|
|
195
269
|
normed_output = self.layer_norm_masked_attention(output)
|
|
196
|
-
|
|
270
|
+
if cache is None:
|
|
271
|
+
attended = source_attention(normed_output, memory, memory, source_mask)
|
|
272
|
+
else:
|
|
273
|
+
attended = source_attention.attend(normed_output, *cache[i]["source"], source_mask)
|
|
274
|
+
output = output + self.dropout(attended)
|
|
197
275
|
normed_output = self.layer_norm_attention(output)
|
|
198
276
|
output = output + self.dropout(self.position_feed_forward[i](normed_output))
|
|
199
277
|
|
|
200
278
|
# (batch_size, seq_len, d_model)
|
|
201
279
|
return self.layer_norm_output(output)
|
|
280
|
+
|
|
281
|
+
def decode_step(
|
|
282
|
+
self,
|
|
283
|
+
token: torch.Tensor,
|
|
284
|
+
step: torch.Tensor,
|
|
285
|
+
source_kv: list[tuple[torch.Tensor, torch.Tensor]],
|
|
286
|
+
keys: Sequence[torch.Tensor],
|
|
287
|
+
values: Sequence[torch.Tensor],
|
|
288
|
+
) -> tuple[torch.Tensor, list[torch.Tensor], list[torch.Tensor]]:
|
|
289
|
+
"""Decode one token with key / value buffers of a fixed size (inference), as the loop state of a
|
|
290
|
+
`torch.while_loop`, which the `torch.export`-based ONNX exporter turns into an ONNX `Loop`
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
token: the token to decode, of shape (N, 1)
|
|
294
|
+
step: its position in the sequence, a scalar tensor
|
|
295
|
+
source_kv: the transposed keys, of shape (N, num_heads, d_model / num_heads, S), and the values of the
|
|
296
|
+
source, for each layer (cf. `MultiHeadAttention.project_kv`)
|
|
297
|
+
keys: the transposed key buffer of each layer, of shape (N, num_heads, d_model / num_heads, L), filled
|
|
298
|
+
before `step`
|
|
299
|
+
values: the value buffer of each layer, of shape (N, num_heads, L, d_model / num_heads)
|
|
300
|
+
|
|
301
|
+
Returns:
|
|
302
|
+
the decoded token of shape (N, 1, d_model), and the buffers with its key and value written at `step`
|
|
303
|
+
"""
|
|
304
|
+
idx = step.view(1)
|
|
305
|
+
pe = cast(torch.Tensor, self.positional_encoding.pe)
|
|
306
|
+
output = self.embed(token) * math.sqrt(self.d_model) + pe.index_select(1, idx)
|
|
307
|
+
# The token attends to itself and to the previous ones
|
|
308
|
+
mask = (torch.arange(values[0].shape[2], device=token.device) <= step).view(1, 1, 1, -1)
|
|
309
|
+
new_keys, new_values = [], []
|
|
310
|
+
for i in range(self.num_layers):
|
|
311
|
+
self_attention = cast(MultiHeadAttention, self.attention[i])
|
|
312
|
+
source_attention = cast(MultiHeadAttention, self.source_attention[i])
|
|
313
|
+
normed_output = self.layer_norm_input(output)
|
|
314
|
+
key, value = self_attention.project_kv(normed_output, normed_output)
|
|
315
|
+
new_keys.append(keys[i].index_copy(3, idx, key.transpose(-2, -1)))
|
|
316
|
+
new_values.append(values[i].index_copy(2, idx, value))
|
|
317
|
+
output = output + self_attention.attend_transposed(normed_output, new_keys[-1], new_values[-1], mask)
|
|
318
|
+
normed_output = self.layer_norm_masked_attention(output)
|
|
319
|
+
output = output + source_attention.attend_transposed(normed_output, *source_kv[i])
|
|
320
|
+
output = output + self.position_feed_forward[i](self.layer_norm_attention(output))
|
|
321
|
+
return self.layer_norm_output(output), new_keys, new_values
|