





import unittest

import numpy as np

from transformers import is_flax_available
from transformers.testing_utils import require_flax

from ..test_modeling_flax_common import ids_tensor


if is_flax_available():
     import jax
     import jax.numpy as jnp

     from transformers.generation import (
         FlaxForcedBOSTokenLogitsProcessor,
         FlaxForcedEOSTokenLogitsProcessor,
         FlaxLogitsProcessorList,
         FlaxMinLengthLogitsProcessor,
         FlaxTemperatureLogitsWarper,
         FlaxTopKLogitsWarper,
         FlaxTopPLogitsWarper,
     )



@require_flax
class 							_UpperCamelCase					(	unittest.TestCase     ):

       def lowercase (		self: List[str]					,   _SCREAMING_SNAKE_CASE: int					,   _SCREAMING_SNAKE_CASE: int		)       -> Optional[int]:




              """simple docstring"""


              UpperCamelCase_          =  jnp.ones((batch_size, length)		) / length
              return scores

       def lowercase (		self: List[Any]		)       -> List[Any]:




              """simple docstring"""


              UpperCamelCase_          =  None
              UpperCamelCase_          =  20

              UpperCamelCase_          =  self._get_uniform_logits(batch_size=2					,   length=_SCREAMING_SNAKE_CASE		)

              # tweak scores to not be uniform anymore
              UpperCamelCase_          =  scores.at[1, 5].set((1 / length) + 0.1		)  # peak, 1st batch
              UpperCamelCase_          =  scores.at[1, 10].set((1 / length) - 0.4		)  # valley, 1st batch

              # compute softmax
              UpperCamelCase_          =  jax.nn.softmax(_SCREAMING_SNAKE_CASE					,   axis=-1		)

              UpperCamelCase_          =  FlaxTemperatureLogitsWarper(temperature=0.5		)
              UpperCamelCase_          =  FlaxTemperatureLogitsWarper(temperature=1.3		)

              UpperCamelCase_          =  jax.nn.softmax(temp_dist_warper_sharper(_SCREAMING_SNAKE_CASE					,   scores.copy()					,   cur_len=_SCREAMING_SNAKE_CASE		)					,   axis=-1		)
              UpperCamelCase_          =  jax.nn.softmax(temp_dist_warper_smoother(_SCREAMING_SNAKE_CASE					,   scores.copy()					,   cur_len=_SCREAMING_SNAKE_CASE		)					,   axis=-1		)

              # uniform distribution stays uniform
              self.assertTrue(jnp.allclose(probs[0, :]					,   warped_prob_sharp[0, :]					,   atol=1e-3		)		)
              self.assertTrue(jnp.allclose(probs[0, :]					,   warped_prob_smooth[0, :]					,   atol=1e-3		)		)

              # sharp peaks get higher, valleys get lower
              self.assertLess(probs[1, :].max()					,   warped_prob_sharp[1, :].max()		)
              self.assertGreater(probs[1, :].min()					,   warped_prob_sharp[1, :].min()		)

              # smooth peaks get lower, valleys get higher
              self.assertGreater(probs[1, :].max()					,   warped_prob_smooth[1, :].max()		)
              self.assertLess(probs[1, :].min()					,   warped_prob_smooth[1, :].min()		)

       def lowercase (		self: str		)       -> Optional[Any]:




              """simple docstring"""


              UpperCamelCase_          =  None
              UpperCamelCase_          =  10
              UpperCamelCase_          =  2

              # create ramp distribution
              UpperCamelCase_          =  np.broadcast_to(np.arange(_SCREAMING_SNAKE_CASE		)[None, :]					,   (batch_size, vocab_size)		).copy()
              UpperCamelCase_          =  ramp_logits[1:, : vocab_size // 2] + vocab_size

              UpperCamelCase_          =  FlaxTopKLogitsWarper(3		)

              UpperCamelCase_          =  top_k_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)

              # check that correct tokens are filtered
              self.assertListEqual(jnp.isinf(scores[0]		).tolist()					,   7 * [True] + 3 * [False]		)
              self.assertListEqual(jnp.isinf(scores[1]		).tolist()					,   2 * [True] + 3 * [False] + 5 * [True]		)

              # check special case
              UpperCamelCase_          =  5
              UpperCamelCase_          =  FlaxTopKLogitsWarper(top_k=1					,   filter_value=0.0					,   min_tokens_to_keep=3		)

              UpperCamelCase_          =  np.broadcast_to(np.arange(_SCREAMING_SNAKE_CASE		)[None, :]					,   (batch_size, length)		).copy()
              UpperCamelCase_          =  top_k_warp_safety_check(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)

              # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
              self.assertListEqual((scores == 0.0).sum(axis=-1		).tolist()					,   [2, 2]		)

       def lowercase (		self: Tuple		)       -> Dict:




              """simple docstring"""


              UpperCamelCase_          =  None
              UpperCamelCase_          =  10
              UpperCamelCase_          =  2

              # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
              UpperCamelCase_          =  np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]]		)		)

              UpperCamelCase_          =  FlaxTopPLogitsWarper(0.8		)
              UpperCamelCase_          =  np.exp(top_p_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)		)

              # dist should be filtered to keep min num values so that sum is >= top_p
              # exp (-inf) => 0
              UpperCamelCase_          =  np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]		)
              self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   atol=1e-3		)		)

              # check edge cases with negative and extreme logits
              UpperCamelCase_          =  np.broadcast_to(np.arange(_SCREAMING_SNAKE_CASE		)[None, :]					,   (batch_size, vocab_size)		).copy() - (
                  vocab_size // 2
              )

              # make ramp_logits more extreme
              UpperCamelCase_          =  ramp_logits[1] * 1_00.0

              # make sure at least 2 tokens are kept
              UpperCamelCase_          =  FlaxTopPLogitsWarper(0.9					,   min_tokens_to_keep=2					,   filter_value=0.0		)
              UpperCamelCase_          =  top_p_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)

              # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
              self.assertListEqual((filtered_dist != 0.0).sum(axis=-1		).tolist()					,   [3, 2]		)

       def lowercase (		self: Union[str, Any]		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  20
              UpperCamelCase_          =  4
              UpperCamelCase_          =  0

              UpperCamelCase_          =  FlaxMinLengthLogitsProcessor(min_length=10					,   eos_token_id=_SCREAMING_SNAKE_CASE		)

              # check that min length is applied at length 5
              UpperCamelCase_          =  ids_tensor((batch_size, 20)					,   vocab_size=20		)
              UpperCamelCase_          =  5
              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  min_dist_processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()					,   4 * [-float("inf"		)]		)

              # check that min length is not applied anymore at length 15
              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  15
              UpperCamelCase_          =  min_dist_processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              self.assertFalse(jnp.isinf(_SCREAMING_SNAKE_CASE		).any()		)

       def lowercase (		self: Tuple		)       -> List[Any]:




              """simple docstring"""


              UpperCamelCase_          =  20
              UpperCamelCase_          =  4
              UpperCamelCase_          =  0

              UpperCamelCase_          =  FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE		)

              # check that all scores are -inf except the bos_token_id score
              UpperCamelCase_          =  ids_tensor((batch_size, 1)					,   vocab_size=20		)
              UpperCamelCase_          =  1
              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  logits_processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]		).all()		)
              self.assertListEqual(scores[:, bos_token_id].tolist()					,   4 * [0]		)  # score for bos_token_id shold be zero

              # check that bos_token_id is not forced if current length is greater than 1
              UpperCamelCase_          =  3
              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  logits_processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              self.assertFalse(jnp.isinf(_SCREAMING_SNAKE_CASE		).any()		)

       def lowercase (		self: int		)       -> Dict:




              """simple docstring"""


              UpperCamelCase_          =  20
              UpperCamelCase_          =  4
              UpperCamelCase_          =  0
              UpperCamelCase_          =  5

              UpperCamelCase_          =  FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE					,   eos_token_id=_SCREAMING_SNAKE_CASE		)

              # check that all scores are -inf except the eos_token_id when max_length is reached
              UpperCamelCase_          =  ids_tensor((batch_size, 4)					,   vocab_size=20		)
              UpperCamelCase_          =  4
              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  logits_processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]		).all()		)
              self.assertListEqual(scores[:, eos_token_id].tolist()					,   4 * [0]		)  # score for eos_token_id should be zero

              # check that eos_token_id is not forced if max_length is not reached
              UpperCamelCase_          =  3
              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  logits_processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              self.assertFalse(jnp.isinf(_SCREAMING_SNAKE_CASE		).any()		)

       def lowercase (		self: Union[str, Any]		)       -> int:




              """simple docstring"""


              UpperCamelCase_          =  4
              UpperCamelCase_          =  10
              UpperCamelCase_          =  15
              UpperCamelCase_          =  2
              UpperCamelCase_          =  1
              UpperCamelCase_          =  15

              # dummy input_ids and scores
              UpperCamelCase_          =  ids_tensor((batch_size, sequence_length)					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  input_ids.copy()

              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  scores.copy()

              # instantiate all dist processors
              UpperCamelCase_          =  FlaxTemperatureLogitsWarper(temperature=0.5		)
              UpperCamelCase_          =  FlaxTopKLogitsWarper(3		)
              UpperCamelCase_          =  FlaxTopPLogitsWarper(0.8		)

              # instantiate all logits processors
              UpperCamelCase_          =  FlaxMinLengthLogitsProcessor(min_length=10					,   eos_token_id=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE					,   eos_token_id=_SCREAMING_SNAKE_CASE		)

              UpperCamelCase_          =  10

              # no processor list
              UpperCamelCase_          =  temp_dist_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  top_k_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  top_p_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  min_dist_proc(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  bos_dist_proc(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  eos_dist_proc(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)

              # with processor list
              UpperCamelCase_          =  FlaxLogitsProcessorList(
                  [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]		)
              UpperCamelCase_          =  processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)

              # scores should be equal
              self.assertTrue(jnp.allclose(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   atol=1e-3		)		)

              # input_ids should never be changed
              self.assertListEqual(input_ids.tolist()					,   input_ids_comp.tolist()		)



       def lowercase (		self: Union[str, Any]		)       -> List[str]:




              """simple docstring"""


              UpperCamelCase_          =  4
              UpperCamelCase_          =  10
              UpperCamelCase_          =  15
              UpperCamelCase_          =  2
              UpperCamelCase_          =  1
              UpperCamelCase_          =  15

              # dummy input_ids and scores
              UpperCamelCase_          =  ids_tensor((batch_size, sequence_length)					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  input_ids.copy()

              UpperCamelCase_          =  self._get_uniform_logits(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  scores.copy()

              # instantiate all dist processors
              UpperCamelCase_          =  FlaxTemperatureLogitsWarper(temperature=0.5		)
              UpperCamelCase_          =  FlaxTopKLogitsWarper(3		)
              UpperCamelCase_          =  FlaxTopPLogitsWarper(0.8		)

              # instantiate all logits processors
              UpperCamelCase_          =  FlaxMinLengthLogitsProcessor(min_length=10					,   eos_token_id=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE					,   eos_token_id=_SCREAMING_SNAKE_CASE		)

              UpperCamelCase_          =  10

              # no processor list
              def run_no_processor_list(_SCREAMING_SNAKE_CASE: List[str]					,   _SCREAMING_SNAKE_CASE: Tuple					,   _SCREAMING_SNAKE_CASE: Union[str, Any]		):
                     UpperCamelCase_          =  temp_dist_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  top_k_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  top_p_warp(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  min_dist_proc(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  bos_dist_proc(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  eos_dist_proc(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
                     return scores

              # with processor list
              def run_processor_list(_SCREAMING_SNAKE_CASE: Dict					,   _SCREAMING_SNAKE_CASE: Any					,   _SCREAMING_SNAKE_CASE: Optional[int]		):
                     UpperCamelCase_          =  FlaxLogitsProcessorList(
                         [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]		)
                     UpperCamelCase_          =  processor(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   cur_len=_SCREAMING_SNAKE_CASE		)
                     return scores

              UpperCamelCase_          =  jax.jit(_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  jax.jit(_SCREAMING_SNAKE_CASE		)

              UpperCamelCase_          =  jitted_run_no_processor_list(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  jitted_run_processor_list(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)

              # scores should be equal
              self.assertTrue(jnp.allclose(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE					,   atol=1e-3		)		)

              # input_ids should never be changed
              self.assertListEqual(input_ids.tolist()					,   input_ids_comp.tolist()		)








import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment




def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_=()					,		UpperCamelCase_=None					,		UpperCamelCase_="no"					,		UpperCamelCase_="29500"  )     ->		Optional[Any]:
       UpperCamelCase_          =  False
       UpperCamelCase_          =  False
       if any(key.startswith("KAGGLE"  ) for key in os.environ.keys()  ):
              UpperCamelCase_          =  True
       elif "IPython" in sys.modules:
              UpperCamelCase_          =  "google.colab" in str(sys.modules["IPython"].get_ipython()  )

       try:
              UpperCamelCase_          =  PrecisionType(mixed_precision.lower()  )
       except ValueError:
              raise ValueError(
                  F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.'''  )

       if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME"					,		UpperCamelCase_  ) is not None):
              # TPU launch
              import torch_xla.distributed.xla_multiprocessing as xmp

              if len(AcceleratorState._shared_state  ) > 0:
                     raise ValueError(
                         "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
                         "your training function. Restart your notebook and make sure no cells initializes an "
                         "`Accelerator`."  )
              if num_processes is None:
                     UpperCamelCase_          =  8

              UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		distributed_type="TPU"  )
              print(F'''Launching a training on {num_processes} TPU cores.'''  )
              xmp.spawn(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )
       elif in_colab:
              # No need for a distributed launch otherwise as it's either CPU or one GPU.
              if torch.cuda.is_available():
                     print("Launching training on one GPU."  )
              else:
                     print("Launching training on one CPU."  )
              function(*UpperCamelCase_  )
       else:
              if num_processes is None:
                     raise ValueError(
                         "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."  )

              if num_processes > 1:
                     # Multi-GPU launch
                     from torch.multiprocessing import start_processes
                     from torch.multiprocessing.spawn import ProcessRaisedException

                     if len(AcceleratorState._shared_state  ) > 0:
                            raise ValueError(
                                "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
                                "inside your training function. Restart your notebook and make sure no cells initializes an "
                                "`Accelerator`."  )

                     if torch.cuda.is_initialized():
                            raise ValueError(
                                "To launch a multi-GPU training from your notebook, you need to avoid running any instruction "
                                "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA "
                                "function."  )

                     # torch.distributed will expect a few environment variable to be here. We set the ones common to each
                     # process here (the other ones will be set be the launcher).
                     with patch_environment(
                         world_size=UpperCamelCase_					,		master_addr="127.0.01"					,		master_port=UpperCamelCase_					,		mixed_precision=UpperCamelCase_  ):
                            UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		distributed_type="MULTI_GPU"  )
                            print(F'''Launching training on {num_processes} GPUs.'''  )
                            try:
                                   start_processes(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )
                            except ProcessRaisedException as e:
                                   if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
                                          raise RuntimeError(
                                              "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
                                              "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
                                              "Please review your imports and test them when running the `notebook_launcher()` to identify "
                                              "which one is problematic."  ) from e

              else:
                     # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
                     if is_mps_available():
                            UpperCamelCase_          =  "1"
                            print("Launching training on MPS."  )
                     elif torch.cuda.is_available():
                            print("Launching training on one GPU."  )
                     else:
                            print("Launching training on CPU."  )
                     function(*UpperCamelCase_  )







def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_=()					,		UpperCamelCase_=2  )     ->		Optional[Any]:
       from torch.multiprocessing import start_processes

       with tempfile.NamedTemporaryFile() as tmp_file:
              # torch.distributed will expect a few environment variable to be here. We set the ones common to each
              # process here (the other ones will be set be the launcher).
              with patch_environment(
                  world_size=UpperCamelCase_					,		master_addr="127.0.01"					,		master_port="29500"					,		accelerate_mixed_precision="no"					,		accelerate_debug_rdv_file=tmp_file.name					,		accelerate_use_cpu="yes"					,		):
                     UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		debug=UpperCamelCase_  )
                     start_processes(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )

