






import inspect
import os

import torch
from transformers import AutoModel
from transformers.testing_utils import mockenv_context
from transformers.trainer_utils import set_seed

import accelerate
from accelerate.accelerator import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils.testing import (
    AccelerateTestCase,
    TempDirTestCase,
    execute_subprocess_async,
    require_cuda,
    require_fsdp,
    require_multi_gpu,
    slow,
)
from accelerate.utils.constants import (
    FSDP_AUTO_WRAP_POLICY,
    FSDP_BACKWARD_PREFETCH,
    FSDP_SHARDING_STRATEGY,
    FSDP_STATE_DICT_TYPE,
)
from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin
from accelerate.utils.other import patch_environment


set_seed(42)

__a   :							Dict						= "bert-base-cased"
__a   :							Any						= "fp16"
__a   :							str						= "bf16"
__a   :							Union[str, Any]						= [FPaa, BFaa]


@require_fsdp
@require_cuda
class    __lowercase   (						lowercase_	):







     '''simple docstring'''




     def 		lowerCAmelCase_  (					self							:      Optional[Any]					):


         """simple docstring"""



         super().setUp()

         __A       =						dict(
             ACCELERATE_USE_FSDP="""true"""			,						MASTER_ADDR="""localhost"""			,						MASTER_PORT="""10999"""			,						RANK="""0"""			,						LOCAL_RANK="""0"""			,						WORLD_SIZE="""1"""			,						)




     def 		lowerCAmelCase_  (					self							:      Dict					):


         """simple docstring"""



         from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy

         for i, strategy in enumerate(UpperCamelCase_					):
             __A       =						self.dist_env.copy()
             __A       =						F"{i + 1}"
             __A       =						strategy
             with mockenv_context(**UpperCamelCase_					):
                 __A       =						FullyShardedDataParallelPlugin()
                 self.assertEqual(fsdp_plugin.sharding_strategy			,						ShardingStrategy(i + 1					)					)




     def 		lowerCAmelCase_  (					self							:      List[Any]					):


         """simple docstring"""



         from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch

         for i, prefetch_policy in enumerate(UpperCamelCase_					):
             __A       =						self.dist_env.copy()
             __A       =						prefetch_policy
             with mockenv_context(**UpperCamelCase_					):
                 __A       =						FullyShardedDataParallelPlugin()
                 if prefetch_policy == "NO_PREFETCH":
                     self.assertIsNone(fsdp_plugin.backward_prefetch					)
                 else:
                     self.assertEqual(fsdp_plugin.backward_prefetch			,						BackwardPrefetch(i + 1					)					)




     def 		lowerCAmelCase_  (					self							:      Union[str, Any]					):


         """simple docstring"""



         from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType

         for i, state_dict_type in enumerate(UpperCamelCase_					):
             __A       =						self.dist_env.copy()
             __A       =						state_dict_type
             with mockenv_context(**UpperCamelCase_					):
                 __A       =						FullyShardedDataParallelPlugin()
                 self.assertEqual(fsdp_plugin.state_dict_type			,						StateDictType(i + 1					)					)
                 if state_dict_type == "FULL_STATE_DICT":
                     self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu					)
                     self.assertTrue(fsdp_plugin.state_dict_config.ranka_only					)




     def 		lowerCAmelCase_  (					self							:      Union[str, Any]					):


         """simple docstring"""



         __A       =						AutoModel.from_pretrained(UpperCamelCase_					)
         for policy in FSDP_AUTO_WRAP_POLICY:
             __A       =						self.dist_env.copy()
             __A       =						policy
             if policy == "TRANSFORMER_BASED_WRAP":
                 __A       =						"""BertLayer"""
             elif policy == "SIZE_BASED_WRAP":
                 __A       =						"""2000"""
             with mockenv_context(**UpperCamelCase_					):
                 __A       =						FullyShardedDataParallelPlugin()
                 fsdp_plugin.set_auto_wrap_policy(UpperCamelCase_					)
                 if policy == "NO_WRAP":
                     self.assertIsNone(fsdp_plugin.auto_wrap_policy					)
                 else:
                     self.assertIsNotNone(fsdp_plugin.auto_wrap_policy					)

         __A       =						self.dist_env.copy()
         __A       =						"""TRANSFORMER_BASED_WRAP"""
         __A       =						"""T5Layer"""
         with mockenv_context(**UpperCamelCase_					):
             __A       =						FullyShardedDataParallelPlugin()
             with self.assertRaises(UpperCamelCase_					) as cm:
                 fsdp_plugin.set_auto_wrap_policy(UpperCamelCase_					)
             self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception					)					)

         __A       =						self.dist_env.copy()
         __A       =						"""SIZE_BASED_WRAP"""
         __A       =						"""0"""
         with mockenv_context(**UpperCamelCase_					):
             __A       =						FullyShardedDataParallelPlugin()
             fsdp_plugin.set_auto_wrap_policy(UpperCamelCase_					)
             self.assertIsNone(fsdp_plugin.auto_wrap_policy					)




     def 		lowerCAmelCase_  (					self							:      List[Any]					):


         """simple docstring"""



         from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
         from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler

         for mp_dtype in dtypes:
             __A       =						self.dist_env.copy()
             __A       =						mp_dtype
             with mockenv_context(**UpperCamelCase_					):
                 __A       =						Accelerator()
                 if mp_dtype == "fp16":
                     __A       =						torch.floataa
                 elif mp_dtype == "bf16":
                     __A       =						torch.bfloataa
                 __A       =						MixedPrecision(param_dtype=UpperCamelCase_			,						reduce_dtype=UpperCamelCase_			,						buffer_dtype=UpperCamelCase_					)
                 self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy			,						UpperCamelCase_					)
                 if mp_dtype == FPaa:
                     self.assertTrue(isinstance(accelerator.scaler			,						UpperCamelCase_					)					)
                 elif mp_dtype == BFaa:
                     self.assertIsNone(accelerator.scaler					)
                 AcceleratorState._reset_state(UpperCamelCase_					)





     def 		lowerCAmelCase_  (					self							:      Tuple					):


         """simple docstring"""



         from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload

         for flag in [True, False]:
             __A       =						self.dist_env.copy()
             __A       =						str(UpperCamelCase_					).lower()
             with mockenv_context(**UpperCamelCase_					):
                 __A       =						FullyShardedDataParallelPlugin()
                 self.assertEqual(fsdp_plugin.cpu_offload			,						CPUOffload(offload_params=UpperCamelCase_					)					)


@require_fsdp
@require_multi_gpu
@slow
class    __lowercase   (						lowercase_	):







     '''simple docstring'''




     def 		lowerCAmelCase_  (					self							:      Union[str, Any]					):


         """simple docstring"""



         super().setUp()
         __A       =						0.82
         __A       =						[
             """fsdp_shard_grad_op_transformer_based_wrap""",
             """fsdp_full_shard_transformer_based_wrap""",
         ]
         __A       =						{
             """multi_gpu_fp16""": 3_200,
             """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2_000,
             """fsdp_full_shard_transformer_based_wrap_fp16""": 1_900,
             # Disabling below test as it overwhelms the RAM memory usage
             # on CI self-hosted runner leading to tests getting killed.
             # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500,  # fp16 was leading to indefinite hang
         }
         __A       =						160
         __A       =						160

         __A       =						inspect.getfile(accelerate.test_utils					)
         __A       =						os.path.sep.join(mod_file.split(os.path.sep					)[:-1] + ["""scripts""", """external_deps"""]					)




     def 		lowerCAmelCase_  (					self							:      Any					):


         """simple docstring"""



         __A       =						os.path.join(self.test_scripts_folder			,						"""test_performance.py"""					)
         __A       =						["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""]
         for config in self.performance_configs:
             __A       =						cmd.copy()
             for i, strategy in enumerate(UpperCamelCase_					):
                 if strategy.lower() in config:
                     cmd_config.append(F"--fsdp_sharding_strategy={i+1}"					)
                     break

             if "fp32" in config:
                 cmd_config.append("""--mixed_precision=no"""					)
             else:
                 cmd_config.append("""--mixed_precision=fp16"""					)

             if "cpu_offload" in config:
                 cmd_config.append("""--fsdp_offload_params=True"""					)

             for policy in FSDP_AUTO_WRAP_POLICY:
                 if policy.lower() in config:
                     cmd_config.append(F"--fsdp_auto_wrap_policy={policy}"					)
                     break

             if policy == "TRANSFORMER_BASED_WRAP":
                 cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer"""					)
             elif policy == "SIZE_BASED_WRAP":
                 cmd_config.append("""--fsdp_min_num_params=2000"""					)

             cmd_config.extend(
                 [
                     self.test_file_path,
                     F"--output_dir={self.tmpdir}",
                     F"--performance_lower_bound={self.performance_lower_bound}",
                 ]					)
             with patch_environment(omp_num_threads=1					):
                 execute_subprocess_async(UpperCamelCase_			,						env=os.environ.copy()					)




     def 		lowerCAmelCase_  (					self							:      Dict					):


         """simple docstring"""



         __A       =						os.path.join(self.test_scripts_folder			,						"""test_checkpointing.py"""					)
         __A       =						[
             """accelerate""",
             """launch""",
             """--num_processes=2""",
             """--num_machines=1""",
             """--machine_rank=0""",
             """--use_fsdp""",
             """--mixed_precision=fp16""",
             """--fsdp_transformer_layer_cls_to_wrap=BertLayer""",
         ]

         for i, strategy in enumerate(UpperCamelCase_					):
             __A       =						cmd.copy()
             cmd_config.append(F"--fsdp_sharding_strategy={i+1}"					)
             if strategy != "FULL_SHARD":
                 continue
             __A       =						len(UpperCamelCase_					)
             for state_dict_type in FSDP_STATE_DICT_TYPE:
                 __A       =						cmd_config[:state_dict_config_index]
                 cmd_config.append(F"--fsdp_state_dict_type={state_dict_type}"					)
                 cmd_config.extend(
                     [
                         self.test_file_path,
                         F"--output_dir={self.tmpdir}",
                         """--partial_train_epoch=1""",
                     ]					)
                 with patch_environment(omp_num_threads=1					):
                     execute_subprocess_async(UpperCamelCase_			,						env=os.environ.copy()					)

                 __A       =						cmd_config[:-1]
                 __A       =						os.path.join(self.tmpdir			,						"""epoch_0"""					)
                 cmd_config.extend(
                     [
                         F"--resume_from_checkpoint={resume_from_checkpoint}",
                     ]					)
                 with patch_environment(omp_num_threads=1					):
                     execute_subprocess_async(UpperCamelCase_			,						env=os.environ.copy()					)





     def 		lowerCAmelCase_  (					self							:      Any					):


         """simple docstring"""



         __A       =						os.path.join(self.test_scripts_folder			,						"""test_peak_memory_usage.py"""					)
         __A       =						[
             """accelerate""",
             """launch""",
             """--num_processes=2""",
             """--num_machines=1""",
             """--machine_rank=0""",
         ]
         for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items():
             __A       =						cmd.copy()
             if "fp16" in spec:
                 cmd_config.extend(["""--mixed_precision=fp16"""]					)
             else:
                 cmd_config.extend(["""--mixed_precision=no"""]					)

             if "multi_gpu" in spec:
                 continue
             else:
                 cmd_config.extend(["""--use_fsdp"""]					)
                 for i, strategy in enumerate(UpperCamelCase_					):
                     if strategy.lower() in spec:
                         cmd_config.append(F"--fsdp_sharding_strategy={i+1}"					)
                         break

                 if "cpu_offload" in spec:
                     cmd_config.append("""--fsdp_offload_params=True"""					)

                 for policy in FSDP_AUTO_WRAP_POLICY:
                     if policy.lower() in spec:
                         cmd_config.append(F"--fsdp_auto_wrap_policy={policy}"					)
                         break

                 if policy == "TRANSFORMER_BASED_WRAP":
                     cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer"""					)
                 elif policy == "SIZE_BASED_WRAP":
                     cmd_config.append("""--fsdp_min_num_params=2000"""					)

             cmd_config.extend(
                 [
                     self.test_file_path,
                     F"--output_dir={self.tmpdir}",
                     F"--peak_memory_upper_bound={peak_mem_upper_bound}",
                     F"--n_train={self.n_train}",
                     F"--n_val={self.n_val}",
                 ]					)
             with patch_environment(omp_num_threads=1					):
                 execute_subprocess_async(UpperCamelCase_			,						env=os.environ.copy()					)












from __future__ import annotations

from PIL import Image

# Define glider example
__a   :							Tuple						= [
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [1, 1, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
]

# Define blinker example
__a   :							Optional[Any]						= [[0, 1, 0], [0, 1, 0], [0, 1, 0]]



def       _SCREAMING_SNAKE_CASE    (			__lowercase :      list[list[int]]     )    ->   list[list[int]]:





    """simple docstring"""

    __A       =						[]
    for i in range(len(__lowercase     )     ):
        __A       =						[]
        for j in range(len(cells[i]     )     ):
            # Get the number of live neighbours
            __A       =						0
            if i > 0 and j > 0:
                neighbour_count += cells[i - 1][j - 1]
            if i > 0:
                neighbour_count += cells[i - 1][j]
            if i > 0 and j < len(cells[i]     ) - 1:
                neighbour_count += cells[i - 1][j + 1]
            if j > 0:
                neighbour_count += cells[i][j - 1]
            if j < len(cells[i]     ) - 1:
                neighbour_count += cells[i][j + 1]
            if i < len(__lowercase     ) - 1 and j > 0:
                neighbour_count += cells[i + 1][j - 1]
            if i < len(__lowercase     ) - 1:
                neighbour_count += cells[i + 1][j]
            if i < len(__lowercase     ) - 1 and j < len(cells[i]     ) - 1:
                neighbour_count += cells[i + 1][j + 1]

            # Rules of the game of life (excerpt from Wikipedia):
            # 1. Any live cell with two or three live neighbours survives.
            # 2. Any dead cell with three live neighbours becomes a live cell.
            # 3. All other live cells die in the next generation.
            #    Similarly, all other dead cells stay dead.
            __A       =						cells[i][j] == 1
            if (
                (alive and 2 <= neighbour_count <= 3)
                or not alive
                and neighbour_count == 3
            ):
                next_generation_row.append(1     )
            else:
                next_generation_row.append(0     )

        next_generation.append(__lowercase     )
    return next_generation



def       _SCREAMING_SNAKE_CASE    (			__lowercase :      list[list[int]]      ,					__lowercase :      int     )    ->   list[Image.Image]:





    """simple docstring"""

    __A       =						[]
    for _ in range(__lowercase     ):
        # Create output image
        __A       =						Image.new("""RGB"""      ,					(len(cells[0]     ), len(__lowercase     ))     )
        __A       =						img.load()

        # Save cells to image
        for x in range(len(__lowercase     )     ):
            for y in range(len(cells[0]     )     ):
                __A       =						2_5_5 - cells[y][x] * 2_5_5
                __A       =						(colour, colour, colour)

        # Save image
        images.append(__lowercase     )
        __A       =						new_generation(__lowercase     )
    return images


if __name__ == "__main__":
  __a   :							Optional[int]						= generate_images(GLIDER, 16)
  images[0].save("out.gif", save_all=True, append_images=images[1:])




