
import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
   import torch_xla.core.xla_model as xm



def 						lowercase_			(   A__ ,		A__ = False		)							->							Tuple:
    """simple docstring"""

    if device_specific:
        seed += AcceleratorState().process_index
    random.seed(A__		)
    np.random.seed(A__		)
    torch.manual_seed(A__		)
    if is_xpu_available():
        torch.xpu.manual_seed_all(A__		)
    elif is_npu_available():
        torch.npu.manual_seed_all(A__		)
    else:
        torch.cuda.manual_seed_all(A__		)
    # ^^ safe to call this function even if cuda is not available
    if is_tpu_available():
        xm.set_rng_state(A__		)



def 						lowercase_			(   A__ = None ,		A__ = None		)							->							Optional[Any]:
    """simple docstring"""

    if rng_type == RNGType.TORCH:
        snake_case      =					torch.get_rng_state()
    elif rng_type == RNGType.CUDA:
        snake_case      =					torch.cuda.get_rng_state()
    elif rng_type == RNGType.XLA:
        assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
        snake_case      =					torch.tensor(xm.get_rng_state()		)
    elif rng_type == RNGType.NPU:
        assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
        snake_case      =					torch.npu.get_rng_state()
    elif rng_type == RNGType.XPU:
        assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
        snake_case      =					torch.xpu.get_rng_state()
    elif rng_type == RNGType.GENERATOR:
        assert generator is not None, "Need a generator to synchronize its seed."
        snake_case      =					generator.get_state()

    # Broadcast the rng state from device 0 to other devices
    snake_case      =					AcceleratorState()
    if state.distributed_type == DistributedType.TPU:
        snake_case      =					rng_state.to(xm.xla_device()		)
        xm.collective_broadcast([rng_state]		)
        xm.mark_step()
        snake_case      =					rng_state.cpu()
    elif (
        state.distributed_type in CUDA_DISTRIBUTED_TYPES
        or state.distributed_type == DistributedType.MULTI_NPU
        or state.distributed_type == DistributedType.MULTI_XPU
    ):
        snake_case      =					rng_state.to(state.device		)
        torch.distributed.broadcast(A__ ,		0		)
        snake_case      =					rng_state.cpu()
    elif state.distributed_type == DistributedType.MULTI_CPU:
        torch.distributed.broadcast(A__ ,		0		)

    # Set the broadcast rng state
    if rng_type == RNGType.TORCH:
        torch.set_rng_state(A__		)
    elif rng_type == RNGType.CUDA:
        torch.cuda.set_rng_state(A__		)
    elif rng_type == RNGType.NPU:
        torch.npu.set_rng_state(A__		)
    elif rng_type == RNGType.XPU:
        torch.xpu.set_rng_state(A__		)
    elif rng_type == RNGType.XLA:
        xm.set_rng_state(rng_state.item()		)
    elif rng_type == RNGType.GENERATOR:
        generator.set_state(A__		)





def 						lowercase_			(   A__ ,		A__ = None		)							->							Optional[Any]:
    """simple docstring"""

    for rng_type in rng_types:
        synchronize_rng_state(RNGType(A__		) ,		generator=A__		)



import os
import shutil
import unittest
from unittest.mock import patch

from transformers.testing_utils import CaptureStd, is_pt_tf_cross_test, require_torch







class      lowerCamelCase		(  unittest.TestCase  ):





     @patch("sys.argv"				,    ["fakeprogrampath", "env"]   )
     def 		UpperCAmelCase(self      :    Optional[Any]   )						->						Dict:
         # test transformers-cli env
         import transformers.commands.transformers_cli

         with CaptureStd() as cs:
             transformers.commands.transformers_cli.main()
         self.assertIn("Python version"				,    cs.out   )
         self.assertIn("Platform"				,    cs.out   )
         self.assertIn("Using distributed or parallel set-up in script?"				,    cs.out   )





     @is_pt_tf_cross_test
     @patch(
         "sys.argv"				,    ["fakeprogrampath", "pt-to-tf", "--model-name", "hf-internal-testing/tiny-random-gptj", "--no-pr"]   )
     def 		UpperCAmelCase(self      :    Any   )						->						int:
         import transformers.commands.transformers_cli

         shutil.rmtree("/tmp/hf-internal-testing/tiny-random-gptj"				,    ignore_errors=_A   )  # cleans potential past runs
         transformers.commands.transformers_cli.main()

         # The original repo has no TF weights -- if they exist, they were created by the CLI
         self.assertTrue(os.path.exists("/tmp/hf-internal-testing/tiny-random-gptj/tf_model.h5"   )   )





     @require_torch
     @patch("sys.argv"				,    ["fakeprogrampath", "download", "hf-internal-testing/tiny-random-gptj", "--cache-dir", "/tmp"]   )
     def 		UpperCAmelCase(self      :    Dict   )						->						List[Any]:
         import transformers.commands.transformers_cli

         # # remove any previously downloaded model to start clean
         shutil.rmtree("/tmp/models--hf-internal-testing--tiny-random-gptj"				,    ignore_errors=_A   )

         # run the command
         transformers.commands.transformers_cli.main()

         # check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--tiny-random-gptj
         self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/blobs"   )   )
         self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/refs"   )   )
         self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/snapshots"   )   )





     @require_torch
     @patch(
         "sys.argv"				,    [
             "fakeprogrampath",
             "download",
             "hf-internal-testing/test_dynamic_model_with_tokenizer",
             "--trust-remote-code",
             "--cache-dir",
             "/tmp",
         ]				,    )
     def 		UpperCAmelCase(self      :    Any   )						->						List[str]:
         import transformers.commands.transformers_cli

         # # remove any previously downloaded model to start clean
         shutil.rmtree("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer"				,    ignore_errors=_A   )

         # run the command
         transformers.commands.transformers_cli.main()

         # check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer
         self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/blobs"   )   )
         self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/refs"   )   )
         self.assertTrue(
             os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/snapshots"   )   )

