




"""simple docstring"""







import copy
import inspect

from transformers.testing_utils import require_torch, torch_device
from transformers.utils.backbone_utils import BackboneType

@require_torch
class 							snake_case_ :







   """simple docstring"""




   A_										=					()
   A_										=					True







   def      UpperCAmelCase__ (		self)							->      Tuple:
       UpperCamelCase										=  self.config_class

       # test default config
       UpperCamelCase										=  config_class()
       self.assertIsNotNone(lowerCamelCase_)
       UpperCamelCase										=  ['''stem'''] + [F'stage{idx}' for idx in range(1					,				len(config.depths) + 1)]
       self.assertEqual(config.stage_names					,				lowerCamelCase_)
       self.assertTrue(set(config.out_features).issubset(set(config.stage_names)))

       # Test out_features and out_indices are correctly set
       # out_features and out_indices both None
       UpperCamelCase										=  config_class(out_features=lowerCamelCase_					,				out_indices=lowerCamelCase_)
       self.assertEqual(config.out_features					,				[config.stage_names[-1]])
       self.assertEqual(config.out_indices					,				[len(config.stage_names) - 1])

       # out_features and out_indices both set
       UpperCamelCase										=  config_class(out_features=['''stem''', '''stage1''']					,				out_indices=[0, 1])
       self.assertEqual(config.out_features					,				['''stem''', '''stage1'''])
       self.assertEqual(config.out_indices					,				[0, 1])

       # Only out_features set
       UpperCamelCase										=  config_class(out_features=['''stage1''', '''stage3'''])
       self.assertEqual(config.out_features					,				['''stage1''', '''stage3'''])
       self.assertEqual(config.out_indices					,				[1, 3])

       # Only out_indices set
       UpperCamelCase										=  config_class(out_indices=[0, 2])
       self.assertEqual(config.out_features					,				[config.stage_names[0], config.stage_names[2]])
       self.assertEqual(config.out_indices					,				[0, 2])

       # Error raised when out_indices do not correspond to out_features
       with self.assertRaises(lowerCamelCase_):
           UpperCamelCase										=  config_class(out_features=['''stage1''', '''stage2''']					,				out_indices=[0, 2])







   def      UpperCAmelCase__ (		self)							->      int:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase										=  model_class(lowerCamelCase_)
           UpperCamelCase										=  inspect.signature(model.forward)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           UpperCamelCase										=  [*signature.parameters.keys()]
           UpperCamelCase										=  ['''pixel_values''']
           self.assertListEqual(arg_names[:1]					,				lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[str]:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase										=  model_class(lowerCamelCase_)
           self.assertEqual(len(model.channels)					,				len(config.out_features))
           UpperCamelCase										=  model.num_features
           UpperCamelCase										=  [config.stage_names.index(lowerCamelCase_) for feat in config.out_features]
           UpperCamelCase										=  [num_features[idx] for idx in out_indices]
           self.assertListEqual(model.channels					,				lowerCamelCase_)

           UpperCamelCase										=  copy.deepcopy(lowerCamelCase_)
           UpperCamelCase										=  None
           UpperCamelCase										=  model_class(lowerCamelCase_)
           self.assertEqual(len(model.channels)					,				1)
           self.assertListEqual(model.channels					,				[num_features[-1]])

           UpperCamelCase										=  copy.deepcopy(lowerCamelCase_)
           UpperCamelCase										=  None
           UpperCamelCase										=  model_class(lowerCamelCase_)
           self.assertEqual(len(model.channels)					,				1)
           self.assertListEqual(model.channels					,				[num_features[-1]])







   def      UpperCAmelCase__ (		self)							->      Optional[Any]:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase										=  model_class(lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           UpperCamelCase										=  model(**lowerCamelCase_)

           self.assertEqual(len(result.feature_maps)					,				len(config.out_features))
           self.assertEqual(len(model.channels)					,				len(config.out_features))
           self.assertEqual(len(result.feature_maps)					,				len(config.out_indices))
           self.assertEqual(len(model.channels)					,				len(config.out_indices))

           # Check output of last stage is taken if out_features=None, out_indices=None
           UpperCamelCase										=  copy.deepcopy(lowerCamelCase_)
           UpperCamelCase										=  None
           UpperCamelCase										=  model_class(lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           UpperCamelCase										=  model(**lowerCamelCase_)

           self.assertEqual(len(result.feature_maps)					,				1)
           self.assertEqual(len(model.channels)					,				1)

           UpperCamelCase										=  copy.deepcopy(lowerCamelCase_)
           UpperCamelCase										=  None
           UpperCamelCase										=  model_class(lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           UpperCamelCase										=  model(**lowerCamelCase_)

           self.assertEqual(len(result.feature_maps)					,				1)
           self.assertEqual(len(model.channels)					,				1)

           # Check backbone can be initialized with fresh weights
           UpperCamelCase										=  copy.deepcopy(lowerCamelCase_)
           UpperCamelCase										=  False
           UpperCamelCase										=  model_class(lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           UpperCamelCase										=  model(**lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      Dict:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()

       for backbone_class in self.all_model_classes:
           UpperCamelCase										=  backbone_class(lowerCamelCase_)

           self.assertTrue(hasattr(lowerCamelCase_					,				'''backbone_type'''))
           self.assertTrue(hasattr(lowerCamelCase_					,				'''stage_names'''))
           self.assertTrue(hasattr(lowerCamelCase_					,				'''num_features'''))
           self.assertTrue(hasattr(lowerCamelCase_					,				'''out_indices'''))
           self.assertTrue(hasattr(lowerCamelCase_					,				'''out_features'''))
           self.assertTrue(hasattr(lowerCamelCase_					,				'''out_feature_channels'''))
           self.assertTrue(hasattr(lowerCamelCase_					,				'''channels'''))

           self.assertIsInstance(backbone.backbone_type					,				lowerCamelCase_)
           # Verify num_features has been initialized in the backbone init
           self.assertIsNotNone(backbone.num_features)
           self.assertTrue(len(backbone.channels) == len(backbone.out_indices))
           self.assertTrue(len(backbone.stage_names) == len(backbone.num_features))
           self.assertTrue(len(backbone.channels) <= len(backbone.num_features))
           self.assertTrue(len(backbone.out_feature_channels) == len(backbone.stage_names))







   def      UpperCAmelCase__ (		self)							->      Dict:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase										=  inputs_dict['''pixel_values'''].shape[0]

       for backbone_class in self.all_model_classes:
           UpperCamelCase										=  backbone_class(lowerCamelCase_)
           backbone.to(lowerCamelCase_)
           backbone.eval()

           UpperCamelCase										=  backbone(**lowerCamelCase_)

           # Test default outputs and verify feature maps
           self.assertIsInstance(outputs.feature_maps					,				lowerCamelCase_)
           self.assertTrue(len(outputs.feature_maps) == len(backbone.channels))
           for feature_map, n_channels in zip(outputs.feature_maps					,				backbone.channels):
               self.assertTrue(feature_map.shape[:2]					,				(batch_size, n_channels))
           self.assertIsNone(outputs.hidden_states)
           self.assertIsNone(outputs.attentions)

           # Test output_hidden_states=True
           UpperCamelCase										=  backbone(**lowerCamelCase_					,				output_hidden_states=lowerCamelCase_)
           self.assertIsNotNone(outputs.hidden_states)
           self.assertTrue(len(outputs.hidden_states)					,				len(backbone.stage_names))
           for hidden_state, n_channels in zip(outputs.hidden_states					,				backbone.channels):
               self.assertTrue(hidden_state.shape[:2]					,				(batch_size, n_channels))

           # Test output_attentions=True
           if self.has_attentions:
               UpperCamelCase										=  backbone(**lowerCamelCase_					,				output_attentions=lowerCamelCase_)
               self.assertIsNotNone(outputs.attentions)





"""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 							snake_case_ (				lowerCamelCase_ ):







   """simple docstring"""




   def __init__(		self					,				lowerCamelCase_					,				)							->      Any:
       UpperCamelCase										=  parent
       UpperCamelCase										=  1_3
       UpperCamelCase										=  7
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  9_9
       UpperCamelCase										=  3_2
       UpperCamelCase										=  2
       UpperCamelCase										=  4
       UpperCamelCase										=  3_7
       UpperCamelCase										=  '''gelu'''
       UpperCamelCase										=  0.1
       UpperCamelCase										=  0.1
       UpperCamelCase										=  5_1_2
       UpperCamelCase										=  1_6
       UpperCamelCase										=  2
       UpperCamelCase										=  0.02
       UpperCamelCase										=  3
       UpperCamelCase										=  4
       UpperCamelCase										=  None
       UpperCamelCase										=  self.vocab_size - 1







   def      UpperCAmelCase__ (		self)							->      int:
       UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.vocab_size)

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

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

       UpperCamelCase										=  None
       if self.use_mc_token_ids:
           UpperCamelCase										=  ids_tensor([self.batch_size, self.num_choices]					,				self.seq_length)

       UpperCamelCase										=  None
       UpperCamelCase										=  None
       UpperCamelCase										=  None
       if self.use_labels:
           UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.type_sequence_label_size)
           UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.num_labels)
           UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.num_choices)

       UpperCamelCase										=  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					,				)

       UpperCamelCase										=  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      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      Optional[Any]:
       UpperCamelCase										=  TFCTRLModel(config=lowerCamelCase_)
       UpperCamelCase										=  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
       UpperCamelCase										=  model(lowerCamelCase_)

       UpperCamelCase										=  [input_ids, None, input_mask]  # None is the input for 'past'
       UpperCamelCase										=  model(lowerCamelCase_)

       UpperCamelCase										=  model(lowerCamelCase_)

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







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      int:
       UpperCamelCase										=  TFCTRLLMHeadModel(config=lowerCamelCase_)
       UpperCamelCase										=  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
       UpperCamelCase										=  model(lowerCamelCase_)
       self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.seq_length, self.vocab_size))







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      List[str]:
       UpperCamelCase										=  self.num_labels
       UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.type_sequence_label_size)
       UpperCamelCase										=  {
           '''input_ids''': input_ids,
           '''token_type_ids''': token_type_ids,
           '''labels''': sequence_labels,
       }
       UpperCamelCase										=  TFCTRLForSequenceClassification(lowerCamelCase_)
       UpperCamelCase										=  model(lowerCamelCase_)
       self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.num_labels))







   def      UpperCAmelCase__ (		self)							->      str:
       UpperCamelCase										=  self.prepare_config_and_inputs()

       (
           (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  
       )										=  config_and_inputs

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

@require_tf
class 							snake_case_ (				lowerCamelCase_  ,   lowerCamelCase_  ,   unittest.TestCase ):







   """simple docstring"""




   A_										=					(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
   A_										=					(TFCTRLLMHeadModel,) if is_tf_available() else ()
   A_										=					(
       {
           '''feature-extraction''': TFCTRLModel,
           '''text-classification''': TFCTRLForSequenceClassification,
           '''text-generation''': TFCTRLLMHeadModel,
           '''zero-shot''': TFCTRLForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   A_										=					False
   A_										=					False







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_)							->      int:
       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      UpperCAmelCase__ (		self)							->      int:
       UpperCamelCase										=  TFCTRLModelTester(self)
       UpperCamelCase										=  ConfigTester(self					,				config_class=lowerCamelCase_					,				n_embd=3_7)







   def      UpperCAmelCase__ (		self)							->      int:
       self.config_tester.run_common_tests()







   def      UpperCAmelCase__ (		self)							->      Union[str, Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_model(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_lm_head(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_for_sequence_classification(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[str]:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase										=  [TFCTRLLMHeadModel]
       UpperCamelCase										=  [TFCTRLForSequenceClassification]

       for model_class in self.all_model_classes:
           UpperCamelCase										=  model_class(lowerCamelCase_)
           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:
               UpperCamelCase										=  model.get_output_embeddings()
               assert isinstance(lowerCamelCase_					,				tf.keras.layers.Layer)
               UpperCamelCase										=  model.get_bias()
               assert isinstance(lowerCamelCase_					,				lowerCamelCase_)
               for k, v in name.items():
                   assert isinstance(lowerCamelCase_					,				tf.Variable)
           elif model_class in list_other_models_with_output_ebd:
               UpperCamelCase										=  model.get_output_embeddings()
               assert isinstance(lowerCamelCase_					,				tf.keras.layers.Layer)
               UpperCamelCase										=  model.get_bias()
               assert name is None
           else:
               UpperCamelCase										=  model.get_output_embeddings()
               assert x is None
               UpperCamelCase										=  model.get_bias()
               assert name is None







   @slow
   def      UpperCAmelCase__ (		self)							->      List[Any]:
       for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase										=  TFCTRLModel.from_pretrained(lowerCamelCase_)
           self.assertIsNotNone(lowerCamelCase_)

@require_tf
class 							snake_case_ (				unittest.TestCase ):







   """simple docstring"""




   @slow
   def      UpperCAmelCase__ (		self)							->      str:
       UpperCamelCase										=  TFCTRLLMHeadModel.from_pretrained('''ctrl''')
       UpperCamelCase										=  tf.convert_to_tensor([[1_1_8_5_9, 0, 1_6_1_1, 8]]					,				dtype=tf.intaa)  # Legal the president is
       UpperCamelCase										=  [
           1_1_8_5_9,
           0,
           1_6_1_1,
           8,
           5,
           1_5_0,
           2_6_4_4_9,
           2,
           1_9,
           3_4_8,
           4_6_9,
           3,
           2_5_9_5,
           4_8,
           2_0_7_4_0,
           2_4_6_5_3_3,
           2_4_6_5_3_3,
           1_9,
           3_0,
           5,
       ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

       UpperCamelCase										=  model.generate(lowerCamelCase_					,				do_sample=lowerCamelCase_)
       self.assertListEqual(output_ids[0].numpy().tolist()					,				lowerCamelCase_)