python-doctr 1.1.0__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/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- 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 +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
|
@@ -3,12 +3,14 @@
|
|
|
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
|
+
from collections.abc import Iterable, Sequence
|
|
6
7
|
from typing import Any
|
|
7
8
|
|
|
8
9
|
import numpy as np
|
|
9
10
|
import torch
|
|
10
11
|
from torch import nn
|
|
11
12
|
|
|
13
|
+
from doctr.models._utils import predict_by_chunks
|
|
12
14
|
from doctr.models.detection._utils import _remove_padding
|
|
13
15
|
from doctr.models.preprocessor import PreProcessor
|
|
14
16
|
from doctr.models.utils import set_device_and_dtype
|
|
@@ -22,23 +24,53 @@ class LayoutPredictor(nn.Module):
|
|
|
22
24
|
Args:
|
|
23
25
|
pre_processor: transform inputs for easier batched model inference
|
|
24
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.
|
|
25
31
|
"""
|
|
26
32
|
|
|
27
33
|
def __init__(
|
|
28
34
|
self,
|
|
29
35
|
pre_processor: PreProcessor,
|
|
30
36
|
model: nn.Module,
|
|
37
|
+
chunk_size: int = 32,
|
|
31
38
|
) -> None:
|
|
32
39
|
super().__init__()
|
|
33
40
|
self.pre_processor = pre_processor
|
|
34
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
|
|
35
45
|
|
|
36
46
|
@torch.inference_mode()
|
|
37
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(
|
|
38
68
|
self,
|
|
39
69
|
pages: list[np.ndarray],
|
|
40
70
|
**kwargs: Any,
|
|
41
71
|
) -> list[dict[str, np.ndarray]]:
|
|
72
|
+
if len(pages) == 0:
|
|
73
|
+
return []
|
|
42
74
|
# Extract parameters from the preprocessor
|
|
43
75
|
preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
|
|
44
76
|
symmetric_pad = self.pre_processor.resize.symmetric_pad
|
doctr/models/layout/zoo.py
CHANGED
|
@@ -42,9 +42,11 @@ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = True,
|
|
|
42
42
|
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
43
43
|
kwargs["std"] = kwargs.get("std", _model.cfg["std"])
|
|
44
44
|
kwargs["batch_size"] = kwargs.get("batch_size", 2)
|
|
45
|
+
chunk_size = kwargs.pop("chunk_size", 32)
|
|
45
46
|
predictor = LayoutPredictor(
|
|
46
47
|
PreProcessor(_model.cfg["input_shape"][1:], **kwargs),
|
|
47
48
|
_model,
|
|
49
|
+
chunk_size=chunk_size,
|
|
48
50
|
)
|
|
49
51
|
return predictor
|
|
50
52
|
|
|
@@ -74,6 +76,8 @@ def layout_predictor(
|
|
|
74
76
|
running the detection model on it
|
|
75
77
|
symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
|
|
76
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
|
|
77
81
|
**kwargs: optional keyword arguments passed to the architecture
|
|
78
82
|
|
|
79
83
|
Returns:
|
|
@@ -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
|