


"""simple docstring"""



import argparse
import os
from pathlib import Path
from typing import Dict

import tensorflow as tf
import torch
from tqdm import tqdm

from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer
from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params


lowercase_							=							[
    # replace left string with right string to get the relevant state_dict key (identical state dict to bart)
    ['memory_attention', 'encoder_attn'],
    ['attention', 'attn'],
    ['/', '.'],
    ['.LayerNorm.gamma', '_layer_norm.weight'],
    ['.LayerNorm.beta', '_layer_norm.bias'],
    ['r.layer_', 'r.layers.'],
    ['output_proj', 'out_proj'],
    ['ffn.dense_1.', 'fc2.'],
    ['ffn.dense.', 'fc1.'],
    ['ffn_layer_norm', 'final_layer_norm'],
    ['kernel', 'weight'],
    ['encoder_layer_norm.', 'encoder.layer_norm.'],
    ['decoder_layer_norm.', 'decoder.layer_norm.'],
    ['embeddings.weights', 'shared.weight'],
]
def      UpperCAmelCase     (       _lowercase :   Tuple	)						-> Optional[int]:


	"""simple docstring"""




	for pegasus_name, hf_name in PATTERNS:
		lowerCAmelCase_      							=			k.replace(_lowercase			,   _lowercase	)
	return k
def      UpperCAmelCase     (       _lowercase :   dict			,   _lowercase :   dict	)						-> PegasusForConditionalGeneration:


	"""simple docstring"""




	lowerCAmelCase_      							=			DEFAULTS.copy()
	cfg_kwargs.update(_lowercase	)
	lowerCAmelCase_      							=			PegasusConfig(**_lowercase	)
	lowerCAmelCase_      							=			PegasusForConditionalGeneration(_lowercase	)
	lowerCAmelCase_      							=			torch_model.model.state_dict()
	lowerCAmelCase_      							=			{}
	for k, v in tf_weights.items():
		lowerCAmelCase_      							=			rename_state_dict_key(_lowercase	)
		if new_k not in sd:
			raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})"""	)

		if "dense" in k or "proj" in new_k:
			lowerCAmelCase_      							=			v.T
		lowerCAmelCase_      							=			torch.tensor(_lowercase			,   dtype=sd[new_k].dtype	)
		assert v.shape == sd[new_k].shape, F"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}"""
	# make sure embedding.padding_idx is respected
	lowerCAmelCase_      							=			torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1]	)
	lowerCAmelCase_      							=			mapping['''shared.weight''']
	lowerCAmelCase_      							=			mapping['''shared.weight''']
	lowerCAmelCase_      							=			{k: torch.zeros_like(_lowercase	) for k, v in sd.items() if k.endswith('''bias'''	) and k not in mapping}
	mapping.update(**_lowercase	)
	lowerCAmelCase_							,	lowerCAmelCase_      							=			torch_model.model.load_state_dict(_lowercase			,   strict=_lowercase	)
	lowerCAmelCase_      							=			[
	    k for k in missing if k not in ['''encoder.embed_positions.weight''', '''decoder.embed_positions.weight''']
	]
	assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}"""
	assert extra == [], F"""no matches found for the following tf keys {extra}"""
	return torch_model
def      UpperCAmelCase     (       _lowercase :   Tuple="./ckpt/aeslc/model.ckpt-32000"	)						-> Dict:


	"""simple docstring"""




	lowerCAmelCase_      							=			tf.train.list_variables(_lowercase	)
	lowerCAmelCase_      							=			{}
	lowerCAmelCase_      							=			['''Adafactor''', '''global_step''']
	for name, shape in tqdm(_lowercase			,   desc='''converting tf checkpoint to dict'''	):
		lowerCAmelCase_      							=			any(pat in name for pat in ignore_name	)
		if skip_key:
			continue
		lowerCAmelCase_      							=			tf.train.load_variable(_lowercase			,   _lowercase	)
		lowerCAmelCase_      							=			array
	return tf_weights
def      UpperCAmelCase     (       _lowercase :   str			,   _lowercase :   str	)						-> int:


	"""simple docstring"""




	lowerCAmelCase_      							=			Path(_lowercase	).parent.name
	lowerCAmelCase_      							=			task_specific_params[F"""summarization_{dataset}"""]['''max_position_embeddings''']
	lowerCAmelCase_      							=			PegasusTokenizer.from_pretrained('''sshleifer/pegasus'''			,   model_max_length=_lowercase	)
	assert tok.model_max_length == desired_max_model_length
	tok.save_pretrained(_lowercase	)

	# convert model
	lowerCAmelCase_      							=			get_tf_weights_as_numpy(_lowercase	)
	lowerCAmelCase_      							=			task_specific_params[F"""summarization_{dataset}"""]
	if dataset == "large":
		lowerCAmelCase_      							=			task_specific_params
	lowerCAmelCase_      							=			convert_pegasus(_lowercase			,   _lowercase	)
	torch_model.save_pretrained(_lowercase	)
	lowerCAmelCase_      							=			torch_model.state_dict()
	sd.pop('''model.decoder.embed_positions.weight'''	)
	sd.pop('''model.encoder.embed_positions.weight'''	)
	torch.save(_lowercase			,   Path(_lowercase	) / '''pytorch_model.bin'''	)


if __name__ == "__main__":
		lowercase_							=							argparse.ArgumentParser()
		# Required parameters
		parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables')
		parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.')
		lowercase_							=							parser.parse_args()
		if args.save_dir is None:
				lowercase_							=							Path(args.tf_ckpt_path).parent.name
				lowercase_							=							os.path.join('pegasus', dataset)
		convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)



"""simple docstring"""



import math
from datetime import datetime, timedelta
def      UpperCAmelCase     (       _lowercase :   int	)						-> datetime:


	"""simple docstring"""




	lowerCAmelCase_      							=			year % 1_9
	lowerCAmelCase_      							=			year % 4
	lowerCAmelCase_      							=			year % 7
	lowerCAmelCase_      							=			math.floor(year / 1_0_0	)
	lowerCAmelCase_      							=			math.floor((1_3 + 8 * leap_day_inhibits) / 2_5	)
	lowerCAmelCase_      							=			leap_day_inhibits / 4
	lowerCAmelCase_      							=			(
	    1_5 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number
	) % 3_0
	lowerCAmelCase_      							=			(4 + leap_day_inhibits - leap_day_reinstall_number) % 7

	# days to be added to March 21
	lowerCAmelCase_      							=			(1_9 * metonic_cycle + secular_moon_shift) % 3_0

	# PHM -> Paschal Full Moon
	lowerCAmelCase_      							=			(
	    2 * julian_leap_year
	    + 4 * non_leap_year
	    + 6 * days_to_add
	    + century_starting_point
	) % 7

	if days_to_add == 2_9 and days_from_phm_to_sunday == 6:
		return datetime(_lowercase			,   4			,   1_9	)
	elif days_to_add == 2_8 and days_from_phm_to_sunday == 6:
		return datetime(_lowercase			,   4			,   1_8	)
	else:
		return datetime(_lowercase			,   3			,   2_2	) + timedelta(
		    days=int(days_to_add + days_from_phm_to_sunday	)	)


if __name__ == "__main__":
		for year in (19_94, 20_00, 20_10, 20_21, 20_23):
				lowercase_							=							'will be' if year > datetime.now().year else 'was'
				print(f"""Easter in {year} {tense} {gauss_easter(year)}""")