
'''simple docstring'''

import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class 					a_					(_a							,     unittest.TestCase      ):
       __lowerCAmelCase      :			Optional[int]      = KandinskyPriorPipeline
       __lowerCAmelCase      :			Tuple      = ["""prompt"""]
       __lowerCAmelCase      :			str      = ["""prompt""", """negative_prompt"""]
       __lowerCAmelCase      :			str      = [
           """num_images_per_prompt""",
           """generator""",
           """num_inference_steps""",
           """latents""",
           """negative_prompt""",
           """guidance_scale""",
           """output_type""",
           """return_dict""",
       ]
       __lowerCAmelCase      :			int      = False




       @property
       def 							__UpperCamelCase    (       self					):
         return 3_2




       @property
       def 							__UpperCamelCase    (       self					):
         return 3_2




       @property
       def 							__UpperCamelCase    (       self					):
         return self.time_input_dim




       @property
       def 							__UpperCamelCase    (       self					):
         return self.time_input_dim * 4




       @property
       def 							__UpperCamelCase    (       self					):
         return 1_0_0




       @property
       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Union[str, Any]							=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""					)
         return tokenizer




       @property
       def 							__UpperCamelCase    (       self					):
         torch.manual_seed(0					)
         _lowerCAmelCase    :					List[str]							=   CLIPTextConfig(
             bos_token_id=0				,				eos_token_id=2				,				hidden_size=self.text_embedder_hidden_size				,				projection_dim=self.text_embedder_hidden_size				,				intermediate_size=3_7				,				layer_norm_eps=1E-05				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=1_0_0_0				,				)
         return CLIPTextModelWithProjection(snake_case_					)




       @property
       def 							__UpperCamelCase    (       self					):
         torch.manual_seed(0					)

         _lowerCAmelCase    :					List[str]							=   {
             """num_attention_heads""": 2,
             """attention_head_dim""": 1_2,
             """embedding_dim""": self.text_embedder_hidden_size,
             """num_layers""": 1,
         }

         _lowerCAmelCase    :					Optional[int]							=   PriorTransformer(**snake_case_					)
         # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
         _lowerCAmelCase    :					List[str]							=   nn.Parameter(torch.ones(model.clip_std.shape					)					)
         return model




       @property
       def 							__UpperCamelCase    (       self					):
         torch.manual_seed(0					)
         _lowerCAmelCase    :					List[Any]							=   CLIPVisionConfig(
             hidden_size=self.text_embedder_hidden_size				,				image_size=2_2_4				,				projection_dim=self.text_embedder_hidden_size				,				intermediate_size=3_7				,				num_attention_heads=4				,				num_channels=3				,				num_hidden_layers=5				,				patch_size=1_4				,				)

         _lowerCAmelCase    :					Union[str, Any]							=   CLIPVisionModelWithProjection(snake_case_					)
         return model




       @property
       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Tuple							=   CLIPImageProcessor(
             crop_size=2_2_4				,				do_center_crop=snake_case_				,				do_normalize=snake_case_				,				do_resize=snake_case_				,				image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]				,				image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]				,				resample=3				,				size=2_2_4				,				)

         return image_processor




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					str							=   self.dummy_prior
         _lowerCAmelCase    :					Optional[int]							=   self.dummy_image_encoder
         _lowerCAmelCase    :					Optional[int]							=   self.dummy_text_encoder
         _lowerCAmelCase    :					Optional[Any]							=   self.dummy_tokenizer
         _lowerCAmelCase    :					int							=   self.dummy_image_processor

         _lowerCAmelCase    :					Tuple							=   UnCLIPScheduler(
             variance_type="""fixed_small_log"""				,				prediction_type="""sample"""				,				num_train_timesteps=1_0_0_0				,				clip_sample=snake_case_				,				clip_sample_range=10.0				,				)

         _lowerCAmelCase    :					Union[str, Any]							=   {
             """prior""": prior,
             """image_encoder""": image_encoder,
             """text_encoder""": text_encoder,
             """tokenizer""": tokenizer,
             """scheduler""": scheduler,
             """image_processor""": image_processor,
         }

         return components




       def 							__UpperCamelCase    (       self				,				snake_case_				,				snake_case_=0					):
         if str(snake_case_					).startswith("""mps"""					):
           _lowerCAmelCase    :					List[str]							=   torch.manual_seed(snake_case_					)
         else:
           _lowerCAmelCase    :					List[Any]							=   torch.Generator(device=snake_case_					).manual_seed(snake_case_					)
         _lowerCAmelCase    :					str							=   {
             """prompt""": """horse""",
             """generator""": generator,
             """guidance_scale""": 4.0,
             """num_inference_steps""": 2,
             """output_type""": """np""",
         }
         return inputs




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Union[str, Any]							=   """cpu"""

         _lowerCAmelCase    :					Tuple							=   self.get_dummy_components()

         _lowerCAmelCase    :					int							=   self.pipeline_class(**snake_case_					)
         _lowerCAmelCase    :					List[str]							=   pipe.to(snake_case_					)

         pipe.set_progress_bar_config(disable=snake_case_					)

         _lowerCAmelCase    :					Union[str, Any]							=   pipe(**self.get_dummy_inputs(snake_case_					)					)
         _lowerCAmelCase    :					Tuple							=   output.image_embeds

         _lowerCAmelCase    :					List[Any]							=   pipe(
             **self.get_dummy_inputs(snake_case_					)				,				return_dict=snake_case_				,				)[0]

         _lowerCAmelCase    :					Optional[int]							=   image[0, -1_0:]
         _lowerCAmelCase    :					Dict							=   image_from_tuple[0, -1_0:]

         assert image.shape == (1, 3_2)

         _lowerCAmelCase    :					Any							=   np.array(
             [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]					)

         assert np.abs(image_slice.flatten() - expected_slice					).max() < 1E-2
         assert np.abs(image_from_tuple_slice.flatten() - expected_slice					).max() < 1E-2




       @skip_mps
       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Any							=   torch_device == """cpu"""
         _lowerCAmelCase    :					Optional[int]							=   True
         _lowerCAmelCase    :					Dict							=   False

         self._test_inference_batch_single_identical(
             test_max_difference=snake_case_				,				relax_max_difference=snake_case_				,				test_mean_pixel_difference=snake_case_				,				)







       @skip_mps
       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Union[str, Any]							=   torch_device == """cpu"""
         _lowerCAmelCase    :					Any							=   False

         self._test_attention_slicing_forward_pass(
             test_max_difference=snake_case_				,				test_mean_pixel_difference=snake_case_				,				)




'''simple docstring'''

def 		_UpperCAmelCase			(					_lowerCamelCase  :    list[list[int]]					, _lowerCamelCase  :    list[list[int]]						)      ->  list[list[int]]:
  _lowerCAmelCase    :					int							=   []
  _lowerCAmelCase    :					Union[str, Any]							=   len(_lowerCamelCase						)
  for i in range(_lowerCamelCase						):
    _lowerCAmelCase    :					List[str]							=   []
    for j in range(_lowerCamelCase						):
      _lowerCAmelCase    :					Union[str, Any]							=   0
      for k in range(_lowerCamelCase						):
        _lowerCAmelCase    :					Any							=   val + matrix_a[i][k] * matrix_b[k][j]
      list_a.append(_lowerCamelCase						)
    matrix_c.append(_lowerCamelCase						)
  return matrix_c


def 		_UpperCAmelCase			(					_lowerCamelCase  :    int						)      ->  list[list[int]]:
  return [[int(row == column						) for column in range(_lowerCamelCase						)] for row in range(_lowerCamelCase						)]


def 		_UpperCAmelCase			(					_lowerCamelCase  :    int						)      ->  int:
  if n <= 1:
    return n
  _lowerCAmelCase    :					Tuple							=   identity(2						)
  _lowerCAmelCase    :					Union[str, Any]							=   [[1, 1], [1, 0]]
  _lowerCAmelCase    :					Optional[int]							=   n - 1
  while n > 0:
    if n % 2 == 1:
      _lowerCAmelCase    :					str							=   multiply(_lowerCamelCase					, _lowerCamelCase						)
    _lowerCAmelCase    :					Tuple							=   multiply(_lowerCamelCase					, _lowerCamelCase						)
    _lowerCAmelCase    :					Dict							=   int(n / 2						)
  return res_matrix[0][0]


def 		_UpperCAmelCase			(					_lowerCamelCase  :    int						)      ->  int:
  if n <= 1:
    return n
  _lowerCAmelCase    :					Any							=   0
  _lowerCAmelCase    :					Dict							=   1
  for _ in range(2					, n + 1						):
    _lowerCAmelCase			,   _lowerCAmelCase    :					int							=   fiba, fiba + fiba
  return fiba


def 		_UpperCAmelCase			(					)      ->  None:
  for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split():
    _lowerCAmelCase    :					Union[str, Any]							=   int("""""".join(c for c in ordinal if c in """0123456789"""						)						)  # 1000th --> 1000
    print(
        f'{ordinal} fibonacci number using matrix exponentiation is '
        f'{nth_fibonacci_matrix(_lowerCamelCase						)} and using bruteforce is '
        f'{nth_fibonacci_bruteforce(_lowerCamelCase						)}\n'						)
  # from timeit import timeit
  # print(timeit("nth_fibonacci_matrix(1000000)",
  #              "from main import nth_fibonacci_matrix", number=5))
  # print(timeit("nth_fibonacci_bruteforce(1000000)",
  #              "from main import nth_fibonacci_bruteforce", number=5))
  # 2.3342058970001744
  # 57.256506615000035


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     main()


