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,587 @@
|
|
|
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, Sequence
|
|
8
|
+
from copy import deepcopy
|
|
9
|
+
from typing import Any, cast
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import torch
|
|
13
|
+
from torch import nn
|
|
14
|
+
from torch.nn import functional as F
|
|
15
|
+
from torchvision.models._utils import IntermediateLayerGetter
|
|
16
|
+
|
|
17
|
+
from doctr.datasets import LATEX_TOKENS
|
|
18
|
+
|
|
19
|
+
from ..._utils import ConfidenceAggregation, aggregate_confidence
|
|
20
|
+
from ...classification import hgnetv2_b4
|
|
21
|
+
from ...utils import _bf16_to_float32, load_pretrained_params
|
|
22
|
+
from .base import _FormulaNet, _FormulaNetPostProcessor
|
|
23
|
+
|
|
24
|
+
__all__ = ["FormulaNet", "formulanet"]
|
|
25
|
+
|
|
26
|
+
default_cfgs: dict[str, dict[str, Any]] = {
|
|
27
|
+
"formulanet": {
|
|
28
|
+
"mean": (0.7931, 0.7931, 0.7931),
|
|
29
|
+
"std": (0.1738, 0.1738, 0.1738),
|
|
30
|
+
"input_shape": (3, 256, 768),
|
|
31
|
+
"vocab": LATEX_TOKENS,
|
|
32
|
+
"url": "https://github.com/mindee/doctr/releases/download/v1.1.0/formulanet-66790059.pt",
|
|
33
|
+
},
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _sincos_2d(height: int, width: int, dim: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
|
38
|
+
"""Fixed 2D sinusoidal positional encoding of a feature map, half of the channels for each axis
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
the encoding, of shape (height * width, dim)
|
|
42
|
+
"""
|
|
43
|
+
quarter = dim // 4
|
|
44
|
+
omega = 1.0 / (10000 ** (torch.arange(quarter, device=device, dtype=torch.float32) / quarter))
|
|
45
|
+
ys = torch.arange(height, device=device, dtype=torch.float32)[:, None] * omega[None] # (H, D/4)
|
|
46
|
+
xs = torch.arange(width, device=device, dtype=torch.float32)[:, None] * omega[None] # (W, D/4)
|
|
47
|
+
pos_y = torch.cat([ys.sin(), ys.cos()], dim=1)[:, None].expand(height, width, 2 * quarter)
|
|
48
|
+
pos_x = torch.cat([xs.sin(), xs.cos()], dim=1)[None].expand(height, width, 2 * quarter)
|
|
49
|
+
pos = torch.cat([pos_y, pos_x], dim=-1).reshape(height * width, 4 * quarter)
|
|
50
|
+
return F.pad(pos, (0, dim - 4 * quarter)).to(dtype)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class MultiHeadAttention(nn.Module):
|
|
54
|
+
"""Multi-head attention with separate key / value projections, to cache them during decoding
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
d_model: dimension of the model
|
|
58
|
+
num_heads: number of attention heads
|
|
59
|
+
dropout: dropout rate of the attention weights
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, d_model: int, num_heads: int, dropout: float = 0.0) -> None:
|
|
63
|
+
super().__init__()
|
|
64
|
+
if d_model % num_heads != 0:
|
|
65
|
+
raise ValueError(f"d_model ({d_model}) must be divisible by num_heads ({num_heads})")
|
|
66
|
+
self.num_heads = num_heads
|
|
67
|
+
self.head_dim = d_model // num_heads
|
|
68
|
+
self.dropout = dropout
|
|
69
|
+
self.q_proj = nn.Linear(d_model, d_model)
|
|
70
|
+
self.k_proj = nn.Linear(d_model, d_model)
|
|
71
|
+
self.v_proj = nn.Linear(d_model, d_model)
|
|
72
|
+
self.out_proj = nn.Linear(d_model, d_model)
|
|
73
|
+
|
|
74
|
+
def _split_heads(self, x: torch.Tensor) -> torch.Tensor:
|
|
75
|
+
# (N, L, D) -> (N, H, L, D / H)
|
|
76
|
+
return x.reshape(x.shape[0], x.shape[1], self.num_heads, self.head_dim).transpose(1, 2)
|
|
77
|
+
|
|
78
|
+
def project_kv(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
|
79
|
+
"""Project a sequence into the keys and values of the attention, of shape (N, H, L, D / H)"""
|
|
80
|
+
return self._split_heads(self.k_proj(x)), self._split_heads(self.v_proj(x))
|
|
81
|
+
|
|
82
|
+
def forward(
|
|
83
|
+
self, query: torch.Tensor, key_value: tuple[torch.Tensor, torch.Tensor], is_causal: bool = False
|
|
84
|
+
) -> torch.Tensor:
|
|
85
|
+
q = self._split_heads(self.q_proj(query))
|
|
86
|
+
out = F.scaled_dot_product_attention(
|
|
87
|
+
q, *key_value, dropout_p=self.dropout if self.training else 0.0, is_causal=is_causal
|
|
88
|
+
)
|
|
89
|
+
return self.out_proj(out.transpose(1, 2).reshape(query.shape[0], query.shape[1], -1))
|
|
90
|
+
|
|
91
|
+
def attend_transposed(
|
|
92
|
+
self, query: torch.Tensor, key_t: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None = None
|
|
93
|
+
) -> torch.Tensor:
|
|
94
|
+
"""Attention (inference) over keys transposed beforehand, of shape (N, H, D / H, S): the exported decoding loop
|
|
95
|
+
then has no transpose of the keys at each step
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
query: the queries, of shape (N, L, D)
|
|
99
|
+
key_t: the transposed keys, of shape (N, H, D / H, S)
|
|
100
|
+
value: the values, of shape (N, H, S, D / H)
|
|
101
|
+
mask: optional boolean mask broadcastable to (N, H, L, S), False on the keys a query must not attend to
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
the attention output, of shape (N, L, D)
|
|
105
|
+
"""
|
|
106
|
+
scores = torch.matmul(self._split_heads(self.q_proj(query)), key_t) * self.head_dim**-0.5
|
|
107
|
+
if mask is not None:
|
|
108
|
+
scores = scores.masked_fill(~mask, float("-inf"))
|
|
109
|
+
out = torch.matmul(scores.softmax(-1), value)
|
|
110
|
+
return self.out_proj(out.transpose(1, 2).flatten(2))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class FormulaDecoderLayer(nn.Module):
|
|
114
|
+
"""Pre-norm transformer decoder layer (causal self-attention, cross-attention on the image features, MLP)
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
d_model: dimension of the model
|
|
118
|
+
num_heads: number of attention heads
|
|
119
|
+
ffn_dim: hidden dimension of the feed-forward network
|
|
120
|
+
dropout: dropout rate
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(self, d_model: int, num_heads: int, ffn_dim: int, dropout: float = 0.1) -> None:
|
|
124
|
+
super().__init__()
|
|
125
|
+
self.self_attn = MultiHeadAttention(d_model, num_heads, dropout)
|
|
126
|
+
self.cross_attn = MultiHeadAttention(d_model, num_heads, dropout)
|
|
127
|
+
self.ffn = nn.Sequential(
|
|
128
|
+
nn.Linear(d_model, ffn_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(ffn_dim, d_model)
|
|
129
|
+
)
|
|
130
|
+
self.self_attn_norm = nn.LayerNorm(d_model)
|
|
131
|
+
self.cross_attn_norm = nn.LayerNorm(d_model)
|
|
132
|
+
self.ffn_norm = nn.LayerNorm(d_model)
|
|
133
|
+
self.dropout = nn.Dropout(dropout)
|
|
134
|
+
|
|
135
|
+
def forward(
|
|
136
|
+
self,
|
|
137
|
+
x: torch.Tensor,
|
|
138
|
+
memory_kv: tuple[torch.Tensor, torch.Tensor],
|
|
139
|
+
cache: tuple[torch.Tensor, torch.Tensor] | None = None,
|
|
140
|
+
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
|
|
141
|
+
"""Decode a sequence (causally), or the next tokens of a sequence given the cached keys / values
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
x: the embedded tokens, of shape (N, L, D)
|
|
145
|
+
memory_kv: the keys and values of the image features (cf. `MultiHeadAttention.project_kv`)
|
|
146
|
+
cache: the keys and values of the previous tokens, None for the start of the sequence
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
the decoded tokens, and the keys and values of the sequence decoded so far
|
|
150
|
+
"""
|
|
151
|
+
h = self.self_attn_norm(x)
|
|
152
|
+
k, v = self.self_attn.project_kv(h)
|
|
153
|
+
if cache is not None:
|
|
154
|
+
k, v = torch.cat([cache[0], k], dim=2), torch.cat([cache[1], v], dim=2)
|
|
155
|
+
# With a cache, the new tokens attend to all the previous ones (decoding one token at a time)
|
|
156
|
+
x = x + self.dropout(self.self_attn(h, (k, v), is_causal=cache is None))
|
|
157
|
+
x = x + self.dropout(self.cross_attn(self.cross_attn_norm(x), memory_kv))
|
|
158
|
+
x = x + self.dropout(self.ffn(self.ffn_norm(x)))
|
|
159
|
+
return x, (k, v)
|
|
160
|
+
|
|
161
|
+
def decode_step(
|
|
162
|
+
self,
|
|
163
|
+
x: torch.Tensor,
|
|
164
|
+
memory_kv_t: tuple[torch.Tensor, torch.Tensor],
|
|
165
|
+
write_cache: Callable[[torch.Tensor, torch.Tensor], tuple[torch.Tensor, torch.Tensor, torch.Tensor]],
|
|
166
|
+
) -> torch.Tensor:
|
|
167
|
+
"""Decode the next token (inference), with keys transposed beforehand (cf. `FormulaNet._decode_greedy_loop`)
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
x: the embedded token, of shape (N, 1, D)
|
|
171
|
+
memory_kv_t: the transposed keys and the values of the image features
|
|
172
|
+
write_cache: stores the transposed key and the value of the token, and returns the transposed keys, the
|
|
173
|
+
values and the mask of the tokens to attend to
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
the decoded token, of shape (N, 1, D)
|
|
177
|
+
"""
|
|
178
|
+
h = self.self_attn_norm(x)
|
|
179
|
+
k, v = self.self_attn.project_kv(h)
|
|
180
|
+
keys_t, values, mask = write_cache(k.transpose(-2, -1), v)
|
|
181
|
+
x = x + self.self_attn.attend_transposed(h, keys_t, values, mask)
|
|
182
|
+
x = x + self.cross_attn.attend_transposed(self.cross_attn_norm(x), *memory_kv_t)
|
|
183
|
+
return x + self.ffn(self.ffn_norm(x))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class FormulaNet(_FormulaNet, nn.Module):
|
|
187
|
+
"""Implements a formula recognition model: a convolutional encoder (HGNetV2) whose last feature map is flattened
|
|
188
|
+
into a sequence, and a small autoregressive transformer decoder (MBart-style) predicting LaTeX tokens, as in
|
|
189
|
+
`"PP-FormulaNet" <https://arxiv.org/abs/2503.18382>`_.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
feature_extractor: the backbone serving as feature extractor
|
|
193
|
+
vocab: the list of LaTeX tokens
|
|
194
|
+
d_model: dimension of the decoder
|
|
195
|
+
num_layers: number of decoder layers
|
|
196
|
+
num_heads: number of attention heads of the decoder
|
|
197
|
+
ffn_dim: hidden dimension of the feed-forward networks of the decoder
|
|
198
|
+
max_length: maximum number of tokens of a formula: size of the positional embeddings and maximum length of the
|
|
199
|
+
training labels
|
|
200
|
+
max_decode_length: maximum number of tokens generated by the greedy decoding (at most `max_length`). The
|
|
201
|
+
decoding stops once every formula of a batch is complete: this caps the time spent on a formula the model
|
|
202
|
+
fails to end (e.g. a repetition loop), which holds up its whole batch
|
|
203
|
+
dropout_prob: dropout probability of the decoder
|
|
204
|
+
feat_channels: number of channels of the feature map of the backbone
|
|
205
|
+
input_shape: input shape of the image
|
|
206
|
+
exportable: onnx exportable returns only logits
|
|
207
|
+
cfg: dictionary containing information about the model
|
|
208
|
+
confidence_aggregation: aggregation method of the token probabilities into the formula confidence
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
# Number of steps of each loop of the decoding exported with `torch.export` (cf. `_decode_greedy_loop`)
|
|
212
|
+
export_chunk_size: int = 64
|
|
213
|
+
|
|
214
|
+
def __init__(
|
|
215
|
+
self,
|
|
216
|
+
feature_extractor: nn.Module,
|
|
217
|
+
vocab: Sequence[str],
|
|
218
|
+
d_model: int = 384,
|
|
219
|
+
num_layers: int = 4,
|
|
220
|
+
num_heads: int = 16,
|
|
221
|
+
ffn_dim: int = 1536,
|
|
222
|
+
max_length: int = 4096,
|
|
223
|
+
max_decode_length: int = 2048,
|
|
224
|
+
dropout_prob: float = 0.1,
|
|
225
|
+
feat_channels: int = 2048,
|
|
226
|
+
input_shape: tuple[int, int, int] = (3, 256, 768),
|
|
227
|
+
exportable: bool = False,
|
|
228
|
+
cfg: dict[str, Any] | None = None,
|
|
229
|
+
confidence_aggregation: ConfidenceAggregation = "mean",
|
|
230
|
+
) -> None:
|
|
231
|
+
super().__init__()
|
|
232
|
+
self.vocab = list(vocab)
|
|
233
|
+
self.vocab_size = len(self.vocab)
|
|
234
|
+
self.max_length = max_length
|
|
235
|
+
self.max_decode_length = max_decode_length
|
|
236
|
+
self.d_model = d_model
|
|
237
|
+
self.exportable = exportable
|
|
238
|
+
self.cfg = cfg
|
|
239
|
+
# Special tokens, after the vocab
|
|
240
|
+
self.eos, self.sos, self.pad = self.vocab_size, self.vocab_size + 1, self.vocab_size + 2
|
|
241
|
+
|
|
242
|
+
self.feat_extractor = feature_extractor
|
|
243
|
+
self.feat_proj = nn.Linear(feat_channels, d_model)
|
|
244
|
+
self.feat_norm = nn.LayerNorm(d_model)
|
|
245
|
+
|
|
246
|
+
self.embed = nn.Embedding(self.vocab_size + 3, d_model, padding_idx=self.pad) # +3 for EOS, SOS, PAD
|
|
247
|
+
self.pos_embed = nn.Embedding(max_length + 1, d_model) # SOS + tokens
|
|
248
|
+
self.embed_norm = nn.LayerNorm(d_model)
|
|
249
|
+
self.dropout = nn.Dropout(dropout_prob)
|
|
250
|
+
self.layers = nn.ModuleList([
|
|
251
|
+
FormulaDecoderLayer(d_model, num_heads, ffn_dim, dropout_prob) for _ in range(num_layers)
|
|
252
|
+
])
|
|
253
|
+
self.norm = nn.LayerNorm(d_model)
|
|
254
|
+
self.head = nn.Linear(d_model, self.vocab_size + 1) # +1 for EOS
|
|
255
|
+
|
|
256
|
+
self.postprocessor = FormulaNetPostProcessor(vocab=self.vocab, confidence_aggregation=confidence_aggregation)
|
|
257
|
+
|
|
258
|
+
for n, m in self.named_modules():
|
|
259
|
+
# Don't override the initialization of the backbone
|
|
260
|
+
if n.startswith("feat_extractor."):
|
|
261
|
+
continue
|
|
262
|
+
if isinstance(m, nn.Linear):
|
|
263
|
+
nn.init.trunc_normal_(m.weight, std=0.02)
|
|
264
|
+
if m.bias is not None:
|
|
265
|
+
nn.init.zeros_(m.bias)
|
|
266
|
+
elif isinstance(m, nn.Embedding):
|
|
267
|
+
nn.init.trunc_normal_(m.weight, std=0.02)
|
|
268
|
+
if m.padding_idx is not None:
|
|
269
|
+
m.weight.data[m.padding_idx].zero_()
|
|
270
|
+
|
|
271
|
+
def from_pretrained(self, path_or_url: str, **kwargs: Any) -> None:
|
|
272
|
+
"""Load pretrained parameters onto the model
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
path_or_url: the path or URL to the model parameters (checkpoint)
|
|
276
|
+
**kwargs: additional arguments to be passed to `doctr.models.utils.load_pretrained_params`
|
|
277
|
+
"""
|
|
278
|
+
load_pretrained_params(self, path_or_url, **kwargs)
|
|
279
|
+
|
|
280
|
+
def _decoder_layers(self) -> list[FormulaDecoderLayer]:
|
|
281
|
+
return cast(list[FormulaDecoderLayer], list(self.layers))
|
|
282
|
+
|
|
283
|
+
def encode(self, x: torch.Tensor) -> torch.Tensor:
|
|
284
|
+
"""Encode images into a sequence of features, of shape (N, H / 32 * W / 32, d_model)"""
|
|
285
|
+
features = self.feat_extractor(x)["features"] # (N, C, H, W)
|
|
286
|
+
_, _, height, width = features.shape
|
|
287
|
+
memory = self.feat_proj(features.flatten(2).transpose(1, 2))
|
|
288
|
+
memory = memory + _sincos_2d(height, width, self.d_model, memory.device, memory.dtype)
|
|
289
|
+
return self.feat_norm(memory)
|
|
290
|
+
|
|
291
|
+
def _embed_tokens(self, tokens: torch.Tensor, start: int = 0) -> torch.Tensor:
|
|
292
|
+
positions = torch.arange(start, start + tokens.shape[1], device=tokens.device)
|
|
293
|
+
x = math.sqrt(self.d_model) * self.embed(tokens) + self.pos_embed(positions)[None]
|
|
294
|
+
return self.dropout(self.embed_norm(x))
|
|
295
|
+
|
|
296
|
+
def decode(self, tokens: torch.Tensor, memory: torch.Tensor) -> torch.Tensor:
|
|
297
|
+
"""Decode full token sequences in parallel (teacher forcing)
|
|
298
|
+
|
|
299
|
+
Args:
|
|
300
|
+
tokens: the input tokens, starting with SOS, of shape (N, L)
|
|
301
|
+
memory: the encoded images
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
the logits of the next token at each position, of shape (N, L, vocab_size + 1)
|
|
305
|
+
"""
|
|
306
|
+
x = self._embed_tokens(tokens)
|
|
307
|
+
for layer in self._decoder_layers():
|
|
308
|
+
x, _ = layer(x, layer.cross_attn.project_kv(memory))
|
|
309
|
+
return self.head(self.norm(x))
|
|
310
|
+
|
|
311
|
+
# The greedy decoding is not differentiable (argmax), and tracking the gradients of the growing key / value caches
|
|
312
|
+
# would take a memory quadratic in the number of tokens: the training relies on `decode` (teacher forcing)
|
|
313
|
+
@torch.no_grad()
|
|
314
|
+
def decode_greedy(self, memory: torch.Tensor, max_len: int | None = None) -> torch.Tensor:
|
|
315
|
+
"""Generate token sequences greedily, one token at a time, caching the keys / values of the decoded tokens
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
memory: the encoded images
|
|
319
|
+
max_len: maximum number of tokens to generate (`max_decode_length` by default), at most `max_length`
|
|
320
|
+
|
|
321
|
+
Returns:
|
|
322
|
+
the logits of the generated tokens, of shape (N, L, vocab_size + 1)
|
|
323
|
+
"""
|
|
324
|
+
steps = min(self.max_decode_length if max_len is None else max_len, self.max_length) + 1 # tokens + EOS
|
|
325
|
+
if torch.compiler.is_exporting():
|
|
326
|
+
return self._decode_greedy_loop(memory, steps)
|
|
327
|
+
memory_kv = [layer.cross_attn.project_kv(memory) for layer in self._decoder_layers()]
|
|
328
|
+
caches: list[tuple[torch.Tensor, torch.Tensor] | None] = [None] * len(self.layers)
|
|
329
|
+
token = torch.full((memory.shape[0], 1), self.sos, dtype=torch.long, device=memory.device)
|
|
330
|
+
done = torch.zeros(memory.shape[0], dtype=torch.bool, device=memory.device)
|
|
331
|
+
logits = []
|
|
332
|
+
for step in range(steps):
|
|
333
|
+
x = self._embed_tokens(token, start=step)
|
|
334
|
+
for idx, layer in enumerate(self.layers):
|
|
335
|
+
x, caches[idx] = layer(x, memory_kv[idx], caches[idx])
|
|
336
|
+
step_logits = self.head(self.norm(x))
|
|
337
|
+
logits.append(step_logits)
|
|
338
|
+
token = step_logits.argmax(-1)
|
|
339
|
+
# Stop once every sequence has produced EOS
|
|
340
|
+
# NOTE: `break` isn't translated by the tracing ONNX exporter, which runs every step (`torch.export` relies
|
|
341
|
+
# on `_decode_greedy_loop`)
|
|
342
|
+
if not self.exportable:
|
|
343
|
+
done |= token[:, 0] == self.eos
|
|
344
|
+
if bool(done.all()):
|
|
345
|
+
break
|
|
346
|
+
return torch.cat(logits, dim=1)
|
|
347
|
+
|
|
348
|
+
def _decode_greedy_loop(self, memory: torch.Tensor, steps: int) -> torch.Tensor:
|
|
349
|
+
"""Greedy decoding with `torch.while_loop`, used when the model is traced by `torch.export` (e.g.
|
|
350
|
+
`export_model_to_onnx(..., dynamo=True)`): each loop is exported as an ONNX `Loop`, which stops once every
|
|
351
|
+
formula of the batch is complete, instead of the `steps` unrolled steps of the tracing exporter.
|
|
352
|
+
|
|
353
|
+
The state of a loop keeps its shape: the steps are split into chunks of `export_chunk_size` steps, one loop
|
|
354
|
+
each, whose keys and values are written into buffers of the size of the chunk. A step attends to the tokens of
|
|
355
|
+
the chunks decoded so far, as the cached decoding of `decode_greedy`, and the loops after the end of every
|
|
356
|
+
formula do not run.
|
|
357
|
+
|
|
358
|
+
Args:
|
|
359
|
+
memory: the encoded images
|
|
360
|
+
steps: the maximum number of decoding steps
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
the logits of every step, of shape (N, steps, vocab_size + 1), zeros after the end of every formula
|
|
364
|
+
"""
|
|
365
|
+
from torch._higher_order_ops.while_loop import while_loop
|
|
366
|
+
|
|
367
|
+
n, device = memory.shape[0], memory.device
|
|
368
|
+
layers = self._decoder_layers()
|
|
369
|
+
num_layers = len(layers)
|
|
370
|
+
num_heads, head_dim = layers[0].self_attn.num_heads, layers[0].self_attn.head_dim
|
|
371
|
+
memory_kv_t = []
|
|
372
|
+
for layer in layers:
|
|
373
|
+
key, value = layer.cross_attn.project_kv(memory)
|
|
374
|
+
memory_kv_t.append((key.transpose(-2, -1).contiguous(), value))
|
|
375
|
+
|
|
376
|
+
step = torch.zeros((), dtype=torch.long, device=device)
|
|
377
|
+
token = torch.full((n, 1), self.sos, dtype=torch.long, device=device)
|
|
378
|
+
done = torch.zeros(n, dtype=torch.bool, device=device)
|
|
379
|
+
# The transposed keys and the values of the previous chunks, for each layer
|
|
380
|
+
past_keys: list[list[torch.Tensor]] = [[] for _ in layers]
|
|
381
|
+
past_values: list[list[torch.Tensor]] = [[] for _ in layers]
|
|
382
|
+
logits = []
|
|
383
|
+
for start in range(0, steps, self.export_chunk_size):
|
|
384
|
+
size = min(self.export_chunk_size, steps - start)
|
|
385
|
+
offsets = torch.arange(size, device=device)
|
|
386
|
+
chunk_keys = [list(keys) for keys in past_keys]
|
|
387
|
+
chunk_values = [list(values) for values in past_values]
|
|
388
|
+
|
|
389
|
+
def cond_fn(
|
|
390
|
+
step: torch.Tensor, token: torch.Tensor, done: torch.Tensor, *buffers: torch.Tensor, end=start + size
|
|
391
|
+
):
|
|
392
|
+
return (step < end) & ~done.all()
|
|
393
|
+
|
|
394
|
+
def body_fn(
|
|
395
|
+
step: torch.Tensor,
|
|
396
|
+
token: torch.Tensor,
|
|
397
|
+
done: torch.Tensor,
|
|
398
|
+
*buffers: torch.Tensor,
|
|
399
|
+
start=start,
|
|
400
|
+
size=size,
|
|
401
|
+
offsets=offsets,
|
|
402
|
+
chunk_keys=chunk_keys,
|
|
403
|
+
chunk_values=chunk_values,
|
|
404
|
+
):
|
|
405
|
+
keys, values, chunk_logits = buffers[:num_layers], buffers[num_layers:-1], buffers[-1]
|
|
406
|
+
local = (step - start).view(1)
|
|
407
|
+
# The tokens of the previous chunks and of this chunk up to the current step
|
|
408
|
+
mask = (offsets <= step - start).view(1, 1, 1, size)
|
|
409
|
+
if start > 0:
|
|
410
|
+
mask = torch.cat([torch.ones(1, 1, 1, start, dtype=torch.bool, device=mask.device), mask], dim=-1)
|
|
411
|
+
new_keys, new_values = [], []
|
|
412
|
+
x = self.embed_norm(math.sqrt(self.d_model) * self.embed(token) + self.pos_embed(step.view(1))[None])
|
|
413
|
+
for idx, layer in enumerate(layers):
|
|
414
|
+
|
|
415
|
+
def write_cache(key_t: torch.Tensor, value: torch.Tensor, idx=idx):
|
|
416
|
+
new_keys.append(keys[idx].index_copy(3, local, key_t))
|
|
417
|
+
new_values.append(values[idx].index_copy(2, local, value))
|
|
418
|
+
if not chunk_keys[idx]:
|
|
419
|
+
return new_keys[-1], new_values[-1], mask
|
|
420
|
+
all_keys = torch.cat([*chunk_keys[idx], new_keys[-1]], dim=3)
|
|
421
|
+
all_values = torch.cat([*chunk_values[idx], new_values[-1]], dim=2)
|
|
422
|
+
return all_keys, all_values, mask
|
|
423
|
+
|
|
424
|
+
x = layer.decode_step(x, memory_kv_t[idx], write_cache)
|
|
425
|
+
step_logits = self.head(self.norm(x))
|
|
426
|
+
token = step_logits.argmax(-1)
|
|
427
|
+
return (
|
|
428
|
+
step + 1,
|
|
429
|
+
token,
|
|
430
|
+
done | (token[:, 0] == self.eos),
|
|
431
|
+
*new_keys,
|
|
432
|
+
*new_values,
|
|
433
|
+
chunk_logits.index_copy(1, local, step_logits),
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
out = while_loop(
|
|
437
|
+
cond_fn,
|
|
438
|
+
body_fn,
|
|
439
|
+
(
|
|
440
|
+
step,
|
|
441
|
+
token,
|
|
442
|
+
done,
|
|
443
|
+
*[memory.new_zeros(n, num_heads, head_dim, size) for _ in layers],
|
|
444
|
+
*[memory.new_zeros(n, num_heads, size, head_dim) for _ in layers],
|
|
445
|
+
memory.new_zeros(n, size, self.vocab_size + 1),
|
|
446
|
+
),
|
|
447
|
+
)
|
|
448
|
+
step, token, done = out[:3]
|
|
449
|
+
for idx in range(num_layers):
|
|
450
|
+
past_keys[idx].append(out[3 + idx])
|
|
451
|
+
past_values[idx].append(out[3 + num_layers + idx])
|
|
452
|
+
logits.append(out[-1])
|
|
453
|
+
return torch.cat(logits, dim=1)
|
|
454
|
+
|
|
455
|
+
def forward(
|
|
456
|
+
self,
|
|
457
|
+
x: torch.Tensor,
|
|
458
|
+
target: list[str] | None = None,
|
|
459
|
+
return_model_output: bool = False,
|
|
460
|
+
return_preds: bool = False,
|
|
461
|
+
) -> dict[str, Any]:
|
|
462
|
+
memory = self.encode(x)
|
|
463
|
+
|
|
464
|
+
if self.training and target is None:
|
|
465
|
+
raise ValueError("Need to provide labels during training")
|
|
466
|
+
|
|
467
|
+
loss = None
|
|
468
|
+
if target is not None:
|
|
469
|
+
# Teacher forcing: predict each token from the previous ones
|
|
470
|
+
_gt, _seq_len = self.build_target(target)
|
|
471
|
+
gt = torch.from_numpy(_gt).to(dtype=torch.long, device=x.device)
|
|
472
|
+
gt = gt[:, : max(_seq_len, default=0) + 2] # SOS + longest sequence + EOS
|
|
473
|
+
logits = self.decode(gt[:, :-1], memory)
|
|
474
|
+
loss = F.cross_entropy(logits.flatten(end_dim=1), gt[:, 1:].flatten(), ignore_index=self.pad)
|
|
475
|
+
|
|
476
|
+
if target is None or return_preds:
|
|
477
|
+
logits = self.decode_greedy(memory)
|
|
478
|
+
|
|
479
|
+
logits = _bf16_to_float32(logits)
|
|
480
|
+
|
|
481
|
+
out: dict[str, Any] = {}
|
|
482
|
+
if self.exportable:
|
|
483
|
+
out["logits"] = logits
|
|
484
|
+
return out
|
|
485
|
+
|
|
486
|
+
if return_model_output:
|
|
487
|
+
out["out_map"] = logits
|
|
488
|
+
|
|
489
|
+
if target is None or return_preds:
|
|
490
|
+
# Disable for torch.compile compatibility
|
|
491
|
+
@torch.compiler.disable
|
|
492
|
+
def _postprocess(logits: torch.Tensor) -> list[tuple[str, float]]:
|
|
493
|
+
return self.postprocessor(logits)
|
|
494
|
+
|
|
495
|
+
out["preds"] = _postprocess(logits)
|
|
496
|
+
|
|
497
|
+
if loss is not None:
|
|
498
|
+
out["loss"] = loss
|
|
499
|
+
|
|
500
|
+
return out
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
class FormulaNetPostProcessor(_FormulaNetPostProcessor):
|
|
504
|
+
"""Post processor for FormulaNet architecture
|
|
505
|
+
|
|
506
|
+
Args:
|
|
507
|
+
vocab: the list of LaTeX tokens of the model
|
|
508
|
+
confidence_aggregation: aggregation method of the token probabilities into the formula confidence
|
|
509
|
+
"""
|
|
510
|
+
|
|
511
|
+
def __call__(self, logits: torch.Tensor) -> list[tuple[str, float]]:
|
|
512
|
+
out_idxs = logits.argmax(-1).detach().cpu().numpy()
|
|
513
|
+
probs = torch.softmax(logits, -1).max(dim=-1)[0].detach().float().cpu().numpy()
|
|
514
|
+
eos = len(self.vocab)
|
|
515
|
+
|
|
516
|
+
results: list[tuple[str, float]] = []
|
|
517
|
+
for idxs, token_probs in zip(out_idxs, probs):
|
|
518
|
+
ends = np.flatnonzero(idxs == eos)
|
|
519
|
+
length = int(ends[0]) if ends.size > 0 else len(idxs)
|
|
520
|
+
latex = " ".join(self.vocab[idx] for idx in idxs[:length])
|
|
521
|
+
results.append((latex, aggregate_confidence(token_probs[:length], self.confidence_aggregation)))
|
|
522
|
+
return results
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _formulanet(
|
|
526
|
+
arch: str,
|
|
527
|
+
pretrained: bool,
|
|
528
|
+
backbone_fn: Callable[..., nn.Module],
|
|
529
|
+
layer: str,
|
|
530
|
+
pretrained_backbone: bool = True,
|
|
531
|
+
ignore_keys: list[str] | None = None,
|
|
532
|
+
**kwargs: Any,
|
|
533
|
+
) -> FormulaNet:
|
|
534
|
+
pretrained_backbone = pretrained_backbone and not pretrained
|
|
535
|
+
|
|
536
|
+
# Patch the config
|
|
537
|
+
_cfg = deepcopy(default_cfgs[arch])
|
|
538
|
+
_cfg["vocab"] = list(kwargs.get("vocab", _cfg["vocab"]))
|
|
539
|
+
_cfg["input_shape"] = kwargs.get("input_shape", _cfg["input_shape"])
|
|
540
|
+
|
|
541
|
+
kwargs["vocab"] = _cfg["vocab"]
|
|
542
|
+
kwargs["input_shape"] = _cfg["input_shape"]
|
|
543
|
+
|
|
544
|
+
# Feature extractor: the classification model (head included, to load its pretrained weights as they are), of which
|
|
545
|
+
# only the layers up to `layer` are kept
|
|
546
|
+
backbone = backbone_fn(pretrained_backbone)
|
|
547
|
+
feat_extractor = IntermediateLayerGetter(backbone, {layer: "features"})
|
|
548
|
+
|
|
549
|
+
# Build the model
|
|
550
|
+
feat_channels = cast(list[int], backbone.channels)[-1]
|
|
551
|
+
model = FormulaNet(feat_extractor, feat_channels=feat_channels, cfg=_cfg, **kwargs)
|
|
552
|
+
# Load pretrained parameters
|
|
553
|
+
if pretrained:
|
|
554
|
+
# The number of tokens is not the same as the number of tokens of the pretrained model =>
|
|
555
|
+
# remove the embedding and the last layer weights
|
|
556
|
+
_ignore_keys = ignore_keys if _cfg["vocab"] != default_cfgs[arch]["vocab"] else None
|
|
557
|
+
model.from_pretrained(default_cfgs[arch]["url"], ignore_keys=_ignore_keys)
|
|
558
|
+
|
|
559
|
+
return model
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def formulanet(pretrained: bool = False, **kwargs: Any) -> FormulaNet:
|
|
563
|
+
"""FormulaNet: a HGNetV2-B4 encoder with a transformer decoder predicting LaTeX tokens, following
|
|
564
|
+
`"PP-FormulaNet: Bridging Accuracy and Efficiency in Advanced Formula Recognition"
|
|
565
|
+
<https://arxiv.org/abs/2503.18382>`_.
|
|
566
|
+
|
|
567
|
+
>>> import torch
|
|
568
|
+
>>> from doctr.models import formulanet
|
|
569
|
+
>>> model = formulanet(pretrained=False)
|
|
570
|
+
>>> input_tensor = torch.rand((1, 3, 256, 768))
|
|
571
|
+
>>> out = model(input_tensor)
|
|
572
|
+
|
|
573
|
+
Args:
|
|
574
|
+
pretrained: If True, returns a model pre-trained on a formula recognition dataset
|
|
575
|
+
**kwargs: keyword arguments of the FormulaNet architecture
|
|
576
|
+
|
|
577
|
+
Returns:
|
|
578
|
+
formula recognition architecture
|
|
579
|
+
"""
|
|
580
|
+
return _formulanet(
|
|
581
|
+
"formulanet",
|
|
582
|
+
pretrained,
|
|
583
|
+
hgnetv2_b4,
|
|
584
|
+
"4",
|
|
585
|
+
ignore_keys=["embed.weight", "head.weight", "head.bias"],
|
|
586
|
+
**kwargs,
|
|
587
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|