Skip to content
Advertisement

How to use ‘collate_fn’ with dataloaders?

I am trying to train a pretrained roberta model using 3 inputs, 3 input_masks and a label as tensors of my training dataset.

I do this using the following code:

JavaScript

However this gives me the following error:

TypeError: vars() argument must have dict attribute

Now I have found out that it is probably because I don’t use collate_fn when using DataLoader, but I can’t really find a source that helps me define this correctly so the trainer understands the different tensors I put in.

Can anyone point me in the right direction?

Advertisement

Answer

Basically, the collate_fn receives a list of tuples if your __getitem__ function from a Dataset subclass returns a tuple, or just a normal list if your Dataset subclass returns only one element. Its main objective is to create your batch without spending much time implementing it manually. Try to see it as a glue that you specify the way examples stick together in a batch. If you don’t use it, PyTorch only put batch_size examples together as you would using torch.stack (not exactly it, but it is simple like that).

Suppose for example, you want to create batches of a list of varying dimension tensors. The below code pads sequences with 0 until the maximum sequence size of the batch, that is why we need the collate_fn, because a standard batching algorithm (simply using torch.stack) won’t work in this case, and we need to manually pad different sequences with variable length to the same size before creating the batch.

JavaScript

The function above is fed to the collate_fn param in the DataLoader, as this example:

JavaScript

With this collate_fn function, you always gonna have a tensor where all your examples have the same size. So, when you feed your forward() function with this data, you need to use the length to get the original data back, to not use those meaningless zeros in your computation.

Source: Pytorch Forum

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement