
import copy
import logging
import random

import joblib
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AdamW, GPTaLMHeadModel, get_linear_schedule_with_warmup


a__				:      Tuple    		=     logging.getLogger(__name__)







def 				UpperCAmelCase_(    a__   ):



    """simple docstring"""



    random.seed(a__   )
    np.random.seed(a__   )
    torch.manual_seed(a__   )
    torch.cuda.manual_seed_all(a__   )







def 				UpperCAmelCase_(    a__ ,						a__ ,						a__   ):



    """simple docstring"""



    model.eval()
    SCREAMING_SNAKE_CASE				:				Any				      = next(model.parameters()   ).device
    SCREAMING_SNAKE_CASE				:				str				      = 1
    SCREAMING_SNAKE_CASE				:				List[Any]				      = torch.zeros((eval_batch_size, context_len) ,						dtype=torch.long ,						device=a__   )
    SCREAMING_SNAKE_CASE				:				Dict				      = DataLoader(a__ ,						shuffle=a__ ,						batch_size=a__   )
    SCREAMING_SNAKE_CASE				:				str				      = torch.zeros(1 ,						device=a__   )
    SCREAMING_SNAKE_CASE				:				Optional[int]				      = 0
    for batch in eval_dataloader:
        batch.to(a__   )
        # pad
        context.zero_()
        for i in range(a__   ):
            SCREAMING_SNAKE_CASE				:				List[Any]				      = batch[i]
        SCREAMING_SNAKE_CASE				:				Dict				      = model(a__ ,						labels=a__   )
        eval_loss += outputs[0].sum().item()
        nb_eval_examples += batch.size(0   )
    SCREAMING_SNAKE_CASE				:				str				      = eval_loss / nb_eval_examples
    SCREAMING_SNAKE_CASE				:				Dict				      = torch.exp(a__   )
    model.train()
    return perplexity







def 				UpperCAmelCase_(    a__="gpt2"   ):



    """simple docstring"""



    SCREAMING_SNAKE_CASE				:				Optional[int]				      = GPTaLMHeadModel.from_pretrained(a__ ,						output_hidden_states=a__   )
    torch.save(model.state_dict() ,						model_name + '''local.pt'''   )
    return model







def 				UpperCAmelCase_(    a__ ,						a__ ,						a__   ):



    """simple docstring"""



    SCREAMING_SNAKE_CASE				:				List[Any]				      = copy.deepcopy(a__   )
    model.to(a__   )

    SCREAMING_SNAKE_CASE				:				List[str]				      = ['''bias''', '''LayerNorm.weight''']
    SCREAMING_SNAKE_CASE				:				Optional[int]				      = [
        {
            '''params''': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay   )],
            '''weight_decay''': 0.0,
        },
        {'''params''': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay   )], '''weight_decay''': 0.0},
    ]
    SCREAMING_SNAKE_CASE				:				Optional[int]				      = AdamW(a__ ,						lr=5e-5 ,						eps=1e-8   )
    SCREAMING_SNAKE_CASE				:				Dict				      = get_linear_schedule_with_warmup(a__ ,						0 ,						a__   )
    torch.cuda.empty_cache()
    return model, lm_optimizer, lm_scheduler







def 				UpperCAmelCase_(    a__ ,						a__ ,						a__ ,						a__   ):



    """simple docstring"""



    SCREAMING_SNAKE_CASE				:				Optional[Any]				      = np.array(a__   ).mean()
    SCREAMING_SNAKE_CASE				:				str				      = np.array(a__   ).std()
    SCREAMING_SNAKE_CASE				:				Any				      = (real_perps - avg) / std
    SCREAMING_SNAKE_CASE				:				List[Any]				      = list(zip(a__ ,						a__ ,						a__   )   )
    joblib.dump(a__ ,						a__   )







def 				UpperCAmelCase_(    a__ ,						a__ ,						a__ ,						a__ ,						a__ ,						a__ ,						a__ ,						a__="dev.jbl" ,						a__=recopy_gpta ,						):



    """simple docstring"""



    SCREAMING_SNAKE_CASE				:				str				      = []
    SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = []
    SCREAMING_SNAKE_CASE				:				str				      = []

    # Initialize the transformer model
    SCREAMING_SNAKE_CASE				:				Optional[int]				      = copy.deepcopy(a__   )
    orig_model.to(device='''cpu'''   )
    torch.cuda.empty_cache()

    # Compute perplexity of initial transformer model for comparison
    model.train()
    SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE				:				Tuple				      = recopy_model(a__ ,						a__ ,						a__   )

    for step in tqdm(range(a__   )   ):
        SCREAMING_SNAKE_CASE				:				List[Any]				      = torch.zeros((1, context_len) ,						dtype=torch.long ,						device=a__   )
        SCREAMING_SNAKE_CASE				:				str				      = random.choice(a__   )
        SCREAMING_SNAKE_CASE				:				Optional[Any]				      = random.randint(0 ,						len(story[0]   ) - context_len - 1   )
        SCREAMING_SNAKE_CASE				:				List[Any]				      = story[0][start : start + context_len]
        lm_optimizer.zero_grad()
        SCREAMING_SNAKE_CASE				:				str				      = model(a__ ,						labels=a__   )
        SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = outputs[0]
        SCREAMING_SNAKE_CASE				:				Any				      = compute_perplexity(a__ ,						a__ ,						a__   )
        model.train()
        lm_loss.backward()
        # Do LM backprop
        torch.nn.utils.clip_grad_norm_(model.parameters() ,						3.0   )
        lm_optimizer.step()
        lm_scheduler.step()  # Update learning rate schedule

        # Compute perplexity after back-propagating on the selected context
        SCREAMING_SNAKE_CASE				:				str				      = compute_perplexity(a__ ,						a__ ,						a__   )

        # Periodically save the stored (X, IG(X)) pairs
        if step % 1_000 == 0 and step > 1:
            intermittent_save(a__ ,						a__ ,						a__ ,						a__   )

        # Reset the pretrained model to the original pretrained GPT-2 weights after each iteration
        SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE				:				Any				      = recopy_model(a__ ,						a__ ,						a__   )

        past_perps.append(past_perp.item()   )
        real_perps.append(orig_perp - real_perp.item()   )
        contexts.append(np.array(context.cpu()   )   )

    intermittent_save(a__ ,						a__ ,						a__ ,						a__   )







def 				UpperCAmelCase_(    a__ ,						a__="data/tokenized_stories_train_wikitext103.jbl" ,						a__=100 ,						a__=1_026 ,						a__=True   ):



    """simple docstring"""



    SCREAMING_SNAKE_CASE				:				Optional[Any]				      = joblib.load(a__   )
    print('''data loaded'''   )
    SCREAMING_SNAKE_CASE				:				List[str]				      = []
    if trim:
        for i, example in enumerate(a__   ):
            if len(example[0]   ) > min_len:
                SCREAMING_SNAKE_CASE				:				Optional[Any]				      = random.randint(0 ,						len(example[0]   ) - context_len - 1   )
                objective_set.append(example[0, start : start + context_len]   )
            if len(a__   ) >= number:
                break
        SCREAMING_SNAKE_CASE				:				List[Any]				      = []
        for j in range(i + 1 ,						len(a__   )   ):
            if len(data[j][0]   ) > min_len:
                train_data.append(data[j]   )
    else:
        SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = data[0:number]
        SCREAMING_SNAKE_CASE				:				List[str]				      = data[number:]

    joblib.dump(a__ ,						'''objective_set.jbl'''   )
    print('''objective set saved'''   )
    return train_data, objective_set







def 				UpperCAmelCase_(    a__ ,						a__ ,						a__ ,						a__ ,						a__=50 ,						a__="secondary_learner.pt"   ):



    """simple docstring"""



    SCREAMING_SNAKE_CASE				:				List[Any]				      = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu'''   )
    # We will use the first 512 pairs from our dataset as a test set for
    # our secondary learner and the rest to train
    SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = train_dataset[:512]
    SCREAMING_SNAKE_CASE				:				Optional[Any]				      = train_dataset[512:]
    SCREAMING_SNAKE_CASE				:				Dict				      = DataLoader(a__ ,						shuffle=a__ ,						batch_size=a__   )
    SCREAMING_SNAKE_CASE				:				Optional[int]				      = DataLoader(a__ ,						shuffle=a__ ,						batch_size=a__   )

    # secondary learner model set up
    SCREAMING_SNAKE_CASE				:				int				      = nn.MSELoss()
    SCREAMING_SNAKE_CASE				:				List[str]				      = nn.MSELoss(reduction='''sum'''   )
    secondary_learner.to(a__   )
    SCREAMING_SNAKE_CASE				:				Optional[Any]				      = torch.optim.Adam(secondary_learner.parameters() ,						lr=0.00_001   )
    secondary_learner.train()

    # TODO in original code this is written as number of actual batches seen
    # not number of items seen but other places it is number of items instead.
    # improve consistency! changed this to epochs for clarity
    SCREAMING_SNAKE_CASE				:				List[Any]				      = float('''inf'''   )
    # Iterate through batches until we've used max_steps batches
    for epoch in range(int(a__   )   ):
        SCREAMING_SNAKE_CASE				:				Dict				      = 0.0
        secondary_learner.train()
        for step, batch in enumerate(a__   ):
            SCREAMING_SNAKE_CASE				:				Any				      = batch[0].to(a__   )
            SCREAMING_SNAKE_CASE				:				Tuple				      = batch[1].to(a__   )
            SCREAMING_SNAKE_CASE				:				List[Any]				      = secondary_learner(a__   )
            q_optimizer.zero_grad()
            SCREAMING_SNAKE_CASE				:				Any				      = loss(a__ ,						real_q.float()   )
            q_loss.backward()
            q_optimizer.step()
            tr_q_loss += q_loss.item()

            # model trains fairly quickly so we won't wait for a full epoch
            # eval is triggered at eval_freq and end of epochs
            if (step % eval_freq == 0 and step > 0) or ((step + 1) == len(a__   )):
                SCREAMING_SNAKE_CASE				:				str				      = tr_q_loss / (step + 1)

                secondary_learner.eval()
                SCREAMING_SNAKE_CASE				:				List[Any]				      = 0.0
                SCREAMING_SNAKE_CASE				:				int				      = 0.0
                SCREAMING_SNAKE_CASE				:				List[str]				      = []
                SCREAMING_SNAKE_CASE				:				Optional[int]				      = []
                # Compute performance of the secondary learner after this batch
                for stepa, batcha in enumerate(a__   ):
                    SCREAMING_SNAKE_CASE				:				List[str]				      = batcha[0].to(a__   )
                    SCREAMING_SNAKE_CASE				:				Dict				      = batcha[1].to(a__   )
                    SCREAMING_SNAKE_CASE				:				Optional[Any]				      = secondary_learner(a__   )
                    q_lossa += test_loss(a__ ,						a__   ).item()
                    sum_qa += torch.sum(a__   ).item()
                    for ei, i in enumerate(predicted_qa.cpu().detach().numpy()   ):
                        predicted.append(i.item()   )
                    for ei, i in enumerate(real_qa.cpu().detach().numpy()   ):
                        actual.append(i.item()   )

                q_lossa /= len(a__   )
                print(
                    '''Epoch: ''' ,						a__ ,						'''step: ''' ,						a__ ,						'''Avg. q:''' ,						sum_qa / len(a__   ) ,						'''Train Loss: ''' ,						a__ ,						'''Test Loss: ''' ,						a__ ,						)
                if q_lossa < best_test_loss:
                    joblib.dump((predicted, actual) ,						'''pred_vs_actual.jbl'''   )
                    torch.save(secondary_learner.state_dict() ,						a__   )
                    SCREAMING_SNAKE_CASE				:				Optional[int]				      = q_lossa

            secondary_learner.train()
    return secondary_learner






class     a_       (			nn.Module							):



       """simple docstring"""






       def __init__(		self				,       _lowerCamelCase   )					->Dict:
           super(_lowerCamelCase				,       self   ).__init__()
           SCREAMING_SNAKE_CASE				:				List[str]				      = model.transformer.wte
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = copy.deepcopy(model.transformer.wte.weight   )
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = nn.Convad(self.embeddings.weight.size(1   )				,       256				,       3				,       padding=1   )
           SCREAMING_SNAKE_CASE				:				List[Any]				      = nn.Sequential(nn.Linear(256				,       32   )				,       nn.Dropout(p=0.1   )				,       nn.Linear(32				,       32   )				,       nn.Linear(32				,       1   )   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->List[str]:
           SCREAMING_SNAKE_CASE				:				List[str]				      = torch.max(self.conv(self.embeddings(_lowerCamelCase   ).squeeze(1   ).transpose(1				,       2   )   )				,       2   )[0]
           SCREAMING_SNAKE_CASE				:				int				      = self.fc(_lowerCamelCase   )
           return qs.squeeze(1   )






       @classmethod
       def 	__lowerCAmelCase     (		cls				,       _lowerCamelCase				,       _lowerCamelCase   )					->List[Any]:
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = cls(_lowerCamelCase   )  # this calls __init__
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = torch.load(_lowerCamelCase   )
           secondary_learner.load_state_dict(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				str				      = model.transformer.wte
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = copy.deepcopy(model.transformer.wte.weight   )
           return secondary_learner


from __future__ import annotations

import unittest

from transformers import AlbertConfig, is_tf_available
from transformers.models.auto import get_values
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 TF_MODEL_FOR_PRETRAINING_MAPPING
      from transformers.models.albert.modeling_tf_albert import (
          TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFAlbertForMaskedLM,
          TFAlbertForMultipleChoice,
          TFAlbertForPreTraining,
          TFAlbertForQuestionAnswering,
          TFAlbertForSequenceClassification,
          TFAlbertForTokenClassification,
          TFAlbertModel,
      )






class     a_       :



       """simple docstring"""






       def __init__(		self				,       _lowerCamelCase				,       _lowerCamelCase=13				,       _lowerCamelCase=7				,       _lowerCamelCase=True				,       _lowerCamelCase=True				,       _lowerCamelCase=True				,       _lowerCamelCase=True				,       _lowerCamelCase=99				,       _lowerCamelCase=16				,       _lowerCamelCase=32				,       _lowerCamelCase=2				,       _lowerCamelCase=4				,       _lowerCamelCase=37				,       _lowerCamelCase="gelu"				,       _lowerCamelCase=0.1				,       _lowerCamelCase=0.1				,       _lowerCamelCase=512				,       _lowerCamelCase=16				,       _lowerCamelCase=2				,       _lowerCamelCase=0.0_2				,       _lowerCamelCase=3				,       _lowerCamelCase=4				,       _lowerCamelCase=None				,       )					->List[Any]:
           SCREAMING_SNAKE_CASE				:				int				      = parent
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = 13
           SCREAMING_SNAKE_CASE				:				int				      = 7
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = True
           SCREAMING_SNAKE_CASE				:				List[str]				      = True
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = True
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = True
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = 99
           SCREAMING_SNAKE_CASE				:				str				      = 16
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = 32
           SCREAMING_SNAKE_CASE				:				str				      = 2
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = 4
           SCREAMING_SNAKE_CASE				:				int				      = 37
           SCREAMING_SNAKE_CASE				:				Any				      = '''gelu'''
           SCREAMING_SNAKE_CASE				:				str				      = 0.1
           SCREAMING_SNAKE_CASE				:				Dict				      = 0.1
           SCREAMING_SNAKE_CASE				:				Tuple				      = 512
           SCREAMING_SNAKE_CASE				:				Any				      = 16
           SCREAMING_SNAKE_CASE				:				str				      = 2
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = 0.0_2
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = 3
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = 4
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = None






       def 	__lowerCAmelCase     (		self   )					->List[str]:
           SCREAMING_SNAKE_CASE				:				Tuple				      = ids_tensor([self.batch_size, self.seq_length]				,       self.vocab_size   )

           SCREAMING_SNAKE_CASE				:				Optional[int]				      = None
           if self.use_input_mask:
               SCREAMING_SNAKE_CASE				:				Optional[int]				      = random_attention_mask([self.batch_size, self.seq_length]   )

           SCREAMING_SNAKE_CASE				:				Dict				      = None
           if self.use_token_type_ids:
               SCREAMING_SNAKE_CASE				:				Dict				      = ids_tensor([self.batch_size, self.seq_length]				,       self.type_vocab_size   )

           SCREAMING_SNAKE_CASE				:				str				      = None
           SCREAMING_SNAKE_CASE				:				Any				      = None
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = None
           if self.use_labels:
               SCREAMING_SNAKE_CASE				:				str				      = ids_tensor([self.batch_size]				,       self.type_sequence_label_size   )
               SCREAMING_SNAKE_CASE				:				List[str]				      = ids_tensor([self.batch_size, self.seq_length]				,       self.num_labels   )
               SCREAMING_SNAKE_CASE				:				Tuple				      = ids_tensor([self.batch_size]				,       self.num_choices   )

           SCREAMING_SNAKE_CASE				:				List[Any]				      = AlbertConfig(
               vocab_size=self.vocab_size				,       hidden_size=self.hidden_size				,       embedding_size=self.embedding_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 config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase   )					->List[str]:
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = TFAlbertModel(config=_lowerCamelCase   )
           # inputs = {'input_ids': input_ids,
           #           'attention_mask': input_mask,
           #           'token_type_ids': token_type_ids}
           # sequence_output, pooled_output = model(**inputs)
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = model(_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				List[str]				      = [input_ids, input_mask]
           SCREAMING_SNAKE_CASE				:				List[str]				      = model(_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Any				      = model(_lowerCamelCase   )

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






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase   )					->List[Any]:
           SCREAMING_SNAKE_CASE				:				str				      = self.num_labels
           SCREAMING_SNAKE_CASE				:				List[str]				      = TFAlbertForPreTraining(config=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Any				      = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
           SCREAMING_SNAKE_CASE				:				int				      = model(_lowerCamelCase   )
           self.parent.assertEqual(result.prediction_logits.shape				,       (self.batch_size, self.seq_length, self.vocab_size)   )
           self.parent.assertEqual(result.sop_logits.shape				,       (self.batch_size, self.num_labels)   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase   )					->str:
           SCREAMING_SNAKE_CASE				:				str				      = TFAlbertForMaskedLM(config=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				int				      = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = model(_lowerCamelCase   )
           self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.seq_length, self.vocab_size)   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase   )					->int:
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = self.num_labels
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = TFAlbertForSequenceClassification(config=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
           SCREAMING_SNAKE_CASE				:				Tuple				      = model(_lowerCamelCase   )
           self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.num_labels)   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase   )					->Dict:
           SCREAMING_SNAKE_CASE				:				List[str]				      = TFAlbertForQuestionAnswering(config=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
           SCREAMING_SNAKE_CASE				:				int				      = model(_lowerCamelCase   )
           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 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase   )					->Any:
           SCREAMING_SNAKE_CASE				:				List[Any]				      = self.num_choices
           SCREAMING_SNAKE_CASE				:				Any				      = TFAlbertForMultipleChoice(config=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Tuple				      = tf.tile(tf.expand_dims(_lowerCamelCase				,       1   )				,       (1, self.num_choices, 1)   )
           SCREAMING_SNAKE_CASE				:				Tuple				      = tf.tile(tf.expand_dims(_lowerCamelCase				,       1   )				,       (1, self.num_choices, 1)   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = tf.tile(tf.expand_dims(_lowerCamelCase				,       1   )				,       (1, self.num_choices, 1)   )
           SCREAMING_SNAKE_CASE				:				Tuple				      = {
               '''input_ids''': multiple_choice_inputs_ids,
               '''attention_mask''': multiple_choice_input_mask,
               '''token_type_ids''': multiple_choice_token_type_ids,
           }
           SCREAMING_SNAKE_CASE				:				str				      = model(_lowerCamelCase   )
           self.parent.assertListEqual(list(result['''logits'''].shape   )				,       [self.batch_size, self.num_choices]   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase   )					->Optional[Any]:
           SCREAMING_SNAKE_CASE				:				str				      = self.num_labels
           SCREAMING_SNAKE_CASE				:				List[Any]				      = TFAlbertForTokenClassification(config=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = {
               '''input_ids''': input_ids,
               '''attention_mask''': input_mask,
               '''token_type_ids''': token_type_ids,
           }
           SCREAMING_SNAKE_CASE				:				str				      = model(_lowerCamelCase   )
           self.parent.assertListEqual(list(result['''logits'''].shape   )				,       [self.batch_size, self.seq_length, self.num_labels]   )






       def 	__lowerCAmelCase     (		self   )					->List[Any]:
           SCREAMING_SNAKE_CASE				:				List[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
           )      ,							
           )				:				Any				      = config_and_inputs
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = {'''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							):



       """simple docstring"""
       __SCREAMING_SNAKE_CASE       :					int						=  (
           (
               TFAlbertModel,
               TFAlbertForPreTraining,
               TFAlbertForMaskedLM,
               TFAlbertForSequenceClassification,
               TFAlbertForQuestionAnswering,
               TFAlbertForTokenClassification,
               TFAlbertForMultipleChoice,
           )
           if is_tf_available()
           else ()
       )
       __SCREAMING_SNAKE_CASE       :					Optional[int]						=  (
           {
               'feature-extraction': TFAlbertModel,
               'fill-mask': TFAlbertForMaskedLM,
               'question-answering': TFAlbertForQuestionAnswering,
               'text-classification': TFAlbertForSequenceClassification,
               'token-classification': TFAlbertForTokenClassification,
               'zero-shot': TFAlbertForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       __SCREAMING_SNAKE_CASE       :					Tuple						=  False
       __SCREAMING_SNAKE_CASE       :					Any						=  False






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase=False   )					->int:
           SCREAMING_SNAKE_CASE				:				Tuple				      = super()._prepare_for_class(_lowerCamelCase				,       _lowerCamelCase				,       return_labels=_lowerCamelCase   )

           if return_labels:
               if model_class in get_values(_lowerCamelCase   ):
                   SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = tf.zeros(self.model_tester.batch_size				,       dtype=tf.intaa   )

           return inputs_dict






       def 	__lowerCAmelCase     (		self   )					->Tuple:
           SCREAMING_SNAKE_CASE				:				Dict				      = TFAlbertModelTester(self   )
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = ConfigTester(self				,       config_class=_lowerCamelCase				,       hidden_size=37   )






       def 	__lowerCAmelCase     (		self   )					->Union[str, Any]:
           self.config_tester.run_common_tests()






       def 	__lowerCAmelCase     (		self   )					->str:
           SCREAMING_SNAKE_CASE				:				Tuple				      = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_albert_model(*_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self   )					->str:
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_albert_for_pretraining(*_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self   )					->Any:
           SCREAMING_SNAKE_CASE				:				Dict				      = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_albert_for_masked_lm(*_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self   )					->Optional[Any]:
           SCREAMING_SNAKE_CASE				:				List[str]				      = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_albert_for_multiple_choice(*_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self   )					->Dict:
           SCREAMING_SNAKE_CASE				:				List[Any]				      = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_albert_for_sequence_classification(*_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self   )					->str:
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_albert_for_question_answering(*_lowerCamelCase   )






       @slow
       def 	__lowerCAmelCase     (		self   )					->int:
           for model_name in TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               SCREAMING_SNAKE_CASE				:				Tuple				      = TFAlbertModel.from_pretrained(_lowerCamelCase   )
               self.assertIsNotNone(_lowerCamelCase   )






@require_tf
class     a_       (			unittest.TestCase							):



       """simple docstring"""






       @slow
       def 	__lowerCAmelCase     (		self   )					->List[Any]:
           SCREAMING_SNAKE_CASE				:				Dict				      = TFAlbertForPreTraining.from_pretrained('''albert-base-v2'''   )
           SCREAMING_SNAKE_CASE				:				str				      = tf.constant([[0, 1, 2, 3, 4, 5]]   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = model(_lowerCamelCase   )[0]

           SCREAMING_SNAKE_CASE				:				List[str]				      = [1, 6, 3_0000]
           self.assertEqual(output.shape				,       _lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Dict				      = tf.constant(
               [
                   [
                       [4.5_9_5_6_6_8, 0.7_4_4_6_2_7_5_4, -1.8_1_8_1_4_7],
                       [4.5_9_5_4_3_4_7, 0.7_4_5_4_1_8_4, -1.8_1_8_8_2_5_8],
                       [4.5_9_5_4_9_0_5, 0.7_4_4_8_2_3_5, -1.8_1_8_2_3_1_6],
                   ]
               ]   )
           tf.debugging.assert_near(output[:, :3, :3]				,       _lowerCamelCase				,       atol=1e-4   )
