Repository: huggingface/transformers
Pull request: split out accelerator args builder method

# What does this PR do?

Accelerator has a lot of other args that can be passed to it like fp8 support, etc, but requires extensive monkey patching downstream to make it work. This makes it easier to extend the accelerator args building method to include more args to accelerator.
<!--
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 # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] 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.
- [ ] 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).
- [ ] 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 @Cyrilvallez
- vision models: @yonigozlan @molbap
- audio models: @eustlb @ebezzam @vasqu
- multimodal models: @zucchini-nlp
- graph models: @clefourrier

Library:

- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- continuous batching: @remi-or @ArthurZucker @McPatate
- pipelines: @Rocketknight1
- tokenizers: @ArthurZucker and @itazap
- trainer: @SunMarc
- attention: @vasqu @ArthurZucker @CyrilVallez
- model loading (from pretrained, etc): @CyrilVallez
- distributed: @3outeille @ArthurZucker
- CIs: @ydshieh

Integrations:

- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization: @SunMarc @MekkCyber
- kernels: @MekkCyber @drbh
- peft: @BenjaminBossan @githubnemo

Devices/Backends:

- AMD ROCm: @ivarflakstad
- Intel XPU: @IlyasMoutawwakil
- Ascend NPU: @ivarflakstad 

Documentation: @stevhliu

Research projects are not maintained and should be taken as is.

 -->


Changed files:
filename: src/transformers/trainer.py
patch: @@ -694,6 +694,48 @@ def _validate_args(self) -> None:
                 "Samplers cannot be used with IterableDataset as they require indexed access to the dataset."
             )
 
+    def _build_accelerator_args(self, **kwargs) -> dict[str, Any]:
+        """Helper method to build accelerator-specific keyword arguments."""
+        args = {
+            "mixed_precision": self.args.mixed_precision,
+            "deepspeed_plugin": self.args.deepspeed_plugin,
+        }
+        args.update(kwargs)
+
+        # We defer compatibility checks to accelerator
+        if self.args.parallelism_config is not None:
+            min_accelerate_version = "1.12.0"
+            if not is_accelerate_available(min_accelerate_version):
+                raise ImportError(
+                    f"ParallelismConfig requires accelerate>={min_accelerate_version}). Please upgrade accelerate to use this feature."
+                )
+            args["parallelism_config"] = self.args.parallelism_config
+
+        self.is_tp_enabled = False
+        if getattr(self.model, "tp_size", None) is not None and self.model.tp_size > 1:
+            self.is_tp_enabled = True
+            if self.args.parallelism_config is None:
+                if is_accelerate_available("1.12.0"):
+                    if self.args.parallelism_config is None:
+                        from accelerate import ParallelismConfig
+
+                        args["parallelism_config"] = ParallelismConfig(tp_size=self.model.tp_size)
+                else:
+                    raise ValueError("Requires accelerate>1.12.0 to use Tensor Parallelism.")
+            elif args["parallelism_config"].tp_size != self.model.tp_size:
+                args["parallelism_config"].tp_size = self.model.tp_size
+
+        if is_accelerate_available("1.2.0"):
+            # it we don't have the correct version, we will rely on env var instead that were set in TrainingArguments
+            from accelerate.utils import TorchDynamoPlugin
+
+            dynamo_plugin = TorchDynamoPlugin(
+                backend=self.args.torch_compile_backend, mode=self.args.torch_compile_mode
+            )
+            args["dynamo_plugin"] = dynamo_plugin
+
+        return args
+
     def create_accelerator_and_postprocess(self) -> None:
         """Create the accelerator and perform post-creation setup (FSDP, DeepSpeed, etc.)."""
         # We explicitly don't rely on the `Accelerator` to do gradient accumulation
@@ -744,44 +786,11 @@ def create_accelerator_and_postprocess(self) -> None:
 
             fsdp_plugin = FullyShardedDataParallelPlugin(**self.args.fsdp_plugin_args)
 
-        args = {
-            "mixed_precision": self.args.mixed_precision,
-            "dataloader_config": dataloader_config,
-            "fsdp_plugin": fsdp_plugin,
-            "deepspeed_plugin": self.args.deepspeed_plugin,
-            "gradient_accumulation_plugin": gradient_accumulation_plugin,
-        }
-
-        # We defer compatibility checks to accelerator
-        if self.args.parallelism_config is not None:
-            min_accelerate_version = "1.12.0"
-            if not is_accelerate_available(min_accelerate_version):
-                raise ImportError(
-                    f"ParallelismConfig requires accelerate>={min_accelerate_version}). Please upgrade accelerate to use this feature."
-                )
-            args["parallelism_config"] = self.args.parallelism_config
-
-        self.is_tp_enabled = False
-        if getattr(self.model, "tp_size", None) is not None and self.model.tp_size > 1:
-            self.is_tp_enabled = True
-            if self.args.parallelism_config is None:
-                if is_accelerate_available("1.12.0"):
-                    if self.args.parallelism_config is None:
-                        from accelerate import ParallelismConfig
-
-                        args["parallelism_config"] = ParallelismConfig(tp_size=self.model.tp_size)
-                else:
-                    raise ValueError("Requires accelerate>1.12.0 to use Tensor Parallelism.")
-            elif args["parallelism_config"].tp_size != self.model.tp_size:
-                args["parallelism_config"].tp_size = self.model.tp_size
-        if is_accelerate_available("1.2.0"):
-            # it we don't have the correct version, we will rely on env var instead that were set in TrainingArguments
-            from accelerate.utils import TorchDynamoPlugin
-
-            dynamo_plugin = TorchDynamoPlugin(
-                backend=self.args.torch_compile_backend, mode=self.args.torch_compile_mode
-            )
-            args["dynamo_plugin"] = dynamo_plugin
+        args = self._build_accelerator_args(
+            dataloader_config=dataloader_config,
+            fsdp_plugin=fsdp_plugin,
+            gradient_accumulation_plugin=gradient_accumulation_plugin,
+        )
 
         # create accelerator object
         self.accelerator = Accelerator(**args)