

"""simple docstring"""


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__   (				SCREAMING_SNAKE_CASE     ,   unittest.TestCase    ):



    '''simple docstring'''




    _lowerCamelCase					=   ShapEPipeline
    _lowerCamelCase					=   ['''prompt''']
    _lowerCamelCase					=   ['''prompt''']
    _lowerCamelCase					=   [
        '''num_images_per_prompt''',
        '''num_inference_steps''',
        '''generator''',
        '''latents''',
        '''guidance_scale''',
        '''frame_size''',
        '''output_type''',
        '''return_dict''',
    ]
    _lowerCamelCase					=   False




    @property
    def UpperCamelCase__		( self    )    ->      List[str]:
          return 3_2




    @property
    def UpperCamelCase__		( self    )    ->      Any:
          return 3_2




    @property
    def UpperCamelCase__		( self    )    ->      Optional[int]:
          return self.time_input_dim * 4




    @property
    def UpperCamelCase__		( self    )    ->      Any:
          return 8




    @property
    def UpperCamelCase__		( self    )    ->      List[Any]:
          A				  =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )
          return tokenizer




    @property
    def UpperCamelCase__		( self    )    ->      Union[str, Any]:
          torch.manual_seed(0    )
          A				  =		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(lowerCamelCase_    )




    @property
    def UpperCamelCase__		( self    )    ->      List[str]:
          torch.manual_seed(0    )

          A				  =		{
              """num_attention_heads""": 2,
              """attention_head_dim""": 1_6,
              """embedding_dim""": self.time_input_dim,
              """num_embeddings""": 3_2,
              """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				  =		PriorTransformer(**lowerCamelCase_    )
          return model




    @property
    def UpperCamelCase__		( self    )    ->      Tuple:
          torch.manual_seed(0    )

          A				  =		{
              """param_shapes""": (
                  (self.renderer_dim, 9_3),
                  (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""": 1_2,
              """background""": (
                  0.1,
                  0.1,
                  0.1,
              ),
          }
          A				  =		ShapERenderer(**lowerCamelCase_    )
          return model




    def UpperCamelCase__		( self    )    ->      Optional[Any]:
          A				  =		self.dummy_prior
          A				  =		self.dummy_text_encoder
          A				  =		self.dummy_tokenizer
          A				  =		self.dummy_renderer

          A				  =		HeunDiscreteScheduler(
              beta_schedule="""exp""" ,num_train_timesteps=1_0_2_4 ,prediction_type="""sample""" ,use_karras_sigmas=lowerCamelCase_ ,clip_sample=lowerCamelCase_ ,clip_sample_range=1.0 ,)
          A				  =		{
              """prior""": prior,
              """text_encoder""": text_encoder,
              """tokenizer""": tokenizer,
              """renderer""": renderer,
              """scheduler""": scheduler,
          }

          return components




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_=0    )    ->      Union[str, Any]:
          if str(lowerCamelCase_    ).startswith("""mps"""    ):
                A				  =		torch.manual_seed(lowerCamelCase_    )
          else:
                A				  =		torch.Generator(device=lowerCamelCase_    ).manual_seed(lowerCamelCase_    )
          A				  =		{
              """prompt""": """horse""",
              """generator""": generator,
              """num_inference_steps""": 1,
              """frame_size""": 3_2,
              """output_type""": """np""",
          }
          return inputs




    def UpperCamelCase__		( self    )    ->      int:
          A				  =		"""cpu"""

          A				  =		self.get_dummy_components()

          A				  =		self.pipeline_class(**lowerCamelCase_    )
          A				  =		pipe.to(lowerCamelCase_    )

          pipe.set_progress_bar_config(disable=lowerCamelCase_    )

          A				  =		pipe(**self.get_dummy_inputs(lowerCamelCase_    )    )
          A				  =		output.images[0]
          A				  =		image[0, -3:, -3:, -1]

          assert image.shape == (2_0, 3_2, 3_2, 3)

          A				  =		np.array(
              [
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
              ]    )

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




    def UpperCamelCase__		( self    )    ->      List[str]:
          # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
          self._test_inference_batch_consistent(batch_sizes=[1, 2]    )




    def UpperCamelCase__		( self    )    ->      Optional[int]:
          A				  =		torch_device == """cpu"""
          A				  =		True

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




    def UpperCamelCase__		( self    )    ->      List[str]:
          A				  =		self.get_dummy_components()
          A				  =		self.pipeline_class(**lowerCamelCase_    )
          A				  =		pipe.to(lowerCamelCase_    )
          pipe.set_progress_bar_config(disable=lowerCamelCase_    )

          A				  =		1
          A				  =		2

          A				  =		self.get_dummy_inputs(lowerCamelCase_    )

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

          A				  =		pipe(**lowerCamelCase_ ,num_images_per_prompt=lowerCamelCase_    )[0]

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





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



    '''simple docstring'''




    def UpperCamelCase__		( self    )    ->      Dict:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()




    def UpperCamelCase__		( self    )    ->      Any:
          A				  =		load_numpy(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
              """/shap_e/test_shap_e_np_out.npy"""    )
          A				  =		ShapEPipeline.from_pretrained("""openai/shap-e"""    )
          A				  =		pipe.to(lowerCamelCase_    )
          pipe.set_progress_bar_config(disable=lowerCamelCase_    )

          A				  =		torch.Generator(device=lowerCamelCase_    ).manual_seed(0    )

          A				  =		pipe(
              """a shark""" ,generator=lowerCamelCase_ ,guidance_scale=15.0 ,num_inference_steps=6_4 ,frame_size=6_4 ,output_type="""np""" ,).images[0]

          assert images.shape == (2_0, 6_4, 6_4, 3)

          assert_mean_pixel_difference(lowerCamelCase_ ,lowerCamelCase_    )







"""simple docstring"""


import argparse
import json
import os

import tensorstore as ts
import torch
from flax import serialization
from flax.traverse_util import flatten_dict, unflatten_dict
from tensorflow.io import gfile

from transformers.modeling_utils import dtype_byte_size
from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import (
    rename_keys,
)
from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
from transformers.utils.hub import convert_file_size_to_int



def   _A					(	_a	:						Optional[Any]     ,   _a	:						Optional[Any]				):



      """simple docstring"""






      if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3:
            # expert layer
            A				  =		flax_key_tuple[:-1] + ("""weight""",)
            A				  =		torch.permute(_a     ,   (0, 2, 1)				)
      elif flax_key_tuple[-1] == "kernel" and ".".join(_a				):
            # linear layer
            A				  =		flax_key_tuple[:-1] + ("""weight""",)
            A				  =		flax_tensor.T
      elif flax_key_tuple[-1] in ["scale", "embedding"]:
            A				  =		flax_key_tuple[:-1] + ("""weight""",)

      return flax_key_tuple, flax_tensor



def   _A					(	_a	:						Tuple     ,   _a	:						Any     ,   _a	:						Any				):



      """simple docstring"""






      if "metadata" in layer:
            A				  =		layer.split("""metadata"""				)
            A				  =		"""""".join(split_layer[0]				)[:-1]
            A				  =		[tuple(("""metadata""" + split_layer[1]).split("""/"""				)				)]
      elif "kvstore" in layer:
            A				  =		layer.split("""kvstore"""				)
            A				  =		"""""".join(split_layer[0]				)[:-1]
            A				  =		[tuple(("""kvstore""" + split_layer[1]).split("""/"""				)				)]

      else:
            A				  =		layer.split("""/"""				)
            A				  =		"""/""".join(split_layer[:-1]				)
            A				  =		(split_layer[-1],)

      if "kvstore/path" in layer:
            A				  =		f'{switch_checkpoint_path}/{checkpoint_info[layer]}'
      elif "kvstore/driver" in layer:
            A				  =		"""file"""
      else:
            A				  =		checkpoint_info[layer]

      return curr_real_layer_name, split_layer, content



def   _A					(	_a	:						Optional[Any]     ,   _a	:						Optional[int]				):



      """simple docstring"""






      A				  =		rename_keys(_a				)
      A				  =		{}
      for k, v in current_block.items():
            A				  =		v
      A				  =		new_current_block
      torch.save(_a     ,   _a				)



def   _A					(	_a	:						str     ,   _a	:						Optional[Any]     ,   _a	:						int     ,   _a	:						Optional[int]     ,   _a	:						str = WEIGHTS_NAME				):



      """simple docstring"""






      A				  =		convert_file_size_to_int(_a				)
      A				  =		[]
      A				  =		{}
      A				  =		0
      A				  =		0

      os.makedirs(_a     ,   exist_ok=_a				)
      with gfile.GFile(switch_checkpoint_path + """/checkpoint"""     ,   """rb"""				) as fp:
            A				  =		serialization.msgpack_restore(fp.read()				)["""optimizer"""]["""target"""]
            A				  =		flatten_dict(_a     ,   sep="""/"""				)

      A				  =		{}
      for layer in checkpoint_info.keys():
            A  ,			A  ,			A				  =		get_key_and_tensorstore_dict(
                _a     ,   _a     ,   _a				)
            if curr_real_layer_name in all_layers:
                  A				  =		content
            else:
                  A				  =		{split_layer[-1]: content}

      for key in all_layers.keys():
            # open tensorstore file
            A				  =		ts.open(unflatten_dict(all_layers[key]				)				).result().read().result()
            A				  =		torch.tensor(_a				)
            A				  =		raw_weights.numel() * dtype_byte_size(raw_weights.dtype				)

            # use the renaming pattern from the small conversion scripts
            A  ,			A				  =		rename_base_flax_keys(tuple(key.split("""/"""				)				)     ,   _a				)
            A				  =		"""/""".join(_a				)

            # If this weight is going to tip up over the maximal size, we split.
            if current_block_size + weight_size > max_shard_size:
                  A				  =		os.path.join(
                      _a     ,   weights_name.replace(""".bin"""     ,   f'-{len(_a				)+1:05d}-of-???.bin'				)				)
                  rename_and_save_block(_a     ,   _a				)
                  sharded_state_dicts.append(current_block.keys()				)
                  del current_block
                  A				  =		{}
                  A				  =		0

            A				  =		raw_weights.to(getattr(_a     ,   _a				)				)
            current_block_size += weight_size
            total_size += weight_size

      # Add the last block
      A				  =		os.path.join(_a     ,   weights_name.replace(""".bin"""     ,   f'-{len(_a				)+1:05d}-of-???.bin'				)				)
      rename_and_save_block(_a     ,   _a				)
      sharded_state_dicts.append(current_block.keys()				)

      # If we only have one shard, we return it
      if len(_a				) == 1:
            return {weights_name: sharded_state_dicts[0]}, None

      # Otherwise, let's build the index
      A				  =		{}
      A				  =		{}
      for idx, shard in enumerate(_a				):
            A				  =		weights_name.replace(
                """.bin"""     ,   f'-{idx+1:05d}-of-{len(_a				):05d}.bin'				)  # len(sharded_state_dicts):05d}
            A				  =		os.path.join(_a     ,   weights_name.replace(""".bin"""     ,   f'-{idx+1:05d}-of-???.bin'				)				)
            os.rename(_a     ,   os.path.join(_a     ,   _a				)				)
            A				  =		shard
            for key in shard:
                  A				  =		shard_file

    # Add the metadata
      A				  =		{"""total_size""": total_size}
      A				  =		{"""metadata""": metadata, """weight_map""": weight_map}

      with open(os.path.join(_a     ,   _a				)     ,   """w"""     ,   encoding="""utf-8"""				) as f:
            A				  =		json.dumps(_a     ,   indent=2     ,   sort_keys=_a				) + """\n"""
            f.write(_a				)

      return metadata, index


if __name__ == "__main__":
  UpperCAmelCase													=argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      "--switch_t5x_checkpoint_path",
      default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600",
      type=str,
      required=False,
      help="Path to a directory containing a folder per layer. Follows the original Google format.",
  )
  parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size")
  parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model")
  parser.add_argument(
      "--pytorch_dump_folder_path",
      default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted",
      type=str,
      required=False,
      help="Path to the output pytorch model.",
  )
  UpperCAmelCase													=parser.parse_args()
  shard_on_the_fly(
      args.switch_tax_checkpoint_path,
      args.pytorch_dump_folder_path,
      args.max_shard_size,
      args.dtype,
  )





def   _A					(	):



      """simple docstring"""






      from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer

      A				  =		SwitchTransformersConfig.from_pretrained("""google/switch-base-8"""				)
      config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted"""				)
      A				  =		SwitchTransformersForConditionalGeneration.from_pretrained(
          """/home/arthur_huggingface_co/transformers/switch_converted"""     ,   device_map="""auto"""				)

      A				  =		TaTokenizer.from_pretrained("""t5-small"""				)
      A				  =		"""A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>."""

      A				  =		tokenizer(_a     ,   return_tensors="""pt"""				).input_ids
      A				  =		model.generate(_a     ,   decoder_start_token_id=0				)
      print(tokenizer.decode(out[0]				)				)




