
'''simple docstring'''


import argparse
import json
import os.path
from collections import OrderedDict

import numpy as np
import requests
import torch
from flax.training.checkpoints import restore_checkpoint
from huggingface_hub import hf_hub_download

from transformers import VivitConfig, VivitForVideoClassification, VivitImageProcessor
from transformers.image_utils import PILImageResampling
def 				__magic_name__(					UpperCAmelCase__   :					Union[str, Any]  ):
						UpperCamelCase_    :  str				    =    """https://storage.googleapis.com/scenic-bucket/vivit/kinetics_400/vivit_base_16x2_unfactorized/checkpoint"""

						with open(UpperCAmelCase__       ,							"""wb"""  ) as f:
												with requests.get(UpperCAmelCase__       ,							stream=UpperCAmelCase__  ) as req:
																		for chunk in req.iter_content(chunk_size=2048  ):
																								f.write(UpperCAmelCase__  )
def 				__magic_name__(					):
						UpperCamelCase_    :  Tuple				    =    VivitConfig()

						UpperCamelCase_    :  Dict				    =    400
						UpperCamelCase_    :  Any				    =    """huggingface/label-files"""
						UpperCamelCase_    :  Any				    =    """kinetics400-id2label.json"""

						UpperCamelCase_    :  Dict				    =    json.load(open(hf_hub_download(UpperCAmelCase__       ,							UpperCAmelCase__       ,							repo_type="""dataset"""  )       ,							"""r"""  )  )
						UpperCamelCase_    :  Union[str, Any]				    =    {int(UpperCAmelCase__  ): v for k, v in idalabel.items()}
						UpperCamelCase_    :  int				    =    idalabel
						UpperCamelCase_    :  str				    =    {v: k for k, v in idalabel.items()}
						return config
def 				__magic_name__(					):
						UpperCamelCase_    :  List[Any]				    =    hf_hub_download(
						    repo_id="""hf-internal-testing/spaghetti-video"""       ,							filename="""eating_spaghetti_32_frames.npy"""       ,							repo_type="""dataset"""  )
						UpperCamelCase_    :  Optional[Any]				    =    np.load(UpperCAmelCase__  )
						return list(UpperCAmelCase__  )
def 				__magic_name__(					UpperCAmelCase__   :					np.ndarray  ):
						if np.ndim(UpperCAmelCase__  ) == 2:
												return transform_attention_bias(UpperCAmelCase__  )

						elif np.ndim(UpperCAmelCase__  ) == 3:
												return transform_attention_kernel(UpperCAmelCase__  )

						else:
												raise Exception(f"""Invalid number of dimesions: {np.ndim(UpperCAmelCase__  )}"""  )
def 				__magic_name__(					UpperCAmelCase__   :					np.ndarray  ):
						return current.flatten()
def 				__magic_name__(					UpperCAmelCase__   :					np.ndarray  ):
						return np.reshape(UpperCAmelCase__       ,							(current.shape[0], current.shape[1] * current.shape[2])  ).T
def 				__magic_name__(					UpperCAmelCase__   :					np.ndarray  ):
						return np.reshape(UpperCAmelCase__       ,							(current.shape[0] * current.shape[1], current.shape[2])  ).T
def 				__magic_name__(					UpperCAmelCase__   :					List[Any]       ,							UpperCAmelCase__   :					Any  ):
						UpperCamelCase_    :  Tuple				    =    state_dict["""optimizer"""]["""target"""]["""Transformer"""][f"""encoderblock_{i}"""]

						UpperCamelCase_    :  List[Any]				    =    f"""encoder.layer.{i}."""
						UpperCamelCase_    :  Union[str, Any]				    =    {
						    prefix + """intermediate.dense.bias""": state["""MlpBlock_0"""]["""Dense_0"""]["""bias"""],
						    prefix + """intermediate.dense.weight""": np.transpose(state["""MlpBlock_0"""]["""Dense_0"""]["""kernel"""]  ),
						    prefix + """output.dense.bias""": state["""MlpBlock_0"""]["""Dense_1"""]["""bias"""],
						    prefix + """output.dense.weight""": np.transpose(state["""MlpBlock_0"""]["""Dense_1"""]["""kernel"""]  ),
						    prefix + """layernorm_before.bias""": state["""LayerNorm_0"""]["""bias"""],
						    prefix + """layernorm_before.weight""": state["""LayerNorm_0"""]["""scale"""],
						    prefix + """layernorm_after.bias""": state["""LayerNorm_1"""]["""bias"""],
						    prefix + """layernorm_after.weight""": state["""LayerNorm_1"""]["""scale"""],
						    prefix
						    + """attention.attention.query.bias""": transform_attention(
						        state["""MultiHeadDotProductAttention_0"""]["""query"""]["""bias"""]  ),
						    prefix
						    + """attention.attention.query.weight""": transform_attention(
						        state["""MultiHeadDotProductAttention_0"""]["""query"""]["""kernel"""]  ),
						    prefix
						    + """attention.attention.key.bias""": transform_attention(state["""MultiHeadDotProductAttention_0"""]["""key"""]["""bias"""]  ),
						    prefix
						    + """attention.attention.key.weight""": transform_attention(
						        state["""MultiHeadDotProductAttention_0"""]["""key"""]["""kernel"""]  ),
						    prefix
						    + """attention.attention.value.bias""": transform_attention(
						        state["""MultiHeadDotProductAttention_0"""]["""value"""]["""bias"""]  ),
						    prefix
						    + """attention.attention.value.weight""": transform_attention(
						        state["""MultiHeadDotProductAttention_0"""]["""value"""]["""kernel"""]  ),
						    prefix + """attention.output.dense.bias""": state["""MultiHeadDotProductAttention_0"""]["""out"""]["""bias"""],
						    prefix
						    + """attention.output.dense.weight""": transform_attention_output_weight(
						        state["""MultiHeadDotProductAttention_0"""]["""out"""]["""kernel"""]  ),
						}

						return new_state
def 				__magic_name__(					UpperCAmelCase__   :					str  ):
						return sum([1 if """encoderblock_""" in k else 0 for k in state_dict["""optimizer"""]["""target"""]["""Transformer"""].keys()]  )
def 				__magic_name__(					UpperCAmelCase__   :					Optional[int]       ,							UpperCAmelCase__   :					int=False  ):
						UpperCamelCase_    :  Union[str, Any]				    =    get_n_layers(UpperCAmelCase__  )

						UpperCamelCase_    :  int				    =    OrderedDict()

						UpperCamelCase_    :  Tuple				    =    state_dict["""optimizer"""]["""target"""]["""Transformer"""]["""encoder_norm"""]["""bias"""]
						UpperCamelCase_    :  str				    =    state_dict["""optimizer"""]["""target"""]["""Transformer"""]["""encoder_norm"""]["""scale"""]

						UpperCamelCase_    :  List[Any]				    =    np.transpose(
						    state_dict["""optimizer"""]["""target"""]["""embedding"""]["""kernel"""]       ,							(4, 3, 0, 1, 2)  )
						UpperCamelCase_    :  Optional[Any]				    =    state_dict["""optimizer"""]["""target"""]["""embedding"""]["""bias"""]

						UpperCamelCase_    :  Tuple				    =    state_dict["""optimizer"""]["""target"""]["""cls"""]
						UpperCamelCase_    :  Any				    =    state_dict["""optimizer"""]["""target"""]["""Transformer"""]["""posembed_input"""][
						    """pos_embedding"""
						]

						for i in range(UpperCAmelCase__  ):
												new_state.update(transform_state_encoder_block(UpperCAmelCase__       ,							UpperCAmelCase__  )  )

						if classification_head:
												UpperCamelCase_    :  List[str]				    =    {"""vivit.""" + k: v for k, v in new_state.items()}
												UpperCamelCase_    :  Union[str, Any]				    =    np.transpose(state_dict["""optimizer"""]["""target"""]["""output_projection"""]["""kernel"""]  )
												UpperCamelCase_    :  Dict				    =    np.transpose(state_dict["""optimizer"""]["""target"""]["""output_projection"""]["""bias"""]  )

						return {k: torch.tensor(UpperCAmelCase__  ) for k, v in new_state.items()}
def 				__magic_name__(					):
						UpperCamelCase_    :  Dict				    =    VivitImageProcessor()

						assert extractor.do_resize is True
						assert extractor.size == {"shortest_edge": 256}
						assert extractor.do_center_crop is True
						assert extractor.crop_size == {"width": 224, "height": 224}
						assert extractor.resample == PILImageResampling.BILINEAR

						# here: https://github.com/deepmind/dmvr/blob/master/dmvr/modalities.py
						# one can seen that add_image has default values for normalization_mean and normalization_std set to 0 and 1
						# which effectively means no normalization (and ViViT does not overwrite those when calling this func)
						assert extractor.do_normalize is False
						assert extractor.do_rescale is True
						assert extractor.rescale_factor == 1 / 255

						# zero-centering = True in original implementation
						assert extractor.do_zero_centering is True

						return extractor
def 				__magic_name__(					UpperCAmelCase__   :					str  ):
						UpperCamelCase_    :  Union[str, Any]				    =    """checkpoint"""

						if not os.path.exists(UpperCAmelCase__  ):
												download_checkpoint(UpperCAmelCase__  )

						UpperCamelCase_    :  Optional[Any]				    =    restore_checkpoint(UpperCAmelCase__       ,							UpperCAmelCase__  )
						UpperCamelCase_    :  int				    =    transform_state(UpperCAmelCase__       ,							classification_head=UpperCAmelCase__  )

						UpperCamelCase_    :  str				    =    get_vivit_config()

						assert config.image_size == 224
						assert config.num_frames == 32

						UpperCamelCase_    :  int				    =    VivitForVideoClassification(UpperCAmelCase__  )
						model.load_state_dict(UpperCAmelCase__  )
						model.eval()

						UpperCamelCase_    :  Optional[Any]				    =    get_processor()

						UpperCamelCase_    :  Any				    =    prepare_video()
						UpperCamelCase_    :  Union[str, Any]				    =    extractor(UpperCAmelCase__       ,							return_tensors="""pt"""  )

						UpperCamelCase_    :  str				    =    model(**UpperCAmelCase__  )

						UpperCamelCase_    :  int				    =    torch.Size([1, 400]  )
						UpperCamelCase_    :  Optional[int]				    =    torch.tensor([-1.0_543, 2.0_764, -0.2_104, 0.4_439, -0.9_658]  )

						assert outputs.logits.shape == expected_shape
						assert torch.allclose(outputs.logits[0, :5]       ,							UpperCAmelCase__       ,							atol=1E-4  ), outputs.logits[0, :5]

						model.save_pretrained(UpperCAmelCase__  )
						extractor.save_pretrained(UpperCAmelCase__  )


if __name__ == "__main__":
			__SCREAMING_SNAKE_CASE  =			argparse.ArgumentParser()

			parser.add_argument("--output_model_name", "-o", type=str, help="Output path for the converted HuggingFace model")

			__SCREAMING_SNAKE_CASE  =			parser.parse_args()
			convert(args.output_model_name)






'''simple docstring'''


# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


__SCREAMING_SNAKE_CASE  =			os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
__SCREAMING_SNAKE_CASE  =			os.path.join(hf_cache_home, "accelerate")
__SCREAMING_SNAKE_CASE  =			os.path.join(cache_dir, "default_config.yaml")
__SCREAMING_SNAKE_CASE  =			os.path.join(cache_dir, "default_config.yaml")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
	__SCREAMING_SNAKE_CASE  =			default_yaml_config_file
else:
	__SCREAMING_SNAKE_CASE  =			default_json_config_file
def 				__magic_name__(					UpperCAmelCase__   :					int  ):
						if config_file is not None:
												if not os.path.isfile(UpperCAmelCase__  ):
																		raise FileNotFoundError(
																		    f"""The passed configuration file `{config_file}` does not exist. """
																		    """Please pass an existing file to `accelerate launch`, or use the the default one """
																		    """created through `accelerate config` and run `accelerate launch` """
																		    """without the `--config_file` argument."""  )
						else:
												UpperCamelCase_    :  List[Any]				    =    default_config_file
						with open(UpperCAmelCase__       ,							"""r"""       ,							encoding="""utf-8"""  ) as f:
												if config_file.endswith(""".json"""  ):
																		if (
																		    json.load(UpperCAmelCase__  ).get("""compute_environment"""       ,							ComputeEnvironment.LOCAL_MACHINE  )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								UpperCamelCase_    :  int				    =    ClusterConfig
																		else:
																								UpperCamelCase_    :  Optional[Any]				    =    SageMakerConfig
																		return config_class.from_json_file(json_file=UpperCAmelCase__  )
												else:
																		if (
																		    yaml.safe_load(UpperCAmelCase__  ).get("""compute_environment"""       ,							ComputeEnvironment.LOCAL_MACHINE  )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								UpperCamelCase_    :  Union[str, Any]				    =    ClusterConfig
																		else:
																								UpperCamelCase_    :  Optional[int]				    =    SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=UpperCAmelCase__  )




@dataclass
class 						__snake_case :
		a_        =				42
		a_        =				42
		a_        =				42
		a_        =				42




		def   _snake_case  (     self				:List[Any])				-> Optional[Any]:






								'''simple docstring'''






								UpperCamelCase_    :  List[str]				    =    self.__dict__
								# For serialization, it's best to convert Enums to strings (or their underlying value type).
								for key, value in result.items():
														if isinstance(_SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE):
																				UpperCamelCase_    :  str				    =    value.value
														if isinstance(_SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE) and not bool(_SCREAMING_SNAKE_CASE):
																				UpperCamelCase_    :  Dict				    =    None
								UpperCamelCase_    :  Dict				    =    {k: v for k, v in result.items() if v is not None}
								return result




		@classmethod
		def   _snake_case  (     cls				:Dict ,						_SCREAMING_SNAKE_CASE				:Optional[int]=None)				-> int:






								'''simple docstring'''






								UpperCamelCase_    :  str				    =    default_json_config_file if json_file is None else json_file
								with open(_SCREAMING_SNAKE_CASE ,						"""r""" ,						encoding="""utf-8""") as f:
														UpperCamelCase_    :  List[str]				    =    json.load(_SCREAMING_SNAKE_CASE)
								if "compute_environment" not in config_dict:
														UpperCamelCase_    :  Union[str, Any]				    =    ComputeEnvironment.LOCAL_MACHINE
								if "mixed_precision" not in config_dict:
														UpperCamelCase_    :  List[Any]				    =    """fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
								if "fp16" in config_dict:  # Convert the config to the new format.
														del config_dict["fp16"]
								if "dynamo_backend" in config_dict:  # Convert the config to the new format.
														UpperCamelCase_    :  Optional[int]				    =    config_dict.pop("""dynamo_backend""")
														UpperCamelCase_    :  List[str]				    =    {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
								if "use_cpu" not in config_dict:
														UpperCamelCase_    :  Dict				    =    False
								return cls(**_SCREAMING_SNAKE_CASE)




		def   _snake_case  (     self				:int ,						_SCREAMING_SNAKE_CASE				:List[Any])				-> List[str]:






								'''simple docstring'''






								with open(_SCREAMING_SNAKE_CASE ,						"""w""" ,						encoding="""utf-8""") as f:
														UpperCamelCase_    :  Union[str, Any]				    =    json.dumps(self.to_dict() ,						indent=2 ,						sort_keys=_SCREAMING_SNAKE_CASE) + """\n"""
														f.write(_SCREAMING_SNAKE_CASE)




		@classmethod
		def   _snake_case  (     cls				:Optional[Any] ,						_SCREAMING_SNAKE_CASE				:Any=None)				-> List[str]:






								'''simple docstring'''






								UpperCamelCase_    :  List[str]				    =    default_yaml_config_file if yaml_file is None else yaml_file
								with open(_SCREAMING_SNAKE_CASE ,						"""r""" ,						encoding="""utf-8""") as f:
														UpperCamelCase_    :  Any				    =    yaml.safe_load(_SCREAMING_SNAKE_CASE)
								if "compute_environment" not in config_dict:
														UpperCamelCase_    :  Union[str, Any]				    =    ComputeEnvironment.LOCAL_MACHINE

								if "mixed_precision" not in config_dict:
														UpperCamelCase_    :  int				    =    """fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
								if isinstance(config_dict["""mixed_precision"""] ,						_SCREAMING_SNAKE_CASE) and not config_dict["mixed_precision"]:
														UpperCamelCase_    :  Union[str, Any]				    =    """no"""
								if "fp16" in config_dict:  # Convert the config to the new format.
														del config_dict["fp16"]
								if "dynamo_backend" in config_dict:  # Convert the config to the new format.
														UpperCamelCase_    :  Any				    =    config_dict.pop("""dynamo_backend""")
														UpperCamelCase_    :  Optional[Any]				    =    {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
								if "use_cpu" not in config_dict:
														UpperCamelCase_    :  List[str]				    =    False
								return cls(**_SCREAMING_SNAKE_CASE)




		def   _snake_case  (     self				:List[Any] ,						_SCREAMING_SNAKE_CASE				:str)				-> int:






								'''simple docstring'''






								with open(_SCREAMING_SNAKE_CASE ,						"""w""" ,						encoding="""utf-8""") as f:
														yaml.safe_dump(self.to_dict() ,						_SCREAMING_SNAKE_CASE)





		def   _snake_case  (     self				:Any)				-> int:






								'''simple docstring'''






								if isinstance(self.compute_environment ,						_SCREAMING_SNAKE_CASE):
														UpperCamelCase_    :  Dict				    =    ComputeEnvironment(self.compute_environment)
								if isinstance(self.distributed_type ,						_SCREAMING_SNAKE_CASE):
														if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																				UpperCamelCase_    :  Optional[Any]				    =    SageMakerDistributedType(self.distributed_type)
														else:
																				UpperCamelCase_    :  Optional[int]				    =    DistributedType(self.distributed_type)
								if self.dynamo_config is None:
														UpperCamelCase_    :  str				    =    {}







@dataclass
class 						__snake_case (						_a  ):
		a_        =				42
		a_        =				0
		a_        =				1
		a_        =				None
		a_        =				None
		a_        =				None
		a_        =				"static"
		a_        =				False
		a_        =				"main"

		# args for deepspeed_plugin
		a_        =				None
		# args for fsdp
		a_        =				None
		# args for megatron_lm
		a_        =				None
		# args for ipex
		a_        =				None
		# args for TPU
		a_        =				False

		# args for TPU pods
		a_        =				None
		a_        =				None
		a_        =				False
		a_        =				False
		a_        =				None
		a_        =				None
		a_        =				None
		a_        =				None

		# args for dynamo
		a_        =				None




		def   _snake_case  (     self				:List[str])				-> Tuple:






								'''simple docstring'''






								if self.deepspeed_config is None:
														UpperCamelCase_    :  Tuple				    =    {}
								if self.fsdp_config is None:
														UpperCamelCase_    :  Union[str, Any]				    =    {}
								if self.megatron_lm_config is None:
														UpperCamelCase_    :  int				    =    {}
								if self.ipex_config is None:
														UpperCamelCase_    :  Optional[int]				    =    {}
								return super().__post_init__()







@dataclass
class 						__snake_case (						_a  ):
		a_        =				42
		a_        =				42
		a_        =				None
		a_        =				None
		a_        =				"us-east-1"
		a_        =				1
		a_        =				"all"
		a_        =				F"""accelerate-sagemaker-{num_machines}"""
		a_        =				SAGEMAKER_PYTORCH_VERSION
		a_        =				SAGEMAKER_TRANSFORMERS_VERSION
		a_        =				SAGEMAKER_PYTHON_VERSION
		a_        =				None
		a_        =				None
		a_        =				None
		a_        =				None




