Skip to content

Commit

Permalink
Add __len__ method to IndexBatchSamplerWrapper (#7681)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
2 people authored and lexierule committed Jun 1, 2021
1 parent fc95a81 commit ed8d009
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pytorch_lightning/overrides/distributed.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ def __iter__(self) -> Iterator[List[int]]:
self.batch_indices = batch
yield batch

def __len__(self) -> int:
return len(self._sampler)

@property
def drop_last(self) -> bool:
return self._sampler.drop_last
Expand Down
13 changes: 13 additions & 0 deletions tests/overrides/test_distributed.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections.abc import Iterable

import pytest
from torch.utils.data import BatchSampler, SequentialSampler

from pytorch_lightning import seed_everything
from pytorch_lightning.overrides.distributed import IndexBatchSamplerWrapper, UnrepeatedDistributedSampler
from pytorch_lightning.utilities.data import has_len


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

for batch in index_batch_sampler:
assert index_batch_sampler.batch_indices == batch


def test_index_batch_sampler_methods():
dataset = range(15)
sampler = SequentialSampler(dataset)
batch_sampler = BatchSampler(sampler, 3, False)
index_batch_sampler = IndexBatchSamplerWrapper(batch_sampler)

assert isinstance(index_batch_sampler, Iterable)
assert has_len(index_batch_sampler)

0 comments on commit ed8d009

Please sign in to comment.