


import argparse
from pathlib import Path

import requests
import torch
from PIL import Image

from transformers import (
    RobertaTokenizer,
    TrOCRConfig,
    TrOCRForCausalLM,
    TrOCRProcessor,
    VisionEncoderDecoderModel,
    ViTConfig,
    ViTImageProcessor,
    ViTModel,
)
from transformers.utils import logging


logging.set_verbosity_info()
_A		:				List[Any]									=       logging.get_logger(__name__)



def     __lowerCAmelCase						(							snake_case	:    Any						,      snake_case	:    int )       ->							Dict:
   __lowerCamelCase:				Tuple     =	[]
   for i in range(encoder_config.num_hidden_layers ):
      # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
      rename_keys.append(
          (f'encoder.deit.blocks.{i}.norm1.weight', f'encoder.encoder.layer.{i}.layernorm_before.weight') )
      rename_keys.append((f'encoder.deit.blocks.{i}.norm1.bias', f'encoder.encoder.layer.{i}.layernorm_before.bias') )
      rename_keys.append(
          (f'encoder.deit.blocks.{i}.attn.proj.weight', f'encoder.encoder.layer.{i}.attention.output.dense.weight') )
      rename_keys.append(
          (f'encoder.deit.blocks.{i}.attn.proj.bias', f'encoder.encoder.layer.{i}.attention.output.dense.bias') )
      rename_keys.append(
          (f'encoder.deit.blocks.{i}.norm2.weight', f'encoder.encoder.layer.{i}.layernorm_after.weight') )
      rename_keys.append((f'encoder.deit.blocks.{i}.norm2.bias', f'encoder.encoder.layer.{i}.layernorm_after.bias') )
      rename_keys.append(
          (f'encoder.deit.blocks.{i}.mlp.fc1.weight', f'encoder.encoder.layer.{i}.intermediate.dense.weight') )
      rename_keys.append(
          (f'encoder.deit.blocks.{i}.mlp.fc1.bias', f'encoder.encoder.layer.{i}.intermediate.dense.bias') )
      rename_keys.append(
          (f'encoder.deit.blocks.{i}.mlp.fc2.weight', f'encoder.encoder.layer.{i}.output.dense.weight') )
      rename_keys.append((f'encoder.deit.blocks.{i}.mlp.fc2.bias', f'encoder.encoder.layer.{i}.output.dense.bias') )

   # cls token, position embeddings and patch embeddings of encoder
   rename_keys.extend(
       [
           ("""encoder.deit.cls_token""", """encoder.embeddings.cls_token"""),
           ("""encoder.deit.pos_embed""", """encoder.embeddings.position_embeddings"""),
           ("""encoder.deit.patch_embed.proj.weight""", """encoder.embeddings.patch_embeddings.projection.weight"""),
           ("""encoder.deit.patch_embed.proj.bias""", """encoder.embeddings.patch_embeddings.projection.bias"""),
           ("""encoder.deit.norm.weight""", """encoder.layernorm.weight"""),
           ("""encoder.deit.norm.bias""", """encoder.layernorm.bias"""),
       ] )

   return rename_keys



def     __lowerCAmelCase						(							snake_case	:    str						,      snake_case	:    Union[str, Any] )       ->							Tuple:
   for i in range(encoder_config.num_hidden_layers ):
      # queries, keys and values (only weights, no biases)
      __lowerCamelCase:				Union[str, Any]     =	state_dict.pop(f'encoder.deit.blocks.{i}.attn.qkv.weight' )

      __lowerCamelCase:				Any     =	in_proj_weight[
          : encoder_config.hidden_size, :
      ]
      __lowerCamelCase:				Dict     =	in_proj_weight[
          encoder_config.hidden_size : encoder_config.hidden_size * 2, :
      ]
      __lowerCamelCase:				Any     =	in_proj_weight[
          -encoder_config.hidden_size :, :
      ]



def     __lowerCAmelCase						(							snake_case	:    Dict						,      snake_case	:    Union[str, Any]						,      snake_case	:    Optional[int] )       ->							int:
   __lowerCamelCase:				List[str]     =	dct.pop(snake_case )
   __lowerCamelCase:				Tuple     =	val



def     __lowerCAmelCase						(							snake_case	:    Dict )       ->							Any:
   if "handwritten" in checkpoint_url:
      __lowerCamelCase:				Tuple     =	"""https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg"""  # industry
      # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have
      # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let
      # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"  #
      # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg"
   elif "printed" in checkpoint_url or "stage1" in checkpoint_url:
      __lowerCamelCase:				Union[str, Any]     =	"""https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg"""
   __lowerCamelCase:				Union[str, Any]     =	Image.open(requests.get(snake_case						,      stream=snake_case ).raw ).convert("""RGB""" )
   return im



@torch.no_grad()
def     __lowerCAmelCase						(							snake_case	:    List[Any]						,      snake_case	:    Any )       ->							List[str]:
   __lowerCamelCase:				Union[str, Any]     =	ViTConfig(image_size=384						,      qkv_bias=snake_case )
   __lowerCamelCase:				Optional[int]     =	TrOCRConfig()

   # size of the architecture
   if "base" in checkpoint_url:
      __lowerCamelCase:				Optional[int]     =	768
   elif "large" in checkpoint_url:
      # use ViT-large encoder
      __lowerCamelCase:				Optional[int]     =	1024
      __lowerCamelCase:				int     =	4096
      __lowerCamelCase:				Tuple     =	24
      __lowerCamelCase:				Optional[Any]     =	16
      __lowerCamelCase:				str     =	1024
   else:
      raise ValueError("""Should either find 'base' or 'large' in checkpoint URL""" )

   # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards
   if "large-printed" in checkpoint_url or "stage1" in checkpoint_url:
      __lowerCamelCase:				Any     =	False
      __lowerCamelCase:				Optional[Any]     =	"""relu"""
      __lowerCamelCase:				List[Any]     =	1024
      __lowerCamelCase:				List[str]     =	True
      __lowerCamelCase:				int     =	False
      __lowerCamelCase:				int     =	False

   # load HuggingFace model
   __lowerCamelCase:				Any     =	ViTModel(snake_case						,      add_pooling_layer=snake_case )
   __lowerCamelCase:				Dict     =	TrOCRForCausalLM(snake_case )
   __lowerCamelCase:				Any     =	VisionEncoderDecoderModel(encoder=snake_case						,      decoder=snake_case )
   model.eval()

   # load state_dict of original model, rename some keys
   __lowerCamelCase:				Any     =	torch.hub.load_state_dict_from_url(snake_case						,      map_location="""cpu"""						,      check_hash=snake_case )["""model"""]

   __lowerCamelCase:				Optional[Any]     =	create_rename_keys(snake_case						,      snake_case )
   for src, dest in rename_keys:
      rename_key(snake_case						,      snake_case						,      snake_case )
   read_in_q_k_v(snake_case						,      snake_case )

   # remove parameters we don't need
   del state_dict["encoder.deit.head.weight"]
   del state_dict["encoder.deit.head.bias"]
   del state_dict["decoder.version"]

   # add prefix to decoder keys
   for key, val in state_dict.copy().items():
      __lowerCamelCase:				int     =	state_dict.pop(snake_case )
      if key.startswith("""decoder""" ) and "output_projection" not in key:
         __lowerCamelCase:				Any     =	val
      else:
         __lowerCamelCase:				List[str]     =	val

    # load state dict
   model.load_state_dict(snake_case )

   # Check outputs on an image
   __lowerCamelCase:				Any     =	ViTImageProcessor(size=encoder_config.image_size )
   __lowerCamelCase:				Tuple     =	RobertaTokenizer.from_pretrained("""roberta-large""" )
   __lowerCamelCase:				List[Any]     =	TrOCRProcessor(snake_case						,      snake_case )

   __lowerCamelCase:				Optional[int]     =	processor(images=prepare_img(snake_case )						,      return_tensors="""pt""" ).pixel_values

   # verify logits
   __lowerCamelCase:				Tuple     =	torch.tensor([[model.config.decoder.decoder_start_token_id]] )
   __lowerCamelCase:				Dict     =	model(pixel_values=snake_case						,      decoder_input_ids=snake_case )
   __lowerCamelCase:				Any     =	outputs.logits

   __lowerCamelCase:				Dict     =	torch.Size([1, 1, 50265] )
   if "trocr-base-handwritten" in checkpoint_url:
      __lowerCamelCase:				Tuple     =	torch.tensor(
          [-1.4_502, -4.6_683, -0.5_347, -2.9_291, 9.1_435, -3.0_571, 8.9_764, 1.7_560, 8.7_358, -1.5_311] )
   elif "trocr-large-handwritten" in checkpoint_url:
      __lowerCamelCase:				Optional[int]     =	torch.tensor(
          [-2.6_437, -1.3_129, -2.2_596, -5.3_455, 6.3_539, 1.7_604, 5.4_991, 1.4_702, 5.6_113, 2.0_170] )
   elif "trocr-base-printed" in checkpoint_url:
      __lowerCamelCase:				Union[str, Any]     =	torch.tensor(
          [-5.6_816, -5.8_388, 1.1_398, -6.9_034, 6.8_505, -2.4_393, 1.2_284, -1.0_232, -1.9_661, -3.9_210] )
   elif "trocr-large-printed" in checkpoint_url:
      __lowerCamelCase:				Union[str, Any]     =	torch.tensor(
          [-6.0_162, -7.0_959, 4.4_155, -5.1_063, 7.0_468, -3.1_631, 2.6_466, -0.3_081, -0.8_106, -1.7_535] )

   if "stage1" not in checkpoint_url:
      assert logits.shape == expected_shape, "Shape of logits not as expected"
      assert torch.allclose(logits[0, 0, :10]						,      snake_case						,      atol=1e-3 ), "First elements of logits not as expected"

   Path(snake_case ).mkdir(exist_ok=snake_case )
   print(f'Saving model to {pytorch_dump_folder_path}' )
   model.save_pretrained(snake_case )
   print(f'Saving processor to {pytorch_dump_folder_path}' )
   processor.save_pretrained(snake_case )


if __name__ == "__main__":
   _A		:				int									=       argparse.ArgumentParser()

   parser.add_argument(
       '''--checkpoint_url''',
       default='''https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt''',
       type=str,
       help='''URL to the original PyTorch checkpoint (.pth file).''',
   )
   parser.add_argument(
       '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.'''
   )
   _A		:				Optional[int]									=       parser.parse_args()
   convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)






from __future__ import annotations

import unittest

from transformers import DistilBertConfig, 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.models.distilbert.modeling_tf_distilbert import (
       TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFDistilBertForMaskedLM,
       TFDistilBertForMultipleChoice,
       TFDistilBertForQuestionAnswering,
       TFDistilBertForSequenceClassification,
       TFDistilBertForTokenClassification,
       TFDistilBertModel,
   )



class        a					:





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





     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        __lowerCamelCase:				int     =	ids_tensor([self.batch_size, self.seq_length]    ,	self.vocab_size							)

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

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

        __lowerCamelCase:				Any     =	DistilBertConfig(
            vocab_size=self.vocab_size    ,	dim=self.hidden_size    ,	n_layers=self.num_hidden_layers    ,	n_heads=self.num_attention_heads    ,	hidden_dim=self.intermediate_size    ,	hidden_act=self.hidden_act    ,	dropout=self.hidden_dropout_prob    ,	attention_dropout=self.attention_probs_dropout_prob    ,	max_position_embeddings=self.max_position_embeddings    ,	initializer_range=self.initializer_range    ,	)

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





     def  SCREAMING_SNAKE_CASE__       (    self					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				List[str]							):
        __lowerCamelCase:				str     =	TFDistilBertModel(config=SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				List[Any]     =	{"""input_ids""": input_ids, """attention_mask""": input_mask}

        __lowerCamelCase:				Optional[Any]     =	model(SCREAMING_SNAKE_CASE_							)

        __lowerCamelCase:				int     =	[input_ids, input_mask]

        __lowerCamelCase:				str     =	model(SCREAMING_SNAKE_CASE_							)

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





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				str    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				Dict							):
        __lowerCamelCase:				Any     =	TFDistilBertForMaskedLM(config=SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Dict     =	{"""input_ids""": input_ids, """attention_mask""": input_mask}
        __lowerCamelCase:				str     =	model(SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.seq_length, self.vocab_size)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]							):
        __lowerCamelCase:				Optional[int]     =	TFDistilBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Tuple     =	{
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
        }
        __lowerCamelCase:				Tuple     =	model(SCREAMING_SNAKE_CASE_							)
        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  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]							):
        __lowerCamelCase:				Any     =	self.num_labels
        __lowerCamelCase:				Optional[Any]     =	TFDistilBertForSequenceClassification(SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Dict     =	{"""input_ids""": input_ids, """attention_mask""": input_mask}
        __lowerCamelCase:				Optional[int]     =	model(SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.num_labels)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				int    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				int    ,	SCREAMING_SNAKE_CASE_					:				Dict							):
        __lowerCamelCase:				Tuple     =	self.num_choices
        __lowerCamelCase:				Optional[int]     =	TFDistilBertForMultipleChoice(SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Optional[Any]     =	tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_    ,	1							)    ,	(1, self.num_choices, 1)							)
        __lowerCamelCase:				str     =	tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_    ,	1							)    ,	(1, self.num_choices, 1)							)
        __lowerCamelCase:				List[Any]     =	{
            """input_ids""": multiple_choice_inputs_ids,
            """attention_mask""": multiple_choice_input_mask,
        }
        __lowerCamelCase:				int     =	model(SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.num_choices)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]							):
        __lowerCamelCase:				Union[str, Any]     =	self.num_labels
        __lowerCamelCase:				Optional[int]     =	TFDistilBertForTokenClassification(SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Optional[Any]     =	{"""input_ids""": input_ids, """attention_mask""": input_mask}
        __lowerCamelCase:				str     =	model(SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.seq_length, self.num_labels)							)







     def  SCREAMING_SNAKE_CASE__       (    self					:				Tuple							):
        __lowerCamelCase:				Dict     =	self.prepare_config_and_inputs()
        ((__lowerCamelCase)   ,     (__lowerCamelCase)   ,     (__lowerCamelCase)   ,     (__lowerCamelCase)   ,     (__lowerCamelCase)   ,     (__lowerCamelCase)):				Tuple     =	config_and_inputs
        __lowerCamelCase:				Dict     =	{"""input_ids""": input_ids, """attention_mask""": input_mask}
        return config, inputs_dict



@require_tf
class        a					(			_UpperCAmelCase     ,_UpperCAmelCase     ,unittest.TestCase   ):
     UpperCAmelCase__ :  Any						      =	(
         (
             TFDistilBertModel,
             TFDistilBertForMaskedLM,
             TFDistilBertForQuestionAnswering,
             TFDistilBertForSequenceClassification,
             TFDistilBertForTokenClassification,
             TFDistilBertForMultipleChoice,
         )
         if is_tf_available()
         else None
     )
     UpperCAmelCase__ :  Dict						      =	(
         {
             "feature-extraction": TFDistilBertModel,
             "fill-mask": TFDistilBertForMaskedLM,
             "question-answering": TFDistilBertForQuestionAnswering,
             "text-classification": TFDistilBertForSequenceClassification,
             "token-classification": TFDistilBertForTokenClassification,
             "zero-shot": TFDistilBertForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     UpperCAmelCase__ :  Optional[Any]						      =	False
     UpperCAmelCase__ :  Tuple						      =	False





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[int]							):
        __lowerCamelCase:				List[str]     =	TFDistilBertModelTester(self							)
        __lowerCamelCase:				Union[str, Any]     =	ConfigTester(self    ,	config_class=SCREAMING_SNAKE_CASE_    ,	dim=37							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[int]							):
        self.config_tester.run_common_tests()





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]							):
        __lowerCamelCase:				Dict     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_distilbert_model(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        __lowerCamelCase:				List[Any]     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_distilbert_for_masked_lm(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        __lowerCamelCase:				Tuple     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_distilbert_for_question_answering(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]							):
        __lowerCamelCase:				List[Any]     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_distilbert_for_sequence_classification(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]							):
        __lowerCamelCase:				List[Any]     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_distilbert_for_multiple_choice(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				str							):
        __lowerCamelCase:				int     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_distilbert_for_token_classification(*SCREAMING_SNAKE_CASE_							)







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]							):
           __lowerCamelCase:				List[str]     =	TFDistilBertModel.from_pretrained(SCREAMING_SNAKE_CASE_							)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_							)



@require_tf
class        a					(			unittest.TestCase   ):





     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        __lowerCamelCase:				int     =	TFDistilBertModel.from_pretrained("""distilbert-base-uncased"""							)
        __lowerCamelCase:				Optional[Any]     =	tf.constant([[0, 1, 2, 3, 4, 5]]							)
        __lowerCamelCase:				Any     =	model(SCREAMING_SNAKE_CASE_							)[0]

        __lowerCamelCase:				Union[str, Any]     =	[1, 6, 768]
        self.assertEqual(output.shape    ,	SCREAMING_SNAKE_CASE_							)

        __lowerCamelCase:				List[Any]     =	tf.constant(
            [
                [
                    [0.1926_1885, -0.1373_2955, 0.411_9799],
                    [0.2215_0156, -0.0742_2661, 0.3903_7204],
                    [0.2275_6018, -0.089_6414, 0.370_1467],
                ]
            ]							)
        tf.debugging.assert_near(output[:, :3, :3]    ,	SCREAMING_SNAKE_CASE_    ,	atol=1E-4							)


