
'''simple docstring'''
import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


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

    from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor







class  __A				( unittest.TestCase			):
 def __init__(   self			:    Optional[Any]				,   lowerCamelCase			:    int				,   lowerCamelCase			:    List[Any]=3				,   lowerCamelCase			:    Tuple=32				,   lowerCamelCase			:    Optional[Any]=3				,   lowerCamelCase			:    Optional[Any]=10				,   lowerCamelCase			:    Optional[Any]=[10, 20, 30, 40]				,   lowerCamelCase			:    Tuple=[1, 1, 2, 1]				,   lowerCamelCase			:    List[str]=True				,   lowerCamelCase			:    Any=True				,   lowerCamelCase			:    Any="relu"				,   lowerCamelCase			:    str=3				,   lowerCamelCase			:    List[Any]=None				,   ):



   """simple docstring"""





   __A		:     List[Any]												=		parent
   __A		:     Optional[int]												=		batch_size
   __A		:     Tuple												=		image_size
   __A		:     Optional[Any]												=		num_channels
   __A		:     List[str]												=		embeddings_size
   __A		:     Dict												=		hidden_sizes
   __A		:     Union[str, Any]												=		depths
   __A		:     Any												=		is_training
   __A		:     Optional[Any]												=		use_labels
   __A		:     Optional[int]												=		hidden_act
   __A		:     List[Any]												=		num_labels
   __A		:     Optional[int]												=		scope
   __A		:     Union[str, Any]												=		len(lowercase_       )
 def 		lowercase_(   self			:    Optional[int]       ):



   """simple docstring"""





   __A		:     List[Any]												=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

   __A		:     List[str]												=		self.get_config()

   return config, pixel_values
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   return RegNetConfig(
       num_channels=self.num_channels				,   embeddings_size=self.embeddings_size				,   hidden_sizes=self.hidden_sizes				,   depths=self.depths				,   hidden_act=self.hidden_act				,   num_labels=self.num_labels				,   image_size=self.image_size				,   )
 def 		lowercase_(   self			:    List[str]				,   lowerCamelCase			:    Union[str, Any]				,   lowerCamelCase			:    str       ):



   """simple docstring"""





   __A		:     List[str]												=		FlaxRegNetModel(config=lowercase_       )
   __A		:     Dict												=		model(lowercase_       )

   # Output shape (b, c, h, w)
   self.parent.assertEqual(
       result.last_hidden_state.shape				,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,   )
 def 		lowercase_(   self			:    int				,   lowerCamelCase			:    Any				,   lowerCamelCase			:    List[Any]       ):



   """simple docstring"""





   __A		:     Union[str, Any]												=		self.num_labels
   __A		:     Dict												=		FlaxRegNetForImageClassification(config=lowercase_       )
   __A		:     Tuple												=		model(lowercase_       )
   self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_labels)       )






 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   __A		:     Any												=		self.prepare_config_and_inputs()
   __A		:     str												=		config_and_inputs
   __A		:     Union[str, Any]												=		{"pixel_values": pixel_values}
   return config, inputs_dict







@require_flax
class  __A				( snake_case__    ,						unittest.TestCase			):
 lowerCamelCase				       =(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 def 		lowercase_(   self			:    int       ):



   """simple docstring"""





   __A		:     Union[str, Any]												=		FlaxRegNetModelTester(self       )
   __A		:     List[Any]												=		ConfigTester(self				,   config_class=lowercase_				,   has_text_modality=lowercase_       )
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   self.create_and_test_config_common_properties()
   self.config_tester.create_and_test_config_to_json_string()
   self.config_tester.create_and_test_config_to_json_file()
   self.config_tester.create_and_test_config_from_and_save_pretrained()
   self.config_tester.create_and_test_config_with_num_labels()
   self.config_tester.check_config_can_be_init_without_params()
   self.config_tester.check_config_arguments_init()
 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   return
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   __A		:     str												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowercase_       )
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   __A		:     Tuple												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*lowercase_       )
 @unittest.skip(reason="""RegNet does not use inputs_embeds"""       )
 def 		lowercase_(   self			:    Optional[int]       ):



   """simple docstring"""





   pass
 @unittest.skip(reason="""RegNet does not support input and output embeddings"""       )
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   pass
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   __A		:     Optional[Any]												=		self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     __A		:     Dict												=		model_class(lowercase_       )
     __A		:     str												=		inspect.signature(model.__call__       )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     __A		:     str												=		[*signature.parameters.keys()]

     __A		:     int												=		["pixel_values"]
     self.assertListEqual(arg_names[:1]				,   lowercase_       )
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   def check_hidden_states_output(lowerCamelCase			:    Tuple				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    Optional[int]       ):
     __A		:     Tuple												=		model_class(lowercase_       )

     __A		:     Optional[int]												=		model(**self._prepare_for_class(lowercase_				,   lowercase_       )       )

     __A		:     Optional[Any]												=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     __A		:     Union[str, Any]												=		self.model_tester.num_stages
     self.assertEqual(len(lowercase_       )				,   expected_num_stages + 1       )

   __A		:     Dict												=		self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     __A		:     int												=		True
     check_hidden_states_output(lowercase_				,   lowercase_				,   lowercase_       )

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __A		:     str												=		True

     check_hidden_states_output(lowercase_				,   lowercase_				,   lowercase_       )






 def 		lowercase_(   self			:    Optional[int]       ):



   """simple docstring"""





   __A		:     Tuple												=		self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     with self.subTest(model_class.__name__       ):
       __A		:     Union[str, Any]												=		self._prepare_for_class(lowercase_				,   lowercase_       )
       __A		:     str												=		model_class(lowercase_       )

       @jax.jit
       def model_jitted(lowerCamelCase			:    Optional[Any]				,   **lowerCamelCase			:    Tuple       ):
         return model(pixel_values=lowercase_				,   **lowercase_       )

       with self.subTest("""JIT Enabled"""       ):
         __A		:     Optional[Any]												=		model_jitted(**lowercase_       ).to_tuple()

       with self.subTest("""JIT Disabled"""       ):
         with jax.disable_jit():
           __A		:     Union[str, Any]												=		model_jitted(**lowercase_       ).to_tuple()

       self.assertEqual(len(lowercase_       )				,   len(lowercase_       )       )
       for jitted_output, output in zip(lowercase_				,   lowercase_       ):
         self.assertEqual(jitted_output.shape				,   output.shape       )







def        A_     (						)				->       Optional[int]:





  """simple docstring"""

  __A		:     List[Any]												=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
  return image







@require_flax
class  __A				( unittest.TestCase			):
 @cached_property
 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040"""       ) if is_vision_available() else None






 @slow
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   __A		:     Optional[int]												=		FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040"""       )

   __A		:     Optional[Any]												=		self.default_image_processor
   __A		:     Optional[Any]												=		prepare_img()
   __A		:     str												=		image_processor(images=lowercase_				,   return_tensors="""np"""       )

   __A		:     Tuple												=		model(**lowercase_       )

   # verify the logits
   __A		:     List[str]												=		(1, 10_00)
   self.assertEqual(outputs.logits.shape				,   lowercase_       )

   __A		:     int												=		jnp.array([-0.4_180, -1.5_051, -3.4_836]       )

   self.assertTrue(jnp.allclose(outputs.logits[0, :3]				,   lowercase_				,   atol=1e-4       )       )





'''simple docstring'''
def        A_     (						__SCREAMING_SNAKE_CASE						:  int )				->       None:





  """simple docstring"""

  __A		:     Tuple												=		generate_pascal_triangle(__SCREAMING_SNAKE_CASE )
  for row_idx in range(__SCREAMING_SNAKE_CASE ):
    # Print left spaces
    for _ in range(num_rows - row_idx - 1 ):
      print(end=""" """ )
    # Print row values
    for col_idx in range(row_idx + 1 ):
      if col_idx != row_idx:
        print(triangle[row_idx][col_idx]			,     end=""" """ )
      else:
        print(triangle[row_idx][col_idx]			,     end="""""" )
    print()







def        A_     (						__SCREAMING_SNAKE_CASE						:  int )				->       list[list[int]]:





  """simple docstring"""

  if not isinstance(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE ):
    raise TypeError("""The input value of 'num_rows' should be 'int'""" )

  if num_rows == 0:
    return []
  elif num_rows < 0:
    raise ValueError(
        """The input value of 'num_rows' should be greater than or equal to 0""" )

  __A		:     list[list[int]]												=		[]
  for current_row_idx in range(__SCREAMING_SNAKE_CASE ):
    __A		:     Tuple												=		populate_current_row(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE )
    triangle.append(__SCREAMING_SNAKE_CASE )
  return triangle







def        A_     (						__SCREAMING_SNAKE_CASE						:  list[list[int]]			,     __SCREAMING_SNAKE_CASE						:  int )				->       list[int]:





  """simple docstring"""

  __A		:     Union[str, Any]												=		[-1] * (current_row_idx + 1)
  # first and last elements of current row are equal to 1
  __A							,					__A		:     Tuple												=		1, 1
  for current_col_idx in range(1			,     __SCREAMING_SNAKE_CASE ):
    calculate_current_element(
        __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE )
  return current_row







def        A_     (						__SCREAMING_SNAKE_CASE						:  list[list[int]]			,     __SCREAMING_SNAKE_CASE						:  list[int]			,     __SCREAMING_SNAKE_CASE						:  int			,     __SCREAMING_SNAKE_CASE						:  int			,     )				->       None:





  """simple docstring"""

  __A		:     str												=		triangle[current_row_idx - 1][current_col_idx - 1]
  __A		:     Union[str, Any]												=		triangle[current_row_idx - 1][current_col_idx]
  __A		:     Any												=		above_to_left_elt + above_to_right_elt







def        A_     (						__SCREAMING_SNAKE_CASE						:  int )				->       list[list[int]]:





  """simple docstring"""

  if not isinstance(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE ):
    raise TypeError("""The input value of 'num_rows' should be 'int'""" )

  if num_rows == 0:
    return []
  elif num_rows < 0:
    raise ValueError(
        """The input value of 'num_rows' should be greater than or equal to 0""" )

  __A		:     list[list[int]]												=		[[1]]

  for row_index in range(1			,     __SCREAMING_SNAKE_CASE ):
    __A		:     Optional[Any]												=		[0] + result[-1] + [0]
    __A		:     Optional[Any]												=		row_index + 1
    # Calculate the number of distinct elements in a row
    __A		:     int												=		sum(divmod(__SCREAMING_SNAKE_CASE			,     2 ) )
    __A		:     str												=		[
        temp_row[i - 1] + temp_row[i] for i in range(1			,     distinct_elements + 1 )
    ]
    __A		:     Tuple												=		row_first_half[: (row_index + 1) // 2]
    row_second_half.reverse()
    __A		:     Any												=		row_first_half + row_second_half
    result.append(__SCREAMING_SNAKE_CASE )

  return result







def        A_     (						)				->       None:





  """simple docstring"""

  from collections.abc import Callable
  from timeit import timeit

  def benchmark_a_function(__SCREAMING_SNAKE_CASE						:  Callable			,     __SCREAMING_SNAKE_CASE						:  int ) -> None:
    __A		:     List[Any]												=		F"{func.__name__}({value})"
    __A		:     Dict												=		timeit(F"__main__.{call}"			,     setup="""import __main__""" )
    # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
    print(F"{call:38} -- {timing:.4f} seconds" )

  for value in range(15 ):  # (1, 7, 14):
    for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
      benchmark_a_function(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE )
    print()


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     benchmark()



