





import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference







class 	__lowerCAmelCase      (       _UpperCamelCase		,unittest.TestCase	):
   _UpperCamelCase			:    Optional[int]  		=					ShapEPipeline
   _UpperCamelCase			:    List[str]  		=					["""prompt"""]
   _UpperCamelCase			:    Optional[int]  		=					["""prompt"""]
   _UpperCamelCase			:    int  		=					[
       """num_images_per_prompt""",
       """num_inference_steps""",
       """generator""",
       """latents""",
       """guidance_scale""",
       """frame_size""",
       """output_type""",
       """return_dict""",
   ]
   _UpperCamelCase			:    int  		=					False





   @property
   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      return 32





   @property
   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





      return 32





   @property
   def 						_snake_case			(			self   )					->	Optional[Any]:
      """simple docstring"""





      return self.time_input_dim * 4





   @property
   def 						_snake_case			(			self   )					->	int:
      """simple docstring"""





      return 8





   @property
   def 						_snake_case			(			self   )					->	Optional[Any]:
      """simple docstring"""





      a__						:    Dict   		=	CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"   )
      return tokenizer





   @property
   def 						_snake_case			(			self   )					->	Optional[Any]:
      """simple docstring"""





      torch.manual_seed(0   )
      a__						:    Optional[int]   		=	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=37       ,      layer_norm_eps=1E-05       ,      num_attention_heads=4       ,      num_hidden_layers=5       ,      pad_token_id=1       ,      vocab_size=1_000       ,      )
      return CLIPTextModelWithProjection(snake_case   )





   @property
   def 						_snake_case			(			self   )					->	List[str]:
      """simple docstring"""





      torch.manual_seed(0   )

      a__						:    List[str]   		=	{
          "num_attention_heads": 2,
          "attention_head_dim": 16,
          "embedding_dim": self.time_input_dim,
          "num_embeddings": 32,
          "embedding_proj_dim": self.text_embedder_hidden_size,
          "time_embed_dim": self.time_embed_dim,
          "num_layers": 1,
          "clip_embed_dim": self.time_input_dim * 2,
          "additional_embeddings": 0,
          "time_embed_act_fn": "gelu",
          "norm_in_type": "layer",
          "encoder_hid_proj_type": None,
          "added_emb_type": None,
      }

      a__						:    Dict   		=	PriorTransformer(**snake_case   )
      return model





   @property
   def 						_snake_case			(			self   )					->	Optional[int]:
      """simple docstring"""





      torch.manual_seed(0   )

      a__						:    int   		=	{
          "param_shapes": (
              (self.renderer_dim, 93),
              (self.renderer_dim, 8),
              (self.renderer_dim, 8),
              (self.renderer_dim, 8),
          ),
          "d_latent": self.time_input_dim,
          "d_hidden": self.renderer_dim,
          "n_output": 12,
          "background": (
              0.1,
              0.1,
              0.1,
          ),
      }
      a__						:    Any   		=	ShapERenderer(**snake_case   )
      return model





   def 						_snake_case			(			self   )					->	Optional[Any]:
      """simple docstring"""





      a__						:    Optional[int]   		=	self.dummy_prior
      a__						:    Dict   		=	self.dummy_text_encoder
      a__						:    Tuple   		=	self.dummy_tokenizer
      a__						:    Optional[int]   		=	self.dummy_renderer

      a__						:    List[str]   		=	HeunDiscreteScheduler(
          beta_schedule="exp"       ,      num_train_timesteps=1_024       ,      prediction_type="sample"       ,      use_karras_sigmas=snake_case       ,      clip_sample=snake_case       ,      clip_sample_range=1.0       ,      )
      a__						:    Optional[Any]   		=	{
          "prior": prior,
          "text_encoder": text_encoder,
          "tokenizer": tokenizer,
          "renderer": renderer,
          "scheduler": scheduler,
      }

      return components





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case=0   )					->	Dict:
      """simple docstring"""





      if str(snake_case   ).startswith("mps"   ):
         a__						:    Optional[int]   		=	torch.manual_seed(snake_case   )
      else:
         a__						:    int   		=	torch.Generator(device=snake_case   ).manual_seed(snake_case   )
      a__						:    int   		=	{
          "prompt": "horse",
          "generator": generator,
          "num_inference_steps": 1,
          "frame_size": 32,
          "output_type": "np",
      }
      return inputs





   def 						_snake_case			(			self   )					->	Optional[Any]:
      """simple docstring"""





      a__						:    List[Any]   		=	"cpu"

      a__						:    Union[str, Any]   		=	self.get_dummy_components()

      a__						:    List[str]   		=	self.pipeline_class(**snake_case   )
      a__						:    Dict   		=	pipe.to(snake_case   )

      pipe.set_progress_bar_config(disable=snake_case   )

      a__						:    Optional[Any]   		=	pipe(**self.get_dummy_inputs(snake_case   )   )
      a__						:    str   		=	output.images[0]
      a__						:    Tuple   		=	image[0, -3:, -3:, -1]

      assert image.shape == (20, 32, 32, 3)

      a__						:    Union[str, Any]   		=	np.array(
          [
              0.00_039_216,
              0.00_039_216,
              0.00_039_216,
              0.00_039_216,
              0.00_039_216,
              0.00_039_216,
              0.00_039_216,
              0.00_039_216,
              0.00_039_216,
          ]   )

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





   def 						_snake_case			(			self   )					->	Union[str, Any]:
      """simple docstring"""





      self._test_inference_batch_consistent(batch_sizes=[1, 2]   )





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    Dict   		=	torch_device == "cpu"
      a__						:    str   		=	True

      self._test_inference_batch_single_identical(
          batch_size=2       ,      test_max_difference=snake_case       ,      relax_max_difference=snake_case       ,      )





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	self.get_dummy_components()
      a__						:    Tuple   		=	self.pipeline_class(**snake_case   )
      a__						:    Tuple   		=	pipe.to(snake_case   )
      pipe.set_progress_bar_config(disable=snake_case   )

      a__						:    Optional[int]   		=	1
      a__						:    int   		=	2

      a__						:    Dict   		=	self.get_dummy_inputs(snake_case   )

      for key in inputs.keys():
         if key in self.batch_params:
            a__						:    Dict   		=	batch_size * [inputs[key]]

      a__						:    Any   		=	pipe(**snake_case       ,      num_images_per_prompt=snake_case   )[0]

      assert images.shape[0] == batch_size * num_images_per_prompt







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





   def 						_snake_case			(			self   )					->	Optional[Any]:
      """simple docstring"""





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





   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





      a__						:    List[Any]   		=	load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/shap_e/test_shap_e_np_out.npy"   )
      a__						:    Dict   		=	ShapEPipeline.from_pretrained("openai/shap-e"   )
      a__						:    Tuple   		=	pipe.to(snake_case   )
      pipe.set_progress_bar_config(disable=snake_case   )

      a__						:    Optional[int]   		=	torch.Generator(device=snake_case   ).manual_seed(0   )

      a__						:    Dict   		=	pipe(
          "a shark"       ,      generator=snake_case       ,      guidance_scale=15.0       ,      num_inference_steps=64       ,      frame_size=64       ,      output_type="np"       ,      ).images[0]

      assert images.shape == (20, 64, 64, 3)

      assert_mean_pixel_difference(snake_case       ,      snake_case   )








# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


SCREAMING_SNAKE_CASE__							:      List[str]         =    Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(4_2)

SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    {"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

SCREAMING_SNAKE_CASE__							:      Any         =    """zero2"""
SCREAMING_SNAKE_CASE__							:      Dict         =    """zero3"""
SCREAMING_SNAKE_CASE__							:      str         =    [ZEROa, ZEROa]






def    _A	(   lowerCamelCase				,			lowerCamelCase				,			lowerCamelCase ):
   # customize the test name generator function as we want both params to appear in the sub-test
   # name, as by default it shows only the first param
   a__						:    Optional[Any]   		=	parameterized.to_safe_name("_".join(str(lowerCamelCase ) for x in param.args ) )
   return F"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    list(itertools.product(stages, models.keys()))







@slow
@require_deepspeed
@require_torch_gpu
class 	__lowerCAmelCase      (       _UpperCamelCase	):





   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	Dict:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   @require_torch_multi_gpu
   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	str:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	List[str]:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   @require_torch_multi_gpu
   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	List[str]:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   def 						_snake_case			(			self       ,      snake_case   )					->	str:
      """simple docstring"""





      pass





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = 10       ,      snake_case = True       ,      snake_case = True       ,      snake_case = True       ,      )					->	str:
      """simple docstring"""





      a__						:    Tuple   		=	models[model]

      a__						:    int   		=	self.run_trainer(
          stage=snake_case       ,      model_name=snake_case       ,      eval_steps=snake_case       ,      num_train_epochs=1       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )

      self.do_checks(snake_case   )

      return output_dir





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = 10       ,      snake_case = 1       ,      snake_case = True       ,      snake_case = True       ,      )					->	Optional[Any]:
      """simple docstring"""





      a__						:    str   		=	self.get_auto_remove_tmp_dir("./xxx"       ,      after=snake_case   )
      a__						:    List[Any]   		=	F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(snake_case   )}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

      if fpaa:
         args.extend(["--fp16"]   )

      # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
      # hence the separate config files
      a__						:    str   		=	F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
      a__						:    Dict   		=	[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
      a__						:    Optional[int]   		=	self.get_launcher(snake_case   )

      a__						:    Optional[int]   		=	launcher + script + args + ds_args
      # keep for quick debug
      # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
      execute_subprocess_async(snake_case       ,      env=self.get_env()   )

      return output_dir





   def 						_snake_case			(			self       ,      snake_case=False   )					->	List[Any]:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	min(2       ,      get_gpu_count()   ) if distributed else 1
      return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()

