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.
Files changed (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -7,6 +7,11 @@
7
7
  import numpy as np
8
8
 
9
9
  from doctr.datasets import encode_sequences
10
+ from doctr.models._utils import (
11
+ ConfidenceAggregation,
12
+ _confidence_aggregation_repr,
13
+ _resolve_confidence_aggregation,
14
+ )
10
15
  from doctr.utils.repr import NestedObject
11
16
 
12
17
  __all__ = ["RecognitionPostProcessor", "RecognitionModel"]
@@ -41,14 +46,22 @@ class RecognitionPostProcessor(NestedObject):
41
46
 
42
47
  Args:
43
48
  vocab: string containing the ordered sequence of supported characters
49
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence:
50
+ "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a callable
44
51
  """
45
52
 
46
53
  def __init__(
47
54
  self,
48
55
  vocab: str,
56
+ confidence_aggregation: ConfidenceAggregation = "mean",
49
57
  ) -> None:
58
+ _resolve_confidence_aggregation(confidence_aggregation)
50
59
  self.vocab = vocab
60
+ self.confidence_aggregation = confidence_aggregation
51
61
  self._embedding = list(self.vocab) + ["<eos>"]
52
62
 
53
63
  def extra_repr(self) -> str:
54
- return f"vocab_size={len(self.vocab)}"
64
+ return (
65
+ f"vocab_size={len(self.vocab)}, "
66
+ f"confidence_aggregation={_confidence_aggregation_repr(self.confidence_aggregation)}"
67
+ )
@@ -5,15 +5,16 @@
5
5
 
6
6
  from collections.abc import Callable
7
7
  from copy import deepcopy
8
- from itertools import groupby
9
8
  from typing import Any
10
9
 
10
+ import numpy as np
11
11
  import torch
12
12
  from torch import nn
13
13
  from torch.nn import functional as F
14
14
 
15
15
  from doctr.datasets import VOCABS, decode_sequence
16
16
 
17
+ from ..._utils import ConfidenceAggregation, aggregate_confidence
17
18
  from ...classification import mobilenet_v3_large_r, mobilenet_v3_small_r, vgg16_bn_r
18
19
  from ...utils import load_pretrained_params
19
20
  from ..core import RecognitionModel, RecognitionPostProcessor
@@ -50,13 +51,22 @@ class CTCPostProcessor(RecognitionPostProcessor):
50
51
 
51
52
  Args:
52
53
  vocab: string containing the ordered sequence of supported characters
54
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence
53
55
  """
54
56
 
57
+ def __init__(
58
+ self,
59
+ vocab: str,
60
+ confidence_aggregation: ConfidenceAggregation = "min",
61
+ ) -> None:
62
+ super().__init__(vocab, confidence_aggregation)
63
+
55
64
  @staticmethod
56
65
  def ctc_best_path(
57
66
  logits: torch.Tensor,
58
67
  vocab: str = VOCABS["french"],
59
68
  blank: int = 0,
69
+ confidence_aggregation: ConfidenceAggregation = "min",
60
70
  ) -> list[tuple[str, float]]:
61
71
  """Implements best path decoding as shown by Graves (Dissertation, p63), highly inspired from
62
72
  <https://github.com/githubharald/CTCDecoder>`_.
@@ -65,18 +75,27 @@ class CTCPostProcessor(RecognitionPostProcessor):
65
75
  logits: model output, shape: N x T x C
66
76
  vocab: vocabulary to use
67
77
  blank: index of blank label
78
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence
68
79
 
69
80
  Returns:
70
81
  A list of tuples: (word, confidence)
71
82
  """
72
- # Gather the most confident characters, and assign the smallest conf among those to the sequence prob
73
- probs = F.softmax(logits, dim=-1).max(dim=-1).values.min(dim=1).values
74
-
75
- # collapse best path (using itertools.groupby), map to chars, join char list to string
76
- best_paths = torch.argmax(logits, dim=-1).detach().cpu().numpy()
77
- words = [decode_sequence([k for k, _ in groupby(seq.tolist()) if k != blank], vocab) for seq in best_paths]
78
-
79
- return list(zip(words, probs.tolist()))
83
+ best_paths = logits.argmax(dim=-1).detach().cpu().numpy()
84
+ probs = F.softmax(logits.float(), dim=-1).max(dim=-1).values.detach().cpu().numpy()
85
+
86
+ results = []
87
+ for path, path_probs in zip(best_paths, probs):
88
+ # Collapse the repeated labels: the probability of a character is the highest one within its run
89
+ run_starts = np.flatnonzero(np.r_[True, path[1:] != path[:-1]])
90
+ labels, label_probs = path[run_starts], np.maximum.reduceat(path_probs, run_starts)
91
+ # Remove the blanks
92
+ is_char = labels != blank
93
+ results.append((
94
+ decode_sequence(labels[is_char].tolist(), vocab),
95
+ aggregate_confidence(label_probs[is_char], confidence_aggregation),
96
+ ))
97
+
98
+ return results
80
99
 
81
100
  def __call__(self, logits: torch.Tensor) -> list[tuple[str, float]]:
82
101
  """Performs decoding of raw output with CTC and decoding of CTC predictions
@@ -90,7 +109,12 @@ class CTCPostProcessor(RecognitionPostProcessor):
90
109
 
91
110
  """
92
111
  # Decode CTC
93
- return self.ctc_best_path(logits=logits, vocab=self.vocab, blank=len(self.vocab))
112
+ return self.ctc_best_path(
113
+ logits=logits,
114
+ vocab=self.vocab,
115
+ blank=len(self.vocab),
116
+ confidence_aggregation=self.confidence_aggregation,
117
+ )
94
118
 
95
119
 
96
120
  class CRNN(RecognitionModel, nn.Module):
@@ -103,6 +127,7 @@ class CRNN(RecognitionModel, nn.Module):
103
127
  rnn_units: number of units in the LSTM layers
104
128
  exportable: onnx exportable returns only logits
105
129
  cfg: configuration dictionary
130
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence
106
131
  """
107
132
 
108
133
  _children_names: list[str] = ["feat_extractor", "decoder", "linear", "postprocessor"]
@@ -115,6 +140,7 @@ class CRNN(RecognitionModel, nn.Module):
115
140
  input_shape: tuple[int, int, int] = (3, 32, 128),
116
141
  exportable: bool = False,
117
142
  cfg: dict[str, Any] | None = None,
143
+ confidence_aggregation: ConfidenceAggregation = "min",
118
144
  ) -> None:
119
145
  super().__init__()
120
146
  self.vocab = vocab
@@ -139,7 +165,7 @@ class CRNN(RecognitionModel, nn.Module):
139
165
  # features units = 2 * rnn_units because bidirectional layers
140
166
  self.linear = nn.Linear(in_features=2 * rnn_units, out_features=len(vocab) + 1)
141
167
 
142
- self.postprocessor = CTCPostProcessor(vocab=vocab)
168
+ self.postprocessor = CTCPostProcessor(vocab=vocab, confidence_aggregation=confidence_aggregation)
143
169
 
144
170
  for n, m in self.named_modules():
145
171
  # Don't override the initialization of the backbone
@@ -7,6 +7,7 @@
7
7
  import numpy as np
8
8
 
9
9
  from ....datasets import encode_sequences
10
+ from ..._utils import ConfidenceAggregation
10
11
  from ..core import RecognitionPostProcessor
11
12
 
12
13
 
@@ -44,11 +45,13 @@ class _MASTERPostProcessor(RecognitionPostProcessor):
44
45
 
45
46
  Args:
46
47
  vocab: string containing the ordered sequence of supported characters
48
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence
47
49
  """
48
50
 
49
51
  def __init__(
50
52
  self,
51
53
  vocab: str,
54
+ confidence_aggregation: ConfidenceAggregation = "min",
52
55
  ) -> None:
53
- super().__init__(vocab)
56
+ super().__init__(vocab, confidence_aggregation)
54
57
  self._embedding = list(vocab) + ["<eos>"] + ["<sos>"] + ["<pad>"]
@@ -5,8 +5,9 @@
5
5
 
6
6
  from collections.abc import Callable
7
7
  from copy import deepcopy
8
- from typing import Any
8
+ from typing import Any, cast
9
9
 
10
+ import numpy as np
10
11
  import torch
11
12
  from torch import nn
12
13
  from torch.nn import functional as F
@@ -14,8 +15,9 @@ from torchvision.models._utils import IntermediateLayerGetter
14
15
 
15
16
  from doctr.datasets import VOCABS
16
17
  from doctr.models.classification import magc_resnet31
17
- from doctr.models.modules.transformer import Decoder, PositionalEncoding
18
+ from doctr.models.modules.transformer import Decoder, MultiHeadAttention, PositionalEncoding
18
19
 
20
+ from ..._utils import ConfidenceAggregation, aggregate_confidence
19
21
  from ...utils import _bf16_to_float32, load_pretrained_params
20
22
  from .base import _MASTER, _MASTERPostProcessor
21
23
 
@@ -49,6 +51,7 @@ class MASTER(_MASTER, nn.Module):
49
51
  input_shape: size of the image inputs
50
52
  exportable: onnx exportable returns only logits
51
53
  cfg: dictionary containing information about the model
54
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence
52
55
  """
53
56
 
54
57
  def __init__(
@@ -64,6 +67,7 @@ class MASTER(_MASTER, nn.Module):
64
67
  input_shape: tuple[int, int, int] = (3, 32, 128), # different from the paper
65
68
  exportable: bool = False,
66
69
  cfg: dict[str, Any] | None = None,
70
+ confidence_aggregation: ConfidenceAggregation = "min",
67
71
  ) -> None:
68
72
  super().__init__()
69
73
 
@@ -88,7 +92,7 @@ class MASTER(_MASTER, nn.Module):
88
92
  )
89
93
 
90
94
  self.linear = nn.Linear(self.d_model, self.vocab_size + 3)
91
- self.postprocessor = MASTERPostProcessor(vocab=self.vocab)
95
+ self.postprocessor = MASTERPostProcessor(vocab=self.vocab, confidence_aggregation=confidence_aggregation)
92
96
 
93
97
  for n, m in self.named_modules():
94
98
  # Don't override the initialization of the backbone
@@ -243,17 +247,71 @@ class MASTER(_MASTER, nn.Module):
243
247
  ys = torch.full((b, self.max_length), self.vocab_size + 2, dtype=torch.long, device=encoded.device) # pad
244
248
  ys[:, 0] = self.vocab_size + 1 # sos
245
249
 
246
- # Final dimension include EOS/SOS/PAD
247
- for i in range(self.max_length - 1):
248
- source_mask, target_mask = self.make_source_and_target_mask(encoded, ys)
249
- output = self.decoder(ys, encoded, source_mask, target_mask)
250
- # update ys with the next token and ignore the first token (SOS)
251
- ys[:, i + 1] = self.linear(output[:, i]).argmax(-1)
252
- if (ys == self.vocab_size).any(dim=-1).all(): # every sequence has emitted EOS
253
- break
250
+ if torch.compiler.is_exporting():
251
+ return self._decode_loop(encoded, ys)
252
+
253
+ # Incremental decoding: each step only decodes the last token, the previous ones are cached
254
+ cache: list[dict[str, tuple[torch.Tensor, torch.Tensor]]] = []
255
+ logits = []
256
+ for i in range(self.max_length):
257
+ step_logits = self.linear(self.decoder(ys[:, i : i + 1], encoded, cache=cache))
258
+ logits.append(step_logits)
259
+ if i + 1 < self.max_length:
260
+ # update ys with the next token
261
+ ys[:, i + 1] = step_logits[:, 0].argmax(-1)
262
+ # Stop decoding if all sequences have reached the EOS token
263
+ # NOTE: `break` isn't correctly translated to Onnx so we don't break here if we want to export
264
+ if not self.exportable and (ys == self.vocab_size).any(dim=-1).all():
265
+ break
266
+
267
+ out = torch.cat(logits, dim=1)
268
+ # Shape (N, max_length, vocab_size + 1): the positions after an early stop come after the EOS of every
269
+ # sequence, and are not decoded
270
+ return F.pad(out, (0, 0, 0, self.max_length - out.size(1)))
271
+
272
+ def _decode_loop(self, encoded: torch.Tensor, ys: torch.Tensor) -> torch.Tensor:
273
+ """Greedy decoding with `torch.while_loop`, used when the model is traced by `torch.export` (e.g.
274
+ `export_model_to_onnx(..., dynamo=True)`): it is exported as an ONNX `Loop`, which stops once every sequence is
275
+ complete, instead of the `max_length` unrolled steps of the tracing exporter
254
276
 
255
- # Shape (N, max_length, vocab_size + 1)
256
- return self.linear(output)
277
+ Args:
278
+ encoded: the encoded images
279
+ ys: the initial tokens (SOS, then padding), of shape (N, max_length)
280
+
281
+ Returns:
282
+ the logits, of shape (N, max_length, vocab_size + 3), zeros after the end of every sequence (as `decode`)
283
+ """
284
+ from torch._higher_order_ops.while_loop import while_loop
285
+
286
+ decoder = self.decoder
287
+ attentions = [cast(MultiHeadAttention, attention) for attention in decoder.attention]
288
+ # Keys transposed once: no transpose in the loop
289
+ source_kv = []
290
+ for attention in decoder.source_attention:
291
+ key, value = cast(MultiHeadAttention, attention).project_kv(encoded, encoded)
292
+ source_kv.append((key.transpose(-2, -1).contiguous(), value))
293
+ num_layers, heads, head_dim = len(attentions), attentions[0].num_heads, attentions[0].d_k
294
+ length, eos = self.max_length, self.vocab_size
295
+ positions = torch.arange(length, device=encoded.device).view(1, -1)
296
+
297
+ def cond_fn(step: torch.Tensor, ys: torch.Tensor, logits: torch.Tensor, *buffers: torch.Tensor):
298
+ # Stop once every sequence has reached the EOS token
299
+ return (step < length) & ~(ys == eos).any(dim=-1).all()
300
+
301
+ def body_fn(step: torch.Tensor, ys: torch.Tensor, logits: torch.Tensor, *buffers: torch.Tensor):
302
+ output, keys, values = decoder.decode_step(
303
+ ys.index_select(1, step.view(1)), step, source_kv, buffers[:num_layers], buffers[num_layers:]
304
+ )
305
+ step_logits = self.linear(output)
306
+ # Write the next token (none after the last step)
307
+ ys = torch.where(positions == step + 1, step_logits[:, 0].argmax(-1, keepdim=True), ys)
308
+ return step + 1, ys, logits.index_copy(1, step.view(1), step_logits), *keys, *values
309
+
310
+ buffers = [encoded.new_zeros(encoded.size(0), heads, head_dim, length) for _ in range(num_layers)]
311
+ buffers += [encoded.new_zeros(encoded.size(0), heads, length, head_dim) for _ in range(num_layers)]
312
+ logits = encoded.new_zeros(encoded.size(0), length, self.linear.out_features)
313
+ step = torch.zeros((), dtype=torch.long, device=encoded.device)
314
+ return while_loop(cond_fn, body_fn, (step, ys, logits, *buffers))[2]
257
315
 
258
316
 
259
317
  class MASTERPostProcessor(_MASTERPostProcessor):
@@ -264,19 +322,24 @@ class MASTERPostProcessor(_MASTERPostProcessor):
264
322
  logits: torch.Tensor,
265
323
  ) -> list[tuple[str, float]]:
266
324
  # compute pred with argmax for attention models
267
- out_idxs = logits.argmax(-1)
325
+ out_idxs = logits.argmax(-1).detach().cpu().numpy()
268
326
  # N x L
269
- probs = torch.gather(torch.softmax(logits, -1), -1, out_idxs.unsqueeze(-1)).squeeze(-1)
270
- # Take the minimum confidence of the sequence
271
- probs = probs.min(dim=1).values.detach().cpu()
327
+ preds_prob = torch.softmax(logits, -1).max(dim=-1)[0].detach().cpu().numpy()
272
328
 
273
329
  # Manual decoding
274
330
  word_values = [
275
- "".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
276
- for encoded_seq in out_idxs.detach().cpu().numpy()
331
+ "".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0] for encoded_seq in out_idxs
332
+ ]
333
+ # aggregate the character probabilities of each word up to the EOS token: the number of predicted tokens is
334
+ # used since the <sos> and <pad> tokens are decoded as several characters
335
+ is_eos = out_idxs == len(self.vocab)
336
+ seq_lens = np.where(is_eos.any(axis=-1), is_eos.argmax(axis=-1), out_idxs.shape[-1])
337
+ probs = [
338
+ aggregate_confidence(preds_prob[i, :seq_len], self.confidence_aggregation)
339
+ for i, seq_len in enumerate(seq_lens)
277
340
  ]
278
341
 
279
- return list(zip(word_values, probs.numpy().clip(0, 1).tolist()))
342
+ return list(zip(word_values, probs))
280
343
 
281
344
 
282
345
  def _master(
@@ -7,6 +7,7 @@
7
7
  import numpy as np
8
8
 
9
9
  from ....datasets import encode_sequences
10
+ from ..._utils import ConfidenceAggregation
10
11
  from ..core import RecognitionPostProcessor
11
12
 
12
13
 
@@ -44,11 +45,13 @@ class _PARSeqPostProcessor(RecognitionPostProcessor):
44
45
 
45
46
  Args:
46
47
  vocab: string containing the ordered sequence of supported characters
48
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence
47
49
  """
48
50
 
49
51
  def __init__(
50
52
  self,
51
53
  vocab: str,
54
+ confidence_aggregation: ConfidenceAggregation = "mean",
52
55
  ) -> None:
53
- super().__init__(vocab)
56
+ super().__init__(vocab, confidence_aggregation)
54
57
  self._embedding = list(vocab) + ["<eos>", "<sos>", "<pad>"]
@@ -18,6 +18,7 @@ from torchvision.models._utils import IntermediateLayerGetter
18
18
  from doctr.datasets import VOCABS
19
19
  from doctr.models.modules.transformer import MultiHeadAttention, PositionwiseFeedForward
20
20
 
21
+ from ..._utils import ConfidenceAggregation, aggregate_confidence
21
22
  from ...classification import vit_s
22
23
  from ...utils import _bf16_to_float32, load_pretrained_params
23
24
  from .base import _PARSeq, _PARSeqPostProcessor
@@ -84,21 +85,45 @@ class PARSeqDecoder(nn.Module):
84
85
  self.cross_attention_dropout = nn.Dropout(dropout)
85
86
  self.feed_forward_dropout = nn.Dropout(dropout)
86
87
 
88
+ def project_content(self, content: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
89
+ """Normalize and project the content into the keys and values of the self-attention"""
90
+ content_norm = self.content_norm(content)
91
+ return self.attention.project_kv(content_norm, content_norm)
92
+
87
93
  def forward(
88
94
  self,
89
95
  target,
90
96
  content,
91
97
  memory,
92
98
  target_mask: torch.Tensor | None = None,
99
+ content_kv: tuple[torch.Tensor, torch.Tensor] | None = None,
100
+ memory_kv: tuple[torch.Tensor, torch.Tensor] | None = None,
101
+ keys_transposed: bool = False,
93
102
  ):
103
+ """Decode the target queries
104
+
105
+ Args:
106
+ target: target queries of shape (N, L, d_model)
107
+ content: content of shape (N, S, d_model), unused if `content_kv` is given
108
+ memory: encoded image of shape (N, T, d_model), unused if `memory_kv` is given
109
+ target_mask: optional mask of the content for the target queries
110
+ content_kv: optional keys and values of the content, cf. `project_content`
111
+ memory_kv: optional keys and values of the memory, cf. `MultiHeadAttention.project_kv`
112
+ keys_transposed: whether the keys of `content_kv` and `memory_kv` are transposed, of shape
113
+ (N, num_heads, d_k, S) (inference, cf. `MultiHeadAttention.attend_transposed`)
114
+
115
+ Returns:
116
+ the decoded queries of shape (N, L, d_model)
117
+ """
94
118
  query_norm = self.query_norm(target)
95
- content_norm = self.content_norm(content)
96
- target = target.clone() + self.attention_dropout(
97
- self.attention(query_norm, content_norm, content_norm, mask=target_mask)
98
- )
99
- target = target.clone() + self.cross_attention_dropout(
100
- self.cross_attention(self.query_norm(target), memory, memory)
101
- )
119
+ if content_kv is None:
120
+ content_kv = self.project_content(content)
121
+ attend = self.attention.attend_transposed if keys_transposed else self.attention.attend
122
+ target = target.clone() + self.attention_dropout(attend(query_norm, *content_kv, mask=target_mask))
123
+ if memory_kv is None:
124
+ memory_kv = self.cross_attention.project_kv(memory, memory)
125
+ attend = self.cross_attention.attend_transposed if keys_transposed else self.cross_attention.attend
126
+ target = target.clone() + self.cross_attention_dropout(attend(self.query_norm(target), *memory_kv))
102
127
  target = target.clone() + self.feed_forward_dropout(self.position_feed_forward(self.feed_forward_norm(target)))
103
128
  return self.output_norm(target)
104
129
 
@@ -120,6 +145,7 @@ class PARSeq(_PARSeq, nn.Module):
120
145
  input_shape: input shape of the image
121
146
  exportable: onnx exportable returns only logits
122
147
  cfg: dictionary containing information about the model
148
+ confidence_aggregation: aggregation method of the character probabilities into the word confidence
123
149
  """
124
150
 
125
151
  def __init__(
@@ -135,6 +161,7 @@ class PARSeq(_PARSeq, nn.Module):
135
161
  input_shape: tuple[int, int, int] = (3, 32, 128),
136
162
  exportable: bool = False,
137
163
  cfg: dict[str, Any] | None = None,
164
+ confidence_aggregation: ConfidenceAggregation = "mean",
138
165
  ) -> None:
139
166
  super().__init__()
140
167
  self.vocab = vocab
@@ -152,7 +179,7 @@ class PARSeq(_PARSeq, nn.Module):
152
179
  self.pos_queries = nn.Parameter(torch.Tensor(1, self.max_length + 1, embedding_units)) # +1 for EOS
153
180
  self.dropout = nn.Dropout(p=dropout_prob)
154
181
 
155
- self.postprocessor = PARSeqPostProcessor(vocab=self.vocab)
182
+ self.postprocessor = PARSeqPostProcessor(vocab=self.vocab, confidence_aggregation=confidence_aggregation)
156
183
 
157
184
  nn.init.trunc_normal_(self.pos_queries, std=0.02)
158
185
  for n, m in self.named_modules():
@@ -281,14 +308,25 @@ class PARSeq(_PARSeq, nn.Module):
281
308
  torch.tril(torch.ones((max_length, max_length), device=features.device), diagonal=0).to(dtype=torch.bool)
282
309
  ).int()
283
310
 
311
+ if max_len is None and torch.compiler.is_exporting():
312
+ return self._decode_autoregressive_loop(features, ys, pos_queries, query_mask)
313
+
314
+ # Incremental decoding: project the image features once and the content one token at a time (cached)
315
+ memory_kv = self.decoder.cross_attention.project_kv(features, features)
316
+ content_kv: tuple[torch.Tensor, torch.Tensor] | None = None
284
317
  pos_logits = []
285
318
  for i in range(max_length):
319
+ # Content of the last token: its embedding, with the position it is read at (none for SOS)
320
+ content = self.embed(ys[:, i : i + 1])
321
+ if i > 0:
322
+ content = self.pos_queries[:, i - 1 : i] + content
323
+ key, value = self.decoder.project_content(self.dropout(content))
324
+ if content_kv is not None:
325
+ key, value = torch.cat([content_kv[0], key], dim=2), torch.cat([content_kv[1], value], dim=2)
326
+ content_kv = (key, value)
286
327
  # Decode one token at a time without providing information about the future tokens
287
- tgt_out = self.decode(
288
- ys[:, : i + 1],
289
- features,
290
- query_mask[i : i + 1, : i + 1],
291
- target_query=pos_queries[:, i : i + 1],
328
+ tgt_out = self.decoder(
329
+ self.dropout(pos_queries[:, i : i + 1]), None, None, content_kv=content_kv, memory_kv=memory_kv
292
330
  )
293
331
  pos_prob = self.head(tgt_out)
294
332
  pos_logits.append(pos_prob)
@@ -304,21 +342,83 @@ class PARSeq(_PARSeq, nn.Module):
304
342
 
305
343
  logits = torch.cat(pos_logits, dim=1) # (N, max_length, vocab_size + 1)
306
344
 
307
- # One refine iteration
308
- # Update query mask
309
- query_mask[torch.triu(torch.ones(max_length, max_length, dtype=torch.bool, device=features.device), 2)] = 1
310
-
311
345
  # Prepare target input for 1 refine iteration
312
346
  sos = torch.full((features.size(0), 1), self.vocab_size + 1, dtype=torch.long, device=features.device)
313
- ys = torch.cat([sos, logits[:, :-1].argmax(-1)], dim=1)
347
+ return self._refine(torch.cat([sos, logits[:, :-1].argmax(-1)], dim=1), features, pos_queries, query_mask)
348
+
349
+ def _refine(
350
+ self, ys: torch.Tensor, features: torch.Tensor, pos_queries: torch.Tensor, query_mask: torch.Tensor
351
+ ) -> torch.Tensor:
352
+ """One refine iteration of the decoded tokens `ys` (starting with SOS), with the context of every token"""
353
+ max_length = query_mask.shape[0]
354
+ # Update query mask
355
+ query_mask[torch.triu(torch.ones(max_length, max_length, dtype=torch.bool, device=features.device), 2)] = 1
314
356
 
315
357
  # Create padding mask for refined target input maskes all behind EOS token as False
316
358
  # (N, 1, 1, max_length)
317
359
  target_pad_mask = ~((ys == self.vocab_size).int().cumsum(-1) > 0).unsqueeze(1).unsqueeze(1)
318
360
  mask = (target_pad_mask.bool() & query_mask[:, : ys.shape[1]].bool()).int()
319
- logits = self.head(self.decode(ys, features, mask, target_query=pos_queries))
361
+ return self.head(self.decode(ys, features, mask, target_query=pos_queries)) # (N, max_length, vocab_size + 1)
362
+
363
+ def _decode_autoregressive_loop(
364
+ self, features: torch.Tensor, ys: torch.Tensor, pos_queries: torch.Tensor, query_mask: torch.Tensor
365
+ ) -> torch.Tensor:
366
+ """Autoregressive decoding with `torch.while_loop`, used when the model is traced by `torch.export` (e.g.
367
+ `export_model_to_onnx(..., dynamo=True)`): it is exported as an ONNX `Loop`, which stops once every sequence is
368
+ complete, instead of the `max_length` unrolled steps of the tracing exporter
369
+
370
+ Args:
371
+ features: the image features
372
+ ys: the initial tokens (SOS, then padding), of shape (N, max_length)
373
+ pos_queries: the position queries, of shape (N, max_length, d_model)
374
+ query_mask: the query mask of the decoder attention
320
375
 
321
- return logits # (N, max_length, vocab_size + 1)
376
+ Returns:
377
+ the refined logits, as `decode_autoregressive`
378
+ """
379
+ from torch._higher_order_ops.while_loop import while_loop
380
+
381
+ decoder, length, eos = self.decoder, ys.shape[1], self.vocab_size
382
+ heads, head_dim = decoder.attention.num_heads, decoder.attention.d_k
383
+ positions = torch.arange(length, device=features.device).view(1, -1)
384
+ # Keys transposed once (image features) or when written (content): no transpose in the loop
385
+ memory_k, memory_v = decoder.cross_attention.project_kv(features, features)
386
+ memory_kv = (memory_k.transpose(-2, -1).contiguous(), memory_v)
387
+ # The content of a token is its embedding, with the position it is read at (none for SOS)
388
+ content_pos = F.pad(self.pos_queries[:, : length - 1], (0, 0, 1, 0))
389
+
390
+ def cond_fn(step: torch.Tensor, ys: torch.Tensor, keys: torch.Tensor, values: torch.Tensor):
391
+ # Stop once every sequence has reached the EOS token
392
+ return (step < length) & ~(ys == eos).any(dim=-1).all()
393
+
394
+ def body_fn(step: torch.Tensor, ys: torch.Tensor, keys: torch.Tensor, values: torch.Tensor):
395
+ idx = step.view(1)
396
+ content = self.embed(ys.index_select(1, idx)) + content_pos.index_select(1, idx)
397
+ key, value = decoder.project_content(self.dropout(content))
398
+ keys, values = keys.index_copy(3, idx, key.transpose(-2, -1)), values.index_copy(2, idx, value)
399
+ # Decode one token at a time without providing information about the future tokens
400
+ query = self.dropout(self.pos_queries.index_select(1, idx).expand(ys.shape[0], -1, -1))
401
+ tgt_out = decoder(
402
+ query,
403
+ None,
404
+ None,
405
+ (positions <= step).view(1, 1, 1, -1),
406
+ content_kv=(keys, values),
407
+ memory_kv=memory_kv,
408
+ keys_transposed=True,
409
+ )
410
+ # Write the next token (none after the last step)
411
+ ys = torch.where(positions == step + 1, self.head(tgt_out)[:, 0].argmax(-1, keepdim=True), ys)
412
+ return step + 1, ys, keys, values
413
+
414
+ buffers = [
415
+ features.new_zeros(features.size(0), heads, head_dim, length), # transposed keys
416
+ features.new_zeros(features.size(0), heads, length, head_dim),
417
+ ]
418
+ step = torch.zeros((), dtype=torch.long, device=features.device)
419
+ steps, ys, _, _ = while_loop(cond_fn, body_fn, (step, ys, *buffers))
420
+ # The positions that were not decoded come after the EOS of every sequence: they are read as padding
421
+ return self._refine(torch.where(positions < steps, ys, eos), features, pos_queries, query_mask)
322
422
 
323
423
  def forward(
324
424
  self,
@@ -424,9 +524,10 @@ class PARSeqPostProcessor(_PARSeqPostProcessor):
424
524
  "".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
425
525
  for encoded_seq in out_idxs.detach().cpu().numpy()
426
526
  ]
427
- # compute probabilties for each word up to the EOS token
527
+ # aggregate the character probabilities of each word up to the EOS token
428
528
  probs = [
429
- float(preds_prob[i, : len(word)].clip(0, 1).mean()) if word else 0.0 for i, word in enumerate(word_values)
529
+ aggregate_confidence(preds_prob[i, : len(word)], self.confidence_aggregation)
530
+ for i, word in enumerate(word_values)
430
531
  ]
431
532
 
432
533
  return list(zip(word_values, probs))