

"""simple docstring"""


import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import (
      MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
      TimesformerForVideoClassification,
      TimesformerModel,
  )
  from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from transformers import VideoMAEImageProcessor





class lowerCamelCase__   :



    '''simple docstring'''




    def __init__( self ,lowerCamelCase_ ,lowerCamelCase_=1_3 ,lowerCamelCase_=1_0 ,lowerCamelCase_=3 ,lowerCamelCase_=2 ,lowerCamelCase_=2 ,lowerCamelCase_=True ,lowerCamelCase_=True ,lowerCamelCase_=3_2 ,lowerCamelCase_=5 ,lowerCamelCase_=4 ,lowerCamelCase_=3_7 ,lowerCamelCase_="gelu" ,lowerCamelCase_=0.1 ,lowerCamelCase_=0.1 ,lowerCamelCase_=1_0 ,lowerCamelCase_=0.02 ,lowerCamelCase_="divided_space_time" ,lowerCamelCase_=None ,)    ->      Dict:
          A				  =		parent
          A				  =		batch_size
          A				  =		image_size
          A				  =		num_channels
          A				  =		patch_size
          A				  =		num_frames
          A				  =		is_training
          A				  =		use_labels
          A				  =		hidden_size
          A				  =		num_hidden_layers
          A				  =		num_attention_heads
          A				  =		intermediate_size
          A				  =		hidden_act
          A				  =		hidden_dropout_prob
          A				  =		attention_probs_dropout_prob
          A				  =		attention_type
          A				  =		initializer_range
          A				  =		scope
          A				  =		num_labels

          # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
          A				  =		(image_size // patch_size) ** 2
          A				  =		(num_frames) * self.num_patches_per_frame + 1




    def UpperCamelCase__		( self    )    ->      Any:
          A				  =		floats_tensor(
              [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]    )

          A				  =		None
          if self.use_labels:
                A				  =		ids_tensor([self.batch_size] ,self.num_labels    )

          A				  =		self.get_config()

          return config, pixel_values, labels




    def UpperCamelCase__		( self    )    ->      Union[str, Any]:
          A				  =		TimesformerConfig(
              image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,num_frames=self.num_frames ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,initializer_range=self.initializer_range ,attention_type=self.attention_type ,)
          A				  =		self.num_labels
          return config




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_    )    ->      Optional[int]:
          A				  =		TimesformerModel(config=lowerCamelCase_    )
          model.to(lowerCamelCase_    )
          model.eval()
          A				  =		model(lowerCamelCase_    )
          self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)    )




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_    )    ->      List[Any]:
          A				  =		TimesformerForVideoClassification(lowerCamelCase_    )
          model.to(lowerCamelCase_    )
          model.eval()

          A				  =		model(lowerCamelCase_    )

          # verify the logits shape
          A				  =		torch.Size((self.batch_size, self.num_labels)    )
          self.parent.assertEqual(result.logits.shape ,lowerCamelCase_    )




    def UpperCamelCase__		( self    )    ->      Tuple:
          A				  =		self.prepare_config_and_inputs()
          A  ,			A  ,			A				  =		config_and_inputs
          A				  =		{"""pixel_values""": pixel_values}
          return config, inputs_dict





@require_torch
class lowerCamelCase__   (				SCREAMING_SNAKE_CASE     ,   SCREAMING_SNAKE_CASE     ,   unittest.TestCase    ):



    '''simple docstring'''




    _lowerCamelCase					=   (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
    _lowerCamelCase					=   (
        {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification}
        if is_torch_available()
        else {}
    )

    _lowerCamelCase					=   False
    _lowerCamelCase					=   False
    _lowerCamelCase					=   False
    _lowerCamelCase					=   False




    def UpperCamelCase__		( self    )    ->      Tuple:
          A				  =		TimesformerModelTester(self    )
          A				  =		ConfigTester(
              self ,config_class=lowerCamelCase_ ,has_text_modality=lowerCamelCase_ ,hidden_size=3_7    )




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_=False    )    ->      Dict:
          A				  =		copy.deepcopy(lowerCamelCase_    )

          if return_labels:
                if model_class in get_values(lowerCamelCase_    ):
                      A				  =		torch.zeros(
                          self.model_tester.batch_size ,dtype=torch.long ,device=lowerCamelCase_    )

          return inputs_dict




    def UpperCamelCase__		( self    )    ->      Optional[int]:
          self.config_tester.run_common_tests()




    @unittest.skip(reason="""TimeSformer does not use inputs_embeds"""    )
    def UpperCamelCase__		( self    )    ->      Union[str, Any]:
          pass




    def UpperCamelCase__		( self    )    ->      Any:
          A  ,			A				  =		self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                A				  =		model_class(lowerCamelCase_    )
                self.assertIsInstance(model.get_input_embeddings() ,(nn.Module)    )
                A				  =		model.get_output_embeddings()
                self.assertTrue(x is None or isinstance(lowerCamelCase_ ,nn.Linear    )    )




    def UpperCamelCase__		( self    )    ->      str:
          A  ,			A				  =		self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                A				  =		model_class(lowerCamelCase_    )
                A				  =		inspect.signature(model.forward    )
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                A				  =		[*signature.parameters.keys()]

                A				  =		["""pixel_values"""]
                self.assertListEqual(arg_names[:1] ,lowerCamelCase_    )




    def UpperCamelCase__		( self    )    ->      Any:
          A				  =		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase_    )




    def UpperCamelCase__		( self    )    ->      Any:
          A				  =		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_video_classification(*lowerCamelCase_    )




    @slow
    def UpperCamelCase__		( self    )    ->      Union[str, Any]:
          for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                A				  =		TimesformerModel.from_pretrained(lowerCamelCase_    )
                self.assertIsNotNone(lowerCamelCase_    )




    def UpperCamelCase__		( self    )    ->      Dict:
          if not self.has_attentions:
                pass

          else:
                A  ,			A				  =		self.model_tester.prepare_config_and_inputs_for_common()
                A				  =		True

                for model_class in self.all_model_classes:
                      A				  =		self.model_tester.seq_length
                      A				  =		self.model_tester.num_frames

                      A				  =		True
                      A				  =		False
                      A				  =		True
                      A				  =		model_class(lowerCamelCase_    )
                      model.to(lowerCamelCase_    )
                      model.eval()
                      with torch.no_grad():
                            A				  =		model(**self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_    )    )
                      A				  =		outputs.attentions
                      self.assertEqual(len(lowerCamelCase_    ) ,self.model_tester.num_hidden_layers    )

                      # check that output_attentions also work using config
                      del inputs_dict["output_attentions"]
                      A				  =		True
                      A				  =		model_class(lowerCamelCase_    )
                      model.to(lowerCamelCase_    )
                      model.eval()
                      with torch.no_grad():
                            A				  =		model(**self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_    )    )
                      A				  =		outputs.attentions
                      self.assertEqual(len(lowerCamelCase_    ) ,self.model_tester.num_hidden_layers    )

                      # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
                      self.assertListEqual(
                          list(attentions[0].shape[-3:]    ) ,[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,)
                      A				  =		len(lowerCamelCase_    )

                      # Check attention is always last and order is fine
                      A				  =		True
                      A				  =		True
                      A				  =		model_class(lowerCamelCase_    )
                      model.to(lowerCamelCase_    )
                      model.eval()
                      with torch.no_grad():
                            A				  =		model(**self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_    )    )

                      self.assertEqual(out_len + 1 ,len(lowerCamelCase_    )    )

                      A				  =		outputs.attentions

                      self.assertEqual(len(lowerCamelCase_    ) ,self.model_tester.num_hidden_layers    )

                      # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
                      self.assertListEqual(
                          list(self_attentions[0].shape[-3:]    ) ,[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,)




    def UpperCamelCase__		( self    )    ->      List[str]:
          def check_hidden_states_output(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_    ):
                A				  =		model_class(lowerCamelCase_    )
                model.to(lowerCamelCase_    )
                model.eval()

                with torch.no_grad():
                      A				  =		model(**self._prepare_for_class(lowerCamelCase_ ,lowerCamelCase_    )    )

                A				  =		outputs.hidden_states
                A				  =		self.model_tester.num_hidden_layers + 1
                self.assertEqual(len(lowerCamelCase_    ) ,lowerCamelCase_    )

                A				  =		self.model_tester.seq_length

                self.assertListEqual(
                    list(hidden_states[0].shape[-2:]    ) ,[seq_length, self.model_tester.hidden_size] ,)

          A  ,			A				  =		self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                A				  =		True
                check_hidden_states_output(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_    )

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                A				  =		True

                check_hidden_states_output(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_    )




def   _A					(	):



      """simple docstring"""






      A				  =		hf_hub_download(
          repo_id="""hf-internal-testing/spaghetti-video"""     ,   filename="""eating_spaghetti.npy"""     ,   repo_type="""dataset"""				)
      A				  =		np.load(_a				)
      return list(_a				)





@require_torch
@require_vision
class lowerCamelCase__   (				unittest.TestCase    ):



    '''simple docstring'''




    @cached_property
    def UpperCamelCase__		( self    )    ->      Optional[int]:
          # logits were tested with a different mean and std, so we use the same here
          return (
              VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] ,image_std=[0.5, 0.5, 0.5]    )
              if is_vision_available()
              else None
          )




    @slow
    def UpperCamelCase__		( self    )    ->      str:
          A				  =		TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400"""    ).to(
              lowerCamelCase_    )

          A				  =		self.default_image_processor
          A				  =		prepare_video()
          A				  =		image_processor(video[:8] ,return_tensors="""pt"""    ).to(lowerCamelCase_    )

          # forward pass
          with torch.no_grad():
                A				  =		model(**lowerCamelCase_    )

          # verify the logits
          A				  =		torch.Size((1, 4_0_0)    )
          self.assertEqual(outputs.logits.shape ,lowerCamelCase_    )

          A				  =		torch.tensor([-0.30_16, -0.77_13, -0.42_05]    ).to(lowerCamelCase_    )

          self.assertTrue(torch.allclose(outputs.logits[0, :3] ,lowerCamelCase_ ,atol=1E-4    )    )







"""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]				)				)




