Incorrect preprocessing in run_t5_mlm_flax.py
### System Info

Hi there!

I am running the run_t5_mlm_flax.py as is and noticed this error 
`ValueError: `input_ids` are incorrectly preprocessed. `input_ids` length is 922, but should be 1024.`

while running

```
for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
    samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
    model_inputs = data_collator(samples)```

I see the following output from a demo e.g.
`print(tokenizer.batch_decode(input_ids, skip_special_tokens=False)[0])`
 gives 
`<unk> file_gif></s> Stacy: OK Stacy: let's go over the list one more time! Angelica: haha, you don't have to do it... Stacy:<extra_id_0>? of course I do!<extra_id_1> acy: I'm your maid of honor<extra_id_2> OK ;* <unk> <extra_id_3> of songs for the DJ? Angelica: sent Stacy: Flower arrangements and your bouquet? Angelica: done Stacy: comfortable shoes for after midnight? Angelica: bought and packed Stacy: Make-up and hair? Angelica: scheduled Angelica: they'll be at my place at 10 am St<extra_id_4> How much time<extra_id_5> we need? Angelica: around 3 hours the both of us? Stacy: OK, that gives us enough time to go get dressed and get to the church Angelica: Yeah, my mom wants to have her hair done as well, but we'll go seperate<extra_id_6> OK Angelica: anything else? Stacy<extra_id_7> ica: Nick's got them Stacy: Remind him to BRING them :D Angelica: maybe you're right... ;)<extra_id_8> in: Have u watched<extra_id_9>? Izayah: No what's it about? Westin: I don't know yet Izayah: So why are you asking? Westin: Haha I wanna watch this but it's a fantasy movie Izayah<extra_id_10> Hmm not into such movies Westin: Neither me but this one<extra_id_11> yah: Enjoy Westin<extra_id_12> Thanks anyway I<extra_id_13> </s> Macy: when is the deadline for our project? Mac<extra_id_14> or <extra_id_15> day Sloane: next monday :) Macy: oh shit, i better start working faster Veronica: yeah, monday - please make sure you have your part ready Veronica: Monica will be mad if we don<extra_id_16> it on time</s> Francesca: girls, I<extra_id_17> your advice Blake: what's up? Vivienne: yes? Francesca<extra_id_18> wants us to go on a dancing course<extra_id_19>'s not that i don't like it but I'm stressed<extra_id_20> can't dance,<extra_id_21> can barely walk :/ Blake: you know, the courses are to go and<extra_id_22> them...s<extra_id_23> you're a perfect candidate to try it Vivienne: that'<extra_id_24>, nobody who can dance would pay to go on a dancing course Francesca: I get it, but I'm so im<extra_id_25> doesn't work out as I want :/ Francesca: and Brian is 100% sure and is<extra_id_26> to stop freaking out Blake: oh come on, maybe it'<extra_id_27> something you will love? you won't know until you try Blake: sometimes you just have<extra_id_28> the deep end and see<extra_id_29> happens Vivienne: Blake's right Vivienne: c'mon Francesca: I'll reconsider it...maybe <extra_id_30> the parties where you can be the couple of the night Blake: exactly!!!!! Blake:<extra_id_31> re scared then Viv and I<extra_id_32> a couple<extra_id_33> hahaha<extra_id_34> this is absolutely fantastic, I'm in XDDDD Francesca:<extra_id_35> mg, really? xddd Blake: why not Blake: Viv, will you<extra_id_36> gf during that course? xd Viv: of course DARLING hahahahahaah Francesca: I can't believe it X<extra_id_37> already see myself introducing<extra_id_38> as the lesbian couple<extra_id_39> </s> Elizabeth: How about the cathedral? Kathleen: Eh probably there’<extra_id_40> <extra_id_41> tower... Elizabeth: Yes, there<extra_id_42> ;] Kathleen: No way, I’m not climbing some stupid stairs Elizabeth: You<extra_id_43>, it’ll not take long... Kathleen: Great, standing there alone<extra_id_44> organization! Elizabeth: How on earth am I<extra_id_45> are against anything I come up with!! Kathleen: Maybe you just have bad ideas ;/ Elizabeth: The rest of the group is not complaining, only you Kathleen:<extra_id_46> you<extra_id_47> about it Elizabeth: Listen, I’m done, I<extra_id_48> ask you about anything, you’ll see the program in a few days and tell me if you want to go<extra_id_49> It’s even worse, you promised everyone will have a chance to express their opinions! Elizabeth: But<extra_id_50> </s>`
and 
`print(tokenizer.batch_decode(labels, skip_special_tokens=False)[0])`
gives
`<extra_id_0> are you kidding me<extra_id_1> St<extra_id_2>! Angelica:<extra_id_3> 3 Stacy: List<extra_id_4> acy:<extra_id_5> do<extra_id_6> ly Stacy:<extra_id_7> : the rings? Angel<extra_id_8> </s> West<extra_id_9> beasts of the southern wild<extra_id_10> :<extra_id_11> seems to be interesting Iza<extra_id_12> :<extra_id_13> zayah: Haha ok<extra_id_14> y: next monday<extra_id_15> thurs<extra_id_16> 't deliver<extra_id_17> need<extra_id_18> : Brian<extra_id_19>, it<extra_id_20> out...i<extra_id_21> I<extra_id_22> learn from<extra_id_23> o<extra_id_24> s right<extra_id_25> patient when something<extra_id_26> almost bullying me<extra_id_27> s<extra_id_28> to jump in<extra_id_29> what<extra_id_30> Vivienne: just think about all<extra_id_31> If you'<extra_id_32> can go as<extra_id_33> on that course ha<extra_id_34> Vivienne: Blake....<extra_id_35> o<extra_id_36> be my <extra_id_37> DDDD I<extra_id_38> you to my boyfriend<extra_id_39> I know and respect XD<extra_id_40> s<extra_id_41> a<extra_id_42> is <extra_id_43> can wait outside<extra_id_44>, nice<extra_id_45> supposed to organize anything when you<extra_id_46> Maybe<extra_id_47> just don’t know<extra_id_48> will not<extra_id_49> or not Kathleen:<extra_id_50> I</s>`


What am I missing here? As there any helper script to run data preprocessing ad-hoc?

Thank you!


### Information

- [X] The official example scripts
- [ ] My own modified scripts

### Tasks

- [X] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [ ] My own task or dataset (give details below)

### Reproduction

Occurs while running 


from transformers import T5Tokenizer, T5ForConditionalGeneration
import torch
from datasets import load_dataset
from itertools import chain
from dataclasses import dataclass
from transformers import (
    BatchEncoding,
     PreTrainedTokenizerBase
)
from typing import Dict, List, Optional
import numpy as np
from tqdm imprt tqdm

tokenizer = T5Tokenizer.from_pretrained("t5-small")
model = T5ForConditionalGeneration.from_pretrained("t5-small")

# Load dataset from the hub
datasets = load_dataset("samsum")

print(f"Train dataset size: {len(dataset['train'])}")
print(f"Test dataset size: {len(dataset['test'])}")

def tokenize_function(examples):
        return tokenizer(examples["dialogue"], return_attention_mask=False)

tokenized_datasets = datasets.map(
        tokenize_function,
        batched=True,
        num_proc=4,
        load_from_cache_file=False,
    )

def compute_input_and_target_lengths(inputs_length, noise_density=0.15, mean_noise_span_length=1.0):
    """This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2466>`__ .
    Training parameters to avoid padding with random_spans_noise_mask.
    When training a model with random_spans_noise_mask, we would like to set the other
    training hyperparmeters in a way that avoids padding.
    This function helps us compute these hyperparameters.
    We assume that each noise span in the input is replaced by extra_tokens_per_span_inputs sentinel tokens,
    and each non-noise span in the targets is replaced by extra_tokens_per_span_targets sentinel tokens.
    This function tells us the required number of tokens in the raw example (for split_tokens())
    as well as the length of the encoded targets. Note that this function assumes
    the inputs and targets will have EOS appended and includes that in the reported length.
    Args:
        inputs_length: an integer - desired length of the tokenized inputs sequence
        noise_density: a float
        mean_noise_span_length: a float
    Returns:
        tokens_length: length of original text in tokens
        targets_length: an integer - length in tokens of encoded targets sequence
    """
    def _tokens_length_to_inputs_length_targets_length(tokens_length):
        num_noise_tokens = int(round(tokens_length * noise_density))
        num_nonnoise_tokens = tokens_length - num_noise_tokens
        num_noise_spans = int(round(num_noise_tokens / mean_noise_span_length))
        # inputs contain all nonnoise tokens, sentinels for all noise spans
        # and one EOS token.
        _input_length = num_nonnoise_tokens + num_noise_spans + 1
        _output_length = num_noise_tokens + num_noise_spans + 1
        return _input_length, _output_length
    tokens_length = inputs_length
    while _tokens_length_to_inputs_length_targets_length(tokens_length + 1)[0] <= inputs_length:
        tokens_length += 1
    inputs_length, targets_length = _tokens_length_to_inputs_length_targets_length(tokens_length)
    # minor hack to get the targets length to be equal to inputs length
    # which is more likely to have been set to a nice round number.
    if noise_density == 0.5 and targets_length > inputs_length:
        tokens_length -= 1
        targets_length -= 1
    return tokens_length, targets_length


expanded_inputs_length, targets_length = compute_input_and_target_lengths(
        inputs_length=1024,
        noise_density=0.15,
        mean_noise_span_length=1.0,
    )

def group_texts(examples):
        # Concatenate all texts.
        concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
        total_length = len(concatenated_examples[list(examples.keys())[0]])
        # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
        # customize this part to your needs.
        if total_length >= expanded_inputs_length:
            total_length = (total_length // expanded_inputs_length) * expanded_inputs_length
        # Split by chunks of max_len.
        result = {
            k: [t[i : i + expanded_inputs_length] for i in range(0, total_length, expanded_inputs_length)]
            for k, t in concatenated_examples.items()
        }
        return result

tokenized_datasets = tokenized_datasets.map(
        group_texts,
        batched=True,
        num_proc=4,
        load_from_cache_file=False,
    )

@dataclass
class FlaxDataCollatorForT5MLM:
    """
    Data collator used for T5 span-masked language modeling.
    It is made sure that after masking the inputs are of length `data_args.max_seq_length` and targets are also of fixed length.
    For more information on how T5 span-masked language modeling works, one can take a look
    at the `official paper <https://arxiv.org/pdf/1910.10683.pdf>`__
    or the `official code for preprocessing <https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/data/preprocessors.py>`__ .
    Args:
        tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
            The tokenizer used for encoding the data.
        noise_density (:obj:`float`):
            The probability with which to (randomly) mask tokens in the input.
        mean_noise_span_length (:obj:`float`):
            The average span length of the masked tokens.
        input_length (:obj:`int`):
            The expected input length after masking.
        target_length (:obj:`int`):
            The expected target length after masking.
        pad_token_id: (:obj:`int`):
            The pad token id of the model
        decoder_start_token_id: (:obj:`int):
            The decoder start token id of the model
    """
    tokenizer: PreTrainedTokenizerBase
    noise_density: float
    mean_noise_span_length: float
    input_length: int
    target_length: int
    pad_token_id: int
    decoder_start_token_id: int
    def __call__(self, examples: List[Dict[str, np.ndarray]]) -> BatchEncoding:
        # convert list to dict and tensorize input
        batch = BatchEncoding(
            {k: np.array([examples[i][k] for i in range(len(examples))]) for k, v in examples[0].items()}
        )
        input_ids = batch["input_ids"]
        batch_size, expandend_input_length = input_ids.shape
        mask_indices = np.asarray([self.random_spans_noise_mask(expandend_input_length) for i in range(batch_size)])
        labels_mask = ~mask_indices
        input_ids_sentinel = self.create_sentinel_ids(mask_indices.astype(np.int8))
        labels_sentinel = self.create_sentinel_ids(labels_mask.astype(np.int8))
        batch["input_ids"] = self.filter_input_ids(input_ids, input_ids_sentinel)
        batch["labels"] = self.filter_input_ids(input_ids, labels_sentinel)
        print(">>>>> sanity check <<<<<<<<<<")
        print("\n")
        print(">>>>> inputs <<<<<<<<<<")
        print(self.tokenizer.batch_decode(batch["input_ids"])[0])
        print("\n")
        print(">>>>> masks <<<<<<<<<<")
        print(self.tokenizer.batch_decode(batch["labels"])[0])
        print("\n")
        print(">>>>> snity check <<<<<<<<<<")        
        if batch["input_ids"].shape[-1] != self.input_length:
            raise ValueError(
                f"`input_ids` are incorrectly preprocessed. `input_ids` length is {batch['input_ids'].shape[-1]}, but"
                f" should be {self.input_length}."
            )
        if batch["labels"].shape[-1] != self.target_length:
            raise ValueError(
                f"`labels` are incorrectly preprocessed. `labels` length is {batch['labels'].shape[-1]}, but should be"
                f" {self.target_length}."
            )
        # to check that tokens are correctly preprocessed, one can run `self.tokenizer.batch_decode(input_ids)` and `self.tokenizer.batch_decode(labels)` here...
        return batch
    def create_sentinel_ids(self, mask_indices):
        """
        Sentinel ids creation given the indices that should be masked.
        The start indices of each mask are replaced by the sentinel ids in increasing
        order. Consecutive mask indices to be deleted are replaced with `-1`.
        """
        start_indices = mask_indices - np.roll(mask_indices, 1, axis=-1) * mask_indices
        start_indices[:, 0] = mask_indices[:, 0]
        sentinel_ids = np.where(start_indices != 0, np.cumsum(start_indices, axis=-1), start_indices)
        sentinel_ids = np.where(sentinel_ids != 0, (len(self.tokenizer) - sentinel_ids), 0)
        sentinel_ids -= mask_indices - start_indices
        return sentinel_ids
    def filter_input_ids(self, input_ids, sentinel_ids):
        """
        Puts sentinel mask on `input_ids` and fuse consecutive mask tokens into a single mask token by deleting.
        This will reduce the sequence length from `expanded_inputs_length` to `input_length`.
        """
        batch_size = input_ids.shape[0]
        input_ids_full = np.where(sentinel_ids != 0, sentinel_ids, input_ids)
        # input_ids tokens and sentinel tokens are >= 0, tokens < 0 are
        # masked tokens coming after sentinel tokens and should be removed
        input_ids = input_ids_full[input_ids_full >= 0].reshape((batch_size, -1))
        input_ids = np.concatenate(
            [input_ids, np.full((batch_size, 1), self.tokenizer.eos_token_id, dtype=np.int32)], axis=-1
        )
        return input_ids
    def random_spans_noise_mask(self, length):
        """This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2682>`__ .
        Noise mask consisting of random spans of noise tokens.
        The number of noise tokens and the number of noise spans and non-noise spans
        are determined deterministically as follows:
        num_noise_tokens = round(length * noise_density)
        num_nonnoise_spans = num_noise_spans = round(num_noise_tokens / mean_noise_span_length)
        Spans alternate between non-noise and noise, beginning with non-noise.
        Subject to the above restrictions, all masks are equally likely.
        Args:
            length: an int32 scalar (length of the incoming token sequence)
            noise_density: a float - approximate density of output mask
            mean_noise_span_length: a number
        Returns:
            a boolean tensor with shape [length]
        """
        orig_length = length
        num_noise_tokens = int(np.round(length * self.noise_density))
        num_nonnoise_tokens = length - num_noise_tokens
        # avoid degeneracy by ensuring positive numbers of noise and nonnoise tokens.
        num_noise_tokens = min(max(num_noise_tokens, 1), length - 1)
        # num_noise_tokens should be less than num_noise_tokens and num_nonnoise_tokens
        num_noise_spans = int(np.round(min(num_noise_tokens, num_nonnoise_tokens) / self.mean_noise_span_length))
        # avoid degeneracy by ensuring positive number of noise spans
        num_noise_spans = max(num_noise_spans, 1)
        # pick the lengths of the noise spans and the non-noise spans
        def _random_segmentation(num_items, num_segments):
            """Partition a sequence of items randomly into non-empty segments.
            Args:
                num_items: an integer scalar > 0
                num_segments: an integer scalar in [1, num_items]
            Returns:
                a Tensor with shape [num_segments] containing positive integers that add
                up to num_items
            """
            mask_indices = np.arange(num_items - 1) < (num_segments - 1)
            np.random.shuffle(mask_indices)
            first_in_segment = np.pad(mask_indices, [[1, 0]])
            segment_id = np.cumsum(first_in_segment)
            # count length of sub segments assuming that list is sorted
            _, segment_length = np.unique(segment_id, return_counts=True)
            return segment_length
        noise_span_lengths = _random_segmentation(num_noise_tokens, num_noise_spans)
        nonnoise_span_lengths = _random_segmentation(num_nonnoise_tokens, num_noise_spans)
        interleaved_span_lengths = np.reshape(
            np.stack([nonnoise_span_lengths, noise_span_lengths], axis=1), [num_noise_spans * 2]
        )
        span_starts = np.cumsum(interleaved_span_lengths)[:-1]
        span_start_indicator = np.zeros((length,), dtype=np.int8)
        span_start_indicator[span_starts] = True
        span_num = np.cumsum(span_start_indicator)
        is_noise = np.equal(span_num % 2, 1)
        return is_noise[:orig_length]


data_collator = FlaxDataCollatorForT5MLM(
        tokenizer=tokenizer,
        noise_density=0.15,
        mean_noise_span_length=3.0,
        input_length=1024,
        target_length=309,
        pad_token_id=0,
        decoder_start_token_id=0,
    )


def generate_batch_splits(samples_idx: np.ndarray, batch_size: int, drop_last=True) -> np.ndarray:
    """Generate batches of data for a specified batch size from sample indices. If the dataset size is not divisible by
    the batch size and `drop_last` is `True`, the last incomplete batch is dropped. Else, it is returned."""
    num_samples = len(samples_idx)
    if drop_last:
        samples_to_remove = num_samples % batch_size
        if samples_to_remove != 0:
            samples_idx = samples_idx[:-samples_to_remove]
        sections_split = num_samples // batch_size
        samples_idx = samples_idx.reshape((sections_split, batch_size))
    else:
        sections_split = math.ceil(num_samples / batch_size)
        samples_idx = np.array_split(samples_idx, sections_split)
    return samples_idx

# Generate an epoch by shuffling sampling indices from the train dataset
num_train_samples = len(tokenized_datasets["train"])
# Avoid using jax.numpy here in case of TPU training
train_samples_idx = np.random.permutation(np.arange(num_train_samples))
train_batch_idx = generate_batch_splits(train_samples_idx, 4)

for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
    samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
    model_inputs = data_collator(samples)




from `run_t5_mlm_flax.py`

### Expected behavior

I expected to run run_t5_mlm_flax.py script without an error
Hi @BSharmi, 

The example code here isn't exactly the same as the `run_t5_mlm_flax.py` script and is missing some important lines. For example, [this one](https://github.com/huggingface/transformers/blob/291c5e9b256ad3ae970f8ef47d1693f3ae976a6e/examples/flax/language-modeling/run_t5_mlm_flax.py#LL660C10-L660C10), which enforces the length of the returned sequences from the tokenizer. Additionally, the model being imported is a pytorch model - `T5ForConditionalGeneration` - wheras the flax equivalent would be required for the flax script: `FlaxT5ForConditionalGeneration`. 

I would first make sure you can run the script with the [example snippet from the README](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#train-model-2) and then start to adapt to the new use case. <|||||>This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.