RuntimeError Traceback (most recent call last)
Cell In[5], line 137
135 i = 0
136 for epoch in range(EPOCHS):
--> 137 for batch in tqdm(dataloaders["train"], desc=f"Epoch {epoch + 1}/{EPOCHS}"):
138 i += 1
140 loss = compute_loss(batch)
File ~/.local/lib/python3.10/site-packages/tqdm/std.py:1181, in tqdm.iter(self)
1178 time = self._time
1180 try:
-> 1181 for obj in iterable:
1182 yield obj
1183 # Update and possibly print the progressbar.
1184 # Note: does not call self.update(1) for speed optimisation.
File ~/.local/lib/python3.10/site-packages/torch/utils/data/dataloader.py:631, in _BaseDataLoaderIter.next(self)
628 if self._sampler_iter is None:
629 # TODO(https://github.com/pytorch/pytorch/issues/76750)
630 self._reset() # type: ignore[call-arg]
--> 631 data = self._next_data()
632 self._num_yielded += 1
633 if self._dataset_kind == _DatasetKind.Iterable and
634 self._IterableDataset_len_called is not None and
635 self._num_yielded > self._IterableDataset_len_called:
File ~/.local/lib/python3.10/site-packages/torch/utils/data/dataloader.py:675, in _SingleProcessDataLoaderIter._next_data(self)
673 def _next_data(self):
674 index = self._next_index() # may raise StopIteration
--> 675 data = self._dataset_fetcher.fetch(index) # may raise StopIteration
676 if self._pin_memory:
677 data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)
File ~/.local/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py:54, in _MapDatasetFetcher.fetch(self, possibly_batched_index)
52 else:
53 data = self.dataset[possibly_batched_index]
---> 54 return self.collate_fn(data)
Cell In[5], line 14
12 def collate_fn(batch):
13 images = [sample['image'] for sample in batch]
---> 14 images = torch.stack(moondream.vision_encoder.preprocess(images))
15 images = rearrange(images,
16 "b c (h p1) (w p2) -> b (h w) (c p1 p2)",
17 p1=14, p2=14)
19 labels_acc = []
File ~/.local/lib/python3.10/site-packages/torch/nn/modules/module.py:1541, in Module._call_impl(self, *args, **kwargs)
1536 # If we don't have any hooks, we want to skip the rest of the logic in
1537 # this function, and just call forward.
1538 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1539 or _global_backward_pre_hooks or _global_backward_hooks
1540 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1541 return forward_call(*args, **kwargs)
1543 try:
1544 result = None
Assistant
File ~/.local/lib/python3.10/site-packages/torchvision/transforms/v2/_container.py:51, in Compose.forward(self, *inputs)
49 needs_unpacking = len(inputs) > 1
50 for transform in self.transforms:
---> 51 outputs = transform(*inputs)
52 inputs = outputs if needs_unpacking else (outputs,)
53 return outputs
File ~/.local/lib/python3.10/site-packages/torch/nn/modules/module.py:1541, in Module._call_impl(self, *args, **kwargs)
1536 # If we don't have any hooks, we want to skip the rest of the logic in
1537 # this function, and just call forward.
1538 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1539 or _global_backward_pre_hooks or _global_backward_hooks
1540 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1541 return forward_call(*args, **kwargs)
1543 try:
1544 result = None
File ~/.local/lib/python3.10/site-packages/torchvision/transforms/v2/_transform.py:50, in Transform.forward(self, *inputs)
45 needs_transform_list = self._needs_transform_list(flat_inputs)
46 params = self._get_params(
47 [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform]
48 )
---> 50 flat_outputs = [
51 self._transform(inpt, params) if needs_transform else inpt
52 for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list)
53 ]
55 return tree_unflatten(flat_outputs, spec)
File ~/.local/lib/python3.10/site-packages/torchvision/transforms/v2/_transform.py:51, in (.0)
45 needs_transform_list = self._needs_transform_list(flat_inputs)
46 params = self._get_params(
47 [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform]
48 )
50 flat_outputs = [
---> 51 self._transform(inpt, params) if needs_transform else inpt
52 for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list)
53 ]
55 return tree_unflatten(flat_outputs, spec)
File ~/.local/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_utils.py:31, in _kernel_tv_tensor_wrapper..wrapper(inpt, *args, **kwargs)
20 @functools.wraps(kernel)
21 def wrapper(inpt, *args, **kwargs):
22 # If you're wondering whether we could / should get rid of this wrapper,
(...)
29 # lost after the first operation due to our own torch_function
30 # logic.
---> 31 output = kernel(inpt.as_subclass(torch.Tensor), *args, **kwargs)
32 return tv_tensors.wrap(output, like=inpt)
i = 0
for epoch in range(EPOCHS):
for batch in tqdm(dataloaders["train"], desc=f"Epoch {epoch + 1}/{EPOCHS}"):
i += 1
code
loss = compute_loss(batch)
loss.backward()
if i % GRAD_ACCUM_STEPS == 0:
optimizer.step()
optimizer.zero_grad()
lr = lr_schedule(i / GRAD_ACCUM_STEPS, total_steps)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
if i % 8 == 0:
torch.cuda.empty_cache()
if i % 100 == 0 and USE_WANDB:
# Calculate validation loss
val_loss = 0
for val_batch in tqdm(dataloaders["val"], desc="Validation"):
with torch.no_grad():
val_loss += compute_loss(val_batch).item()
val_loss /= len(dataloaders["val"])
if USE_WANDB:
wandb.log({
"loss/train": loss.item(),
"lr": optimizer.param_groups[0]['lr']
} | ({"loss/val": val_loss} if i % 100 == 0 else {}))
if USE_WANDB:
wandb.finish()
The error message you're encountering indicates that there's a mismatch in the dimensions of tensors during a normalization step in your data processing pipeline. Specifically, the error states:
code
RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0
This error typically occurs when an operation expects tensors of the same dimension but receives tensors of different sizes. In your case, it seems that the problem is happening with the normalization step applied to the images in your processing pipeline. The normalization transform is expecting the number of channels in the tensor representing the image to match the length of the mean and std lists provided (mean and std should have the same length as the number of channels in your images).
Let’s breakdown likely points to investigate:
Mismatched Number of Channels: The error is quite typical in scenarios where the image has a different number of channels from what the normalization process expects. Make sure that your images and the normalization parameters (mean and std) match in terms of the number of channels:
For RGB images, mean and std should each have three elements, corresponding to each channel (R, G, B).
For greyscale images which have only one channel, both mean and std should have only one element.
Transforms Application: Ensure that your transformations are correctly applied to the dataset. If you are operating on a dataset that includes images with both RGB and greyscale images, this might be causing an inconsistency.
Debugging the collate_fn: The error stack indicates the problem is occurring when processing batches of images. Double check the output of moondream.vision_encoder.preprocess(images) in your collate function. Here is the modified function for logging:
python
def collate_fn(batch):
images = [sample['image'] for sample in batch]
preprocessed_images = moondream.vision_encoder.preprocess(images)
print("Preprocessed Images Shape:", [img.shape for img in preprocessed_images])
images = torch.stack(preprocessed_images)
print("Stacked Images Shape:", images.shape)
images = rearrange(images, "b c (h p1) (w p2) -> b (h w) (c p1 p2)", p1=14, p2=14)
# rest of your code...
By adding such print statements, you can validate if the shapes of the preprocessed_images and images are as expected after processing.
Verifying Dataset Consistency: Inspect your dataset to make sure that all images conform to the expected format (e.g., all RGB or all greyscale, and dimensions).
Correct Configuration of Preprocessing: Verify that the normalization parameters (mean, std) used in moondream.vision_encoder.preprocess() are consistent with the expected formats and number of channels of the images in your dataset.
Fixing data inconsistency or ensuring the correct transformation parameters should resolve the error. Also, consider adding some error handling in your data loading and preprocessing steps to catch such issues early in the process.