


'''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__(    lowerCamelCase):
						__lowerCAmelCase											=					'''https://storage.googleapis.com/scenic-bucket/vivit/kinetics_400/vivit_base_16x2_unfactorized/checkpoint'''

						with open(lowerCamelCase,					'''wb''') as f:
												with requests.get(lowerCamelCase,					stream=lowerCamelCase) as req:
																		for chunk in req.iter_content(chunk_size=2_0_4_8):
																								f.write(lowerCamelCase)

def 				__magic_name__(    ):
						__lowerCAmelCase											=					VivitConfig()

						__lowerCAmelCase											=					4_0_0
						__lowerCAmelCase											=					'''huggingface/label-files'''
						__lowerCAmelCase											=					'''kinetics400-id2label.json'''

						__lowerCAmelCase											=					json.load(open(hf_hub_download(lowerCamelCase,					lowerCamelCase,					repo_type='''dataset'''),					'''r'''))
						__lowerCAmelCase											=					{int(lowerCamelCase): v for k, v in idalabel.items()}
						__lowerCAmelCase											=					idalabel
						__lowerCAmelCase											=					{v: k for k, v in idalabel.items()}
						return config

def 				__magic_name__(    ):
						__lowerCAmelCase											=					hf_hub_download(
						    repo_id='''hf-internal-testing/spaghetti-video''',					filename='''eating_spaghetti_32_frames.npy''',					repo_type='''dataset''')
						__lowerCAmelCase											=					np.load(lowerCamelCase)
						return list(lowerCamelCase)

def 				__magic_name__(    lowerCamelCase):
						if np.ndim(lowerCamelCase) == 2:
												return transform_attention_bias(lowerCamelCase)

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

						else:
												raise Exception(F"""Invalid number of dimesions: {np.ndim(lowerCamelCase)}""")

def 				__magic_name__(    lowerCamelCase):
						return current.flatten()

def 				__magic_name__(    lowerCamelCase):
						return np.reshape(lowerCamelCase,					(current.shape[0], current.shape[1] * current.shape[2])).T

def 				__magic_name__(    lowerCamelCase):
						return np.reshape(lowerCamelCase,					(current.shape[0] * current.shape[1], current.shape[2])).T

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase):
						__lowerCAmelCase											=					state_dict['''optimizer''']['''target''']['''Transformer'''][F"""encoderblock_{i}"""]

						__lowerCAmelCase											=					F"""encoder.layer.{i}."""
						__lowerCAmelCase											=					{
						    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__(    lowerCamelCase):
						return sum([1 if '''encoderblock_''' in k else 0 for k in state_dict['''optimizer''']['''target''']['''Transformer'''].keys()])

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase=False):
						__lowerCAmelCase											=					get_n_layers(lowerCamelCase)

						__lowerCAmelCase											=					OrderedDict()

						__lowerCAmelCase											=					state_dict['''optimizer''']['''target''']['''Transformer''']['''encoder_norm''']['''bias''']
						__lowerCAmelCase											=					state_dict['''optimizer''']['''target''']['''Transformer''']['''encoder_norm''']['''scale''']

						__lowerCAmelCase											=					np.transpose(
						    state_dict['''optimizer''']['''target''']['''embedding''']['''kernel'''],					(4, 3, 0, 1, 2))
						__lowerCAmelCase											=					state_dict['''optimizer''']['''target''']['''embedding''']['''bias''']

						__lowerCAmelCase											=					state_dict['''optimizer''']['''target''']['''cls''']
						__lowerCAmelCase											=					state_dict['''optimizer''']['''target''']['''Transformer''']['''posembed_input'''][
						    '''pos_embedding'''
						]

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

						if classification_head:
												__lowerCAmelCase											=					{'''vivit.''' + k: v for k, v in new_state.items()}
												__lowerCAmelCase											=					np.transpose(state_dict['''optimizer''']['''target''']['''output_projection''']['''kernel'''])
												__lowerCAmelCase											=					np.transpose(state_dict['''optimizer''']['''target''']['''output_projection''']['''bias'''])

						return {k: torch.tensor(lowerCamelCase) for k, v in new_state.items()}

def 				__magic_name__(    ):
						__lowerCAmelCase											=					VivitImageProcessor()

						assert extractor.do_resize is True
						assert extractor.size == {"shortest_edge": 2_5_6}
						assert extractor.do_center_crop is True
						assert extractor.crop_size == {"width": 2_2_4, "height": 2_2_4}
						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 / 2_5_5

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

						return extractor

def 				__magic_name__(    lowerCamelCase):
						__lowerCAmelCase											=					'''checkpoint'''

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

						__lowerCAmelCase											=					restore_checkpoint(lowerCamelCase,					lowerCamelCase)
						__lowerCAmelCase											=					transform_state(lowerCamelCase,					classification_head=lowerCamelCase)

						__lowerCAmelCase											=					get_vivit_config()

						assert config.image_size == 2_2_4
						assert config.num_frames == 3_2

						__lowerCAmelCase											=					VivitForVideoClassification(lowerCamelCase)
						model.load_state_dict(lowerCamelCase)
						model.eval()

						__lowerCAmelCase											=					get_processor()

						__lowerCAmelCase											=					prepare_video()
						__lowerCAmelCase											=					extractor(lowerCamelCase,					return_tensors='''pt''')

						__lowerCAmelCase											=					model(**lowerCamelCase)

						__lowerCAmelCase											=					torch.Size([1, 4_0_0])
						__lowerCAmelCase											=					torch.tensor([-1.05_43, 2.07_64, -0.21_04, 0.44_39, -0.96_58])

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

						model.save_pretrained(lowerCamelCase)
						extractor.save_pretrained(lowerCamelCase)


if __name__ == "__main__":
	_UpperCAmelCase					:			Union[str, Any]				     =					argparse.ArgumentParser()

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

	_UpperCAmelCase					:			Optional[int]				     =					parser.parse_args()
	convert(args.output_model_name)





'''simple docstring'''

import argparse
import json
import logging
import os
import sys
from unittest import skip
from unittest.mock import patch

import tensorflow as tf

from transformers.testing_utils import TestCasePlus, get_gpu_count, slow


_UpperCAmelCase					:			str				     =					[
    os.path.join(os.path.dirname(__file__), dirname)
    for dirname in [
        """text-generation""",
        """text-classification""",
        """token-classification""",
        """language-modeling""",
        """multiple-choice""",
        """question-answering""",
        """summarization""",
        """translation""",
        """image-classification""",
    ]
]
sys.path.extend(SRC_DIRS)


if SRC_DIRS is not None:
	import run_clm
	import run_image_classification
	import run_mlm
	import run_ner
	import run_qa as run_squad
	import run_summarization
	import run_swag
	import run_text_classification
	import run_translation


logging.basicConfig(level=logging.DEBUG)

_UpperCAmelCase					:			Optional[Any]				     =					logging.getLogger()

def 				__magic_name__(    ):
						__lowerCAmelCase											=					argparse.ArgumentParser()
						parser.add_argument('''-f''')
						__lowerCAmelCase											=					parser.parse_args()
						return args.f

def 				__magic_name__(    lowerCamelCase):
						__lowerCAmelCase											=					{}
						__lowerCAmelCase											=					os.path.join(lowerCamelCase,					'''all_results.json''')
						if os.path.exists(lowerCamelCase):
												with open(lowerCamelCase,					'''r''') as f:
																		__lowerCAmelCase											=					json.load(lowerCamelCase)
						else:
												raise ValueError(F"""can't find {path}""")
						return results

def 				__magic_name__(    ):
						return bool(tf.config.list_physical_devices('''GPU'''))


_UpperCAmelCase					:			str				     =					logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)




class    a__					(			__A   ):







				"""simple docstring"""



				@skip('''Skipping until shape inference for to_tf_dataset PR is merged.'''		)
				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_text_classification.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            """.split()

										if is_cuda_available():
																testargs.append('''--fp16'''		)

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_text_classification.main()
																# Reset the mixed precision policy so we don't break other tests
																tf.keras.mixed_precision.set_global_policy('''float32'''		)
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertGreaterEqual(result['''eval_accuracy''']							,      0.7_5		)




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_clm.py
            --model_name_or_path distilgpt2
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --do_train
            --do_eval
            --block_size 128
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 1
            --num_train_epochs 2
            --output_dir {tmp_dir}
            --overwrite_output_dir
            """.split()

										if len(tf.config.list_physical_devices('''GPU'''		)		) > 1:
																# Skipping because there are not enough batches to train the model + would need a drop_last to work.
																return

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_clm.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertLess(result['''eval_perplexity''']							,      1_00		)




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_mlm.py
            --model_name_or_path distilroberta-base
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --max_seq_length 64
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --do_train
            --do_eval
            --prediction_loss_only
            --num_train_epochs=1
            --learning_rate=1e-4
        """.split()

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_mlm.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertLess(result['''eval_perplexity''']							,      42		)




				def        _snake_case	(self		):
										# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
										__lowerCAmelCase											=					7 if get_gpu_count() > 1 else 2

										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_ner.py
            --model_name_or_path bert-base-uncased
            --train_file tests/fixtures/tests_samples/conll/sample.json
            --validation_file tests/fixtures/tests_samples/conll/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --do_train
            --do_eval
            --warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=2
            --num_train_epochs={epochs}
            --seed 7
        """.split()

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_ner.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertGreaterEqual(result['''accuracy''']							,      0.7_5		)




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_qa.py
            --model_name_or_path bert-base-uncased
            --version_2_with_negative
            --train_file tests/fixtures/tests_samples/SQUAD/sample.json
            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --max_steps=10
            --warmup_steps=2
            --do_train
            --do_eval
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
        """.split()

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_squad.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertGreaterEqual(result['''f1''']							,      30		)
																self.assertGreaterEqual(result['''exact''']							,      30		)




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_swag.py
            --model_name_or_path bert-base-uncased
            --train_file tests/fixtures/tests_samples/swag/sample.json
            --validation_file tests/fixtures/tests_samples/swag/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --max_steps=20
            --warmup_steps=2
            --do_train
            --do_eval
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
        """.split()

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_swag.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertGreaterEqual(result['''val_accuracy''']							,      0.8		)




				@slow
				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_summarization.py
            --model_name_or_path t5-small
            --train_file tests/fixtures/tests_samples/xsum/sample.json
            --validation_file tests/fixtures/tests_samples/xsum/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --max_steps=50
            --warmup_steps=8
            --do_train
            --do_eval
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
        """.split()

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_summarization.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertGreaterEqual(result['''rouge1''']							,      10		)
																self.assertGreaterEqual(result['''rouge2''']							,      2		)
																self.assertGreaterEqual(result['''rougeL''']							,      7		)
																self.assertGreaterEqual(result['''rougeLsum''']							,      7		)




				@slow
				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_translation.py
            --model_name_or_path Rocketknight1/student_marian_en_ro_6_1
            --source_lang en
            --target_lang ro
            --train_file tests/fixtures/tests_samples/wmt16/sample.json
            --validation_file tests/fixtures/tests_samples/wmt16/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --warmup_steps=8
            --do_train
            --do_eval
            --learning_rate=3e-3
            --num_train_epochs 12
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --source_lang en_XX
            --target_lang ro_RO
        """.split()

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_translation.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertGreaterEqual(result['''bleu''']							,      30		)




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.get_auto_remove_tmp_dir()
										__lowerCAmelCase											=					F"""
            run_image_classification.py
            --dataset_name hf-internal-testing/cats_vs_dogs_sample
            --model_name_or_path microsoft/resnet-18
            --do_train
            --do_eval
            --learning_rate 1e-4
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 1
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --dataloader_num_workers 16
            --num_train_epochs 2
            --train_val_split 0.1
            --seed 42
            --ignore_mismatched_sizes True
            """.split()

										with patch.object(__lowercase							,      '''argv'''							,      __lowercase		):
																run_image_classification.main()
																__lowerCAmelCase											=					get_results(__lowercase		)
																self.assertGreaterEqual(result['''accuracy''']							,      0.7		)

