




import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only

from utils import save_json

def 					SCREAMING_SNAKE_CASE							(   __UpperCamelCase)			->     int:
     a      =      filter(lambda __UpperCamelCase: p.requires_grad		,					model.parameters())
     a      =      sum([np.prod(p.size()) for p in model_parameters])
     return params


lowercase__      :			Optional[int]           =					logging.getLogger(__name__)




class 			a__       (					pl.Callback      ):







     def 			lowerCAmelCase_				(	self  ,		A  ,		A )  ->    str:



          '''simple docstring'''



          a      =      {F'''lr_group_{i}''': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )}
          pl_module.logger.log_metrics(A )







     @rank_zero_only
     def 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A=True )  ->    None:



          '''simple docstring'''



          logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' )
          a      =      trainer.callback_metrics
          trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} )
          # Log results
          a      =      Path(pl_module.hparams.output_dir )
          if type_path == "test":
               a      =      od / "test_results.txt"
               a      =      od / "test_generations.txt"
          else:
               # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
               # If people want this it will be easy enough to add back.
               a      =      od / F'''{type_path}_results/{trainer.global_step:05d}.txt'''
               a      =      od / F'''{type_path}_generations/{trainer.global_step:05d}.txt'''
               results_file.parent.mkdir(exist_ok=A )
               generations_file.parent.mkdir(exist_ok=A )
          with open(A  ,		"a+" ) as writer:
               for key in sorted(A ):
                    if key in ["log", "progress_bar", "preds"]:
                         continue
                    a      =      metrics[key]
                    if isinstance(A  ,		torch.Tensor ):
                         a      =      val.item()
                    a      =      F'''{key}: {val:.6f}\n'''
                    writer.write(A )

          if not save_generations:
               return

          if "preds" in metrics:
               a      =      "\n".join(metrics["preds"] )
               generations_file.open("w+" ).write(A )







     @rank_zero_only
     def 			lowerCAmelCase_				(	self  ,		A  ,		A )  ->    Any:



          '''simple docstring'''



          try:
               a      =      pl_module.model.model.num_parameters()
          except AttributeError:
               a      =      pl_module.model.num_parameters()

          a      =      count_trainable_parameters(A )
          # mp stands for million parameters
          trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} )







     @rank_zero_only
     def 			lowerCAmelCase_				(	self  ,		A  ,		A )  ->    Optional[int]:



          '''simple docstring'''



          save_json(pl_module.metrics  ,		pl_module.metrics_save_path )
          return self._write_logs(A  ,		A  ,		"test" )







     @rank_zero_only
     def 			lowerCAmelCase_				(	self  ,		A  ,		A )  ->    Dict:



          '''simple docstring'''



          save_json(pl_module.metrics  ,		pl_module.metrics_save_path )
          # Uncommenting this will save val generations
          # return self._write_logs(trainer, pl_module, "valid")







def 					SCREAMING_SNAKE_CASE							(   __UpperCamelCase		,					__UpperCamelCase		,					__UpperCamelCase=1		,					__UpperCamelCase=False)			->     Optional[int]:
     if metric == "rouge2":
          a      =      "{val_avg_rouge2:.4f}-{step_count}"
     elif metric == "bleu":
          a      =      "{val_avg_bleu:.4f}-{step_count}"
     elif metric == "loss":
          a      =      "{val_avg_loss:.4f}-{step_count}"
     else:
          raise NotImplementedError(
              f'''seq2seq callbacks only support rouge2, bleu and loss, got {metric}, You can make your own by adding to'''
              " this function.")

     a      =      ModelCheckpoint(
         dirpath=__UpperCamelCase		,					filename=__UpperCamelCase		,					monitor=f'''val_{metric}'''		,					mode="min" if "loss" in metric else "max"		,					save_top_k=__UpperCamelCase		,					)
     return checkpoint_callback





def 					SCREAMING_SNAKE_CASE							(   __UpperCamelCase		,					__UpperCamelCase)			->     Union[str, Any]:
     return EarlyStopping(
         monitor=f'''val_{metric}'''		,					mode="min" if "loss" in metric else "max"		,					patience=__UpperCamelCase		,					verbose=__UpperCamelCase		,					)







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 			a__       (					UpperCamelCase__      ):







     def __init__(	self  ,		A  ,		)  ->    List[Any]:



          '''simple docstring'''



          a      =      parent
          a      =      13
          a      =      7
          a      =      True
          a      =      True
          a      =      True
          a      =      True
          a      =      True
          a      =      99
          a      =      32
          a      =      2
          a      =      4
          a      =      37
          a      =      "gelu"
          a      =      0.1
          a      =      0.1
          a      =      512
          a      =      16
          a      =      2
          a      =      0.0_2
          a      =      3
          a      =      4
          a      =      None
          a      =      self.vocab_size - 1







     def 			lowerCAmelCase_				(	self )  ->    Union[str, Any]:



          '''simple docstring'''



          a      =      ids_tensor([self.batch_size, self.seq_length]  ,		self.vocab_size )

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

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

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

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

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

          a      =      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 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A  ,		*A )  ->    Optional[int]:



          '''simple docstring'''



          a      =      TFCTRLModel(config=A )
          a      =      {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          a      =      model(A )

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

          a      =      model(A )

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







     def 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A  ,		*A )  ->    Tuple:



          '''simple docstring'''



          a      =      TFCTRLLMHeadModel(config=A )
          a      =      {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          a      =      model(A )
          self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.seq_length, self.vocab_size) )







     def 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A  ,		*A )  ->    List[Any]:



          '''simple docstring'''



          a      =      self.num_labels
          a      =      ids_tensor([self.batch_size]  ,		self.type_sequence_label_size )
          a      =      {
              "input_ids": input_ids,
              "token_type_ids": token_type_ids,
              "labels": sequence_labels,
          }
          a      =      TFCTRLForSequenceClassification(A )
          a      =      model(A )
          self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.num_labels) )







     def 			lowerCAmelCase_				(	self )  ->    Union[str, Any]:



          '''simple docstring'''



          a      =      self.prepare_config_and_inputs()

          (
              (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      (
              a
          )  ,      
          )      =      config_and_inputs

          a      =      {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
          return config, inputs_dict







@require_tf
class 			a__       (					UpperCamelCase__   ,					UpperCamelCase__   ,					unittest.TestCase      ):
     a		:			Any							=	(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
     a		:			Optional[Any]							=	(TFCTRLLMHeadModel,) if is_tf_available() else ()
     a		:			List[Any]							=	(
         {
             """feature-extraction""": TFCTRLModel,
             """text-classification""": TFCTRLForSequenceClassification,
             """text-generation""": TFCTRLLMHeadModel,
             """zero-shot""": TFCTRLForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     a		:			Union[str, Any]							=	False
     a		:			str							=	False







     def 			lowerCAmelCase_				(	self  ,		A  ,		A  ,		A  ,		A  ,		A )  ->    List[str]:



          '''simple docstring'''



          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 			lowerCAmelCase_				(	self )  ->    Optional[int]:



          '''simple docstring'''



          a      =      TFCTRLModelTester(self )
          a      =      ConfigTester(self  ,		config_class=A  ,		n_embd=37 )







     def 			lowerCAmelCase_				(	self )  ->    Tuple:



          '''simple docstring'''



          self.config_tester.run_common_tests()







     def 			lowerCAmelCase_				(	self )  ->    Optional[Any]:



          '''simple docstring'''



          a      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_ctrl_model(*A )







     def 			lowerCAmelCase_				(	self )  ->    List[str]:



          '''simple docstring'''



          a      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_ctrl_lm_head(*A )







     def 			lowerCAmelCase_				(	self )  ->    Optional[Any]:



          '''simple docstring'''



          a      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_ctrl_for_sequence_classification(*A )







     def 			lowerCAmelCase_				(	self )  ->    Tuple:



          '''simple docstring'''



          a  ,      a      =      self.model_tester.prepare_config_and_inputs_for_common()
          a      =      [TFCTRLLMHeadModel]
          a      =      [TFCTRLForSequenceClassification]

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







     @slow
     def 			lowerCAmelCase_				(	self )  ->    Tuple:



          '''simple docstring'''



          for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               a      =      TFCTRLModel.from_pretrained(A )
               self.assertIsNotNone(A )







@require_tf
class 			a__       (					unittest.TestCase      ):







     @slow
     def 			lowerCAmelCase_				(	self )  ->    Any:



          '''simple docstring'''



          a      =      TFCTRLLMHeadModel.from_pretrained("ctrl" )
          a      =      tf.convert_to_tensor([[11859, 0, 1611, 8]]  ,		dtype=tf.intaa )  # Legal the president is
          a      =      [
              11859,
              0,
              1611,
              8,
              5,
              150,
              26449,
              2,
              19,
              348,
              469,
              3,
              2595,
              48,
              20740,
              246533,
              246533,
              19,
              30,
              5,
          ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

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

