DataCollator vs. Tokenizers
In@sgugger's example notebookToken ClassificationADataCollatorForTokenClassificationis used:from transformers import DataCollatorForTokenClassification
data_collator = DataCollatorForTokenClassification(tokenizer)
...
trainer = Trainer(
    model,
    args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["validation"],
    data_collator=data_collator,
    tokenizer=tokenizer,
    compute_metrics=compute_metrics
)I am trying to figure out what the real purpose of this is.  It appears that the purpose ofDataCollatorForTokenClassificationis for padding, truncation, etc.  But you can also do this in the tokenizer.  Why do we need this extra thing, then?   Is it because DataCollator does it per batch instead on the fly and is more efficient?Thanks.
2021-05-01T11:15:10Z
hey@hamel, welcome to theforum!you’re spot on about using data collators to do padding on-the-fly. to understand why this helps, consider the following scenarios:use the tokenizer to pad each example in the dataset to the length of the longest example in the datasetuse the tokenizer andDataCollatorWithPadding(docs) to pad each example in a batch to the length of the longest example in the batchclearly, scenario 2 is more efficient, especially in cases where a few examples happen to be much longer than the median length and scenario 1 would introduce a lot of unnecessary padding.btw under the hood, the data collators are fed to thecollate_fnargument of pytorch’sDataLoader, see e.g. here:transformers/trainer.py at 4e7bf94e7280d2b725ac4644dbe9808560afa5d8 · huggingface/transformers · GitHubthe pytorchdocsare not super informative oncollate_fnitself, but you can find various discussion in their forums (e.g.here)