





"""simple docstring"""
import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
       from transformers import (
           FlaxBertModel,
           FlaxCLIPVisionModel,
           FlaxVisionTextDualEncoderModel,
           FlaxViTModel,
           VisionTextDualEncoderConfig,
           VisionTextDualEncoderProcessor,
       )
       from transformers.modeling_flax_pytorch_utils import (
           convert_pytorch_state_dict_to_flax,
           load_flax_weights_in_pytorch_model,
       )


if is_torch_available():
       import torch

       from transformers import VisionTextDualEncoderModel

if is_vision_available():
       from PIL import Image

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    Optional[Any]			):
 if isinstance(_UpperCAmelCase  ,     collections.abc.Iterable			):
  return x
 return (x, x)







@require_flax
class       a							:



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  pass



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  pass



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= np.abs((a - b)     ).max()
  self.assertLessEqual(_snake_case				,       _snake_case				,       F'Difference between torch and flax is {diff} (>= {tol}).'     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case=None				,       **_snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= VisionTextDualEncoderConfig.from_vision_text_configs(_snake_case				,       _snake_case     )

  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel(_snake_case     )

  lowerCAmelCase    				= model(input_ids=_snake_case				,       pixel_values=_snake_case				,       attention_mask=_snake_case     )

  self.assertEqual(output['text_embeds'].shape				,       (input_ids.shape[0], config.projection_dim)     )
  self.assertEqual(output['image_embeds'].shape				,       (pixel_values.shape[0], config.projection_dim)     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case=None				,       **_snake_case     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.get_vision_text_model(_snake_case				,       _snake_case     )
  lowerCAmelCase    				= {'vision_model': vision_model, 'text_model': text_model}
  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_snake_case     )

  lowerCAmelCase    				= model(input_ids=_snake_case				,       pixel_values=_snake_case				,       attention_mask=_snake_case     )

  self.assertEqual(output['text_embeds'].shape				,       (input_ids.shape[0], model.config.projection_dim)     )
  self.assertEqual(output['image_embeds'].shape				,       (pixel_values.shape[0], model.config.projection_dim)     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case=None				,       **_snake_case     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.get_vision_text_model(_snake_case				,       _snake_case     )
  lowerCAmelCase    				= {'vision_model': vision_model, 'text_model': text_model}
  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_snake_case     )

  lowerCAmelCase    				= model(input_ids=_snake_case				,       pixel_values=_snake_case				,       attention_mask=_snake_case     )
  lowerCAmelCase    				= output[0]

  with tempfile.TemporaryDirectory() as tmpdirname:
   model.save_pretrained(_snake_case     )
   lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_pretrained(_snake_case     )

   lowerCAmelCase    				= model(input_ids=_snake_case				,       pixel_values=_snake_case				,       attention_mask=_snake_case     )
   lowerCAmelCase    				= after_output[0]
   lowerCAmelCase    				= np.amax(np.abs(out_a - out_a     )     )
   self.assertLessEqual(_snake_case				,       1E-3     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case=None				,       **_snake_case     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.get_vision_text_model(_snake_case				,       _snake_case     )
  lowerCAmelCase    				= {'vision_model': vision_model, 'text_model': text_model}
  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_snake_case     )

  lowerCAmelCase    				= model(
      input_ids=_snake_case				,       pixel_values=_snake_case				,       attention_mask=_snake_case				,       output_attentions=_snake_case     )

  lowerCAmelCase    				= output.vision_model_output.attentions
  self.assertEqual(len(_snake_case     )				,       vision_config.num_hidden_layers     )

  # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
  lowerCAmelCase    				= to_atuple(vision_model.config.image_size     )
  lowerCAmelCase    				= to_atuple(vision_model.config.patch_size     )
  lowerCAmelCase    				= (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  lowerCAmelCase    				= num_patches + 1
  self.assertEqual(vision_attentions[0].shape[-3:]				,       (vision_config.num_attention_heads, seq_len, seq_len)     )

  lowerCAmelCase    				= output.text_model_output.attentions
  self.assertEqual(len(_snake_case     )				,       text_config.num_hidden_layers     )

  self.assertEqual(
      text_attentions[0].shape[-3:]				,       (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])				,       )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  pt_model.to(_snake_case     )
  pt_model.eval()

  # prepare inputs
  lowerCAmelCase    				= inputs_dict
  lowerCAmelCase    				= {k: torch.tensor(v.tolist()     ) for k, v in flax_inputs.items()}

  with torch.no_grad():
   lowerCAmelCase    				= pt_model(**_snake_case     ).to_tuple()

  lowerCAmelCase    				= fx_model(**_snake_case     ).to_tuple()
  self.assertEqual(len(_snake_case     )				,       len(_snake_case     )				,       'Output lengths differ between Flax and PyTorch'     )
  for fx_output, pt_output in zip(fx_outputs[:4]				,       pt_outputs[:4]     ):
   self.assert_almost_equals(_snake_case				,       pt_output.numpy()				,       4E-2     )

  # PT -> Flax
  with tempfile.TemporaryDirectory() as tmpdirname:
   pt_model.save_pretrained(_snake_case     )
   lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_pretrained(_snake_case				,       from_pt=_snake_case     )

  lowerCAmelCase    				= fx_model_loaded(**_snake_case     ).to_tuple()
  self.assertEqual(len(_snake_case     )				,       len(_snake_case     )				,       'Output lengths differ between Flax and PyTorch'     )
  for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]				,       pt_outputs[:4]     ):
   self.assert_almost_equals(_snake_case				,       pt_output.numpy()				,       4E-2     )

  # Flax -> PT
  with tempfile.TemporaryDirectory() as tmpdirname:
   fx_model.save_pretrained(_snake_case     )
   lowerCAmelCase    				= VisionTextDualEncoderModel.from_pretrained(_snake_case				,       from_flax=_snake_case     )

  pt_model_loaded.to(_snake_case     )
  pt_model_loaded.eval()

  with torch.no_grad():
   lowerCAmelCase    				= pt_model_loaded(**_snake_case     ).to_tuple()

  self.assertEqual(len(_snake_case     )				,       len(_snake_case     )				,       'Output lengths differ between Flax and PyTorch'     )
  for fx_output, pt_output_loaded in zip(fx_outputs[:4]				,       pt_outputs_loaded[:4]     ):
   self.assert_almost_equals(_snake_case				,       pt_output_loaded.numpy()				,       4E-2     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= VisionTextDualEncoderConfig.from_vision_text_configs(_snake_case				,       _snake_case     )

  lowerCAmelCase    				= VisionTextDualEncoderModel(_snake_case     )
  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel(_snake_case     )

  lowerCAmelCase    				= convert_pytorch_state_dict_to_flax(pt_model.state_dict()				,       _snake_case     )
  lowerCAmelCase    				= fx_state

  self.check_pt_flax_equivalence(_snake_case				,       _snake_case				,       _snake_case     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= VisionTextDualEncoderConfig.from_vision_text_configs(_snake_case				,       _snake_case     )

  lowerCAmelCase    				= VisionTextDualEncoderModel(_snake_case     )
  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel(_snake_case     )

  lowerCAmelCase    				= load_flax_weights_in_pytorch_model(_snake_case				,       fx_model.params     )

  self.check_pt_flax_equivalence(_snake_case				,       _snake_case				,       _snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.prepare_config_and_inputs()
  self.check_model_from_pretrained_configs(**_snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.prepare_config_and_inputs()
  self.check_vision_text_dual_encoder_from_pretrained(**_snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.prepare_config_and_inputs()
  self.check_save_load(**_snake_case     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.prepare_config_and_inputs()
  self.check_vision_text_output_attention(**_snake_case     )



 @is_pt_flax_cross_test
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.prepare_config_and_inputs()
  lowerCAmelCase    				= config_inputs_dict.pop('vision_config'     )
  lowerCAmelCase    				= config_inputs_dict.pop('text_config'     )

  lowerCAmelCase    				= config_inputs_dict

  self.check_equivalence_pt_to_flax(_snake_case				,       _snake_case				,       _snake_case     )
  self.check_equivalence_flax_to_pt(_snake_case				,       _snake_case				,       _snake_case     )



 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase				,lowerCAmelCase    				= self.get_pretrained_model_and_inputs()

  lowerCAmelCase    				= model_a(**_snake_case     )
  lowerCAmelCase    				= outputs[0]

  with tempfile.TemporaryDirectory() as tmp_dirname:
   model_a.save_pretrained(_snake_case     )
   lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_pretrained(_snake_case     )

   lowerCAmelCase    				= model_a(**_snake_case     )
   lowerCAmelCase    				= after_outputs[0]
   lowerCAmelCase    				= np.amax(np.abs(out_a - out_a     )     )
   self.assertLessEqual(_snake_case				,       1E-5     )







@require_flax
class       a							(   a__   , unittest.TestCase  ):



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
      'hf-internal-testing/tiny-random-vit'				,       'hf-internal-testing/tiny-bert'				,       vision_from_pt=_snake_case				,       text_from_pt=_snake_case				,       )
  lowerCAmelCase    				= 13
  lowerCAmelCase    				= floats_tensor(
      [
          batch_size,
          model.config.vision_config.num_channels,
          model.config.vision_config.image_size,
          model.config.vision_config.image_size,
      ]     )
  lowerCAmelCase    				= ids_tensor([batch_size, 4]				,       model.config.text_config.vocab_size     )
  lowerCAmelCase    				= random_attention_mask([batch_size, 4]     )
  lowerCAmelCase    				= {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

  return model, inputs



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= FlaxViTModel(_snake_case     )
  lowerCAmelCase    				= FlaxBertModel(_snake_case     )
  return vision_model, text_model



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= FlaxViTModelTester(self     )
  lowerCAmelCase    				= FlaxBertModelTester(self     )
  lowerCAmelCase    				= vit_model_tester.prepare_config_and_inputs()
  lowerCAmelCase    				= bert_model_tester.prepare_config_and_inputs()

  lowerCAmelCase				,lowerCAmelCase    				= vision_config_and_inputs

  lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= text_config_and_inputs

  # make sure that cross attention layers are added
  return {
      "text_config": text_config,
      "vision_config": vision_config,
      "pixel_values": pixel_values,
      "attention_mask": attention_mask,
      "input_ids": input_ids,
      "token_type_ids": token_type_ids,
  }







@require_torch
class       a							(   a__   , unittest.TestCase  ):



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
      'hf-internal-testing/tiny-random-clip'				,       'hf-internal-testing/tiny-bert'				,       vision_from_pt=_snake_case				,       text_from_pt=_snake_case				,       )
  lowerCAmelCase    				= 13
  lowerCAmelCase    				= floats_tensor(
      [
          batch_size,
          model.config.vision_config.num_channels,
          model.config.vision_config.image_size,
          model.config.vision_config.image_size,
      ]     )
  lowerCAmelCase    				= ids_tensor([batch_size, 4]				,       model.config.text_config.vocab_size     )
  lowerCAmelCase    				= random_attention_mask([batch_size, 4]     )
  lowerCAmelCase    				= {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

  return model, inputs



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= FlaxCLIPVisionModel(_snake_case     )
  lowerCAmelCase    				= FlaxBertModel(_snake_case     )
  return vision_model, text_model



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= FlaxCLIPVisionModelTester(self     )
  lowerCAmelCase    				= FlaxBertModelTester(self     )
  lowerCAmelCase    				= clip_model_tester.prepare_config_and_inputs()
  lowerCAmelCase    				= bert_model_tester.prepare_config_and_inputs()

  lowerCAmelCase				,lowerCAmelCase    				= vision_config_and_inputs

  lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= text_config_and_inputs

  # make sure that cross attention layers are added
  return {
      "text_config": text_config,
      "vision_config": vision_config,
      "pixel_values": pixel_values,
      "attention_mask": attention_mask,
      "input_ids": input_ids,
      "token_type_ids": token_type_ids,
  }







@require_flax
@require_vision
class       a							(   unittest.TestCase  ):



 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'				,       logit_scale_init_value=1.0     )
  lowerCAmelCase    				= VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'     )

  lowerCAmelCase    				= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
  lowerCAmelCase    				= processor(
      text=['una foto di un gatto', 'una foto di un cane']				,       images=_snake_case				,       padding=_snake_case				,       return_tensors='np'     )

  lowerCAmelCase    				= model(**_snake_case     )

  # verify the logits
  self.assertEqual(outputs.logits_per_image.shape				,       (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])     )
  self.assertEqual(
      outputs.logits_per_text.shape				,       (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])				,       )

  lowerCAmelCase    				= np.array([[1.2_284_727, 0.3_104_122]]     )

  self.assertTrue(np.allclose(outputs.logits_per_image				,       _snake_case				,       atol=1E-3     )     )












"""simple docstring"""
import gc
import unittest

import numpy as np
import torch

from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class       a							(   a__   , unittest.TestCase  ):
 snake_case__             =       DanceDiffusionPipeline
 snake_case__             =       UNCONDITIONAL_AUDIO_GENERATION_PARAMS
 snake_case__             =       PipelineTesterMixin.required_optional_params - {
     '''callback''',
     '''latents''',
     '''callback_steps''',
     '''output_type''',
     '''num_images_per_prompt''',
 }
 snake_case__             =       UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
 snake_case__             =       False
 snake_case__             =       False



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  torch.manual_seed(0     )
  lowerCAmelCase    				= UNetaDModel(
      block_out_channels=(32, 32, 64)				,       extra_in_channels=16				,       sample_size=5_12				,       sample_rate=1_60_00				,       in_channels=2				,       out_channels=2				,       flip_sin_to_cos=_snake_case				,       use_timestep_embedding=_snake_case				,       time_embedding_type='fourier'				,       mid_block_type='UNetMidBlock1D'				,       down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D')				,       up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip')				,       )
  lowerCAmelCase    				= IPNDMScheduler()

  lowerCAmelCase    				= {
      'unet': unet,
      'scheduler': scheduler,
  }
  return components



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=0     ):







  """simple docstring"""






  if str(_snake_case     ).startswith('mps'     ):
   lowerCAmelCase    				= torch.manual_seed(_snake_case     )
  else:
   lowerCAmelCase    				= torch.Generator(device=_snake_case     ).manual_seed(_snake_case     )
  lowerCAmelCase    				= {
      'batch_size': 1,
      'generator': generator,
      'num_inference_steps': 4,
  }
  return inputs



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= 'cpu'  # ensure determinism for the device-dependent torch.Generator
  lowerCAmelCase    				= self.get_dummy_components()
  lowerCAmelCase    				= DanceDiffusionPipeline(**_snake_case     )
  lowerCAmelCase    				= pipe.to(_snake_case     )
  pipe.set_progress_bar_config(disable=_snake_case     )

  lowerCAmelCase    				= self.get_dummy_inputs(_snake_case     )
  lowerCAmelCase    				= pipe(**_snake_case     )
  lowerCAmelCase    				= output.audios

  lowerCAmelCase    				= audio[0, -3:, -3:]

  assert audio.shape == (1, 2, components["unet"].sample_size)
  lowerCAmelCase    				= np.array([-0.7_265, 1.0_000, -0.8_388, 0.1_175, 0.9_498, -1.0_000]     )
  assert np.abs(audio_slice.flatten() - expected_slice     ).max() < 1E-2



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_save_load_local()



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3     )



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_save_load_optional_components()



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_attention_slicing_forward_pass()



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  super().test_inference_batch_single_identical(expected_max_diff=3E-3     )







@slow
@require_torch_gpu
class       a							(   unittest.TestCase  ):



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  super().tearDown()
  gc.collect()
  torch.cuda.empty_cache()



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= torch_device

  lowerCAmelCase    				= DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'     )
  lowerCAmelCase    				= pipe.to(_snake_case     )
  pipe.set_progress_bar_config(disable=_snake_case     )

  lowerCAmelCase    				= torch.manual_seed(0     )
  lowerCAmelCase    				= pipe(generator=_snake_case				,       num_inference_steps=1_00				,       audio_length_in_s=4.096     )
  lowerCAmelCase    				= output.audios

  lowerCAmelCase    				= audio[0, -3:, -3:]

  assert audio.shape == (1, 2, pipe.unet.sample_size)
  lowerCAmelCase    				= np.array([-0.0_192, -0.0_231, -0.0_318, -0.0_059, 0.0_002, -0.0_020]     )

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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= torch_device

  lowerCAmelCase    				= DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'				,       torch_dtype=torch.floataa     )
  lowerCAmelCase    				= pipe.to(_snake_case     )
  pipe.set_progress_bar_config(disable=_snake_case     )

  lowerCAmelCase    				= torch.manual_seed(0     )
  lowerCAmelCase    				= pipe(generator=_snake_case				,       num_inference_steps=1_00				,       audio_length_in_s=4.096     )
  lowerCAmelCase    				= output.audios

  lowerCAmelCase    				= audio[0, -3:, -3:]

  assert audio.shape == (1, 2, pipe.unet.sample_size)
  lowerCAmelCase    				= np.array([-0.0_367, -0.0_488, -0.0_771, -0.0_525, -0.0_444, -0.0_341]     )

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





