Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a bug when batch type is dict and one of the values is the list #2599

Merged
merged 7 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion composer/core/data_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,16 @@ def _default_get_num_samples_in_batch(self, batch: Batch) -> int:
'`get_num_samples_in_batch(your_batch) -> int` method.')
dim0_sizes.append(t.shape[0])
elif isinstance(batch, dict):
dim0_sizes = [t.shape[0] for t in batch.values()]
for t in batch.values():
if isinstance(t, torch.Tensor):
dim0_sizes.append(t.shape[0])
elif isinstance(t, list):
dim0_sizes.append(len(t))
else:
raise ValueError('Unable to determine the batch size as batch is a dict '
f'with an element of type {type(t)} which is not Tensor '
'or list. Please use a DataSpec and provide a '
'`get_num_samples_in_batch(your_batch) -> int` method.')

if len(set(dim0_sizes)) == 1:
return dim0_sizes[0]
Expand Down
26 changes: 26 additions & 0 deletions tests/trainer/test_dataspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,29 @@ def test_small_batch_at_end_warning():

with pytest.warns(UserWarning, match='Cannot split tensor of length.*'):
trainer.fit()


@pytest.mark.parametrize(
'batch,num_samples',
[
[{
'a': torch.rand(N, 8),
'b': torch.rand(N, 64)
}, N], # dict
[[{
'a': torch.rand(N, 8)
}, {
'c': torch.rand(N, 64)
}], N], # list of dict
[{
'a': [1, 2],
'b': [3, 4]
}, 2], # dict of lists
[(torch.rand(N, 8), torch.rand(N, 64)), N], # tuple
[[torch.rand(N, 8), torch.rand(N, 64)], N], # list
[torch.rand(N, 8), N], # tensor
[torch.rand(N, 8, 4, 2), N], # 4-dim tensor
])
def test_num_samples_in_batch(batch, num_samples):
data_spec = DataSpec(dataloader=DataLoader(RandomClassificationDataset(size=17), batch_size=4))
assert data_spec.get_num_samples_in_batch(batch) == num_samples