


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


__lowerCamelCase      :List[str]	    =		[
    # 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   snake_case		(     UpperCamelCase__       :						int    )   ->      List[str]:

      '''simple docstring'''





      for pegasus_name, hf_name in PATTERNS:
            lowerCamelCase					:					List[Any]        =	k.replace(UpperCamelCase__			,				UpperCamelCase__    )
      return k




def   snake_case		(     UpperCamelCase__       :						Tuple			,				UpperCamelCase__       :						List[Any]    )   ->      PegasusForConditionalGeneration:

      '''simple docstring'''





      lowerCamelCase					:					Union[str, Any]        =	DEFAULTS.copy()
      cfg_kwargs.update(UpperCamelCase__    )
      lowerCamelCase					:					List[Any]        =	PegasusConfig(**UpperCamelCase__    )
      lowerCamelCase					:					Optional[Any]        =	PegasusForConditionalGeneration(UpperCamelCase__    )
      lowerCamelCase					:					str        =	torch_model.model.state_dict()
      lowerCamelCase					:					Any        =	{}
      for k, v in tf_weights.items():
            lowerCamelCase					:					Optional[Any]        =	rename_state_dict_key(UpperCamelCase__    )
            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					:					Dict        =	v.T
            lowerCamelCase					:					Optional[Any]        =	torch.tensor(UpperCamelCase__			,				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					:					int        =	torch.zeros_like(mapping["""shared.weight"""][cfg.pad_token_id + 1]    )
      lowerCamelCase					:					Tuple        =	mapping["""shared.weight"""]
      lowerCamelCase					:					List[str]        =	mapping["""shared.weight"""]
      lowerCamelCase					:					str        =	{k: torch.zeros_like(UpperCamelCase__    ) for k, v in sd.items() if k.endswith("""bias"""    ) and k not in mapping}
      mapping.update(**UpperCamelCase__    )
      lowerCamelCase     ,			lowerCamelCase					:					Tuple        =	torch_model.model.load_state_dict(UpperCamelCase__			,				strict=UpperCamelCase__    )
      lowerCamelCase					:					List[str]        =	[
          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   snake_case		(     UpperCamelCase__       :						Optional[int]="./ckpt/aeslc/model.ckpt-32000"    )   ->      Dict:

      '''simple docstring'''





      lowerCamelCase					:					int        =	tf.train.list_variables(UpperCamelCase__    )
      lowerCamelCase					:					Union[str, Any]        =	{}
      lowerCamelCase					:					Dict        =	["""Adafactor""", """global_step"""]
      for name, shape in tqdm(UpperCamelCase__			,				desc="""converting tf checkpoint to dict"""    ):
            lowerCamelCase					:					Optional[int]        =	any(pat in name for pat in ignore_name    )
            if skip_key:
                  continue
            lowerCamelCase					:					Any        =	tf.train.load_variable(UpperCamelCase__			,				UpperCamelCase__    )
            lowerCamelCase					:					Union[str, Any]        =	array
      return tf_weights




def   snake_case		(     UpperCamelCase__       :						int			,				UpperCamelCase__       :						str    )   ->      Union[str, Any]:

      '''simple docstring'''





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

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


if __name__ == "__main__":
    __lowerCamelCase      :str	    =		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.')
    __lowerCamelCase      :Tuple	    =		parser.parse_args()
    if args.save_dir is None:
        __lowerCamelCase      :Optional[int]	    =		Path(args.tf_ckpt_path).parent.name
        __lowerCamelCase      :Union[str, Any]	    =		os.path.join('pegasus', dataset)
    convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)








"""simple docstring"""


import os




def   snake_case		(     )   ->      Optional[Any]:
      with open(os.path.dirname(UpperCamelCase__    ) + """/grid.txt"""    ) as f:
            lowerCamelCase					:					int        =	[]  # noqa: E741
            for _ in range(20    ):
                  l.append([int(UpperCamelCase__    ) for x in f.readline().split()]    )

            lowerCamelCase					:					Union[str, Any]        =	0

            # right
            for i in range(20    ):
                  for j in range(17    ):
                        lowerCamelCase					:					Dict        =	l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3]
                        if temp > maximum:
                              lowerCamelCase					:					Tuple        =	temp

        # down
            for i in range(17    ):
                  for j in range(20    ):
                        lowerCamelCase					:					Any        =	l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j]
                        if temp > maximum:
                              lowerCamelCase					:					Optional[Any]        =	temp

        # diagonal 1
            for i in range(17    ):
                  for j in range(17    ):
                        lowerCamelCase					:					List[Any]        =	l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3]
                        if temp > maximum:
                              lowerCamelCase					:					List[str]        =	temp

        # diagonal 2
            for i in range(17    ):
                  for j in range(3			,				20    ):
                        lowerCamelCase					:					List[str]        =	l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3]
                        if temp > maximum:
                              lowerCamelCase					:					List[Any]        =	temp
            return maximum


if __name__ == "__main__":
    print(solution())




