Skip to content

RandGridPatch crashes for documented 0 or None patch_size entries #9046

Description

@Rajioba1

Describe the bug
RandGridPatch documents that patch_size entries of 0 or None select the whole dimension, matching GridPatch. However, when max_offset is not supplied, RandGridPatch.__call__ computes s % p for each spatial dimension. This crashes for p == 0 and p is None before patch generation starts.

The dictionary wrapper RandGridPatchd is affected through the same array transform.

To Reproduce

import torch
from monai.transforms import GridPatch, RandGridPatch

img = torch.arange(1 * 8 * 8 * 8, dtype=torch.float32).reshape(1, 8, 8, 8)

for patch_size in [(0, 4, 4), (None, 4, 4)]:
    print("GridPatch", patch_size, GridPatch(patch_size=patch_size)(img).shape)
    print("RandGridPatch", patch_size, RandGridPatch(patch_size=patch_size)(img).shape)

Current behavior:

GridPatch (0, 4, 4) torch.Size([4, 1, 8, 4, 4])
RandGridPatch (0, 4, 4) ZeroDivisionError: integer modulo by zero
GridPatch (None, 4, 4) torch.Size([4, 1, 8, 4, 4])
RandGridPatch (None, 4, 4) TypeError: unsupported operand type(s) for %: 'int' and 'NoneType'

Expected behavior
RandGridPatch should honor the documented 0 / None whole-dimension behavior and return patches like GridPatch for these inputs.

Environment

MONAI version: 1.6.0rc1+48.g8690ae74
Numpy version: 1.26.4
Pytorch version: 2.10.0+cpu
MONAI rev id: 8690ae74a8a489d31fe1f9ac8ef0bff63165383e
System: Windows-11-10.0.26200-SP0
Python version: 3.12.1

Additional context
The likely failing expression is in monai/transforms/spatial/array.py, where default max_offset is computed as tuple(s % p for s, p in zip(array.shape[1:], self.patch_size)).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions