

import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
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,
						    VideoMAEForPreTraining,
						    VideoMAEForVideoClassification,
						    VideoMAEModel,
						)
						from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from transformers import VideoMAEImageProcessor



class   __lowercase    :




			"""simple docstring"""







			def __init__(			self  :					Any       ,						lowerCAmelCase__  :					Any       ,						lowerCAmelCase__  :					Optional[int]=13       ,						lowerCAmelCase__  :					Optional[int]=10       ,						lowerCAmelCase__  :					Optional[Any]=3       ,						lowerCAmelCase__  :					Optional[Any]=2       ,						lowerCAmelCase__  :					Dict=2       ,						lowerCAmelCase__  :					Union[str, Any]=2       ,						lowerCAmelCase__  :					List[str]=True       ,						lowerCAmelCase__  :					List[str]=True       ,						lowerCAmelCase__  :					List[Any]=32       ,						lowerCAmelCase__  :					Any=5       ,						lowerCAmelCase__  :					Optional[int]=4       ,						lowerCAmelCase__  :					List[str]=37       ,						lowerCAmelCase__  :					str="gelu"       ,						lowerCAmelCase__  :					Tuple=0.1       ,						lowerCAmelCase__  :					List[str]=0.1       ,						lowerCAmelCase__  :					List[str]=10       ,						lowerCAmelCase__  :					Optional[Any]=0.02       ,						lowerCAmelCase__  :					List[Any]=0.9       ,						lowerCAmelCase__  :					List[str]=None       ,						):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	parent
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	batch_size
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	image_size
									SCREAMING_SNAKE_CASE_:			Dict  		=	num_channels
									SCREAMING_SNAKE_CASE_:			Any  		=	patch_size
									SCREAMING_SNAKE_CASE_:			str  		=	tubelet_size
									SCREAMING_SNAKE_CASE_:			Any  		=	num_frames
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	is_training
									SCREAMING_SNAKE_CASE_:			List[str]  		=	use_labels
									SCREAMING_SNAKE_CASE_:			Dict  		=	hidden_size
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	num_hidden_layers
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	num_attention_heads
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	intermediate_size
									SCREAMING_SNAKE_CASE_:			Dict  		=	hidden_act
									SCREAMING_SNAKE_CASE_:			Tuple  		=	hidden_dropout_prob
									SCREAMING_SNAKE_CASE_:			Dict  		=	attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE_:			List[str]  		=	type_sequence_label_size
									SCREAMING_SNAKE_CASE_:			int  		=	initializer_range
									SCREAMING_SNAKE_CASE_:			Dict  		=	mask_ratio
									SCREAMING_SNAKE_CASE_:			Dict  		=	scope

									# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
									SCREAMING_SNAKE_CASE_:			int  		=	(image_size // patch_size) ** 2
									SCREAMING_SNAKE_CASE_:			Any  		=	(num_frames // tubelet_size) * self.num_patches_per_frame

									# use this variable to define bool_masked_pos
									SCREAMING_SNAKE_CASE_:			Tuple  		=	int(mask_ratio * self.seq_length)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			Any  		=	floats_tensor(
									    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size])

									SCREAMING_SNAKE_CASE_:			Dict  		=	None
									if self.use_labels:
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	ids_tensor([self.batch_size]       ,						self.type_sequence_label_size)

									SCREAMING_SNAKE_CASE_:			Dict  		=	self.get_config()

									return config, pixel_values, labels



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[str]):
									return VideoMAEConfig(
									    image_size=self.image_size       ,						patch_size=self.patch_size       ,						num_channels=self.num_channels       ,						num_frames=self.num_frames       ,						tubelet_size=self.tubelet_size       ,						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       ,						is_decoder=lowerCAmelCase__       ,						initializer_range=self.initializer_range       ,						)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					List[Any]       ,						lowerCAmelCase__  :					List[Any]       ,						lowerCAmelCase__  :					Any):
									SCREAMING_SNAKE_CASE_:			int  		=	VideoMAEModel(config=lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_:			int  		=	model(lowerCAmelCase__)
									self.parent.assertEqual(result.last_hidden_state.shape       ,						(self.batch_size, self.seq_length, self.hidden_size))



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any       ,						lowerCAmelCase__  :					List[str]       ,						lowerCAmelCase__  :					Optional[int]       ,						lowerCAmelCase__  :					Union[str, Any]):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	VideoMAEForPreTraining(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									# important: each video needs to have the same number of masked patches
									# hence we define a single mask, which we then repeat for each example in the batch
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	torch.ones((self.num_masks,))
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	torch.cat([mask, torch.zeros(self.seq_length - mask.size(0))])
									SCREAMING_SNAKE_CASE_:			Any  		=	mask.expand(self.batch_size       ,						-1).bool()

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model(lowerCAmelCase__       ,						lowerCAmelCase__)
									# model only returns predictions for masked patches
									SCREAMING_SNAKE_CASE_:			Tuple  		=	mask.sum().item()
									SCREAMING_SNAKE_CASE_:			Tuple  		=	3 * self.tubelet_size * self.patch_size**2
									self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, num_masked_patches, decoder_num_labels))




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									SCREAMING_SNAKE_CASE_:			str  		=	self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	config_and_inputs
									SCREAMING_SNAKE_CASE_:			Any  		=	{"pixel_values": pixel_values}
									return config, inputs_dict







@require_torch
class   __lowercase    (			UpperCAmelCase_		,	UpperCAmelCase_		,	unittest.TestCase     ):




			"""simple docstring"""







			_UpperCAmelCase       :							List[Any]      							=					(
			    (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
			)
			_UpperCAmelCase       :							List[str]      							=					(
			    {'''feature-extraction''': VideoMAEModel, '''video-classification''': VideoMAEForVideoClassification}
			    if is_torch_available()
			    else {}
			)

			_UpperCAmelCase       :							Dict      							=					False
			_UpperCAmelCase       :							List[str]      							=					False
			_UpperCAmelCase       :							Optional[Any]      							=					False
			_UpperCAmelCase       :							str      							=					False



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									SCREAMING_SNAKE_CASE_:			int  		=	VideoMAEModelTester(self)
									SCREAMING_SNAKE_CASE_:			List[str]  		=	ConfigTester(self       ,						config_class=lowerCAmelCase__       ,						has_text_modality=lowerCAmelCase__       ,						hidden_size=37)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					str       ,						lowerCAmelCase__  :					List[str]       ,						lowerCAmelCase__  :					List[Any]=False):
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	copy.deepcopy(lowerCAmelCase__)

									if model_class == VideoMAEForPreTraining:
															# important: each video needs to have the same number of masked patches
															# hence we define a single mask, which we then repeat for each example in the batch
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	torch.ones((self.model_tester.num_masks,))
															SCREAMING_SNAKE_CASE_:			Tuple  		=	torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0))])
															SCREAMING_SNAKE_CASE_:			str  		=	mask.expand(self.model_tester.batch_size       ,						-1).bool()
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	bool_masked_pos.to(lowerCAmelCase__)

									if return_labels:
															if model_class in [
															    *get_values(lowerCAmelCase__),
															]:
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	torch.zeros(
																					    self.model_tester.batch_size       ,						dtype=torch.long       ,						device=lowerCAmelCase__)

									return inputs_dict



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Dict):
									self.config_tester.run_common_tests()



			@unittest.skip(reason="VideoMAE does not use inputs_embeds")
			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									pass



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[str]):
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Tuple  		=	self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model_class(lowerCAmelCase__)
															self.assertIsInstance(model.get_input_embeddings()       ,						(nn.Module))
															SCREAMING_SNAKE_CASE_:			Dict  		=	model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowerCAmelCase__       ,						nn.Linear))



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			int  		=	self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	model_class(lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	inspect.signature(model.forward)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															SCREAMING_SNAKE_CASE_:			str  		=	[*signature.parameters.keys()]

															SCREAMING_SNAKE_CASE_:			Any  		=	["pixel_values"]
															self.assertListEqual(arg_names[:1]       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									SCREAMING_SNAKE_CASE_:			str  		=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__)



			@slow
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	VideoMAEModel.from_pretrained(lowerCAmelCase__)
															self.assertIsNotNone(lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									if not self.has_attentions:
															pass

									else:
															SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Dict  		=	self.model_tester.prepare_config_and_inputs_for_common()
															SCREAMING_SNAKE_CASE_:			Tuple  		=	True

															for model_class in self.all_model_classes:
																					SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self.model_tester.seq_length - self.model_tester.num_masks
																					SCREAMING_SNAKE_CASE_:			int  		=	(
																					    num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
																					)

																					SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	True
																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	False
																					SCREAMING_SNAKE_CASE_:			Dict  		=	True
																					SCREAMING_SNAKE_CASE_:			List[Any]  		=	model_class(lowerCAmelCase__)
																					model.to(lowerCAmelCase__)
																					model.eval()
																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_:			Dict  		=	model(**self._prepare_for_class(lowerCAmelCase__       ,						lowerCAmelCase__))
																					SCREAMING_SNAKE_CASE_:			Dict  		=	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"]
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	True
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	model_class(lowerCAmelCase__)
																					model.to(lowerCAmelCase__)
																					model.eval()
																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_:			List[Any]  		=	model(**self._prepare_for_class(lowerCAmelCase__       ,						lowerCAmelCase__))
																					SCREAMING_SNAKE_CASE_:			Any  		=	outputs.attentions
																					self.assertEqual(len(lowerCAmelCase__)       ,						self.model_tester.num_hidden_layers)

																					self.assertListEqual(
																					    list(attentions[0].shape[-3:])       ,						[self.model_tester.num_attention_heads, seq_len, seq_len]       ,						)
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	len(lowerCAmelCase__)

																					# Check attention is always last and order is fine
																					SCREAMING_SNAKE_CASE_:			Any  		=	True
																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	True
																					SCREAMING_SNAKE_CASE_:			int  		=	model_class(lowerCAmelCase__)
																					model.to(lowerCAmelCase__)
																					model.eval()
																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	model(**self._prepare_for_class(lowerCAmelCase__       ,						lowerCAmelCase__))

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

																					SCREAMING_SNAKE_CASE_:			List[str]  		=	outputs.attentions

																					self.assertEqual(len(lowerCAmelCase__)       ,						self.model_tester.num_hidden_layers)
																					self.assertListEqual(
																					    list(self_attentions[0].shape[-3:])       ,						[self.model_tester.num_attention_heads, seq_len, seq_len]       ,						)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[str]):
									def check_hidden_states_output(lowerCAmelCase__  :					Tuple       ,						lowerCAmelCase__  :					Dict       ,						lowerCAmelCase__  :					List[Any]):
															SCREAMING_SNAKE_CASE_:			Any  		=	model_class(lowerCAmelCase__)
															model.to(lowerCAmelCase__)
															model.eval()

															with torch.no_grad():
																					SCREAMING_SNAKE_CASE_:			Dict  		=	model(**self._prepare_for_class(lowerCAmelCase__       ,						lowerCAmelCase__))

															SCREAMING_SNAKE_CASE_:			int  		=	outputs.hidden_states
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	self.model_tester.num_hidden_layers + 1
															self.assertEqual(len(lowerCAmelCase__)       ,						lowerCAmelCase__)

															SCREAMING_SNAKE_CASE_:			str  		=	self.model_tester.seq_length - self.model_tester.num_masks
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

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

									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Dict  		=	self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	True
															check_hidden_states_output(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															SCREAMING_SNAKE_CASE_:			List[str]  		=	True

															check_hidden_states_output(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)




			@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any):
									pass







def       A_				(   ):
						SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	hf_hub_download(
						    repo_id="hf-internal-testing/spaghetti-video"    ,     filename="eating_spaghetti.npy"    ,     repo_type="dataset"   )
						SCREAMING_SNAKE_CASE_:			Tuple  		=	np.load(_UpperCAmelCase   )
						return list(_UpperCAmelCase   )



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




			"""simple docstring"""







			@cached_property
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									# 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 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics").to(
									    lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	self.default_image_processor
									SCREAMING_SNAKE_CASE_:			Any  		=	prepare_video()
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	image_processor(lowerCAmelCase__       ,						return_tensors="pt").to(lowerCAmelCase__)

									# forward pass
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	model(**lowerCAmelCase__)

									# verify the logits
									SCREAMING_SNAKE_CASE_:			str  		=	torch.Size((1, 400))
									self.assertEqual(outputs.logits.shape       ,						lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Tuple  		=	torch.tensor([0.3669, -0.0688, -0.2421]).to(lowerCAmelCase__)

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




			@slow
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			Tuple  		=	VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short").to(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	self.default_image_processor
									SCREAMING_SNAKE_CASE_:			Any  		=	prepare_video()
									SCREAMING_SNAKE_CASE_:			Dict  		=	image_processor(lowerCAmelCase__       ,						return_tensors="pt").to(lowerCAmelCase__)

									# add boolean mask, indicating which patches to mask
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos"       ,						filename="bool_masked_pos.pt")
									SCREAMING_SNAKE_CASE_:			Any  		=	torch.load(lowerCAmelCase__)

									# forward pass
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model(**lowerCAmelCase__)

									# verify the logits
									SCREAMING_SNAKE_CASE_:			List[str]  		=	torch.Size([1, 1408, 1536])
									SCREAMING_SNAKE_CASE_:			Tuple  		=	torch.tensor(
									    [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]]       ,						device=lowerCAmelCase__)
									self.assertEqual(outputs.logits.shape       ,						lowerCAmelCase__)
									self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]       ,						lowerCAmelCase__       ,						atol=1E-4))

									# verify the loss (`config.norm_pix_loss` = `True`)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	torch.tensor([0.5142]       ,						device=lowerCAmelCase__)
									self.assertTrue(torch.allclose(outputs.loss       ,						lowerCAmelCase__       ,						atol=1E-4))

									# verify the loss (`config.norm_pix_loss` = `False`)
									SCREAMING_SNAKE_CASE_:			Tuple  		=	VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short"       ,						norm_pix_loss=lowerCAmelCase__).to(
									    lowerCAmelCase__)

									with torch.no_grad():
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	model(**lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			int  		=	torch.tensor(torch.tensor([0.6469])       ,						device=lowerCAmelCase__)
									self.assertTrue(torch.allclose(outputs.loss       ,						lowerCAmelCase__       ,						atol=1E-4))









import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
						from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
						from tensorflow.keras.optimizers import Adam



class   __lowercase    (			tf.keras.optimizers.schedules.LearningRateSchedule     ):




			"""simple docstring"""







			def __init__(			self  :					List[Any]       ,						lowerCAmelCase__  :					float       ,						lowerCAmelCase__  :					Callable       ,						lowerCAmelCase__  :					int       ,						lowerCAmelCase__  :					float = 1.0       ,						lowerCAmelCase__  :					str = None       ,						):
									super().__init__()
									SCREAMING_SNAKE_CASE_:			str  		=	initial_learning_rate
									SCREAMING_SNAKE_CASE_:			Dict  		=	warmup_steps
									SCREAMING_SNAKE_CASE_:			Any  		=	power
									SCREAMING_SNAKE_CASE_:			int  		=	decay_schedule_fn
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	name



			def __call__(			self  :					Optional[Any]       ,						lowerCAmelCase__  :					Any):
									with tf.name_scope(self.name or "WarmUp") as name:
															# Implements polynomial warmup. i.e., if global_step < warmup_steps, the
															# learning rate will be `global_step/num_warmup_steps * init_lr`.
															SCREAMING_SNAKE_CASE_:			Any  		=	tf.cast(lowerCAmelCase__       ,						tf.floataa)
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	tf.cast(self.warmup_steps       ,						tf.floataa)
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	global_step_float / warmup_steps_float
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	self.initial_learning_rate * tf.math.pow(lowerCAmelCase__       ,						self.power)
															return tf.cond(
															    global_step_float < warmup_steps_float       ,						lambda: warmup_learning_rate       ,						lambda: self.decay_schedule_fn(step - self.warmup_steps)       ,						name=lowerCAmelCase__       ,						)




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									return {
									    "initial_learning_rate": self.initial_learning_rate,
									    "decay_schedule_fn": self.decay_schedule_fn,
									    "warmup_steps": self.warmup_steps,
									    "power": self.power,
									    "name": self.name,
									}







def       A_				(   _UpperCAmelCase    ,     _UpperCAmelCase    ,     _UpperCAmelCase    ,     _UpperCAmelCase = 0.0    ,     _UpperCAmelCase = 0.9    ,     _UpperCAmelCase = 0.9_9_9    ,     _UpperCAmelCase = 1e-8    ,     _UpperCAmelCase = None    ,     _UpperCAmelCase = None    ,     _UpperCAmelCase = 0.0    ,     _UpperCAmelCase = 1.0    ,     _UpperCAmelCase = None    ,     ):
						SCREAMING_SNAKE_CASE_:			Optional[int]  		=	tf.keras.optimizers.schedules.PolynomialDecay(
						    initial_learning_rate=_UpperCAmelCase    ,     decay_steps=num_train_steps - num_warmup_steps    ,     end_learning_rate=init_lr * min_lr_ratio    ,     power=_UpperCAmelCase    ,     )
						if num_warmup_steps:
												SCREAMING_SNAKE_CASE_:			Tuple  		=	WarmUp(
												    initial_learning_rate=_UpperCAmelCase    ,     decay_schedule_fn=_UpperCAmelCase    ,     warmup_steps=_UpperCAmelCase    ,     )
						if weight_decay_rate > 0.0:
												SCREAMING_SNAKE_CASE_:			List[str]  		=	AdamWeightDecay(
												    learning_rate=_UpperCAmelCase    ,     weight_decay_rate=_UpperCAmelCase    ,     beta_a=_UpperCAmelCase    ,     beta_a=_UpperCAmelCase    ,     epsilon=_UpperCAmelCase    ,     clipnorm=_UpperCAmelCase    ,     global_clipnorm=_UpperCAmelCase    ,     exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]    ,     include_in_weight_decay=_UpperCAmelCase    ,     )
						else:
												SCREAMING_SNAKE_CASE_:			int  		=	tf.keras.optimizers.Adam(
												    learning_rate=_UpperCAmelCase    ,     beta_a=_UpperCAmelCase    ,     beta_a=_UpperCAmelCase    ,     epsilon=_UpperCAmelCase    ,     clipnorm=_UpperCAmelCase    ,     global_clipnorm=_UpperCAmelCase    ,     )
						# We return the optimizer and the LR scheduler in order to better track the
						# evolution of the LR independently of the optimizer.
						return optimizer, lr_schedule



class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			def __init__(			self  :					List[Any]       ,						lowerCAmelCase__  :					Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001       ,						lowerCAmelCase__  :					float = 0.9       ,						lowerCAmelCase__  :					float = 0.999       ,						lowerCAmelCase__  :					float = 1E-7       ,						lowerCAmelCase__  :					bool = False       ,						lowerCAmelCase__  :					float = 0.0       ,						lowerCAmelCase__  :					Optional[List[str]] = None       ,						lowerCAmelCase__  :					Optional[List[str]] = None       ,						lowerCAmelCase__  :					str = "AdamWeightDecay"       ,						**lowerCAmelCase__  :					int       ,						):
									super().__init__(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__       ,						**lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	weight_decay_rate
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	include_in_weight_decay
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	exclude_from_weight_decay



			@classmethod
			def 	_SCREAMING_SNAKE_CASE      (			cls  :					Dict       ,						lowerCAmelCase__  :					Dict):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	{"WarmUp": WarmUp}
									return super(lowerCAmelCase__       ,						cls).from_config(lowerCAmelCase__       ,						custom_objects=lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[str]       ,						lowerCAmelCase__  :					List[str]       ,						lowerCAmelCase__  :					List[Any]       ,						lowerCAmelCase__  :					Optional[int]):
									super(lowerCAmelCase__       ,						self)._prepare_local(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	tf.constant(
									    self.weight_decay_rate       ,						name="adam_weight_decay_rate")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]       ,						lowerCAmelCase__  :					str       ,						lowerCAmelCase__  :					Any       ,						lowerCAmelCase__  :					Tuple):
									SCREAMING_SNAKE_CASE_:			str  		=	self._do_use_weight_decay(var.name)
									if do_decay:
															return var.assign_sub(
															    learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["weight_decay_rate"]       ,						use_locking=self._use_locking       ,						)
									return tf.no_op()



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Dict       ,						lowerCAmelCase__  :					Optional[int]       ,						lowerCAmelCase__  :					Optional[Any]=None       ,						**lowerCAmelCase__  :					List[str]):
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Any  		=	list(zip(*lowerCAmelCase__))
									return super(lowerCAmelCase__       ,						self).apply_gradients(zip(lowerCAmelCase__       ,						lowerCAmelCase__)       ,						name=lowerCAmelCase__       ,						**lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]       ,						lowerCAmelCase__  :					Any       ,						lowerCAmelCase__  :					Tuple       ,						lowerCAmelCase__  :					Tuple):
									if apply_state is None:
															return self._decayed_lr_t[var_dtype], {}

									SCREAMING_SNAKE_CASE_:			Dict  		=	apply_state or {}
									SCREAMING_SNAKE_CASE_:			List[str]  		=	apply_state.get((var_device, var_dtype))
									if coefficients is None:
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	self._fallback_apply_state(lowerCAmelCase__       ,						lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_:			Any  		=	coefficients

									return coefficients["lr_t"], {"apply_state": apply_state}



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str       ,						lowerCAmelCase__  :					List[Any]       ,						lowerCAmelCase__  :					Dict       ,						lowerCAmelCase__  :					Tuple=None):
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self._get_lr(var.device       ,						var.dtype.base_dtype       ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	self._decay_weights_op(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)
									with tf.control_dependencies([decay]):
															return super(lowerCAmelCase__       ,						self)._resource_apply_dense(lowerCAmelCase__       ,						lowerCAmelCase__       ,						**lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					List[str]       ,						lowerCAmelCase__  :					Dict       ,						lowerCAmelCase__  :					Dict       ,						lowerCAmelCase__  :					Dict=None):
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			List[str]  		=	self._get_lr(var.device       ,						var.dtype.base_dtype       ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	self._decay_weights_op(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)
									with tf.control_dependencies([decay]):
															return super(lowerCAmelCase__       ,						self)._resource_apply_sparse(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__       ,						**lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	super().get_config()
									config.update({"weight_decay_rate": self.weight_decay_rate})
									return config




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					Tuple):
									if self.weight_decay_rate == 0:
															return False

									if self._include_in_weight_decay:
															for r in self._include_in_weight_decay:
																					if re.search(lowerCAmelCase__       ,						lowerCAmelCase__) is not None:
																											return True

									if self._exclude_from_weight_decay:
															for r in self._exclude_from_weight_decay:
																					if re.search(lowerCAmelCase__       ,						lowerCAmelCase__) is not None:
																											return False
									return True







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			def __init__(			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			Any  		=	[]
									SCREAMING_SNAKE_CASE_:			Any  		=	None



			@property
			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									if self._accum_steps is None:
															SCREAMING_SNAKE_CASE_:			Tuple  		=	tf.Variable(
															    tf.constant(0       ,						dtype=tf.intaa)       ,						trainable=lowerCAmelCase__       ,						synchronization=tf.VariableSynchronization.ON_READ       ,						aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA       ,						)

									return self._accum_steps.value()



			@property
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									if not self._gradients:
															raise ValueError("The accumulator should be called first to initialize the gradients")
									return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]



			def __call__(			self  :					str       ,						lowerCAmelCase__  :					Tuple):
									if not self._gradients:
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self.step  # Create the step variable.
															self._gradients.extend(
															    [
															        tf.Variable(
															            tf.zeros_like(lowerCAmelCase__)       ,						trainable=lowerCAmelCase__       ,						synchronization=tf.VariableSynchronization.ON_READ       ,						aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA       ,						)
															        if gradient is not None
															        else gradient
															        for gradient in gradients
															    ])
									if len(lowerCAmelCase__) != len(self._gradients):
															raise ValueError(F"Expected {len(self._gradients)} gradients, but got {len(lowerCAmelCase__)}")

									for accum_gradient, gradient in zip(self._gradients       ,						lowerCAmelCase__):
															if accum_gradient is not None and gradient is not None:
																					accum_gradient.assign_add(lowerCAmelCase__)

									self._accum_steps.assign_add(1)




			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									if not self._gradients:
															return
									self._accum_steps.assign(0)
									for gradient in self._gradients:
															if gradient is not None:
																					gradient.assign(tf.zeros_like(lowerCAmelCase__))






