Add support for seed in `DataCollatorForLanguageModeling`
Author: capemox
Pull request: yes

# What does this PR do?
This PR adds support for setting a seed in the class `DataCollatorForLanguageModeling`. This helps with reproducibility in generating masks for masked language modeling (MLM). This issue was approved by @Rocketknight1 (https://github.com/huggingface/transformers/issues/36357)

Currently, there is a way for ensuring reproducibility by using the function `transformers.set_seed()`. However, this function sets the seed of the global RNG for PyTorch, Numpy, etc. What this means is that, setting a global seed can impact other pseudo-random functions outside the scope of the collator such as parameter initialization for models. This also means, that changes in the script outside the collator can impact the masking.

Instead, it is preferred to create generator objects which can be passed around to different functions. [This is also considered good practice](https://blog.scientific-python.org/numpy/numpy-rng/). What my PR does, is:

- Allows users to pass a `seed` parameter to `DataCollatorForLanguageModeling`
- Instantiates a generator object with the seed depending on the `return_tensors` parameter
- The generator object is used for pseudo-random functions within the class
- In case the user does not pass a seed, the collator falls back to its default implementation, for backwards compatibility

The generator object is scoped to the collator class, so it won't affect pseudo-random functions outside the class and vice-versa.

One important factor to consider is using multiple workers for the collator function, as PyTorch's `DataLoader` does. [PyTorch has documentation regarding this](https://pytorch.org/docs/stable/data.html#randomness-in-multi-process-data-loading), whereby we set a different seed for each worker given by `shared_seed + worker_id`. This is because the worker's seeds would be cloned, and so each worker would mask the input in exactly the same manner, which is undesirable. A critical part of PyTorch's `DataLoader` is that from within the worker, it is possible to access the worker's `id` (important to set the worker seed). Because of this constraint, this PR **only supports multi-worker scenarios with PyTorch's `DataLoader`**. With the `seed` set, if the code detects that the collator is running in a multi-processing scenario and the worker information is unavailable, an error is thrown.

The algorithm for creating the generator object is:
```python
# use multiprocessing to get current process' name
if current_process == "MainProcess":
    # Collator running in the in main python process
    # No issues here
    generator = get_generator(seed)
else:
    # Multiprocess scenario. Throw an error if
    # we cannot access PyTorch's worker info.
    worker_info = torch.utils.data.get_worker_info()
    if worker_info is None:
        raise ValueError
    
    generator = get_generator(seed + worker_info.id)
```

Tests have also been written to verify this behaviour in `tests/trainer/test_data_collator.py`.

These changes were done on Python 3.12.8. The dependencies installed were as pip install -e ".[dev]" along with:

- torch==2.6.0
- tensorflow==2.18.0
- tf-keras==2.18.0

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes #36357 

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [x] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [x] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [x] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts, @qubvel
- speech models: @ylacombe, @eustlb
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->

@Rocketknight1 should be the right person to review this.


Comments:
Hi 👋, thank you for opening this pull request! The pull request is converted to draft by default. When it is ready for review, please click the `Ready for review` button (at the bottom of the PR page).

@Rocketknight1 this won't pass a few data collator tests, but I submitted a PR to fix these (https://github.com/huggingface/transformers/pull/36457) 

@Rocketknight1, this PR should be good to go given the fix above now

> The main thing I wanted to check was that there wouldn't be any regression if self.seed = None, but I believe that in this case self.generator will always be None as well, and therefore behaviour will be unchanged from before.

Yep @Rocketknight1, this is exactly the case! in the post_init method, self.generator is initialized to None, and there wouldn't be any changes compared to before. The `create_rng` method would initialize the generator, but that would only be the case if seed is set.

About the core maintainer review - since you're most familiar with the code, I'll leave it up to you! I wouldn't mind their inputs as well.

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_36497). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

hi @capemox, it's up to the core maintainers to decide if they want to review this themselves or not!

Whoops nvm, thought it was directed at me :D

My bad lol, it did look like I was asking you to decide

I'm happy with it at this point! Doing a rebase to hopefully clear the CI and then we can merge

Merged, and thank you for the PR!

My pleasure!