title: Pad torch tensors of different sizes to be equal
body: <p>I am looking for a way to take an image/target batch for segmentation and return the batch where the image dimensions have been changed to be equal for the whole batch.  I have tried this using the code below:</p>
  
  <pre><code>def collate_fn_padd(batch):
      '''
      Padds batch of variable length
  
      note: it converts things ToTensor manually here since the ToTensor transform
      assume it takes in images rather than arbitrary tensors.
      '''
      # separate the image and masks
      image_batch,mask_batch = zip(*batch)
  
      # pad the images and masks
      image_batch = torch.nn.utils.rnn.pad_sequence(image_batch, batch_first=True)
      mask_batch = torch.nn.utils.rnn.pad_sequence(mask_batch, batch_first=True)
  
      # rezip the batch
      batch = list(zip(image_batch, mask_batch))
  
      return batch
  </code></pre>
  
  <p>However, I get this error: </p>
  
  <pre><code>RuntimeError: The expanded size of the tensor (650) must match the existing size (439) at non-singleton dimension 2.  Target sizes: [3, 650, 650].  Tensor sizes: [3, 406, 439]
  </code></pre>
  
  <p>How do I efficiently pad the tensors to be of equal dimensions and avoid this issue?</p>