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
@@ -0,0 +1,132 @@
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.preprocessor import PreProcessor
15
+ from doctr.models.utils import set_device_and_dtype
16
+ from doctr.utils.geometry import extract_crops, extract_rcrops
17
+
18
+ __all__ = ["FormulaPredictor"]
19
+
20
+
21
+ def _crop_region(page: np.ndarray, region: np.ndarray) -> np.ndarray | None:
22
+ """Crop a page-relative region, a straight box (4,) or a polygon (4, 2), None for a degenerate region"""
23
+ region = np.asarray(region, dtype=np.float32)
24
+ if region.ndim == 1:
25
+ crop = extract_crops(page, np.clip(region, 0, 1)[None])[0]
26
+ else:
27
+ crop = extract_rcrops(page, np.clip(region, 0, 1)[None], assume_horizontal=False)[0]
28
+ return crop if crop.shape[0] >= 2 and crop.shape[1] >= 2 else None
29
+
30
+
31
+ class FormulaPredictor(nn.Module):
32
+ """Implements an object able to recognize mathematical formulas as LaTeX strings
33
+
34
+ Each formula image is resized (keeping its aspect ratio), padded and normalized. The margins around a formula
35
+ (e.g. of a layout region) are kept: the model is trained to read formulas with margins.
36
+
37
+ Args:
38
+ pre_processor: transform inputs for easier batched model inference
39
+ model: core formula recognition architecture
40
+ chunk_size: the maximum number of formula images decoded and processed at once (128 by default). Longer
41
+ inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
42
+ chunk by chunk, with a memory footprint that does not grow with the number of images. It is rounded
43
+ up to a multiple of the batch size, so that the predictions are the same as in a single pass.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ pre_processor: PreProcessor,
49
+ model: nn.Module,
50
+ chunk_size: int = 128,
51
+ ) -> None:
52
+ super().__init__()
53
+ self.pre_processor = pre_processor
54
+ self.model = model.eval()
55
+ if chunk_size < 1:
56
+ raise ValueError("`chunk_size` must be a positive integer")
57
+ self.chunk_size = chunk_size
58
+
59
+ @torch.inference_mode()
60
+ def forward(
61
+ self,
62
+ crops: Sequence[np.ndarray] | Iterable[np.ndarray],
63
+ **kwargs: Any,
64
+ ) -> list[tuple[str, float]]:
65
+ """Recognize the formula of each image
66
+
67
+ Args:
68
+ crops: a list of formula images (numpy arrays of shape H x W x C), a lazy page source
69
+ (cf. `DocumentFile.from_images(..., lazy=True)`) or any iterable of images
70
+ **kwargs: keyword arguments forwarded to the model
71
+
72
+ Returns:
73
+ the LaTeX string (tokens separated by spaces) and the confidence of each image
74
+ """
75
+ return predict_by_chunks(
76
+ lambda chunk: self._predict(chunk, **kwargs), crops, self.chunk_size, self.pre_processor.batch_size
77
+ )
78
+
79
+ @torch.inference_mode()
80
+ def _predict(self, crops: Sequence[np.ndarray], **kwargs: Any) -> list[tuple[str, float]]:
81
+ if len(crops) == 0:
82
+ return []
83
+ # Dimension check
84
+ if any(crop.ndim != 3 for crop in crops):
85
+ raise ValueError("incorrect input shape: all crops are expected to be multi-channel 2D images.")
86
+ empty = next((crop for crop in crops if not all(s > 0 for s in crop.shape)), None)
87
+ if empty is not None:
88
+ raise ValueError(f"incorrect input shape: crops are expected to be non-empty, got shape {empty.shape}.")
89
+
90
+ processed_batches = self.pre_processor(list(crops))
91
+ _params = next(self.model.parameters())
92
+ self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
93
+ self.model, processed_batches, _params.device, _params.dtype
94
+ )
95
+ raw = [self.model(batch, return_preds=True, **kwargs)["preds"] for batch in processed_batches]
96
+ return [pred for batch in raw for pred in batch]
97
+
98
+ @torch.inference_mode()
99
+ def predict_regions(
100
+ self,
101
+ pages: list[np.ndarray],
102
+ regions: list[dict[str, Any] | None],
103
+ class_name: str = "Formula",
104
+ **kwargs: Any,
105
+ ) -> list[list[dict[str, Any]]]:
106
+ """Recognize the formulas a layout model located on pages
107
+
108
+ Args:
109
+ pages: the page images
110
+ regions: the per-page layout predictions `{"class_names", "boxes", "scores"}` (None for none)
111
+ class_name: the layout class of the formula regions
112
+ **kwargs: keyword arguments forwarded to the model
113
+
114
+ Returns:
115
+ a per-page list of formulas `{"geometry", "value", "confidence", "score"}`, with the geometry of the
116
+ layout region (page-relative) and its layout score
117
+ """
118
+ crops: list[np.ndarray] = []
119
+ meta: list[tuple[int, np.ndarray, float | None]] = []
120
+ for p_idx, (page, region) in enumerate(zip(pages, regions)):
121
+ region = region or {}
122
+ scores = region.get("scores")
123
+ for r_idx, (cls_name, box) in enumerate(zip(region.get("class_names", []), region.get("boxes", []))):
124
+ crop = _crop_region(page, box) if cls_name == class_name else None
125
+ if crop is not None:
126
+ crops.append(crop)
127
+ meta.append((p_idx, np.asarray(box), None if scores is None else float(scores[r_idx])))
128
+
129
+ formulas: list[list[dict[str, Any]]] = [[] for _ in pages]
130
+ for (p_idx, box, score), (latex, confidence) in zip(meta, self(crops, **kwargs) if crops else []):
131
+ formulas[p_idx].append({"geometry": box, "value": latex, "confidence": confidence, "score": score})
132
+ return formulas
@@ -0,0 +1,102 @@
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 formula
11
+ from .._utils import ConfidenceAggregation, _resolve_confidence_aggregation
12
+ from ..preprocessor import PreProcessor
13
+ from .predictor import FormulaPredictor
14
+
15
+ __all__ = ["formula_predictor"]
16
+
17
+ ARCHS: list[str] = ["formulanet"]
18
+
19
+
20
+ def _predictor(
21
+ arch: Any,
22
+ pretrained: bool,
23
+ confidence_aggregation: ConfidenceAggregation | None = None,
24
+ max_decode_length: int | None = None,
25
+ **kwargs: Any,
26
+ ) -> FormulaPredictor:
27
+ if confidence_aggregation is not None:
28
+ _resolve_confidence_aggregation(confidence_aggregation)
29
+
30
+ if isinstance(arch, str):
31
+ if arch not in ARCHS:
32
+ raise ValueError(f"unknown architecture '{arch}'")
33
+ _model = formula.__dict__[arch](
34
+ pretrained=pretrained, pretrained_backbone=kwargs.get("pretrained_backbone", True)
35
+ )
36
+ else:
37
+ # Adding the type for torch compiled models to the allowed architectures
38
+ allowed_archs = [formula.FormulaNet, _CompiledModule]
39
+ if not isinstance(arch, tuple(allowed_archs)):
40
+ raise ValueError(f"unknown architecture: {type(arch)}")
41
+ _model = arch
42
+
43
+ if confidence_aggregation is not None:
44
+ _model.postprocessor.confidence_aggregation = confidence_aggregation
45
+ if max_decode_length is not None:
46
+ _model.max_decode_length = max_decode_length
47
+
48
+ kwargs.pop("pretrained_backbone", None)
49
+ kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
50
+ kwargs["std"] = kwargs.get("std", _model.cfg["std"])
51
+ kwargs["batch_size"] = kwargs.get("batch_size", 16)
52
+ chunk_size = kwargs.pop("chunk_size", 128)
53
+ # Same resizing as during training: aspect ratio preserved, padded at the bottom-right
54
+ kwargs.setdefault("symmetric_pad", False)
55
+ predictor = FormulaPredictor(
56
+ PreProcessor(_model.cfg["input_shape"][1:], preserve_aspect_ratio=True, **kwargs),
57
+ _model,
58
+ chunk_size=chunk_size,
59
+ )
60
+ return predictor
61
+
62
+
63
+ def formula_predictor(
64
+ arch: Any = "formulanet",
65
+ pretrained: bool = False,
66
+ batch_size: int = 16,
67
+ confidence_aggregation: ConfidenceAggregation | None = None,
68
+ max_decode_length: int | None = None,
69
+ **kwargs: Any,
70
+ ) -> FormulaPredictor:
71
+ """Formula recognition architecture: turns images of mathematical formulas into LaTeX strings.
72
+
73
+ >>> import numpy as np
74
+ >>> from doctr.models import formula_predictor
75
+ >>> model = formula_predictor(arch='formulanet', pretrained=True)
76
+ >>> input_crop = (255 * np.random.rand(64, 256, 3)).astype(np.uint8)
77
+ >>> out = model([input_crop])
78
+
79
+ Args:
80
+ arch: name of the architecture or model itself to use (e.g. 'formulanet')
81
+ pretrained: If True, returns a model pre-trained on a formula recognition dataset
82
+ batch_size: number of samples the model processes in parallel
83
+ confidence_aggregation: aggregation method of the token probabilities into the formula confidence:
84
+ "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a callable. If None, the one of
85
+ the model is kept ("mean" by default)
86
+ max_decode_length: maximum number of tokens generated per formula. If None, the one of the model is kept
87
+ (2048 by default). A model instance passed as `arch` is modified.
88
+ chunk_size: maximum number of formula images decoded and processed at once (128 by default): longer inputs and
89
+ lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
90
+ **kwargs: optional keyword arguments passed to the architecture
91
+
92
+ Returns:
93
+ Formula recognition predictor
94
+ """
95
+ return _predictor(
96
+ arch=arch,
97
+ pretrained=pretrained,
98
+ batch_size=batch_size,
99
+ confidence_aggregation=confidence_aggregation,
100
+ max_decode_length=max_decode_length,
101
+ **kwargs,
102
+ )
@@ -6,6 +6,7 @@
6
6
  from collections.abc import Collection
7
7
  from typing import Any
8
8
 
9
+ from doctr.io.elements import Document, KIEDocument
9
10
  from doctr.models.builder import KIEDocumentBuilder
10
11
 
11
12
  from ..classification.predictor import OrientationPredictor
@@ -32,11 +33,15 @@ class _KIEPredictor(_OCRPredictor):
32
33
  be masked out (filled with black) before passing the pages to the detection/recognition modules.
33
34
  preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
34
35
  original page coordinates. Useful for redaction and annotation.
36
+ page_chunk_size: the maximum number of pages processed at once for lazy page sources, iterators and
37
+ `stream`, so that the memory footprint does not grow with the number of pages. Lists and tuples of pages
38
+ are processed in a single pass.
35
39
  kwargs: keyword args of `DocumentBuilder`
36
40
  """
37
41
 
38
42
  crop_orientation_predictor: OrientationPredictor | None
39
43
  page_orientation_predictor: OrientationPredictor | None
44
+ _document_cls: type[Document] = KIEDocument
40
45
 
41
46
  def __init__(
42
47
  self,
@@ -47,6 +52,7 @@ class _KIEPredictor(_OCRPredictor):
47
52
  detect_orientation: bool = False,
48
53
  ignore_regions: Collection[str] | None = None,
49
54
  preserve_original_coords: bool = False,
55
+ page_chunk_size: int = 32,
50
56
  **kwargs: Any,
51
57
  ) -> None:
52
58
  super().__init__(
@@ -57,6 +63,7 @@ class _KIEPredictor(_OCRPredictor):
57
63
  detect_orientation,
58
64
  ignore_regions,
59
65
  preserve_original_coords=preserve_original_coords,
66
+ page_chunk_size=page_chunk_size,
60
67
  **kwargs,
61
68
  )
62
69
 
@@ -3,13 +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
 
12
- from doctr.io.elements import Document
13
+ from doctr.io.elements import Document, KIEDocument
13
14
  from doctr.models._utils import get_language, invert_data_structure
14
15
  from doctr.models.detection.predictor import DetectionPredictor
15
16
  from doctr.models.layout.predictor import LayoutPredictor
@@ -39,6 +40,9 @@ class KIEPredictor(nn.Module, _KIEPredictor):
39
40
  preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
40
41
  original page coordinates. Useful for redaction and annotation.
41
42
  layout_predictor: optional layout detection module
43
+ page_chunk_size: the maximum number of pages processed at once (32 by default) for lazy page sources
44
+ (cf. `DocumentFile.from_pdf(..., lazy=True)`), iterators and :meth:`stream`, with a memory footprint that
45
+ does not grow with the number of pages. Lists and tuples of pages are processed in a single pass.
42
46
  **kwargs: keyword args of `DocumentBuilder`
43
47
  """
44
48
 
@@ -75,10 +79,33 @@ class KIEPredictor(nn.Module, _KIEPredictor):
75
79
 
76
80
  @torch.inference_mode()
77
81
  def forward(
82
+ self,
83
+ pages: Sequence[np.ndarray] | Iterable[np.ndarray],
84
+ **kwargs: Any,
85
+ ) -> Document:
86
+ """Predict on a document
87
+
88
+ Args:
89
+ pages: a list of pages (numpy arrays of shape H x W x C), processed in a single pass, or a lazy page
90
+ source (cf. `DocumentFile.from_pdf(..., lazy=True)`) or any iterable of pages, processed chunk by
91
+ chunk (`page_chunk_size` pages at a time) with a bounded memory footprint
92
+ **kwargs: keyword arguments forwarded to the sub-predictors, and `on_error` for lazy page sources
93
+ (cf. :meth:`stream`): "skip" leaves out the pages that cannot be read instead of raising an error
94
+
95
+ Returns:
96
+ the predicted document
97
+ """
98
+ return self._run(pages, **kwargs)
99
+
100
+ @torch.inference_mode()
101
+ def _predict_pages(
78
102
  self,
79
103
  pages: list[np.ndarray],
80
104
  **kwargs: Any,
81
105
  ) -> Document:
106
+ if len(pages) == 0:
107
+ return KIEDocument(pages=[])
108
+
82
109
  # Dimension check
83
110
  if any(page.ndim != 3 for page in pages):
84
111
  raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
@@ -128,7 +155,7 @@ class KIEPredictor(nn.Module, _KIEPredictor):
128
155
  det_pages = self._mask_regions(pages, regions)
129
156
 
130
157
  # Forward again to get predictions on straight pages
131
- loc_preds = self.det_predictor(det_pages, **kwargs)
158
+ loc_preds = self._detect_straightened(loc_preds, _orig_pages, pages, det_pages, **kwargs)
132
159
 
133
160
  dict_loc_preds: dict[str, list[np.ndarray]] = invert_data_structure(loc_preds) # type: ignore[assignment]
134
161
 
@@ -139,19 +166,33 @@ class KIEPredictor(nn.Module, _KIEPredictor):
139
166
  dict_loc_preds[class_name] = _loc_preds
140
167
  objectness_scores[class_name] = _scores
141
168
 
142
- # Apply hooks to loc_preds if any
143
- for hook in self.hooks:
144
- dict_loc_preds = hook(dict_loc_preds)
169
+ # Apply hooks to loc_preds if any, before the crops are extracted so that the hooked boxes are read
170
+ if self.hooks:
171
+ # Pass a copy, so that a hook modifying its input in place does not alter the reference
172
+ hooked_preds: Any = {class_name: list(preds) for class_name, preds in dict_loc_preds.items()}
173
+ for hook in self.hooks:
174
+ hooked_preds = hook(hooked_preds)
175
+ if not isinstance(hooked_preds, dict) or set(hooked_preds) != set(dict_loc_preds):
176
+ raise ValueError(
177
+ "hooks of the KIE predictor must return a dict with the same classes as their input: "
178
+ f"{sorted(dict_loc_preds)}"
179
+ )
180
+ for class_name in dict_loc_preds.keys():
181
+ dict_loc_preds[class_name], objectness_scores[class_name] = self._align_hook_output(
182
+ dict_loc_preds[class_name], hooked_preds[class_name], objectness_scores[class_name]
183
+ )
145
184
 
146
185
  # Crop images
147
186
  crops = {}
148
187
  for class_name in dict_loc_preds.keys():
149
- crops[class_name], dict_loc_preds[class_name] = self._prepare_crops(
188
+ crops[class_name], dict_loc_preds[class_name], objectness_scores[class_name] = self._prepare_crops(
150
189
  pages,
151
190
  dict_loc_preds[class_name],
191
+ objectness_scores[class_name],
152
192
  assume_straight_pages=self.assume_straight_pages,
153
193
  assume_horizontal=self._page_orientation_disabled,
154
194
  )
195
+
155
196
  # Rectify crop orientation
156
197
  crop_orientations: Any = {}
157
198
  if not self.assume_straight_pages:
@@ -65,7 +65,7 @@ default_cfgs: dict[str, dict[str, Any]] = {
65
65
  "Text",
66
66
  "Title",
67
67
  ],
68
- "url": None,
68
+ "url": "https://github.com/mindee/doctr/releases/download/v1.1.0/lw_detr_m-12c799e1.pt",
69
69
  },
70
70
  }
71
71
 
@@ -577,37 +577,29 @@ class LWDETR(nn.Module, _LWDETR):
577
577
  # ProbIoU is computed in pixel coordinates
578
578
  box_scale = float(max(input.shape[-2], input.shape[-1]))
579
579
 
580
- # Main loss from final decoder layer (group DETR: each group is matched independently)
581
- split_logits = logits.chunk(group_detr, dim=1)
582
- split_boxes = pred_boxes.chunk(group_detr, dim=1)
583
-
584
- main_loss: float | torch.Tensor = 0.0
585
- for g_logits, g_boxes in zip(split_logits, split_boxes):
586
- main_loss += self.compute_loss(g_logits, g_boxes, processed_targets, box_scale=box_scale)
587
- loss = main_loss / group_detr
588
-
589
- # Auxiliary losses from intermediate decoder layers
590
- # (`intermediate_reference_points[i]` is the reference INPUT to decoder layer i)
580
+ # Every prediction set supervised by the loss, each holding (B, num_queries, ...) tensors:
581
+ # the final decoder layer split by group, the intermediate decoder layers split by group
582
+ # (`intermediate_reference_points[i]` is the reference INPUT to decoder layer i) and the selected
583
+ # encoder proposals of every group. They are all weighted 1 / group_detr, so they can be matched and
584
+ # scored in one batched pass instead of one Hungarian matching per (set, sample).
585
+ logits_sets = list(logits.chunk(group_detr, dim=1))
586
+ boxes_sets = list(pred_boxes.chunk(group_detr, dim=1))
591
587
  for i in range(intermediate.shape[0] - 1):
592
588
  aux_logits = self.class_embed(intermediate[i])
593
589
  aux_boxes_delta = self.bbox_embed(intermediate[i])
594
590
  aux_boxes = refine_obb_boxes(intermediate_reference_points[i], aux_boxes_delta)
595
-
596
- split_aux_logits = aux_logits.chunk(group_detr, dim=1)
597
- split_aux_boxes = aux_boxes.chunk(group_detr, dim=1)
598
-
599
- aux_loss: float | torch.Tensor = 0.0
600
- for g_logits, g_boxes in zip(split_aux_logits, split_aux_boxes):
601
- aux_loss += self.compute_loss(g_logits, g_boxes, processed_targets, box_scale=box_scale)
602
- loss += aux_loss / group_detr
603
-
604
- # Auxiliary losses for the selected encoder proposals
605
- enc_loss: float | torch.Tensor = 0.0
606
- for group_logits, group_coords in zip(all_group_enc_logits, all_group_enc_coords):
607
- enc_loss += self.compute_loss(group_logits, group_coords, processed_targets, box_scale=box_scale)
608
- loss += enc_loss / group_detr
609
-
610
- out["loss"] = loss
591
+ logits_sets.extend(aux_logits.chunk(group_detr, dim=1))
592
+ boxes_sets.extend(aux_boxes.chunk(group_detr, dim=1))
593
+ logits_sets.extend(all_group_enc_logits)
594
+ boxes_sets.extend(all_group_enc_coords)
595
+
596
+ out["loss"] = self._compute_sets_loss(
597
+ torch.stack([t.float() for t in logits_sets]),
598
+ torch.stack([t.float() for t in boxes_sets]),
599
+ processed_targets,
600
+ box_scale=box_scale,
601
+ set_weight=1.0 / group_detr,
602
+ )
611
603
 
612
604
  return out
613
605
 
@@ -650,90 +642,155 @@ class LWDETR(nn.Module, _LWDETR):
650
642
  Returns:
651
643
  loss: the computed loss value
652
644
  """
645
+ return self._compute_sets_loss(
646
+ logits.float().unsqueeze(0),
647
+ pred_boxes.float().unsqueeze(0),
648
+ targets,
649
+ cls_loss_weight=cls_loss_weight,
650
+ l1_loss_weight=l1_loss_weight,
651
+ iou_loss_weight=iou_loss_weight,
652
+ box_scale=box_scale,
653
+ )
654
+
655
+ @staticmethod
656
+ def _pad_targets(
657
+ targets: list[dict[str, np.ndarray]], device: torch.device
658
+ ) -> tuple[torch.Tensor, torch.Tensor, list[int]]:
659
+ """Stack the per-sample targets into padded tensors with a single host-to-device transfer.
660
+
661
+ Returns:
662
+ boxes: (B, Nmax, 6) float tensor (zero padded), labels: (B, Nmax) long tensor (zero padded),
663
+ counts: number of real boxes of every sample
664
+ """
665
+ counts = [int(np.asarray(sample["labels"]).size) for sample in targets]
666
+ n_max = max(max(counts), 1)
667
+ boxes = np.zeros((len(targets), n_max, 6), dtype=np.float32)
668
+ labels = np.zeros((len(targets), n_max), dtype=np.int64)
669
+ for b, (sample, n) in enumerate(zip(targets, counts)):
670
+ if n:
671
+ boxes[b, :n] = np.asarray(sample["boxes"], dtype=np.float32).reshape(-1, 6)
672
+ labels[b, :n] = np.asarray(sample["labels"], dtype=np.int64).reshape(-1)
673
+ packed = torch.from_numpy(np.concatenate([boxes.reshape(len(targets), -1), labels.astype(np.float32)], 1))
674
+ packed = packed.to(device) # one transfer for boxes and labels
675
+ boxes_t = packed[:, : n_max * 6].reshape(len(targets), n_max, 6)
676
+ labels_t = packed[:, n_max * 6 :].long()
677
+ return boxes_t, labels_t, counts
678
+
679
+ def _compute_sets_loss(
680
+ self,
681
+ logits: torch.Tensor,
682
+ pred_boxes: torch.Tensor,
683
+ targets: list[dict[str, np.ndarray]],
684
+ cls_loss_weight: float = 1.0,
685
+ l1_loss_weight: float = 5.0,
686
+ iou_loss_weight: float = 2.0,
687
+ box_scale: float = 1024.0,
688
+ set_weight: float = 1.0,
689
+ ) -> torch.Tensor:
690
+ """Batched version of `compute_loss` over S prediction sets sharing the same targets.
691
+
692
+ The Hungarian costs of every (set, sample) pair are computed on the device in one go and copied to the
693
+ host once; the matched pairs are then scored with a handful of vectorized operations. The result equals
694
+ `set_weight * sum(compute_loss(logits[s], pred_boxes[s], targets) for s in range(S))` up to float
695
+ summation order, without the S * B device synchronizations of the per-set formulation.
696
+
697
+ Args:
698
+ logits: (S, B, Q, C) class logits of every prediction set
699
+ pred_boxes: (S, B, Q, 6) oriented boxes of every prediction set
700
+ targets: list of B dictionaries with keys "boxes" ((N, 6) OBB) and "labels" ((N,) class indices)
701
+ cls_loss_weight: weight of the classification loss
702
+ l1_loss_weight: weight of the L1 box regression loss
703
+ iou_loss_weight: weight of the ProbIoU loss
704
+ box_scale: image size used to rescale normalized boxes to pixel coordinates for ProbIoU computation
705
+ set_weight: factor applied to the sum of the per-set losses
706
+
707
+ Returns:
708
+ the loss value
709
+ """
653
710
  alpha, gamma, eps = 0.25, 2.0, 1e-8
654
- # AMP safe-guard
655
- logits = logits.float()
656
- pred_boxes = pred_boxes.float()
657
711
  device = logits.device
658
- batch_size = logits.shape[0]
659
-
660
- tgt_boxes_list: list[torch.Tensor] = []
661
- tgt_labels_list: list[torch.Tensor] = []
662
- for sample in targets:
663
- tgt_boxes_list.append(
664
- torch.as_tensor(sample["boxes"], device=device, dtype=pred_boxes.dtype).reshape(-1, 6)
665
- )
666
- tgt_labels_list.append(torch.as_tensor(sample["labels"], device=device, dtype=torch.long).reshape(-1))
712
+ n_sets, batch_size, _num_queries, _num_classes = logits.shape
667
713
 
714
+ tgt_boxes, tgt_labels, counts = self._pad_targets(targets, device)
668
715
  # Number of target boxes in the batch, for loss normalization
669
- num_boxes = max(sum(int(labels.numel()) for labels in tgt_labels_list), 1)
716
+ num_boxes = max(sum(counts), 1)
717
+
718
+ prob = logits.sigmoid()
670
719
 
671
- # Hungarian matching (one-to-one), performed independently for each sample
672
- indices: list[tuple[torch.Tensor, torch.Tensor]] = []
720
+ # Hungarian matching (one-to-one), independent for every (set, sample) pair but computed together
673
721
  with torch.no_grad():
674
- prob = logits.sigmoid()
675
- for b in range(batch_size):
676
- tgt_boxes, tgt_labels = tgt_boxes_list[b], tgt_labels_list[b]
677
- if tgt_labels.numel() == 0:
678
- empty = torch.empty(0, dtype=torch.long, device=device)
679
- indices.append((empty, empty))
680
- continue
681
-
682
- out_prob = prob[b]
683
- out_boxes = pred_boxes[b]
684
-
685
- # Focal-style classification cost
686
- neg_cost = (1 - alpha) * out_prob.pow(gamma) * (-(1 - out_prob + eps).log())
687
- pos_cost = alpha * (1 - out_prob).pow(gamma) * (-(out_prob + eps).log())
688
- cost_class = pos_cost[:, tgt_labels] - neg_cost[:, tgt_labels]
689
-
690
- # L1 cost on normalized (cx, cy, w, h)
691
- cost_bbox = torch.cdist(out_boxes[:, :4].float(), tgt_boxes[:, :4].float(), p=1)
692
-
693
- # Rotated IoU cost, computed in pixel coordinates
694
- # this term also carries the angle signal for the matching
695
- cost_iou = -_probiou(out_boxes, tgt_boxes, pairwise=True, scale=box_scale)
696
-
697
- cost = 2.0 * cost_class + 5.0 * cost_bbox + 2.0 * cost_iou
698
-
699
- query_idx, tgt_idx = linear_sum_assignment(cost.detach().cpu().numpy())
700
- indices.append((
701
- torch.as_tensor(query_idx, dtype=torch.long, device=device),
702
- torch.as_tensor(tgt_idx, dtype=torch.long, device=device),
703
- ))
704
-
705
- # Flatten the matched pairs across the batch
706
- batch_idx = torch.cat([torch.full_like(src, b) for b, (src, _) in enumerate(indices)])
707
- query_idx = torch.cat([src for (src, _) in indices])
708
- matched_tgt_boxes = torch.cat([tgt_boxes_list[b][tgt] for b, (_, tgt) in enumerate(indices)])
709
- matched_tgt_labels = torch.cat([tgt_labels_list[b][tgt] for b, (_, tgt) in enumerate(indices)])
710
- matched_pred_boxes = pred_boxes[batch_idx, query_idx]
722
+ # Focal-style classification cost, gathered for the (padded) target labels: (S, B, Q, Nmax)
723
+ neg_cost = (1 - alpha) * prob.pow(gamma) * (-(1 - prob + eps).log())
724
+ pos_cost = alpha * (1 - prob).pow(gamma) * (-(prob + eps).log())
725
+ label_idx = tgt_labels[None, :, None, :].expand(n_sets, -1, prob.shape[2], -1)
726
+ cost_class = pos_cost.gather(-1, label_idx) - neg_cost.gather(-1, label_idx)
727
+
728
+ # L1 cost on normalized (cx, cy, w, h)
729
+ cost_bbox = torch.cdist(
730
+ pred_boxes[..., :4].reshape(n_sets * batch_size, -1, 4),
731
+ tgt_boxes[None, :, :, :4].expand(n_sets, -1, -1, -1).reshape(n_sets * batch_size, -1, 4),
732
+ p=1,
733
+ ).reshape(n_sets, batch_size, -1, tgt_boxes.shape[1])
734
+
735
+ # Rotated IoU cost, computed in pixel coordinates (also carries the angle signal for the matching)
736
+ cost_iou = -_probiou(
737
+ pred_boxes, tgt_boxes.unsqueeze(0).expand(n_sets, -1, -1, -1), pairwise=True, scale=box_scale
738
+ )
711
739
 
712
- prob = logits.sigmoid()
740
+ cost = (2.0 * cost_class + 5.0 * cost_bbox + 2.0 * cost_iou).cpu().numpy() # the only sync
741
+
742
+ # Solve the (small) assignment problems on the host and gather the matched (set, sample, query, target)
743
+ # quadruplets, then send them back to the device in a single transfer
744
+ matched_set_ids: list[np.ndarray] = []
745
+ matched_sample_ids: list[np.ndarray] = []
746
+ matched_query_ids: list[np.ndarray] = []
747
+ matched_target_ids: list[np.ndarray] = []
748
+ for sample_id, num_targets in enumerate(counts):
749
+ if num_targets == 0:
750
+ continue
751
+ for set_id in range(n_sets):
752
+ query_ids, target_ids = linear_sum_assignment(cost[set_id, sample_id, :, :num_targets])
753
+ matched_set_ids.append(np.full_like(query_ids, set_id))
754
+ matched_sample_ids.append(np.full_like(query_ids, sample_id))
755
+ matched_query_ids.append(query_ids)
756
+ matched_target_ids.append(target_ids)
757
+ if matched_set_ids:
758
+ matched = torch.from_numpy(
759
+ np.stack([
760
+ np.concatenate(ids)
761
+ for ids in (matched_set_ids, matched_sample_ids, matched_query_ids, matched_target_ids)
762
+ ])
763
+ ).to(device, dtype=torch.long)
764
+ set_ids, sample_ids, query_ids_t, target_ids_t = matched
765
+ else:
766
+ set_ids = sample_ids = query_ids_t = target_ids_t = torch.empty(0, dtype=torch.long, device=device)
767
+
768
+ matched_pred_boxes = pred_boxes[set_ids, sample_ids, query_ids_t]
769
+ matched_tgt_boxes = tgt_boxes[sample_ids, target_ids_t]
770
+ matched_tgt_labels = tgt_labels[sample_ids, target_ids_t]
713
771
 
714
772
  # IoU-aware BCE classification loss (IA-BCE)
715
773
  pos_weights = torch.zeros_like(logits)
716
774
  neg_weights = prob.pow(gamma)
717
- if len(batch_idx) > 0:
775
+ if len(set_ids) > 0:
718
776
  with torch.no_grad():
719
777
  ious = _probiou(matched_pred_boxes, matched_tgt_boxes, scale=box_scale).clamp(min=0.0, max=1.0)
720
- t = prob[batch_idx, query_idx, matched_tgt_labels].pow(alpha) * ious.pow(1 - alpha)
778
+ t = prob[set_ids, sample_ids, query_ids_t, matched_tgt_labels].pow(alpha) * ious.pow(1 - alpha)
721
779
  t = t.clamp(min=0.01)
722
- pos_weights[batch_idx, query_idx, matched_tgt_labels] = t
723
- neg_weights[batch_idx, query_idx, matched_tgt_labels] = 1 - t
780
+ pos_weights[set_ids, sample_ids, query_ids_t, matched_tgt_labels] = t
781
+ neg_weights[set_ids, sample_ids, query_ids_t, matched_tgt_labels] = 1 - t
724
782
 
725
783
  cls_loss = -(pos_weights * (prob + eps).log() + neg_weights * (1 - prob + eps).log())
726
784
  loss = cls_loss_weight * cls_loss.sum() / num_boxes
727
785
 
728
- if len(batch_idx) == 0:
729
- return loss
730
-
731
- # L1 loss on normalized (cx, cy, w, h)
732
- l1_loss = F.l1_loss(matched_pred_boxes[:, :4], matched_tgt_boxes[:, :4], reduction="sum") / num_boxes
733
- # ProbIoU loss on the whole oriented box (position, size and rotation), in pixel coordinates
734
- probiou_loss = (1 - _probiou(matched_pred_boxes, matched_tgt_boxes, scale=box_scale)).sum() / num_boxes
786
+ if len(set_ids) > 0:
787
+ # L1 loss on normalized (cx, cy, w, h)
788
+ l1_loss = F.l1_loss(matched_pred_boxes[:, :4], matched_tgt_boxes[:, :4], reduction="sum") / num_boxes
789
+ # ProbIoU loss on the whole oriented box (position, size and rotation), in pixel coordinates
790
+ probiou_loss = (1 - _probiou(matched_pred_boxes, matched_tgt_boxes, scale=box_scale)).sum() / num_boxes
791
+ loss = loss + l1_loss_weight * l1_loss + iou_loss_weight * probiou_loss
735
792
 
736
- return loss + l1_loss_weight * l1_loss + iou_loss_weight * probiou_loss
793
+ return loss * set_weight
737
794
 
738
795
 
739
796
  def _lw_detr(