Data Collator

Data collators are objects that will form a batch by using a list of dataset elements as input. These elements are of the same type as the elements of `train_dataset` or `eval_dataset`.

To be able to build batches, data collators may apply some processing (like padding). Some of them (like [DataCollatorForLanguageModeling](/docs/transformers/v4.30.0/en/main_classes/data_collator#transformers.DataCollatorForLanguageModeling)) also apply some random data augmentation (like random masking) on the formed batch.

Examples of use can be found in the [example scripts](../examples) or [example notebooks](../notebooks).

## [](#transformers.default_data_collator)Default data collator

#### transformers.default\_data\_collator

[](#transformers.default_data_collator)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L52)

( features: typing.List\[InputDataClass\]return\_tensors = 'pt' )

Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named:

-   `label`: handles a single value (int or float) per object
-   `label_ids`: handles a list of values per object

Does not do any additional preprocessing: property names of the input object will be used as corresponding inputs to the model. See glue and ner for example of how it’s useful.

## [](#transformers.DefaultDataCollator)DefaultDataCollator

### class transformers.DefaultDataCollator

[](#transformers.DefaultDataCollator)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L78)

( return\_tensors: str = 'pt' )

Parameters

-   [](#transformers.DefaultDataCollator.return_tensors)**return\_tensors** (`str`) — The type of Tensor to return. Allowable values are “np”, “pt” and “tf”.

Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named:

-   `label`: handles a single value (int or float) per object
-   `label_ids`: handles a list of values per object

Does not do any additional preprocessing: property names of the input object will be used as corresponding inputs to the model. See glue and ner for example of how it’s useful.

This is an object (like other data collators) rather than a pure function like default\_data\_collator. This can be helpful if you need to set a return\_tensors value at initialization.

## [](#transformers.DataCollatorWithPadding)DataCollatorWithPadding

### class transformers.DataCollatorWithPadding

[](#transformers.DataCollatorWithPadding)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L215)

( tokenizer: PreTrainedTokenizerBasepadding: typing.Union\[bool, str, transformers.utils.generic.PaddingStrategy\] = Truemax\_length: typing.Optional\[int\] = Nonepad\_to\_multiple\_of: typing.Optional\[int\] = Nonereturn\_tensors: str = 'pt' )

Data collator that will dynamically pad the inputs received.

## [](#transformers.DataCollatorForTokenClassification)DataCollatorForTokenClassification

### class transformers.DataCollatorForTokenClassification

[](#transformers.DataCollatorForTokenClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L266)

( tokenizer: PreTrainedTokenizerBasepadding: typing.Union\[bool, str, transformers.utils.generic.PaddingStrategy\] = Truemax\_length: typing.Optional\[int\] = Nonepad\_to\_multiple\_of: typing.Optional\[int\] = Nonelabel\_pad\_token\_id: int = -100return\_tensors: str = 'pt' )

Data collator that will dynamically pad the inputs received, as well as the labels.

## [](#transformers.DataCollatorForSeq2Seq)DataCollatorForSeq2Seq

### class transformers.DataCollatorForSeq2Seq

[](#transformers.DataCollatorForSeq2Seq)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L517)

( tokenizer: PreTrainedTokenizerBasemodel: typing.Optional\[typing.Any\] = Nonepadding: typing.Union\[bool, str, transformers.utils.generic.PaddingStrategy\] = Truemax\_length: typing.Optional\[int\] = Nonepad\_to\_multiple\_of: typing.Optional\[int\] = Nonelabel\_pad\_token\_id: int = -100return\_tensors: str = 'pt' )

Data collator that will dynamically pad the inputs received, as well as the labels.

## [](#transformers.DataCollatorForLanguageModeling)DataCollatorForLanguageModeling

### class transformers.DataCollatorForLanguageModeling

[](#transformers.DataCollatorForLanguageModeling)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L607)

( tokenizer: PreTrainedTokenizerBasemlm: bool = Truemlm\_probability: float = 0.15pad\_to\_multiple\_of: typing.Optional\[int\] = Nonetf\_experimental\_compile: bool = Falsereturn\_tensors: str = 'pt' )

Parameters

-   [](#transformers.DataCollatorForLanguageModeling.tokenizer)**tokenizer** ([PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) or [PreTrainedTokenizerFast](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast)) — The tokenizer used for encoding the data.
-   [](#transformers.DataCollatorForLanguageModeling.mlm)**mlm** (`bool`, _optional_, defaults to `True`) — Whether or not to use masked language modeling. If set to `False`, the labels are the same as the inputs with the padding tokens ignored (by setting them to -100). Otherwise, the labels are -100 for non-masked tokens and the value to predict for the masked token.
-   [](#transformers.DataCollatorForLanguageModeling.mlm_probability)**mlm\_probability** (`float`, _optional_, defaults to 0.15) — The probability with which to (randomly) mask tokens in the input, when `mlm` is set to `True`.
-   [](#transformers.DataCollatorForLanguageModeling.pad_to_multiple_of)**pad\_to\_multiple\_of** (`int`, _optional_) — If set will pad the sequence to a multiple of the provided value.
-   [](#transformers.DataCollatorForLanguageModeling.return_tensors)**return\_tensors** (`str`) — The type of Tensor to return. Allowable values are “np”, “pt” and “tf”.

Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they are not all of the same length.

For best performance, this data collator should be used with a dataset having items that are dictionaries or BatchEncoding, with the `"special_tokens_mask"` key, as returned by a [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) or a [PreTrainedTokenizerFast](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast) with the argument `return_special_tokens_mask=True`.

#### numpy\_mask\_tokens

[](#transformers.DataCollatorForLanguageModeling.numpy_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L806)

( inputs: typing.Anyspecial\_tokens\_mask: typing.Optional\[typing.Any\] = None )

Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.

#### tf\_mask\_tokens

[](#transformers.DataCollatorForLanguageModeling.tf_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L659)

( inputs: typing.Anyvocab\_sizemask\_token\_idspecial\_tokens\_mask: typing.Optional\[typing.Any\] = None )

Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.

#### torch\_mask\_tokens

[](#transformers.DataCollatorForLanguageModeling.torch_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L751)

( inputs: typing.Anyspecial\_tokens\_mask: typing.Optional\[typing.Any\] = None )

Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.

## [](#transformers.DataCollatorForWholeWordMask)DataCollatorForWholeWordMask

### class transformers.DataCollatorForWholeWordMask

[](#transformers.DataCollatorForWholeWordMask)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L845)

( tokenizer: PreTrainedTokenizerBasemlm: bool = Truemlm\_probability: float = 0.15pad\_to\_multiple\_of: typing.Optional\[int\] = Nonetf\_experimental\_compile: bool = Falsereturn\_tensors: str = 'pt' )

Data collator used for language modeling that masks entire words.

-   collates batches of tensors, honoring their tokenizer’s pad\_token
-   preprocesses batches for masked language modeling

This collator relies on details of the implementation of subword tokenization by [BertTokenizer](/docs/transformers/v4.30.0/en/model_doc/bert#transformers.BertTokenizer), specifically that subword tokens are prefixed with _##_. For tokenizers that do not adhere to this scheme, this collator will produce an output that is roughly equivalent to `.DataCollatorForLanguageModeling`.

#### numpy\_mask\_tokens

[](#transformers.DataCollatorForWholeWordMask.numpy_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L1075)

( inputs: typing.Anymask\_labels: typing.Any )

Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set ‘mask\_labels’ means we use whole word mask (wwm), we directly mask idxs according to it’s ref.

#### tf\_mask\_tokens

[](#transformers.DataCollatorForWholeWordMask.tf_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L1033)

( inputs: typing.Anymask\_labels: typing.Any )

Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set ‘mask\_labels’ means we use whole word mask (wwm), we directly mask idxs according to it’s ref.

#### torch\_mask\_tokens

[](#transformers.DataCollatorForWholeWordMask.torch_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L993)

( inputs: typing.Anymask\_labels: typing.Any )

Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set ‘mask\_labels’ means we use whole word mask (wwm), we directly mask idxs according to it’s ref.

## [](#transformers.DataCollatorForPermutationLanguageModeling)DataCollatorForPermutationLanguageModeling

### class transformers.DataCollatorForPermutationLanguageModeling

[](#transformers.DataCollatorForPermutationLanguageModeling)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L1200)

( tokenizer: PreTrainedTokenizerBaseplm\_probability: float = 0.16666666666666666max\_span\_length: int = 5return\_tensors: str = 'pt' )

Data collator used for permutation language modeling.

-   collates batches of tensors, honoring their tokenizer’s pad\_token
-   preprocesses batches for permutation language modeling with procedures specific to XLNet

#### numpy\_mask\_tokens

[](#transformers.DataCollatorForPermutationLanguageModeling.numpy_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L1440)

( inputs: typing.Any )

The masked tokens to be predicted for a particular sequence are determined by the following algorithm:

0.  Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
1.  Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
2.  Reserve a context of length `context_length = span_length / plm_probability` to surround span to be masked
3.  Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length - span_length]` and mask tokens `start_index:start_index + span_length`
4.  Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the sequence to be processed), repeat from Step 1.

The masked tokens to be predicted for a particular sequence are determined by the following algorithm:

0.  Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
1.  Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
2.  Reserve a context of length `context_length = span_length / plm_probability` to surround span to be masked
3.  Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length - span_length]` and mask tokens `start_index:start_index + span_length`
4.  Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the sequence to be processed), repeat from Step 1.

#### torch\_mask\_tokens

[](#transformers.DataCollatorForPermutationLanguageModeling.torch_mask_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/data/data_collator.py#L1234)

( inputs: typing.Any )

The masked tokens to be predicted for a particular sequence are determined by the following algorithm:

0.  Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
1.  Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
2.  Reserve a context of length `context_length = span_length / plm_probability` to surround span to be masked
3.  Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length - span_length]` and mask tokens `start_index:start_index + span_length`
4.  Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the sequence to be processed), repeat from Step 1.