Skip to content

Commit ed8d009

Browse files
kaushikb11pre-commit-ci[bot]
authored andcommitted
Add __len__ method to IndexBatchSamplerWrapper (#7681)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent fc95a81 commit ed8d009

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

pytorch_lightning/overrides/distributed.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,9 @@ def __iter__(self) -> Iterator[List[int]]:
132132
self.batch_indices = batch
133133
yield batch
134134

135+
def __len__(self) -> int:
136+
return len(self._sampler)
137+
135138
@property
136139
def drop_last(self) -> bool:
137140
return self._sampler.drop_last

tests/overrides/test_distributed.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,14 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from collections.abc import Iterable
15+
1416
import pytest
1517
from torch.utils.data import BatchSampler, SequentialSampler
1618

1719
from pytorch_lightning import seed_everything
1820
from pytorch_lightning.overrides.distributed import IndexBatchSamplerWrapper, UnrepeatedDistributedSampler
21+
from pytorch_lightning.utilities.data import has_len
1922

2023

2124
@pytest.mark.parametrize("shuffle", [False, True])
@@ -54,3 +57,13 @@ def test_index_batch_sampler(tmpdir):
5457

5558
for batch in index_batch_sampler:
5659
assert index_batch_sampler.batch_indices == batch
60+
61+
62+
def test_index_batch_sampler_methods():
63+
dataset = range(15)
64+
sampler = SequentialSampler(dataset)
65+
batch_sampler = BatchSampler(sampler, 3, False)
66+
index_batch_sampler = IndexBatchSamplerWrapper(batch_sampler)
67+
68+
assert isinstance(index_batch_sampler, Iterable)
69+
assert has_len(index_batch_sampler)

0 commit comments

Comments
 (0)