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


__lowerCamelCase					:	Tuple       =  logging.getLogger(__name__)






class 		a__						(					A__					):
					A	       =							'summarization'
					A	       =							['loss']
					A	       =							ROUGE_KEYS
					A	       =							'rouge2'

					def __init__(    self      :       Dict,_A      :       Any,**_A      :       List[Any]    ):







							"""simple docstring"""






							if hparams.sortish_sampler and hparams.gpus > 1:
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    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__(_A,num_labels=_A,mode=self.mode,**_A    )
							use_task_specific_params(self.model,"summarization"    )
							save_git_info(self.hparams.output_dir    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    Path(self.output_dir    ) / "metrics.json"
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    Path(self.output_dir    ) / "hparams.pkl"
							pickle_save(self.hparams,self.hparams_save_path    )
							SCREAMING_SNAKE_CASE_  :		int				      =    0
							SCREAMING_SNAKE_CASE_  :		int				      =    defaultdict(_A    )
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.config.model_type
							SCREAMING_SNAKE_CASE_  :		int				      =    self.config.tgt_vocab_size if self.model_type == "fsmt" else self.config.vocab_size

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

							SCREAMING_SNAKE_CASE_  :		str				      =    {
							    "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()    )

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    get_git_info()["repo_sha"]
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    hparams.num_workers
							SCREAMING_SNAKE_CASE_  :		str				      =    None  # default to config
							if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer,_A    ):
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.tokenizer.lang_code_to_id[hparams.tgt_lang]
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.decoder_start_token_id
							SCREAMING_SNAKE_CASE_  :		Dict				      =    (
							    SeqaSeqDataset if hasattr(self.tokenizer,"prepare_seq2seq_batch"    ) else LegacySeqaSeqDataset
							)
							SCREAMING_SNAKE_CASE_  :		str				      =    False
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    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:
									SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.hparams.eval_max_gen_length
							else:
									SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.model.config.max_length
							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric

					def 				__UpperCamelCase   (    self      :       int,_A      :       Dict[str, torch.Tensor]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    {
							    k: self.tokenizer.batch_decode(v.tolist()    ) if "mask" not in k else v.shape for k, v in batch.items()
							}
							save_json(_A,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"    )

							SCREAMING_SNAKE_CASE_  :		str				      =    True
							return readable_batch

					def 				__UpperCamelCase   (    self      :       str,_A      :       List[str],**_A      :       List[Any]    ):







							"""simple docstring"""






							return self.model(_A,**_A    )

					def 				__UpperCamelCase   (    self      :       Any,_A      :       List[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.tokenizer.batch_decode(
							    _A,skip_special_tokens=_A,clean_up_tokenization_spaces=_A    )
							return lmap(str.strip,_A    )

					def 				__UpperCamelCase   (    self      :       Union[str, Any],_A      :       dict    ):







							"""simple docstring"""






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

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self(_A,attention_mask=_A,decoder_input_ids=_A,use_cache=_A    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    outputs["logits"]
							if self.hparams.label_smoothing == 0:
									# Same behavior as modeling_bart.py, besides ignoring pad_token_id
									SCREAMING_SNAKE_CASE_  :		str				      =    nn.CrossEntropyLoss(ignore_index=_A    )

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

					@property
					def 				__UpperCamelCase   (    self      :       Dict    ):







							"""simple docstring"""






							return self.tokenizer.pad_token_id

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       Union[str, Any],_A      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    self._step(_A    )

							SCREAMING_SNAKE_CASE_  :		Any				      =    dict(zip(self.loss_names,_A    )    )
							# tokens per batch
							SCREAMING_SNAKE_CASE_  :		int				      =    batch["input_ids"].ne(self.pad    ).sum() + batch["labels"].ne(self.pad    ).sum()
							SCREAMING_SNAKE_CASE_  :		Any				      =    batch["input_ids"].shape[0]
							SCREAMING_SNAKE_CASE_  :		str				      =    batch["input_ids"].eq(self.pad    ).sum()
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    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 				__UpperCamelCase   (    self      :       List[Any],_A      :       Any,_A      :       Optional[int]    ):







							"""simple docstring"""






							return self._generative_step(_A    )

					def 				__UpperCamelCase   (    self      :       List[str],_A      :       str,_A      :       Optional[Any]="val"    ):







							"""simple docstring"""






							self.step_count += 1
							SCREAMING_SNAKE_CASE_  :		str				      =    {k: torch.stack([x[k] for x in outputs]    ).mean() for k in self.loss_names}
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    losses["loss"]
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    {
							    k: np.array([x[k] for x in outputs]    ).mean() for k in self.metric_names + ["gen_time", "gen_len"]
							}
							SCREAMING_SNAKE_CASE_  :		Any				      =    (
							    generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
							)
							SCREAMING_SNAKE_CASE_  :		torch.FloatTensor				      =    torch.tensor(_A    ).type_as(_A    )
							generative_metrics.update({k: v.item() for k, v in losses.items()}    )
							losses.update(_A    )
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    {F'{prefix}_avg_{k}': x for k, x in losses.items()}
							SCREAMING_SNAKE_CASE_  :		Any				      =    self.step_count
							self.metrics[prefix].append(_A    )  # callback writes this to self.metrics_save_path
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    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 				__UpperCamelCase   (    self      :       Dict,_A      :       Optional[Any],_A      :       Dict    ):







							"""simple docstring"""






							return calculate_rouge(_A,_A    )

					def 				__UpperCamelCase   (    self      :       int,_A      :       dict    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Tuple				      =    time.time()

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

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       Dict,_A      :       Any    ):







							"""simple docstring"""






							return self._generative_step(_A    )

					def 				__UpperCamelCase   (    self      :       Optional[int],_A      :       List[Any]    ):







							"""simple docstring"""






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

					def 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       Any    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.n_obs[type_path]
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.target_lens[type_path]
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.dataset_class(
							    self.tokenizer,type_path=_A,n_obs=_A,max_target_length=_A,**self.dataset_kwargs,)
							return dataset

					def 				__UpperCamelCase   (    self      :       List[str],_A      :       str,_A      :       int,_A      :       bool = False    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    self.get_dataset(_A    )

							if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    dataset.make_sortish_sampler(_A,distributed=self.hparams.gpus > 1    )
									return DataLoader(
									    _A,batch_size=_A,collate_fn=dataset.collate_fn,shuffle=_A,num_workers=self.num_workers,sampler=_A,)

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

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







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.get_dataloader("train",batch_size=self.hparams.train_batch_size,shuffle=_A    )
							return dataloader

					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






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

					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






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






					@staticmethod
					def 				__UpperCamelCase   (    _A      :       List[Any],_A      :       List[Any]    ):







							"""simple docstring"""






							BaseTransformer.add_model_specific_args(_A,_A    )
							add_generic_args(_A,_A    )
							parser.add_argument(
							    "--max_source_length",default=1024,type=_A,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=56,type=_A,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=142,type=_A,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=142,type=_A,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=_A    )
							parser.add_argument("--overwrite_output_dir",action="store_true",default=_A    )
							parser.add_argument("--max_tokens_per_batch",type=_A,default=_A    )
							parser.add_argument("--logger_name",type=_A,choices=["default", "wandb", "wandb_shared"],default="default"    )
							parser.add_argument("--n_train",type=_A,default=-1,required=_A,help="# examples. -1 means use all."    )
							parser.add_argument("--n_val",type=_A,default=500,required=_A,help="# examples. -1 means use all."    )
							parser.add_argument("--n_test",type=_A,default=-1,required=_A,help="# examples. -1 means use all."    )
							parser.add_argument(
							    "--task",type=_A,default="summarization",required=_A,help="# examples. -1 means use all."    )
							parser.add_argument("--label_smoothing",type=_A,default=0.0,required=_A    )
							parser.add_argument("--src_lang",type=_A,default="",required=_A    )
							parser.add_argument("--tgt_lang",type=_A,default="",required=_A    )
							parser.add_argument("--eval_beams",type=_A,default=_A,required=_A    )
							parser.add_argument(
							    "--val_metric",type=_A,default=_A,required=_A,choices=["bleu", "rouge2", "loss", None]    )
							parser.add_argument("--eval_max_gen_length",type=_A,default=_A,help="never generate more than n tokens"    )
							parser.add_argument("--save_top_k",type=_A,default=1,required=_A,help="How many checkpoints to save"    )
							parser.add_argument(
							    "--early_stopping_patience",type=_A,default=-1,required=_A,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 		a__						(					A__					):
					A	       =							'translation'
					A	       =							['loss']
					A	       =							['bleu']
					A	       =							'bleu'

					def __init__(    self      :       str,_A      :       Optional[int],**_A      :       int    ):







							"""simple docstring"""






							super().__init__(_A,**_A    )
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    hparams.src_lang
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    hparams.tgt_lang






					def 				__UpperCamelCase   (    self      :       Any,_A      :       Optional[Any],_A      :       str    ):







							"""simple docstring"""






							return calculate_bleu(_A,_A    )







def       _snake_case	(   lowerCAmelCase							:   Tuple   , lowerCAmelCase							:   List[str]=None	):
		"""simple docstring"""







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

		if model is None:
				if "summarization" in args.task:
						SCREAMING_SNAKE_CASE_  :		SummarizationModule				      =    SummarizationModule(lowerCAmelCase	)
				else:
						SCREAMING_SNAKE_CASE_  :		SummarizationModule				      =    TranslationModule(lowerCAmelCase	)
		SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    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"	)
		):
				SCREAMING_SNAKE_CASE_  :		Tuple				      =    True  # don't pollute wandb logs unnecessarily
		elif args.logger_name == "wandb":
				from pytorch_lightning.loggers import WandbLogger

				SCREAMING_SNAKE_CASE_  :		Tuple				      =    os.environ.get("WANDB_PROJECT"   , lowerCAmelCase	)
				SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    WandbLogger(name=model.output_dir.name   , project=lowerCAmelCase	)

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

				SCREAMING_SNAKE_CASE_  :		List[str]				      =    WandbLogger(name=model.output_dir.name   , project=f'hf_{dataset}'	)

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

		SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    args.val_metric == "loss"
		SCREAMING_SNAKE_CASE_  :		pl.Trainer				      =    generic_train(
		    lowerCAmelCase   , lowerCAmelCase   , logging_callback=SeqaSeqLoggingCallback()   , checkpoint_callback=get_checkpoint_callback(
		        args.output_dir   , model.val_metric   , args.save_top_k   , lowerCAmelCase	)   , early_stopping_callback=lowerCAmelCase   , logger=lowerCAmelCase   , )
		pickle_save(model.hparams   , model.output_dir / "hparams.pkl"	)
		if not args.do_predict:
				return model

		SCREAMING_SNAKE_CASE_  :		Dict				      =    ""
		SCREAMING_SNAKE_CASE_  :		Dict				      =    sorted(glob.glob(os.path.join(args.output_dir   , "*.ckpt"	)   , recursive=lowerCAmelCase	)	)
		if checkpoints:
				SCREAMING_SNAKE_CASE_  :		List[str]				      =    checkpoints[-1]
				SCREAMING_SNAKE_CASE_  :		List[Any]				      =    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__":
		__lowerCamelCase					:	Tuple       =  argparse.ArgumentParser()
		__lowerCamelCase					:	Union[str, Any]       =  pl.Trainer.add_argparse_args(parser)
		__lowerCamelCase					:	List[str]       =  SummarizationModule.add_model_specific_args(parser, os.getcwd())

		__lowerCamelCase					:	Tuple       =  parser.parse_args()

		main(args)

from __future__ import annotations

import os
import tempfile
import unittest

from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TFConvBertForMaskedLM,
		    TFConvBertForMultipleChoice,
		    TFConvBertForQuestionAnswering,
		    TFConvBertForSequenceClassification,
		    TFConvBertForTokenClassification,
		    TFConvBertModel,
		)






class 		a__						:

					def __init__(    self      :       Optional[int],_A      :       Dict,_A      :       List[str]=13,_A      :       List[str]=7,_A      :       int=True,_A      :       str=True,_A      :       Union[str, Any]=True,_A      :       Tuple=True,_A      :       Dict=99,_A      :       Tuple=32,_A      :       Tuple=2,_A      :       Tuple=4,_A      :       Optional[Any]=37,_A      :       str="gelu",_A      :       Dict=0.1,_A      :       List[Any]=0.1,_A      :       List[str]=512,_A      :       str=16,_A      :       int=2,_A      :       Dict=0.02,_A      :       List[Any]=3,_A      :       Optional[Any]=4,_A      :       Optional[int]=None,):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    parent
							SCREAMING_SNAKE_CASE_  :		Any				      =    13
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    7
							SCREAMING_SNAKE_CASE_  :		Dict				      =    True
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    True
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    True
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    99
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    384
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    2
							SCREAMING_SNAKE_CASE_  :		Any				      =    4
							SCREAMING_SNAKE_CASE_  :		str				      =    37
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    "gelu"
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    0.1
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    0.1
							SCREAMING_SNAKE_CASE_  :		Dict				      =    512
							SCREAMING_SNAKE_CASE_  :		int				      =    16
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    2
							SCREAMING_SNAKE_CASE_  :		Any				      =    0.02
							SCREAMING_SNAKE_CASE_  :		str				      =    3
							SCREAMING_SNAKE_CASE_  :		int				      =    4
							SCREAMING_SNAKE_CASE_  :		Dict				      =    128
							SCREAMING_SNAKE_CASE_  :		Any				      =    2
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    9
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    1
							SCREAMING_SNAKE_CASE_  :		Any				      =    None

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size, self.seq_length],self.vocab_size    )

							SCREAMING_SNAKE_CASE_  :		Any				      =    None
							if self.use_input_mask:
									SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    random_attention_mask([self.batch_size, self.seq_length]    )

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    None
							if self.use_token_type_ids:
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    ids_tensor([self.batch_size, self.seq_length],self.type_vocab_size    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    None
							SCREAMING_SNAKE_CASE_  :		Dict				      =    None
							SCREAMING_SNAKE_CASE_  :		str				      =    None
							if self.use_labels:
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size],self.type_sequence_label_size    )
									SCREAMING_SNAKE_CASE_  :		Dict				      =    ids_tensor([self.batch_size, self.seq_length],self.num_labels    )
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size],self.num_choices    )

							SCREAMING_SNAKE_CASE_  :		Any				      =    ConvBertConfig(
							    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,type_vocab_size=self.type_vocab_size,initializer_range=self.initializer_range,return_dict=_A,)

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

					def 				__UpperCamelCase   (    self      :       Optional[int],_A      :       List[Any],_A      :       int,_A      :       Tuple,_A      :       Optional[int],_A      :       Union[str, Any],_A      :       Union[str, Any],_A      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    TFConvBertModel(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

							SCREAMING_SNAKE_CASE_  :		str				      =    [input_ids, input_mask]
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(_A    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    model(_A    )

							self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)    )

					def 				__UpperCamelCase   (    self      :       Dict,_A      :       Dict,_A      :       int,_A      :       Union[str, Any],_A      :       List[Any],_A      :       int,_A      :       str,_A      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    TFConvBertForMaskedLM(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size)    )

					def 				__UpperCamelCase   (    self      :       Any,_A      :       Optional[int],_A      :       List[Any],_A      :       Union[str, Any],_A      :       List[Any],_A      :       Union[str, Any],_A      :       Optional[int],_A      :       Dict    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.num_labels
							SCREAMING_SNAKE_CASE_  :		Any				      =    TFConvBertForSequenceClassification(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)    )

					def 				__UpperCamelCase   (    self      :       int,_A      :       int,_A      :       Dict,_A      :       List[str],_A      :       Tuple,_A      :       Dict,_A      :       Optional[int],_A      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.num_choices
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    TFConvBertForMultipleChoice(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    tf.tile(tf.expand_dims(_A,1    ),(1, self.num_choices, 1)    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    tf.tile(tf.expand_dims(_A,1    ),(1, self.num_choices, 1)    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    tf.tile(tf.expand_dims(_A,1    ),(1, self.num_choices, 1)    )
							SCREAMING_SNAKE_CASE_  :		int				      =    {
							    "input_ids": multiple_choice_inputs_ids,
							    "attention_mask": multiple_choice_input_mask,
							    "token_type_ids": multiple_choice_token_type_ids,
							}
							SCREAMING_SNAKE_CASE_  :		int				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices)    )

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       Union[str, Any],_A      :       int,_A      :       Optional[int],_A      :       str,_A      :       str,_A      :       Tuple,_A      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.num_labels
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    TFConvBertForTokenClassification(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}
							SCREAMING_SNAKE_CASE_  :		str				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels)    )

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       int,_A      :       List[str],_A      :       List[Any],_A      :       Any,_A      :       Optional[int],_A      :       List[str],_A      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    TFConvBertForQuestionAnswering(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

							SCREAMING_SNAKE_CASE_  :		Any				      =    model(_A    )
							self.parent.assertEqual(result.start_logits.shape,(self.batch_size, self.seq_length)    )
							self.parent.assertEqual(result.end_logits.shape,(self.batch_size, self.seq_length)    )






					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    self.prepare_config_and_inputs()
							(
							    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    
							)  :		List[Any]				      =    config_and_inputs
							SCREAMING_SNAKE_CASE_  :		Any				      =    {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
							return config, inputs_dict







@require_tf
class 		a__						(					A__    ,		A__    ,		unittest.TestCase					):
					A	       =							(
					    (
					        TFConvBertModel,
					        TFConvBertForMaskedLM,
					        TFConvBertForQuestionAnswering,
					        TFConvBertForSequenceClassification,
					        TFConvBertForTokenClassification,
					        TFConvBertForMultipleChoice,
					    )
					    if is_tf_available()
					    else ()
					)
					A	       =							(
					    {
					        'feature-extraction': TFConvBertModel,
					        'fill-mask': TFConvBertForMaskedLM,
					        'question-answering': TFConvBertForQuestionAnswering,
					        'text-classification': TFConvBertForSequenceClassification,
					        'token-classification': TFConvBertForTokenClassification,
					        'zero-shot': TFConvBertForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)
					A	       =							False
					A	       =							False
					A	       =							False

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFConvBertModelTester(self    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    ConfigTester(self,config_class=_A,hidden_size=37    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							self.config_tester.run_common_tests()

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*_A    )

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*_A    )

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*_A    )

					@slow
					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		Any				      =    True

							if hasattr(_A,"use_cache"    ):
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    True

							SCREAMING_SNAKE_CASE_  :		int				      =    getattr(self.model_tester,"encoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    getattr(self.model_tester,"key_length",_A    )

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    self._prepare_for_class(_A,_A    )
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    len(model(_A    )    )

									with tempfile.TemporaryDirectory() as tmpdirname:
											model.save_pretrained(_A,saved_model=_A    )
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    os.path.join(_A,"saved_model","1"    )
											SCREAMING_SNAKE_CASE_  :		Tuple				      =    tf.keras.models.load_model(_A    )
											SCREAMING_SNAKE_CASE_  :		str				      =    model(_A    )

											if self.is_encoder_decoder:
													SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    outputs["encoder_hidden_states"]
													SCREAMING_SNAKE_CASE_  :		str				      =    outputs["encoder_attentions"]
											else:
													SCREAMING_SNAKE_CASE_  :		Any				      =    outputs["hidden_states"]
													SCREAMING_SNAKE_CASE_  :		List[str]				      =    outputs["attentions"]

											self.assertEqual(len(_A    ),_A    )

											SCREAMING_SNAKE_CASE_  :		Any				      =    getattr(
											    self.model_tester,"expected_num_hidden_layers",self.model_tester.num_hidden_layers + 1    )

											self.assertEqual(len(_A    ),_A    )
											self.assertListEqual(
											    list(output_hidden_states[0].shape[-2:]    ),[self.model_tester.seq_length, self.model_tester.hidden_size],)

											self.assertEqual(len(_A    ),self.model_tester.num_hidden_layers    )
											self.assertListEqual(
											    list(output_attentions[0].shape[-3:]    ),[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],)

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







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFConvBertModel.from_pretrained("YituTech/conv-bert-base"    )
							self.assertIsNotNone(_A    )






					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Any				      =    self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    getattr(self.model_tester,"decoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    getattr(self.model_tester,"encoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    getattr(self.model_tester,"key_length",_A    )
							SCREAMING_SNAKE_CASE_  :		int				      =    getattr(self.model_tester,"key_length",_A    )

							def check_decoder_attentions_output(_A      :       Dict    ):
									SCREAMING_SNAKE_CASE_  :		int				      =    len(_A    )
									self.assertEqual(out_len % 2,0    )
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    outputs.decoder_attentions
									self.assertEqual(len(_A    ),self.model_tester.num_hidden_layers    )
									self.assertListEqual(
									    list(decoder_attentions[0].shape[-3:]    ),[self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length],)

							def check_encoder_attentions_output(_A      :       Tuple    ):
									SCREAMING_SNAKE_CASE_  :		int				      =    [
									    t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
									]
									self.assertEqual(len(_A    ),self.model_tester.num_hidden_layers    )
									self.assertListEqual(
									    list(attentions[0].shape[-3:]    ),[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],)

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    True
									SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    False
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		Any				      =    model(self._prepare_for_class(_A,_A    )    )
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    len(_A    )
									self.assertEqual(config.output_hidden_states,_A    )
									check_encoder_attentions_output(_A    )

									if self.is_encoder_decoder:
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    model_class(_A    )
											SCREAMING_SNAKE_CASE_  :		int				      =    model(self._prepare_for_class(_A,_A    )    )
											self.assertEqual(config.output_hidden_states,_A    )
											check_decoder_attentions_output(_A    )

									# Check that output attentions can also be changed via the config
									del inputs_dict["output_attentions"]
									SCREAMING_SNAKE_CASE_  :		str				      =    True
									SCREAMING_SNAKE_CASE_  :		int				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(self._prepare_for_class(_A,_A    )    )
									self.assertEqual(config.output_hidden_states,_A    )
									check_encoder_attentions_output(_A    )

									# Check attention is always last and order is fine
									SCREAMING_SNAKE_CASE_  :		str				      =    True
									SCREAMING_SNAKE_CASE_  :		int				      =    True
									SCREAMING_SNAKE_CASE_  :		Dict				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		str				      =    model(self._prepare_for_class(_A,_A    )    )

									self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1),len(_A    )    )
									self.assertEqual(model.config.output_hidden_states,_A    )
									check_encoder_attentions_output(_A    )







@require_tf
class 		a__						(					unittest.TestCase					):

					@slow
					def 				__UpperCamelCase   (    self      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    TFConvBertModel.from_pretrained("YituTech/conv-bert-base"    )
							SCREAMING_SNAKE_CASE_  :		int				      =    tf.constant([[0, 1, 2, 3, 4, 5]]    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    model(_A    )[0]

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    [1, 6, 768]
							self.assertEqual(output.shape,_A    )

							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    tf.constant(
							    [
							        [
							            [-0.03475493, -0.4686034, -0.30638832],
							            [0.22637248, -0.26988646, -0.7423424],
							            [0.10324868, -0.45013508, -0.58280784],
							        ]
							    ]    )
							tf.debugging.assert_near(output[:, :3, :3],_A,atol=1E-4    )
