






"""simple docstring"""
import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json

def 				snake_case      (   A__						):
			UpperCAmelCase_     : List[Any]			     =					filter(lambda A__						: p.requires_grad	,model.parameters()						)
			UpperCAmelCase_     : Dict			     =					sum([np.prod(p.size()						) for p in model_parameters]						)
			return params


lowerCamelCase_					=      logging.getLogger(__name__)

def 				snake_case      (   A__	,A__						):
			if metric == "rouge2":
						UpperCAmelCase_     : Optional[int]			     =					"{val_avg_rouge2:.4f}-{step_count}"
			elif metric == "bleu":
						UpperCAmelCase_     : Optional[Any]			     =					"{val_avg_bleu:.4f}-{step_count}"
			elif metric == "em":
						UpperCAmelCase_     : List[Any]			     =					"{val_avg_em:.4f}-{step_count}"
			elif metric == "loss":
						UpperCAmelCase_     : int			     =					"{val_avg_loss:.4f}-{step_count}"
			else:
						raise NotImplementedError(
						    F"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this"""
						    " function."						)

			UpperCAmelCase_     : List[str]			     =					ModelCheckpoint(
			    dirpath=A__	,filename=A__	,monitor=F"""val_{metric}"""	,mode="max"	,save_top_k=1	,every_n_epochs=1	,)

			return checkpoint_callback

def 				snake_case      (   A__	,A__						):
			return EarlyStopping(
			    monitor=F"""val_{metric}"""	,mode="min" if "loss" in metric else "max"	,patience=A__	,verbose=A__	,)







class 			UpperCamelCase_       (pl.Callback     ):





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]	,	lowerCAmelCase_					: Dict	,	lowerCAmelCase_					: Any						)						->			Dict:
				UpperCAmelCase_     : List[str]			     =					{f"""lr_group_{i}""": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups						)}
				pl_module.logger.log_metrics(lowerCAmelCase_						)





	@rank_zero_only
	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]	,	lowerCAmelCase_					: pl.Trainer	,	lowerCAmelCase_					: pl.LightningModule	,	lowerCAmelCase_					: str	,	lowerCAmelCase_					: Optional[Any]=True						)						->			None:
				logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****"""						)
				UpperCAmelCase_     : Dict			     =					trainer.callback_metrics
				trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]}						)
				# Log results
				UpperCAmelCase_     : str			     =					Path(pl_module.hparams.output_dir						)
				if type_path == "test":
							UpperCAmelCase_     : str			     =					od / "test_results.txt"
							UpperCAmelCase_     : Optional[int]			     =					od / "test_generations.txt"
				else:
							# this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
							# If people want this it will be easy enough to add back.
							UpperCAmelCase_     : Optional[int]			     =					od / f"""{type_path}_results/{trainer.global_step:05d}.txt"""
							UpperCAmelCase_     : Optional[Any]			     =					od / f"""{type_path}_generations/{trainer.global_step:05d}.txt"""
							results_file.parent.mkdir(exist_ok=lowerCAmelCase_						)
							generations_file.parent.mkdir(exist_ok=lowerCAmelCase_						)
				with open(lowerCAmelCase_	,	"a+"						) as writer:
							for key in sorted(lowerCAmelCase_						):
										if key in ["log", "progress_bar", "preds"]:
													continue
										UpperCAmelCase_     : List[Any]			     =					metrics[key]
										if isinstance(lowerCAmelCase_	,	torch.Tensor						):
													UpperCAmelCase_     : str			     =					val.item()
										UpperCAmelCase_     : Tuple			     =					f"""{key}: {val:.6f}\n"""
										writer.write(lowerCAmelCase_						)

				if not save_generations:
							return

				if "preds" in metrics:
							UpperCAmelCase_     : Union[str, Any]			     =					"\n".join(metrics["preds"]						)
							generations_file.open("w+"						).write(lowerCAmelCase_						)





	@rank_zero_only
	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]	,	lowerCAmelCase_					: List[Any]	,	lowerCAmelCase_					: Optional[Any]						)						->			Tuple:
				try:
							UpperCAmelCase_     : Tuple			     =					pl_module.model.model.num_parameters()
				except AttributeError:
							UpperCAmelCase_     : Optional[int]			     =					pl_module.model.num_parameters()

				UpperCAmelCase_     : Dict			     =					count_trainable_parameters(lowerCAmelCase_						)
				# mp stands for million parameters
				trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6}						)





	@rank_zero_only
	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]	,	lowerCAmelCase_					: pl.Trainer	,	lowerCAmelCase_					: pl.LightningModule						)						->			Optional[Any]:
				save_json(pl_module.metrics	,	pl_module.metrics_save_path						)
				return self._write_logs(lowerCAmelCase_	,	lowerCAmelCase_	,	"test"						)





	@rank_zero_only
	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[Any]	,	lowerCAmelCase_					: pl.Trainer	,	lowerCAmelCase_					: Dict						)						->			List[str]:
				save_json(pl_module.metrics	,	pl_module.metrics_save_path						)
				# Uncommenting this will save val generations
				# return self._write_logs(trainer, pl_module, "valid")











"""simple docstring"""
import os

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

						UpperCAmelCase_     : Any			     =					0

						# right
						for i in range(20						):
									for j in range(17						):
												UpperCAmelCase_     : Union[str, Any]			     =					l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3]
												if temp > maximum:
															UpperCAmelCase_     : Any			     =					temp

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

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

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


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



