


'''simple docstring'''



from __future__ import annotations

import unittest

from transformers import CTRLConfig, 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.ctrl.modeling_tf_ctrl import (
          TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFCTRLForSequenceClassification,
          TFCTRLLMHeadModel,
          TFCTRLModel,
      )

class      UpperCAmelCase_						(__SCREAMING_SNAKE_CASE						):





    """simple docstring"""






    def __init__(							self    ,  SCREAMING_SNAKE_CASE_    ,  )       ->  List[Any]:
         __lowerCamelCase     :			List[str]              =	parent
         __lowerCamelCase     :			str              =	13
         __lowerCamelCase     :			Any              =	7
         __lowerCamelCase     :			str              =	True
         __lowerCamelCase     :			int              =	True
         __lowerCamelCase     :			Optional[Any]              =	True
         __lowerCamelCase     :			Optional[Any]              =	True
         __lowerCamelCase     :			str              =	True
         __lowerCamelCase     :			Any              =	99
         __lowerCamelCase     :			int              =	32
         __lowerCamelCase     :			str              =	2
         __lowerCamelCase     :			Optional[Any]              =	4
         __lowerCamelCase     :			str              =	37
         __lowerCamelCase     :			Optional[int]              =	'''gelu'''
         __lowerCamelCase     :			List[Any]              =	0.1
         __lowerCamelCase     :			Dict              =	0.1
         __lowerCamelCase     :			str              =	5_12
         __lowerCamelCase     :			List[str]              =	16
         __lowerCamelCase     :			Tuple              =	2
         __lowerCamelCase     :			List[str]              =	0.0_2
         __lowerCamelCase     :			Optional[int]              =	3
         __lowerCamelCase     :			Optional[int]              =	4
         __lowerCamelCase     :			List[str]              =	None
         __lowerCamelCase     :			List[str]              =	self.vocab_size - 1







    def    lowercase_       (							self			)       ->  Optional[Any]:
         __lowerCamelCase     :			Union[str, Any]              =	ids_tensor([self.batch_size, self.seq_length]    ,  self.vocab_size			)

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

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

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

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

         __lowerCamelCase     :			List[Any]              =	CTRLConfig(
             vocab_size=self.vocab_size    ,  n_embd=self.hidden_size    ,  n_layer=self.num_hidden_layers    ,  n_head=self.num_attention_heads    ,  n_positions=self.max_position_embeddings    ,  pad_token_id=self.pad_token_id    ,  )

         __lowerCamelCase     :			List[Any]              =	ids_tensor([self.num_hidden_layers, self.num_attention_heads]    ,  2			)

         return (
             config,
             input_ids,
             input_mask,
             head_mask,
             token_type_ids,
             mc_token_ids,
             sequence_labels,
             token_labels,
             choice_labels,
         )







    def    lowercase_       (							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  *SCREAMING_SNAKE_CASE_			)       ->  List[str]:
         __lowerCamelCase     :			Tuple              =	TFCTRLModel(config=UpperCamelCase__			)
         __lowerCamelCase     :			Union[str, Any]              =	{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
         __lowerCamelCase     :			Optional[int]              =	model(UpperCamelCase__			)

         __lowerCamelCase     :			Optional[Any]              =	[input_ids, None, input_mask]  # None is the input for 'past'
         __lowerCamelCase     :			str              =	model(UpperCamelCase__			)

         __lowerCamelCase     :			Optional[Any]              =	model(UpperCamelCase__			)

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







    def    lowercase_       (							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  *SCREAMING_SNAKE_CASE_			)       ->  List[Any]:
         __lowerCamelCase     :			Union[str, Any]              =	TFCTRLLMHeadModel(config=UpperCamelCase__			)
         __lowerCamelCase     :			int              =	{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
         __lowerCamelCase     :			Any              =	model(UpperCamelCase__			)
         self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.seq_length, self.vocab_size)			)







    def    lowercase_       (							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  *SCREAMING_SNAKE_CASE_			)       ->  Optional[Any]:
         __lowerCamelCase     :			int              =	self.num_labels
         __lowerCamelCase     :			Optional[int]              =	ids_tensor([self.batch_size]    ,  self.type_sequence_label_size			)
         __lowerCamelCase     :			Any              =	{
             '''input_ids''': input_ids,
             '''token_type_ids''': token_type_ids,
             '''labels''': sequence_labels,
         }
         __lowerCamelCase     :			Dict              =	TFCTRLForSequenceClassification(UpperCamelCase__			)
         __lowerCamelCase     :			int              =	model(UpperCamelCase__			)
         self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.num_labels)			)







    def    lowercase_       (							self			)       ->  str:
         __lowerCamelCase     :			Union[str, Any]              =	self.prepare_config_and_inputs()

         (
             __lowerCamelCase
         )     :			str              =	config_and_inputs

         __lowerCamelCase     :			Any              =	{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
         return config, inputs_dict







@require_tf
class      UpperCAmelCase_						(__SCREAMING_SNAKE_CASE      ,	__SCREAMING_SNAKE_CASE      ,	unittest.TestCase						):





    """simple docstring"""






    lowerCamelCase						:      List[Any]							  =    (TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
    lowerCamelCase						:      int							  =    (TFCTRLLMHeadModel,) if is_tf_available() else ()
    lowerCamelCase						:      str							  =    (
        {
            'feature-extraction': TFCTRLModel,
            'text-classification': TFCTRLForSequenceClassification,
            'text-generation': TFCTRLLMHeadModel,
            'zero-shot': TFCTRLForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    lowerCamelCase						:      Union[str, Any]							  =    False
    lowerCamelCase						:      List[str]							  =    False







    def    lowercase_       (							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			)       ->  str:







         if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
              # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
              # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
              # config could not be created.
              return True

         return False







    def    lowercase_       (							self			)       ->  Optional[Any]:
         __lowerCamelCase     :			str              =	TFCTRLModelTester(self			)
         __lowerCamelCase     :			Dict              =	ConfigTester(self    ,  config_class=UpperCamelCase__    ,  n_embd=37			)







    def    lowercase_       (							self			)       ->  Optional[int]:
         self.config_tester.run_common_tests()







    def    lowercase_       (							self			)       ->  Tuple:
         __lowerCamelCase     :			Optional[int]              =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_model(*UpperCamelCase__			)







    def    lowercase_       (							self			)       ->  List[str]:
         __lowerCamelCase     :			Union[str, Any]              =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_lm_head(*UpperCamelCase__			)







    def    lowercase_       (							self			)       ->  str:
         __lowerCamelCase     :			Dict              =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_for_sequence_classification(*UpperCamelCase__			)







    def    lowercase_       (							self			)       ->  List[Any]:
         __lowerCamelCase     :			Union[str, Any]              =	self.model_tester.prepare_config_and_inputs_for_common()
         __lowerCamelCase     :			int              =	[TFCTRLLMHeadModel]
         __lowerCamelCase     :			Tuple              =	[TFCTRLForSequenceClassification]

         for model_class in self.all_model_classes:
              __lowerCamelCase     :			List[Any]              =	model_class(UpperCamelCase__			)
              model.build()  # may be needed for the get_bias() call below
              assert isinstance(model.get_input_embeddings()    ,  tf.keras.layers.Layer			)

              if model_class in list_lm_models:
                   __lowerCamelCase     :			Optional[Any]              =	model.get_output_embeddings()
                   assert isinstance(UpperCamelCase__    ,  tf.keras.layers.Layer			)
                   __lowerCamelCase     :			Any              =	model.get_bias()
                   assert isinstance(UpperCamelCase__    ,  UpperCamelCase__			)
                   for k, v in name.items():
                        assert isinstance(UpperCamelCase__    ,  tf.Variable			)
              elif model_class in list_other_models_with_output_ebd:
                   __lowerCamelCase     :			List[Any]              =	model.get_output_embeddings()
                   assert isinstance(UpperCamelCase__    ,  tf.keras.layers.Layer			)
                   __lowerCamelCase     :			int              =	model.get_bias()
                   assert name is None
              else:
                   __lowerCamelCase     :			Tuple              =	model.get_output_embeddings()
                   assert x is None
                   __lowerCamelCase     :			Dict              =	model.get_bias()
                   assert name is None







    @slow
    def    lowercase_       (							self			)       ->  Optional[int]:







         for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowerCamelCase     :			str              =	TFCTRLModel.from_pretrained(UpperCamelCase__			)
              self.assertIsNotNone(UpperCamelCase__			)







@require_tf
class      UpperCAmelCase_						(unittest.TestCase						):





    """simple docstring"""






    @slow
    def    lowercase_       (							self			)       ->  Union[str, Any]:
         __lowerCamelCase     :			Optional[Any]              =	TFCTRLLMHeadModel.from_pretrained('ctrl'			)
         __lowerCamelCase     :			Optional[Any]              =	tf.convert_to_tensor([[1_18_59, 0, 16_11, 8]]    ,  dtype=tf.intaa			)  # Legal the president is
         __lowerCamelCase     :			Dict              =	[
             1_18_59,
             0,
             16_11,
             8,
             5,
             1_50,
             2_64_49,
             2,
             19,
             3_48,
             4_69,
             3,
             25_95,
             48,
             2_07_40,
             24_65_33,
             24_65_33,
             19,
             30,
             5,
         ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

         __lowerCamelCase     :			int              =	model.generate(UpperCamelCase__    ,  do_sample=UpperCamelCase__			)
         self.assertListEqual(output_ids[0].numpy().tolist()    ,  UpperCamelCase__			)










'''simple docstring'''



import argparse
import pathlib

import fairseq
import torch
from fairseq.models.roberta import RobertaModel as FairseqRobertaModel
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import RobertaConfig, RobertaForMaskedLM, RobertaForSequenceClassification
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("""0.9.0"""):
      raise Exception("""requires fairseq >= 0.9.0""")


logging.set_verbosity_info()
A__	:      List[str]				=						logging.get_logger(__name__)

A__	:      Union[str, Any]				=						"""Hello world! cécé herlolip"""



def     UpperCAmelCase__      (			UpperCAmelCase_					:       str   ,					UpperCAmelCase_					:       str   ,					UpperCAmelCase_					:       bool							)  ->	Optional[Any]:
     __lowerCamelCase     :			Any              =	FairseqRobertaModel.from_pretrained(UpperCAmelCase_							)
     roberta.eval()  # disable dropout
     __lowerCamelCase     :			Optional[int]              =	roberta.model.encoder.sentence_encoder
     __lowerCamelCase     :			Optional[Any]              =	RobertaConfig(
         vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings   ,					hidden_size=roberta.args.encoder_embed_dim   ,					num_hidden_layers=roberta.args.encoder_layers   ,					num_attention_heads=roberta.args.encoder_attention_heads   ,					intermediate_size=roberta.args.encoder_ffn_embed_dim   ,					max_position_embeddings=5_14   ,					type_vocab_size=1   ,					layer_norm_eps=1e-5   ,					)
     if classification_head:
          __lowerCamelCase     :			Optional[Any]              =	roberta.model.classification_heads['mnli'].out_proj.weight.shape[0]
     print('Our BERT config:'   ,					UpperCAmelCase_							)

     __lowerCamelCase     :			Tuple              =	RobertaForSequenceClassification(UpperCAmelCase_							) if classification_head else RobertaForMaskedLM(UpperCAmelCase_							)
     model.eval()

     # Now let's copy all the weights.
     # Embeddings
     __lowerCamelCase     :			Optional[Any]              =	roberta_sent_encoder.embed_tokens.weight
     __lowerCamelCase     :			List[str]              =	roberta_sent_encoder.embed_positions.weight
     __lowerCamelCase     :			Tuple              =	torch.zeros_like(
         model.roberta.embeddings.token_type_embeddings.weight							)  # just zero them out b/c RoBERTa doesn't use them.
     __lowerCamelCase     :			Any              =	roberta_sent_encoder.emb_layer_norm.weight
     __lowerCamelCase     :			Tuple              =	roberta_sent_encoder.emb_layer_norm.bias

     for i in range(config.num_hidden_layers							):
          # Encoder: start of layer
          __lowerCamelCase     :			BertLayer              =	model.roberta.encoder.layer[i]
          __lowerCamelCase     :			TransformerSentenceEncoderLayer              =	roberta_sent_encoder.layers[i]

          # self attention
          __lowerCamelCase     :			BertSelfAttention              =	layer.attention.self
          assert (
              roberta_layer.self_attn.k_proj.weight.data.shape
              == roberta_layer.self_attn.q_proj.weight.data.shape
              == roberta_layer.self_attn.v_proj.weight.data.shape
              == torch.Size((config.hidden_size, config.hidden_size)							)
          )

          __lowerCamelCase     :			Optional[int]              =	roberta_layer.self_attn.q_proj.weight
          __lowerCamelCase     :			Any              =	roberta_layer.self_attn.q_proj.bias
          __lowerCamelCase     :			Tuple              =	roberta_layer.self_attn.k_proj.weight
          __lowerCamelCase     :			Dict              =	roberta_layer.self_attn.k_proj.bias
          __lowerCamelCase     :			Any              =	roberta_layer.self_attn.v_proj.weight
          __lowerCamelCase     :			List[Any]              =	roberta_layer.self_attn.v_proj.bias

          # self-attention output
          __lowerCamelCase     :			BertSelfOutput              =	layer.attention.output
          assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
          __lowerCamelCase     :			List[Any]              =	roberta_layer.self_attn.out_proj.weight
          __lowerCamelCase     :			Dict              =	roberta_layer.self_attn.out_proj.bias
          __lowerCamelCase     :			Tuple              =	roberta_layer.self_attn_layer_norm.weight
          __lowerCamelCase     :			List[str]              =	roberta_layer.self_attn_layer_norm.bias

          # intermediate
          __lowerCamelCase     :			BertIntermediate              =	layer.intermediate
          assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
          __lowerCamelCase     :			Union[str, Any]              =	roberta_layer.fca.weight
          __lowerCamelCase     :			Optional[Any]              =	roberta_layer.fca.bias

          # output
          __lowerCamelCase     :			BertOutput              =	layer.output
          assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
          __lowerCamelCase     :			str              =	roberta_layer.fca.weight
          __lowerCamelCase     :			Tuple              =	roberta_layer.fca.bias
          __lowerCamelCase     :			Optional[int]              =	roberta_layer.final_layer_norm.weight
          __lowerCamelCase     :			Optional[Any]              =	roberta_layer.final_layer_norm.bias
          # end of layer

     if classification_head:
          __lowerCamelCase     :			Dict              =	roberta.model.classification_heads['mnli'].dense.weight
          __lowerCamelCase     :			Union[str, Any]              =	roberta.model.classification_heads['mnli'].dense.bias
          __lowerCamelCase     :			Optional[int]              =	roberta.model.classification_heads['mnli'].out_proj.weight
          __lowerCamelCase     :			Any              =	roberta.model.classification_heads['mnli'].out_proj.bias
     else:
          # LM Head
          __lowerCamelCase     :			str              =	roberta.model.encoder.lm_head.dense.weight
          __lowerCamelCase     :			List[Any]              =	roberta.model.encoder.lm_head.dense.bias
          __lowerCamelCase     :			str              =	roberta.model.encoder.lm_head.layer_norm.weight
          __lowerCamelCase     :			int              =	roberta.model.encoder.lm_head.layer_norm.bias
          __lowerCamelCase     :			Optional[Any]              =	roberta.model.encoder.lm_head.weight
          __lowerCamelCase     :			Tuple              =	roberta.model.encoder.lm_head.bias

     # Let's check that we get the same results.
     __lowerCamelCase     :			torch.Tensor              =	roberta.encode(UpperCAmelCase_							).unsqueeze(0							)  # batch of size 1

     __lowerCamelCase     :			int              =	model(UpperCAmelCase_							)[0]
     if classification_head:
          __lowerCamelCase     :			List[str]              =	roberta.model.classification_heads['mnli'](roberta.extract_features(UpperCAmelCase_							)							)
     else:
          __lowerCamelCase     :			Dict              =	roberta.model(UpperCAmelCase_							)[0]
     print(our_output.shape   ,					their_output.shape							)
     __lowerCamelCase     :			Union[str, Any]              =	torch.max(torch.abs(our_output - their_output							)							).item()
     print(F'max_absolute_diff = {max_absolute_diff}'							)  # ~ 1e-7
     __lowerCamelCase     :			List[str]              =	torch.allclose(UpperCAmelCase_   ,					UpperCAmelCase_   ,					atol=1e-3							)
     print('Do both models output the same tensors?'   ,					'🔥' if success else '💩'							)
     if not success:
          raise Exception('Something went wRoNg'							)

     pathlib.Path(UpperCAmelCase_							).mkdir(parents=UpperCAmelCase_   ,					exist_ok=UpperCAmelCase_							)
     print(F'Saving model to {pytorch_dump_folder_path}'							)
     model.save_pretrained(UpperCAmelCase_							)


if __name__ == "__main__":
      A__	:      Optional[Any]				=						argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          """--roberta_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump."""
      )
      parser.add_argument(
          """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
      )
      parser.add_argument(
          """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head."""
      )
      A__	:      Optional[Any]				=						parser.parse_args()
      convert_roberta_checkpoint_to_pytorch(
          args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
      )






