



'''simple docstring'''


import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


lowercase											=      logging.get_logger(__name__)

if is_tf_available():
  import tensorflow as tf







@dataclass
class 						UpperCAmelCase						(		__a):


 '''simple docstring'''




 __magic_name__       :			List[str]	=   "tf"
 __magic_name__       :			Optional[str]	=   field(
     default=__a       ,						metadata={"help": "Name of TPU"}       ,						)

 __magic_name__       :			Optional[str]	=   field(
     default=__a       ,						metadata={"help": "Zone of TPU"}       ,						)

 __magic_name__       :			Optional[str]	=   field(
     default=__a       ,						metadata={"help": "Name of Cloud TPU-enabled project"}       ,						)

 __magic_name__       :			float	=   field(
     default=1.0       ,						metadata={"help": "Power for the Polynomial decay LR scheduler."}       ,						)

 __magic_name__       :			bool	=   field(default=__a       ,						metadata={"help": "Whether to activate the XLA compilation or not"})




 @cached_property
 def    lowercase_	( self)			->   Tuple["tf.distribute.Strategy", int]:



      """simple docstring"""







      requires_backends(self				,	["tf"])
      logger.info("Tensorflow: setting up strategy")

      a_									=tf.config.list_physical_devices("GPU")

      # Set to float16 at first
      if self.fpaa:
           tf.keras.mixed_precision.set_global_policy("mixed_float16")

      if self.no_cuda:
           a_									=tf.distribute.OneDeviceStrategy(device="/cpu:0")
      else:
           try:
                if self.tpu_name:
                     a_									=tf.distribute.cluster_resolver.TPUClusterResolver(
                         self.tpu_name				,	zone=self.tpu_zone				,	project=self.gcp_project)
                else:
                     a_									=tf.distribute.cluster_resolver.TPUClusterResolver()
           except ValueError:
                if self.tpu_name:
                     raise RuntimeError(f"""Couldn't connect to TPU {self.tpu_name}!""")
                else:
                     a_									=None

           if tpu:
                # Set to bfloat16 in case of TPU
                if self.fpaa:
                     tf.keras.mixed_precision.set_global_policy("mixed_bfloat16")

                tf.config.experimental_connect_to_cluster(lowerCAmelCase_)
                tf.tpu.experimental.initialize_tpu_system(lowerCAmelCase_)

                a_									=tf.distribute.TPUStrategy(lowerCAmelCase_)

           elif len(lowerCAmelCase_) == 0:
                a_									=tf.distribute.OneDeviceStrategy(device="/cpu:0")
           elif len(lowerCAmelCase_) == 1:
                a_									=tf.distribute.OneDeviceStrategy(device="/gpu:0")
           elif len(lowerCAmelCase_) > 1:
                # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
                a_									=tf.distribute.MirroredStrategy()
           else:
                raise ValueError("Cannot find the proper strategy, please check your environment properties.")

      return strategy




 @property
 def    lowercase_	( self)			->   "tf.distribute.Strategy":



      """simple docstring"""







      requires_backends(self				,	["tf"])
      return self._setup_strategy




 @property
 def    lowercase_	( self)			->   int:



      """simple docstring"""







      requires_backends(self				,	["tf"])
      return self._setup_strategy.num_replicas_in_sync




 @property
 def    lowercase_	( self)			->   List[Any]:



      """simple docstring"""







      return False  # TF Logging is handled by Keras not the Trainer




 @property
 def    lowercase_	( self)			->   int:



      """simple docstring"""







      if self.per_gpu_train_batch_size:
           logger.warning(
               "Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future "
               "version. Using `--per_device_train_batch_size` is preferred.")
      a_									=self.per_gpu_train_batch_size or self.per_device_train_batch_size
      return per_device_batch_size * self.n_replicas




 @property
 def    lowercase_	( self)			->   int:



      """simple docstring"""







      if self.per_gpu_eval_batch_size:
           logger.warning(
               "Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future "
               "version. Using `--per_device_eval_batch_size` is preferred.")
      a_									=self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
      return per_device_batch_size * self.n_replicas




 @property
 def    lowercase_	( self)			->   int:



      """simple docstring"""







      requires_backends(self				,	["tf"])
      warnings.warn(
          "The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead."				,	lowerCAmelCase_				,	)
      return self._setup_strategy.num_replicas_in_sync







'''simple docstring'''


import unittest
from dataclasses import dataclass
from typing import List, Union

import numpy as np
import PIL.Image

from diffusers.utils.outputs import BaseOutput







@dataclass
class 						UpperCAmelCase						(		__a):


 '''simple docstring'''




 __magic_name__       :			Union[List[PIL.Image.Image], np.ndarray]







class 						UpperCAmelCase						(		unittest.TestCase):


 '''simple docstring'''




 def    lowercase_	( self)			->   List[str]:



      """simple docstring"""







      a_									=CustomOutput(images=np.random.rand(1				,	3				,	4				,	4))

      # check every way of getting the attribute
      assert isinstance(outputs.images				,	np.ndarray)
      assert outputs.images.shape == (1, 3, 4, 4)
      assert isinstance(outputs["images"]				,	np.ndarray)
      assert outputs["images"].shape == (1, 3, 4, 4)
      assert isinstance(outputs[0]				,	np.ndarray)
      assert outputs[0].shape == (1, 3, 4, 4)

      # test with a non-tensor attribute
      a_									=CustomOutput(images=[PIL.Image.new("RGB"				,	(4, 4))])

      # check every way of getting the attribute
      assert isinstance(outputs.images				,	lowerCAmelCase_)
      assert isinstance(outputs.images[0]				,	PIL.Image.Image)
      assert isinstance(outputs["images"]				,	lowerCAmelCase_)
      assert isinstance(outputs["images"][0]				,	PIL.Image.Image)
      assert isinstance(outputs[0]				,	lowerCAmelCase_)
      assert isinstance(outputs[0][0]				,	PIL.Image.Image)




 def    lowercase_	( self)			->   Optional[int]:



      """simple docstring"""







      a_									=CustomOutput({"images": np.random.rand(1				,	3				,	4				,	4)})

      # check every way of getting the attribute
      assert isinstance(outputs.images				,	np.ndarray)
      assert outputs.images.shape == (1, 3, 4, 4)
      assert isinstance(outputs["images"]				,	np.ndarray)
      assert outputs["images"].shape == (1, 3, 4, 4)
      assert isinstance(outputs[0]				,	np.ndarray)
      assert outputs[0].shape == (1, 3, 4, 4)

      # test with a non-tensor attribute
      a_									=CustomOutput({"images": [PIL.Image.new("RGB"				,	(4, 4))]})

      # check every way of getting the attribute
      assert isinstance(outputs.images				,	lowerCAmelCase_)
      assert isinstance(outputs.images[0]				,	PIL.Image.Image)
      assert isinstance(outputs["images"]				,	lowerCAmelCase_)
      assert isinstance(outputs["images"][0]				,	PIL.Image.Image)
      assert isinstance(outputs[0]				,	lowerCAmelCase_)
      assert isinstance(outputs[0][0]				,	PIL.Image.Image)


