diff --git a/doctr/datasets/orientation.py b/doctr/datasets/orientation.py index 45779691f4..123e4fca6e 100644 --- a/doctr/datasets/orientation.py +++ b/doctr/datasets/orientation.py @@ -37,4 +37,21 @@ def __init__( ) # initialize dataset with 0 degree rotation targets - self.data: list[tuple[str, np.ndarray]] = [(img_name, np.array([0])) for img_name in os.listdir(self.root)] + # a list-like sequence (only `len` and indexing are used by the base class), not a list: cf. _ZeroTargetSamples + self.data = _ZeroTargetSamples(os.listdir(self.root)) # type: ignore[assignment] + + +class _ZeroTargetSamples: + """The (image name, 0 degree target) samples, with all the names in a single numpy array: + a list of Python objects per image would be copied by every DataLoader worker (refcount updates trigger + copy-on-write), which takes tens of GB with millions of images. + """ + + def __init__(self, img_names: list[str]) -> None: + self.img_names = np.array(img_names) + + def __len__(self) -> int: + return len(self.img_names) + + def __getitem__(self, index: int) -> tuple[str, np.ndarray]: + return str(self.img_names[index]), np.array([0]) diff --git a/doctr/models/classification/mobilenet/pytorch.py b/doctr/models/classification/mobilenet/pytorch.py index c2f139ad19..57a0c44712 100644 --- a/doctr/models/classification/mobilenet/pytorch.py +++ b/doctr/models/classification/mobilenet/pytorch.py @@ -61,14 +61,14 @@ "std": (0.299, 0.296, 0.301), "input_shape": (3, 256, 256), "classes": [0, -90, 180, 90], - "url": "https://doctr-static.mindee.com/models?id=v0.8.1/mobilenet_v3_small_crop_orientation-f0847a18.pt&src=0", + "url": "https://github.com/mindee/doctr/releases/download/v1.2.0/crop_orientation_mnv3s-3753d2cd.pt", }, "mobilenet_v3_small_page_orientation": { "mean": (0.694, 0.695, 0.693), "std": (0.299, 0.296, 0.301), "input_shape": (3, 512, 512), "classes": [0, -90, 180, 90], - "url": "https://doctr-static.mindee.com/models?id=v0.8.1/mobilenet_v3_small_page_orientation-8e60325c.pt&src=0", + "url": "https://github.com/mindee/doctr/releases/download/v1.2.0/page_orientation_mnv3s-58e44dbb.pt", }, "mobilenet_v3_small_font_style": { "mean": (0.694, 0.695, 0.693), diff --git a/doctr/transforms/modules/pytorch.py b/doctr/transforms/modules/pytorch.py index 024516a23e..ae1c861b40 100644 --- a/doctr/transforms/modules/pytorch.py +++ b/doctr/transforms/modules/pytorch.py @@ -194,7 +194,7 @@ def forward( else: offset = (0, 0) - if isinstance(target, str) or (isinstance(target, np.ndarray) and target.ndim < 2): + if isinstance(target, (str, int, np.integer)) or (isinstance(target, np.ndarray) and target.ndim < 2): # Special case for class targets (e.g. orientation, font style), which are not boxes to resize pass elif isinstance(target, dict): diff --git a/references/classification/README.md b/references/classification/README.md index 260bb0477e..dfe8c21f35 100644 --- a/references/classification/README.md +++ b/references/classification/README.md @@ -29,6 +29,8 @@ python references/classification/train_orientation.py resnet18 --type page --tra The type can be either `page` for document images or `crop` for word crops. +The training images are expected upright: each sample is rotated by one of the 4 orientations before being resized and padded, like the inputs at inference. `--class-prior` draws the orientations with the given probabilities (order `0 -90 180 90`, uniform by default): most pages and crops are upright in practice, and a prior such as `--class-prior 0.4 0.2 0.2 0.2` keeps ambiguous inputs (digits, short tokens, single characters) upright instead of rotating them at random. The validation set always uses uniform orientations. + ## Usage font style classification The font style classifier predicts, for each word crop, its emphasis (bold, italic, underline, strikethrough), its text and highlight colors, whether it is handwritten, its font category and its closest font family (cf. `doctr.datasets.FONT_STYLE_ATTRIBUTES`). The model outputs the logits of all these attributes concatenated, and is trained with the sum of their cross entropies. diff --git a/references/classification/train_orientation.py b/references/classification/train_orientation.py index dbba7810f3..6217c1ecf7 100644 --- a/references/classification/train_orientation.py +++ b/references/classification/train_orientation.py @@ -4,6 +4,7 @@ # See LICENSE or go to for full license details. import datetime +import functools import logging import multiprocessing as mp import os @@ -60,14 +61,24 @@ def _scaler(): return torch.amp.GradScaler("cuda", enabled=AMP_DTYPE == torch.float16) -def rnd_rotate(sample: Sample) -> Sample: - angle = int(np.random.choice(CLASSES)) - idx = CLASSES.index(angle) +def rnd_rotate(sample: Sample, class_prior: list[float] | None = None) -> Sample: + """Rotate the image before it is resized and padded, like the crops / pages at inference. + + The orientation is drawn with the probabilities `class_prior` (uniform by default): a prior favoring the upright + class teaches the model the real-world distribution, so that ambiguous inputs (digits, short tokens, single + CJK characters...) are not rotated at random. + + Rotating an already padded image leaks the label: the odd remainder of the symmetric padding always goes to the + top / left (cf. `Resize`), so a rotation moves it to the bottom / right and the model learns that cue instead of + the text orientation (unseen at inference, where the input is padded after being rotated). + """ + idx = int(np.random.choice(len(CLASSES), p=class_prior)) + # class index k <=> rotated counter-clockwise by k * 90 degrees (cf. `rectify_crops`): exact, no interpolation + rotated_img = torch.rot90(sample.image, idx, dims=(-2, -1)) # augment the angle randomly with a probability of 0.5 if np.random.rand() < 0.5: - angle += float(np.random.choice(np.arange(-25, 25, 5))) - rotated_img = F.rotate(sample.image, angle=-angle, fill=0, expand=angle not in CLASSES)[:3] - return Sample(image=rotated_img, target=idx) + rotated_img = F.rotate(rotated_img, angle=float(np.random.choice(np.arange(-25, 30, 5))), fill=0, expand=True) + return Sample(image=rotated_img[:3], target=idx) def record_lr( @@ -249,12 +260,10 @@ def main(args): st = time.time() val_set = OrientationDataset( img_folder=os.path.join(args.val_path, "images"), - img_transforms=Compose([ - T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True), - ]), + # rotate first, then resize & pad: same order as at inference (cf. `rnd_rotate`) sample_transforms=T.SampleCompose([ rnd_rotate, - T.Resize(input_size), + T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True), ]), ) val_loader = DataLoader( @@ -294,20 +303,20 @@ def main(args): st = time.time() train_set = OrientationDataset( img_folder=os.path.join(args.train_path, "images"), - img_transforms=Compose([ - T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True), - # Augmentations - T.RandomApply(T.ColorInversion(), 0.1), - T.RandomApply(T.GaussianNoise(mean=0.1, std=0.1), 0.1), - T.RandomApply(T.RandomShadow(), 0.2), - T.RandomApply(T.GaussianBlur(sigma=(0.5, 1.5)), 0.3), - T.ImageTorchvisionTransform(RandomPhotometricDistort(p=0.1)), - T.ImageTorchvisionTransform(RandomGrayscale(p=0.1)), - T.ImageTorchvisionTransform(RandomPerspective(distortion_scale=0.1, p=0.3)), - ]), + # rotate first, then resize & pad: same order as at inference (cf. `rnd_rotate`) sample_transforms=T.SampleCompose([ - rnd_rotate, - T.Resize(input_size), + functools.partial(rnd_rotate, class_prior=args.class_prior), + Compose([ + T.Resize(input_size, preserve_aspect_ratio=True, symmetric_pad=True), + # Augmentations (independent of the orientation) + T.RandomApply(T.ColorInversion(), 0.1), + T.RandomApply(T.GaussianNoise(mean=0.1, std=0.1), 0.1), + T.RandomApply(T.RandomShadow(), 0.2), + T.RandomApply(T.GaussianBlur(sigma=(0.5, 1.5)), 0.3), + T.ImageTorchvisionTransform(RandomPhotometricDistort(p=0.1)), + T.ImageTorchvisionTransform(RandomGrayscale(p=0.1)), + T.ImageTorchvisionTransform(RandomPerspective(distortion_scale=0.1, p=0.3)), + ]), ]), ) @@ -373,6 +382,7 @@ def main(args): "optimizer": args.optim, "framework": "pytorch", "classes": CLASSES, + "class_prior": args.class_prior, "scheduler": args.sched, "pretrained": args.pretrained, } @@ -548,10 +558,20 @@ def parse_args(): help="autocast dtype for --amp; bfloat16 (Ampere+ GPUs) avoids float16 overflows, no loss scaling", ) parser.add_argument("--find-lr", action="store_true", help="Gridsearch the optimal LR") + parser.add_argument( + "--class-prior", + type=float, + nargs=4, + default=None, + help="probabilities of the training orientations [0, -90, 180, 90] (default: uniform), e.g. 0.4 0.2 0.2 0.2", + ) parser.add_argument("--early-stop", action="store_true", help="Enable early stopping") parser.add_argument("--early-stop-epochs", type=int, default=5, help="Patience for early stopping") parser.add_argument("--early-stop-delta", type=float, default=0.01, help="Minimum Delta for early stopping") args = parser.parse_args() + if args.class_prior is not None: + if any(p < 0 for p in args.class_prior) or abs(sum(args.class_prior) - 1) > 1e-6: + parser.error("--class-prior must be 4 non-negative probabilities summing to 1") return args diff --git a/tests/pytorch/test_transforms_pt.py b/tests/pytorch/test_transforms_pt.py index 932fe538c7..748ea1b643 100644 --- a/tests/pytorch/test_transforms_pt.py +++ b/tests/pytorch/test_transforms_pt.py @@ -85,6 +85,14 @@ def test_resize_preserve_aspect_ratio(symmetric_pad, content_rows): assert torch.equal(mask, expected_mask) +@pytest.mark.parametrize("target", [2, np.int64(2), "label", np.array([2])]) +def test_resize_class_target(target): + # Class targets (e.g. an orientation index) are not boxes: kept as is when the aspect ratio is preserved + data = Resize((32, 32), preserve_aspect_ratio=True, symmetric_pad=True)(Sample(image=_ones(16, 64), target=target)) + assert data.image.shape[-2:] == (32, 32) + assert np.array_equal(data.target, target) if isinstance(target, np.ndarray) else data.target == target + + def test_resize_repr_and_shapes(): transfo = Resize(32, preserve_aspect_ratio=True, symmetric_pad=True) expected = "Resize(output_size=(32, 32), interpolation='bilinear', preserve_aspect_ratio=True, symmetric_pad=True)"