


import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple

import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader

from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
    ROUGE_KEYS,
    LegacySeqaSeqDataset,
    SeqaSeqDataset,
    assert_all_frozen,
    calculate_bleu,
    calculate_rouge,
    check_output_dir,
    flatten_list,
    freeze_embeds,
    freeze_params,
    get_git_info,
    label_smoothed_nll_loss,
    lmap,
    pickle_save,
    save_git_info,
    save_json,
    use_task_specific_params,
)


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train  # noqa


__snake_case            =   logging.getLogger(__name__)




class    UpperCAmelCase					(       __snake_case    ):
			lowercase						= """summarization"""
			lowercase						= ["""loss"""]
			lowercase						= ROUGE_KEYS
			lowercase						= """rouge2"""




			def __init__(						self							:		Optional[Any]       ,       __magic_name__							:		Tuple       ,       **__magic_name__							:		List[Any]						):







						"""simple docstring"""







						if hparams.sortish_sampler and hparams.gpus > 1:
									UpperCamelCase         =					False
						elif hparams.max_tokens_per_batch is not None:
									if hparams.gpus > 1:
												raise NotImplementedError("""Dynamic Batch size does not work for multi-gpu training"""						)
									if hparams.sortish_sampler:
												raise ValueError("""--sortish_sampler and --max_tokens_per_batch may not be used simultaneously"""						)

						super().__init__(__magic_name__       ,       num_labels=__magic_name__       ,       mode=self.mode       ,       **__magic_name__						)
						use_task_specific_params(self.model       ,       """summarization"""						)
						save_git_info(self.hparams.output_dir						)
						UpperCamelCase         =					Path(self.output_dir						) / """metrics.json"""
						UpperCamelCase         =					Path(self.output_dir						) / """hparams.pkl"""
						pickle_save(self.hparams       ,       self.hparams_save_path						)
						UpperCamelCase         =					0
						UpperCamelCase         =					defaultdict(__magic_name__						)
						UpperCamelCase         =					self.config.model_type
						UpperCamelCase         =					self.config.tgt_vocab_size if self.model_type == """fsmt""" else self.config.vocab_size

						UpperCamelCase         =					{
						    "data_dir": self.hparams.data_dir,
						    "max_source_length": self.hparams.max_source_length,
						    "prefix": self.model.config.prefix or "",
						}
						UpperCamelCase         =					{
						    """train""": self.hparams.n_train,
						    """val""": self.hparams.n_val,
						    """test""": self.hparams.n_test,
						}
						UpperCamelCase         =					{k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

						UpperCamelCase         =					{
						    """train""": self.hparams.max_target_length,
						    """val""": self.hparams.val_max_target_length,
						    """test""": self.hparams.test_max_target_length,
						}
						assert self.target_lens["train"] <= self.target_lens["val"], F'target_lens: {self.target_lens}'
						assert self.target_lens["train"] <= self.target_lens["test"], F'target_lens: {self.target_lens}'
						if self.hparams.freeze_embeds:
									freeze_embeds(self.model						)
						if self.hparams.freeze_encoder:
									freeze_params(self.model.get_encoder()						)
									assert_all_frozen(self.model.get_encoder()						)

						UpperCamelCase         =					get_git_info()["""repo_sha"""]
						UpperCamelCase         =					hparams.num_workers
						UpperCamelCase         =					None  # default to config
						if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer       ,       __magic_name__						):
									UpperCamelCase         =					self.tokenizer.lang_code_to_id[hparams.tgt_lang]
									UpperCamelCase         =					self.decoder_start_token_id
						UpperCamelCase         =					(
						    SeqaSeqDataset if hasattr(self.tokenizer       ,       """prepare_seq2seq_batch"""						) else LegacySeqaSeqDataset
						)
						UpperCamelCase         =					False
						UpperCamelCase         =					self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
						if self.hparams.eval_max_gen_length is not None:
									UpperCamelCase         =					self.hparams.eval_max_gen_length
						else:
									UpperCamelCase         =					self.model.config.max_length
						UpperCamelCase         =					self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric




			def   lowerCamelCase_					(						self							:		Optional[int]       ,       __magic_name__							:		Dict[str, torch.Tensor]						):







						"""simple docstring"""







						UpperCamelCase         =					{
						    k: self.tokenizer.batch_decode(v.tolist()						) if """mask""" not in k else v.shape for k, v in batch.items()
						}
						save_json(__magic_name__       ,       Path(self.output_dir						) / """text_batch.json"""						)
						save_json({k: v.tolist() for k, v in batch.items()}       ,       Path(self.output_dir						) / """tok_batch.json"""						)

						UpperCamelCase         =					True
						return readable_batch




			def   lowerCamelCase_					(						self							:		List[str]       ,       __magic_name__							:		int       ,       **__magic_name__							:		Tuple						):







						"""simple docstring"""







						return self.model(__magic_name__       ,       **__magic_name__						)




			def   lowerCamelCase_					(						self							:		str       ,       __magic_name__							:		List[int]						):







						"""simple docstring"""







						UpperCamelCase         =					self.tokenizer.batch_decode(
						    __magic_name__       ,       skip_special_tokens=__magic_name__       ,       clean_up_tokenization_spaces=__magic_name__						)
						return lmap(str.strip       ,       __magic_name__						)




			def   lowerCamelCase_					(						self							:		Tuple       ,       __magic_name__							:		dict						):







						"""simple docstring"""







						UpperCamelCase         =					self.tokenizer.pad_token_id
						UpperCamelCase  ,  UpperCamelCase         =					batch["""input_ids"""], batch["""attention_mask"""]
						UpperCamelCase         =					batch["""labels"""]
						if isinstance(self.model       ,       __magic_name__						):
									UpperCamelCase         =					self.model._shift_right(__magic_name__						)
						else:
									UpperCamelCase         =					shift_tokens_right(__magic_name__       ,       __magic_name__						)
						if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
									UpperCamelCase         =					decoder_input_ids
									self.save_readable_batch(__magic_name__						)

						UpperCamelCase         =					self(__magic_name__       ,       attention_mask=__magic_name__       ,       decoder_input_ids=__magic_name__       ,       use_cache=__magic_name__						)
						UpperCamelCase         =					outputs["""logits"""]
						if self.hparams.label_smoothing == 0:
									# Same behavior as modeling_bart.py, besides ignoring pad_token_id
									UpperCamelCase         =					nn.CrossEntropyLoss(ignore_index=__magic_name__						)

									assert lm_logits.shape[-1] == self.vocab_size
									UpperCamelCase         =					ce_loss_fct(lm_logits.view(-1       ,       lm_logits.shape[-1]						)       ,       tgt_ids.view(-1						)						)
						else:
									UpperCamelCase         =					nn.functional.log_softmax(__magic_name__       ,       dim=-1						)
									UpperCamelCase  ,  UpperCamelCase         =					label_smoothed_nll_loss(
									    __magic_name__       ,       __magic_name__       ,       self.hparams.label_smoothing       ,       ignore_index=__magic_name__						)
						return (loss,)




			@property
			def   lowerCamelCase_					(						self							:		Optional[int]						):







						"""simple docstring"""







						return self.tokenizer.pad_token_id




			def   lowerCamelCase_					(						self							:		Optional[int]       ,       __magic_name__							:		Any       ,       __magic_name__							:		Optional[Any]						):







						"""simple docstring"""







						UpperCamelCase         =					self._step(__magic_name__						)

						UpperCamelCase         =					dict(zip(self.loss_names       ,       __magic_name__						)						)
						# tokens per batch
						UpperCamelCase         =					batch["""input_ids"""].ne(self.pad						).sum() + batch["""labels"""].ne(self.pad						).sum()
						UpperCamelCase         =					batch["""input_ids"""].shape[0]
						UpperCamelCase         =					batch["""input_ids"""].eq(self.pad						).sum()
						UpperCamelCase         =					batch["""input_ids"""].eq(self.pad						).float().mean()
						# TODO(SS): make a wandb summary metric for this
						return {"loss": loss_tensors[0], "log": logs}




			def   lowerCamelCase_					(						self							:		Union[str, Any]       ,       __magic_name__							:		str       ,       __magic_name__							:		Optional[Any]						):







						"""simple docstring"""







						return self._generative_step(__magic_name__						)




			def   lowerCamelCase_					(						self							:		str       ,       __magic_name__							:		Any       ,       __magic_name__							:		List[str]="val"						):







						"""simple docstring"""







						self.step_count += 1
						UpperCamelCase         =					{k: torch.stack([x[k] for x in outputs]						).mean() for k in self.loss_names}
						UpperCamelCase         =					losses["""loss"""]
						UpperCamelCase         =					{
						    k: np.array([x[k] for x in outputs]						).mean() for k in self.metric_names + ["""gen_time""", """gen_len"""]
						}
						UpperCamelCase         =					(
						    generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
						)
						UpperCamelCase         =					torch.tensor(__magic_name__						).type_as(__magic_name__						)
						generative_metrics.update({k: v.item() for k, v in losses.items()}						)
						losses.update(__magic_name__						)
						UpperCamelCase         =					{F'{prefix}_avg_{k}': x for k, x in losses.items()}
						UpperCamelCase         =					self.step_count
						self.metrics[prefix].append(__magic_name__						)  # callback writes this to self.metrics_save_path
						UpperCamelCase         =					flatten_list([x["""preds"""] for x in outputs]						)
						return {
						    "log": all_metrics,
						    "preds": preds,
						    F'{prefix}_loss': loss,
						    F'{prefix}_{self.val_metric}': metric_tensor,
						}




			def   lowerCamelCase_					(						self							:		int       ,       __magic_name__							:		Union[str, Any]       ,       __magic_name__							:		Tuple						):







						"""simple docstring"""







						return calculate_rouge(__magic_name__       ,       __magic_name__						)




			def   lowerCamelCase_					(						self							:		List[Any]       ,       __magic_name__							:		dict						):







						"""simple docstring"""







						UpperCamelCase         =					time.time()

						# parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
						UpperCamelCase         =					self.model.generate(
						    batch["""input_ids"""]       ,       attention_mask=batch["""attention_mask"""]       ,       use_cache=__magic_name__       ,       decoder_start_token_id=self.decoder_start_token_id       ,       num_beams=self.eval_beams       ,       max_length=self.eval_max_length       ,       )
						UpperCamelCase         =					(time.time() - ta) / batch["""input_ids"""].shape[0]
						UpperCamelCase         =					self.ids_to_clean_text(__magic_name__						)
						UpperCamelCase         =					self.ids_to_clean_text(batch["""labels"""]						)
						UpperCamelCase         =					self._step(__magic_name__						)
						UpperCamelCase         =					dict(zip(self.loss_names       ,       __magic_name__						)						)
						UpperCamelCase         =					self.calc_generative_metrics(__magic_name__       ,       __magic_name__						)
						UpperCamelCase         =					np.mean(lmap(__magic_name__       ,       __magic_name__						)						)
						base_metrics.update(gen_time=__magic_name__       ,       gen_len=__magic_name__       ,       preds=__magic_name__       ,       target=__magic_name__       ,       **__magic_name__						)
						return base_metrics




			def   lowerCamelCase_					(						self							:		List[Any]       ,       __magic_name__							:		Optional[int]       ,       __magic_name__							:		List[str]						):







						"""simple docstring"""







						return self._generative_step(__magic_name__						)




			def   lowerCamelCase_					(						self							:		Optional[Any]       ,       __magic_name__							:		Optional[int]						):







						"""simple docstring"""







						return self.validation_epoch_end(__magic_name__       ,       prefix="""test"""						)




			def   lowerCamelCase_					(						self							:		str       ,       __magic_name__							:		List[str]						):







						"""simple docstring"""







						UpperCamelCase         =					self.n_obs[type_path]
						UpperCamelCase         =					self.target_lens[type_path]
						UpperCamelCase         =					self.dataset_class(
						    self.tokenizer       ,       type_path=__magic_name__       ,       n_obs=__magic_name__       ,       max_target_length=__magic_name__       ,       **self.dataset_kwargs       ,       )
						return dataset




			def   lowerCamelCase_					(						self							:		Union[str, Any]       ,       __magic_name__							:		str       ,       __magic_name__							:		int       ,       __magic_name__							:		bool = False						):







						"""simple docstring"""







						UpperCamelCase         =					self.get_dataset(__magic_name__						)

						if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
									UpperCamelCase         =					dataset.make_sortish_sampler(__magic_name__       ,       distributed=self.hparams.gpus > 1						)
									return DataLoader(
									    __magic_name__       ,       batch_size=__magic_name__       ,       collate_fn=dataset.collate_fn       ,       shuffle=__magic_name__       ,       num_workers=self.num_workers       ,       sampler=__magic_name__       ,       )

						elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
									UpperCamelCase         =					dataset.make_dynamic_sampler(
									    self.hparams.max_tokens_per_batch       ,       distributed=self.hparams.gpus > 1						)
									return DataLoader(
									    __magic_name__       ,       batch_sampler=__magic_name__       ,       collate_fn=dataset.collate_fn       ,       num_workers=self.num_workers       ,       )
						else:
									return DataLoader(
									    __magic_name__       ,       batch_size=__magic_name__       ,       collate_fn=dataset.collate_fn       ,       shuffle=__magic_name__       ,       num_workers=self.num_workers       ,       sampler=__magic_name__       ,       )




			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						UpperCamelCase         =					self.get_dataloader("""train"""       ,       batch_size=self.hparams.train_batch_size       ,       shuffle=__magic_name__						)
						return dataloader




			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						return self.get_dataloader("""val"""       ,       batch_size=self.hparams.eval_batch_size						)




			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						return self.get_dataloader("""test"""       ,       batch_size=self.hparams.eval_batch_size						)





			@staticmethod
			def   lowerCamelCase_					(						__magic_name__							:		str       ,       __magic_name__							:		Optional[Any]						):







						"""simple docstring"""







						BaseTransformer.add_model_specific_args(__magic_name__       ,       __magic_name__						)
						add_generic_args(__magic_name__       ,       __magic_name__						)
						parser.add_argument(
						    """--max_source_length"""       ,       default=1_0_2_4       ,       type=__magic_name__       ,       help=(
						        """The maximum total input sequence length after tokenization. Sequences longer """
						        """than this will be truncated, sequences shorter will be padded."""
						    )       ,       )
						parser.add_argument(
						    """--max_target_length"""       ,       default=5_6       ,       type=__magic_name__       ,       help=(
						        """The maximum total input sequence length after tokenization. Sequences longer """
						        """than this will be truncated, sequences shorter will be padded."""
						    )       ,       )
						parser.add_argument(
						    """--val_max_target_length"""       ,       default=1_4_2       ,       type=__magic_name__       ,       help=(
						        """The maximum total input sequence length after tokenization. Sequences longer """
						        """than this will be truncated, sequences shorter will be padded."""
						    )       ,       )
						parser.add_argument(
						    """--test_max_target_length"""       ,       default=1_4_2       ,       type=__magic_name__       ,       help=(
						        """The maximum total input sequence length after tokenization. Sequences longer """
						        """than this will be truncated, sequences shorter will be padded."""
						    )       ,       )
						parser.add_argument("""--freeze_encoder"""       ,       action="""store_true"""						)
						parser.add_argument("""--freeze_embeds"""       ,       action="""store_true"""						)
						parser.add_argument("""--sortish_sampler"""       ,       action="""store_true"""       ,       default=__magic_name__						)
						parser.add_argument("""--overwrite_output_dir"""       ,       action="""store_true"""       ,       default=__magic_name__						)
						parser.add_argument("""--max_tokens_per_batch"""       ,       type=__magic_name__       ,       default=__magic_name__						)
						parser.add_argument("""--logger_name"""       ,       type=__magic_name__       ,       choices=["""default""", """wandb""", """wandb_shared"""]       ,       default="""default"""						)
						parser.add_argument("""--n_train"""       ,       type=__magic_name__       ,       default=-1       ,       required=__magic_name__       ,       help="""# examples. -1 means use all."""						)
						parser.add_argument("""--n_val"""       ,       type=__magic_name__       ,       default=5_0_0       ,       required=__magic_name__       ,       help="""# examples. -1 means use all."""						)
						parser.add_argument("""--n_test"""       ,       type=__magic_name__       ,       default=-1       ,       required=__magic_name__       ,       help="""# examples. -1 means use all."""						)
						parser.add_argument(
						    """--task"""       ,       type=__magic_name__       ,       default="""summarization"""       ,       required=__magic_name__       ,       help="""# examples. -1 means use all."""						)
						parser.add_argument("""--label_smoothing"""       ,       type=__magic_name__       ,       default=0.0       ,       required=__magic_name__						)
						parser.add_argument("""--src_lang"""       ,       type=__magic_name__       ,       default=""""""       ,       required=__magic_name__						)
						parser.add_argument("""--tgt_lang"""       ,       type=__magic_name__       ,       default=""""""       ,       required=__magic_name__						)
						parser.add_argument("""--eval_beams"""       ,       type=__magic_name__       ,       default=__magic_name__       ,       required=__magic_name__						)
						parser.add_argument(
						    """--val_metric"""       ,       type=__magic_name__       ,       default=__magic_name__       ,       required=__magic_name__       ,       choices=["""bleu""", """rouge2""", """loss""", None]						)
						parser.add_argument("""--eval_max_gen_length"""       ,       type=__magic_name__       ,       default=__magic_name__       ,       help="""never generate more than n tokens"""						)
						parser.add_argument("""--save_top_k"""       ,       type=__magic_name__       ,       default=1       ,       required=__magic_name__       ,       help="""How many checkpoints to save"""						)
						parser.add_argument(
						    """--early_stopping_patience"""       ,       type=__magic_name__       ,       default=-1       ,       required=__magic_name__       ,       help=(
						        """-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So"""
						        """ val_check_interval will effect it."""
						    )       ,       )
						return parser




class    UpperCAmelCase					(       __snake_case    ):
			lowercase						= """translation"""
			lowercase						= ["""loss"""]
			lowercase						= ["""bleu"""]
			lowercase						= """bleu"""




			def __init__(						self							:		Any       ,       __magic_name__							:		Optional[Any]       ,       **__magic_name__							:		List[Any]						):







						"""simple docstring"""







						super().__init__(__magic_name__       ,       **__magic_name__						)
						UpperCamelCase         =					hparams.src_lang
						UpperCamelCase         =					hparams.tgt_lang





			def   lowerCamelCase_					(						self							:		List[Any]       ,       __magic_name__							:		Optional[Any]       ,       __magic_name__							:		Optional[Any]						):







						"""simple docstring"""







						return calculate_bleu(__magic_name__       ,       __magic_name__						)






def 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		Tuple       ,  SCREAMING_SNAKE_CASE_   :		Any=None	):





			"""simple docstring"""




			Path(args.output_dir	).mkdir(exist_ok=SCREAMING_SNAKE_CASE_	)
			check_output_dir(SCREAMING_SNAKE_CASE_       ,  expected_items=3	)

			if model is None:
						if "summarization" in args.task:
									UpperCamelCase         =					SummarizationModule(SCREAMING_SNAKE_CASE_	)
						else:
									UpperCamelCase         =					TranslationModule(SCREAMING_SNAKE_CASE_	)
			UpperCamelCase         =					Path(args.data_dir	).name
			if (
			    args.logger_name == "default"
			    or args.fast_dev_run
			    or str(args.output_dir	).startswith("""/tmp"""	)
			    or str(args.output_dir	).startswith("""/var"""	)
			):
						UpperCamelCase         =					True  # don't pollute wandb logs unnecessarily
			elif args.logger_name == "wandb":
						from pytorch_lightning.loggers import WandbLogger

						UpperCamelCase         =					os.environ.get("""WANDB_PROJECT"""       ,  SCREAMING_SNAKE_CASE_	)
						UpperCamelCase         =					WandbLogger(name=model.output_dir.name       ,  project=SCREAMING_SNAKE_CASE_	)

			elif args.logger_name == "wandb_shared":
						from pytorch_lightning.loggers import WandbLogger

						UpperCamelCase         =					WandbLogger(name=model.output_dir.name       ,  project=f'hf_{dataset}'	)

			if args.early_stopping_patience >= 0:
						UpperCamelCase         =					get_early_stopping_callback(model.val_metric       ,  args.early_stopping_patience	)
			else:
						UpperCamelCase         =					False

			UpperCamelCase         =					args.val_metric == """loss"""
			UpperCamelCase         =					generic_train(
			    SCREAMING_SNAKE_CASE_       ,  SCREAMING_SNAKE_CASE_       ,  logging_callback=SeqaSeqLoggingCallback()       ,  checkpoint_callback=get_checkpoint_callback(
			        args.output_dir       ,  model.val_metric       ,  args.save_top_k       ,  SCREAMING_SNAKE_CASE_	)       ,  early_stopping_callback=SCREAMING_SNAKE_CASE_       ,  logger=SCREAMING_SNAKE_CASE_       ,  )
			pickle_save(model.hparams       ,  model.output_dir / """hparams.pkl"""	)
			if not args.do_predict:
						return model

			UpperCamelCase         =					""""""
			UpperCamelCase         =					sorted(glob.glob(os.path.join(args.output_dir       ,  """*.ckpt"""	)       ,  recursive=SCREAMING_SNAKE_CASE_	)	)
			if checkpoints:
						UpperCamelCase         =					checkpoints[-1]
						UpperCamelCase         =					checkpoints[-1]
			trainer.logger.log_hyperparams(model.hparams	)

			# test() without a model tests using the best checkpoint automatically
			trainer.test()
			return model


if __name__ == "__main__":
			__snake_case            =   argparse.ArgumentParser()
			__snake_case            =   pl.Trainer.add_argparse_args(parser)
			__snake_case            =   SummarizationModule.add_model_specific_args(parser, os.getcwd())

			__snake_case            =   parser.parse_args()

			main(args)








import unittest

from transformers import BertGenerationConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import BertGenerationDecoder, BertGenerationEncoder




class    UpperCAmelCase					:




			def __init__(						self							:		Union[str, Any]       ,       __magic_name__							:		List[Any]       ,       __magic_name__							:		str=1_3       ,       __magic_name__							:		str=7       ,       __magic_name__							:		Optional[Any]=True       ,       __magic_name__							:		Optional[Any]=True       ,       __magic_name__							:		Tuple=9_9       ,       __magic_name__							:		List[str]=3_2       ,       __magic_name__							:		List[str]=5       ,       __magic_name__							:		int=4       ,       __magic_name__							:		Union[str, Any]=3_7       ,       __magic_name__							:		List[Any]="gelu"       ,       __magic_name__							:		Any=0.1       ,       __magic_name__							:		Union[str, Any]=0.1       ,       __magic_name__							:		List[Any]=5_0       ,       __magic_name__							:		Tuple=0.02       ,       __magic_name__							:		Optional[int]=True       ,       __magic_name__							:		Optional[Any]=None       ,       ):







						"""simple docstring"""







						UpperCamelCase         =					parent
						UpperCamelCase         =					batch_size
						UpperCamelCase         =					seq_length
						UpperCamelCase         =					is_training
						UpperCamelCase         =					use_input_mask
						UpperCamelCase         =					vocab_size
						UpperCamelCase         =					hidden_size
						UpperCamelCase         =					num_hidden_layers
						UpperCamelCase         =					num_attention_heads
						UpperCamelCase         =					intermediate_size
						UpperCamelCase         =					hidden_act
						UpperCamelCase         =					hidden_dropout_prob
						UpperCamelCase         =					attention_probs_dropout_prob
						UpperCamelCase         =					max_position_embeddings
						UpperCamelCase         =					initializer_range
						UpperCamelCase         =					use_labels
						UpperCamelCase         =					scope




			def   lowerCamelCase_					(						self							:		Optional[int]						):







						"""simple docstring"""







						UpperCamelCase         =					ids_tensor([self.batch_size, self.seq_length]       ,       self.vocab_size						)

						UpperCamelCase         =					None
						if self.use_input_mask:
									UpperCamelCase         =					random_attention_mask([self.batch_size, self.seq_length]						)

						if self.use_labels:
									UpperCamelCase         =					ids_tensor([self.batch_size, self.seq_length]       ,       self.vocab_size						)

						UpperCamelCase         =					self.get_config()

						return config, input_ids, input_mask, token_labels




			def   lowerCamelCase_					(						self							:		str						):







						"""simple docstring"""







						return BertGenerationConfig(
						    vocab_size=self.vocab_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       ,       max_position_embeddings=self.max_position_embeddings       ,       is_decoder=__magic_name__       ,       initializer_range=self.initializer_range       ,       )




			def   lowerCamelCase_					(						self							:		Union[str, Any]						):







						"""simple docstring"""







						(
						    (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  
						)         =					self.prepare_config_and_inputs()

						UpperCamelCase         =					True
						UpperCamelCase         =					floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
						UpperCamelCase         =					ids_tensor([self.batch_size, self.seq_length]       ,       vocab_size=2						)

						return (
						    config,
						    input_ids,
						    input_mask,
						    token_labels,
						    encoder_hidden_states,
						    encoder_attention_mask,
						)




			def   lowerCamelCase_					(						self							:		Tuple       ,       __magic_name__							:		List[Any]       ,       __magic_name__							:		Tuple       ,       __magic_name__							:		str       ,       __magic_name__							:		List[str]       ,       **__magic_name__							:		Optional[Any]       ,       ):







						"""simple docstring"""







						UpperCamelCase         =					BertGenerationEncoder(config=__magic_name__						)
						model.to(__magic_name__						)
						model.eval()
						UpperCamelCase         =					model(__magic_name__       ,       attention_mask=__magic_name__						)
						UpperCamelCase         =					model(__magic_name__						)
						self.parent.assertEqual(result.last_hidden_state.shape       ,       (self.batch_size, self.seq_length, self.hidden_size)						)




			def   lowerCamelCase_					(						self							:		Optional[int]       ,       __magic_name__							:		Dict       ,       __magic_name__							:		str       ,       __magic_name__							:		Union[str, Any]       ,       __magic_name__							:		List[str]       ,       __magic_name__							:		Optional[Any]       ,       __magic_name__							:		Tuple       ,       **__magic_name__							:		Union[str, Any]       ,       ):







						"""simple docstring"""







						UpperCamelCase         =					True
						UpperCamelCase         =					BertGenerationEncoder(config=__magic_name__						)
						model.to(__magic_name__						)
						model.eval()
						UpperCamelCase         =					model(
						    __magic_name__       ,       attention_mask=__magic_name__       ,       encoder_hidden_states=__magic_name__       ,       encoder_attention_mask=__magic_name__       ,       )
						UpperCamelCase         =					model(
						    __magic_name__       ,       attention_mask=__magic_name__       ,       encoder_hidden_states=__magic_name__       ,       )
						self.parent.assertEqual(result.last_hidden_state.shape       ,       (self.batch_size, self.seq_length, self.hidden_size)						)




			def   lowerCamelCase_					(						self							:		Optional[int]       ,       __magic_name__							:		Optional[Any]       ,       __magic_name__							:		str       ,       __magic_name__							:		List[str]       ,       __magic_name__							:		Optional[int]       ,       __magic_name__							:		str       ,       __magic_name__							:		Union[str, Any]       ,       **__magic_name__							:		Dict       ,       ):







						"""simple docstring"""







						UpperCamelCase         =					True
						UpperCamelCase         =					True
						UpperCamelCase         =					BertGenerationDecoder(config=__magic_name__						).to(__magic_name__						).eval()

						# first forward pass
						UpperCamelCase         =					model(
						    __magic_name__       ,       attention_mask=__magic_name__       ,       encoder_hidden_states=__magic_name__       ,       encoder_attention_mask=__magic_name__       ,       use_cache=__magic_name__       ,       )
						UpperCamelCase         =					outputs.past_key_values

						# create hypothetical multiple next token and extent to next_input_ids
						UpperCamelCase         =					ids_tensor((self.batch_size, 3)       ,       config.vocab_size						)
						UpperCamelCase         =					ids_tensor((self.batch_size, 3)       ,       vocab_size=2						)

						# append to next input_ids and
						UpperCamelCase         =					torch.cat([input_ids, next_tokens]       ,       dim=-1						)
						UpperCamelCase         =					torch.cat([input_mask, next_mask]       ,       dim=-1						)

						UpperCamelCase         =					model(
						    __magic_name__       ,       attention_mask=__magic_name__       ,       encoder_hidden_states=__magic_name__       ,       encoder_attention_mask=__magic_name__       ,       output_hidden_states=__magic_name__       ,       )["""hidden_states"""][0]
						UpperCamelCase         =					model(
						    __magic_name__       ,       attention_mask=__magic_name__       ,       encoder_hidden_states=__magic_name__       ,       encoder_attention_mask=__magic_name__       ,       past_key_values=__magic_name__       ,       output_hidden_states=__magic_name__       ,       )["""hidden_states"""][0]

						# select random slice
						UpperCamelCase         =					ids_tensor((1,)       ,       output_from_past.shape[-1]						).item()
						UpperCamelCase         =					output_from_no_past[:, -3:, random_slice_idx].detach()
						UpperCamelCase         =					output_from_past[:, :, random_slice_idx].detach()

						self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]						)

						# test that outputs are equal for slice
						self.parent.assertTrue(torch.allclose(__magic_name__       ,       __magic_name__       ,       atol=1e-3						)						)




			def   lowerCamelCase_					(						self							:		int       ,       __magic_name__							:		Any       ,       __magic_name__							:		List[str]       ,       __magic_name__							:		Union[str, Any]       ,       __magic_name__							:		List[Any]       ,       *__magic_name__							:		Optional[Any]       ,       ):







						"""simple docstring"""







						UpperCamelCase         =					BertGenerationDecoder(__magic_name__						)
						model.to(__magic_name__						)
						model.eval()
						UpperCamelCase         =					model(__magic_name__       ,       attention_mask=__magic_name__       ,       labels=__magic_name__						)
						self.parent.assertEqual(result.logits.shape       ,       (self.batch_size, self.seq_length, self.vocab_size)						)





			def   lowerCamelCase_					(						self							:		List[Any]						):







						"""simple docstring"""







						UpperCamelCase  ,  UpperCamelCase  ,  UpperCamelCase  ,  UpperCamelCase         =					self.prepare_config_and_inputs()
						UpperCamelCase         =					{"""input_ids""": input_ids, """attention_mask""": input_mask}
						return config, inputs_dict




@require_torch
class    UpperCAmelCase					(       __snake_case      , __snake_case      , __snake_case      , unittest.TestCase    ):
			lowercase						= (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
			lowercase						= (BertGenerationDecoder,) if is_torch_available() else ()
			lowercase						= (
			    {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder}
			    if is_torch_available()
			    else {}
			)




			def   lowerCamelCase_					(						self							:		Tuple						):







						"""simple docstring"""







						UpperCamelCase         =					BertGenerationEncoderTester(self						)
						UpperCamelCase         =					ConfigTester(self       ,       config_class=__magic_name__       ,       hidden_size=3_7						)




			def   lowerCamelCase_					(						self							:		Optional[int]						):







						"""simple docstring"""







						self.config_tester.run_common_tests()




			def   lowerCamelCase_					(						self							:		Any						):







						"""simple docstring"""







						UpperCamelCase         =					self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__magic_name__						)




			def   lowerCamelCase_					(						self							:		List[str]						):







						"""simple docstring"""







						UpperCamelCase  ,  UpperCamelCase  ,  UpperCamelCase  ,  UpperCamelCase         =					self.model_tester.prepare_config_and_inputs()
						UpperCamelCase         =					"""bert"""
						self.model_tester.create_and_check_model(__magic_name__       ,       __magic_name__       ,       __magic_name__       ,       __magic_name__						)




			def   lowerCamelCase_					(						self							:		Tuple						):







						"""simple docstring"""







						UpperCamelCase         =					self.model_tester.prepare_config_and_inputs_for_decoder()
						self.model_tester.create_and_check_model_as_decoder(*__magic_name__						)




			def   lowerCamelCase_					(						self							:		List[Any]						):







						"""simple docstring"""







						UpperCamelCase         =					self.model_tester.prepare_config_and_inputs_for_decoder()
						self.model_tester.create_and_check_decoder_model_past_large_inputs(*__magic_name__						)




			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						(
						    (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  (
						    UpperCamelCase
						)  ,  
						)         =					self.model_tester.prepare_config_and_inputs_for_decoder()

						UpperCamelCase         =					None

						self.model_tester.create_and_check_model_as_decoder(
						    __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       )




			def   lowerCamelCase_					(						self							:		str						):







						"""simple docstring"""







						UpperCamelCase         =					self.model_tester.prepare_config_and_inputs_for_decoder()
						self.model_tester.create_and_check_for_causal_lm(*__magic_name__						)





			@slow
			def   lowerCamelCase_					(						self							:		List[Any]						):







						"""simple docstring"""







						UpperCamelCase         =					BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""						)
						self.assertIsNotNone(__magic_name__						)




@require_torch
class    UpperCAmelCase					(       unittest.TestCase    ):




			@slow
			def   lowerCamelCase_					(						self							:		Tuple						):







						"""simple docstring"""







						UpperCamelCase         =					BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""						)
						UpperCamelCase         =					torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]						)
						with torch.no_grad():
									UpperCamelCase         =					model(__magic_name__						)[0]
						UpperCamelCase         =					torch.Size([1, 8, 1_0_2_4]						)
						self.assertEqual(output.shape       ,       __magic_name__						)
						UpperCamelCase         =					torch.tensor(
						    [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]]						)
						self.assertTrue(torch.allclose(output[:, :3, :3]       ,       __magic_name__       ,       atol=1e-4						)						)




@require_torch
class    UpperCAmelCase					(       unittest.TestCase    ):




			@slow
			def   lowerCamelCase_					(						self							:		int						):







						"""simple docstring"""







						UpperCamelCase         =					BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""						)
						UpperCamelCase         =					torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]						)
						with torch.no_grad():
									UpperCamelCase         =					model(__magic_name__						)[0]
						UpperCamelCase         =					torch.Size([1, 8, 5_0_3_5_8]						)
						self.assertEqual(output.shape       ,       __magic_name__						)
						UpperCamelCase         =					torch.tensor(
						    [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]]						)
						self.assertTrue(torch.allclose(output[:, :3, :3]       ,       __magic_name__       ,       atol=1e-4						)						)




