'''simple docstring'''

import unittest

from transformers.testing_utils import is_torch_available, require_torch, tooslow

from ...generation.test_utils import torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          CpmAntConfig,
          CpmAntForCausalLM,
          CpmAntModel,
          CpmAntTokenizer,
      )




@require_torch
class    lowerCamelCase__  :



   def __init__(    self					,      lowerCAmelCase__					,      lowerCAmelCase__=2					,      lowerCAmelCase__=8					,      lowerCAmelCase__=True					,      lowerCAmelCase__=False					,      lowerCAmelCase__=False					,      lowerCAmelCase__=False					,      lowerCAmelCase__=False					,      lowerCAmelCase__=99					,      lowerCAmelCase__=32					,      lowerCAmelCase__=3					,      lowerCAmelCase__=4					,      lowerCAmelCase__=37					,      lowerCAmelCase__=32					,      lowerCAmelCase__=128					,      lowerCAmelCase__=8					,      lowerCAmelCase__=8					,      lowerCAmelCase__=8					,      lowerCAmelCase__=1.0					,      lowerCAmelCase__=True					,      )				->     int:
        """simple docstring"""





        _UpperCamelCase  :Dict       =parent
        _UpperCamelCase  :Optional[int]       =batch_size
        _UpperCamelCase  :int       =seq_length
        _UpperCamelCase  :Union[str, Any]       =is_training
        _UpperCamelCase  :Dict       =use_token_type_ids
        _UpperCamelCase  :Any       =use_input_mask
        _UpperCamelCase  :int       =use_labels
        _UpperCamelCase  :Optional[Any]       =use_mc_token_ids
        _UpperCamelCase  :Any       =vocab_size
        _UpperCamelCase  :Dict       =hidden_size
        _UpperCamelCase  :List[str]       =num_hidden_layers
        _UpperCamelCase  :Tuple       =num_attention_heads
        _UpperCamelCase  :Dict       =intermediate_size
        _UpperCamelCase  :str       =num_buckets
        _UpperCamelCase  :Optional[Any]       =max_distance
        _UpperCamelCase  :str       =prompt_length
        _UpperCamelCase  :Optional[int]       =prompt_types
        _UpperCamelCase  :int       =segment_types
        _UpperCamelCase  :List[Any]       =init_std
        _UpperCamelCase  :Any       =return_dict



   def  _UpperCamelCase		(    self     )				->     Tuple:
        """simple docstring"""





        _UpperCamelCase  :Optional[Any]       ={}
        _UpperCamelCase  :List[Any]       =ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size     ).type(torch.intaa     )
        _UpperCamelCase  :Tuple       =False

        _UpperCamelCase  :Dict       =self.get_config()

        return (config, input_ids)



   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        return CpmAntConfig(
            vocab_size=self.vocab_size					,      hidden_size=self.hidden_size					,      num_hidden_layers=self.num_hidden_layers					,      num_attention_heads=self.num_attention_heads					,      dim_ff=self.intermediate_size					,      position_bias_num_buckets=self.num_buckets					,      position_bias_max_distance=self.max_distance					,      prompt_types=self.prompt_types					,      prompt_length=self.prompt_length					,      segment_types=self.segment_types					,      use_cache=lowerCAmelCase__					,      init_std=self.init_std					,      return_dict=self.return_dict					,      )



   def  _UpperCamelCase		(    self					,      lowerCAmelCase__					,      lowerCAmelCase__					,      *lowerCAmelCase__     )				->     Tuple:
        """simple docstring"""





        _UpperCamelCase  :Dict       =CpmAntModel(config=lowerCAmelCase__     )
        model.to(lowerCAmelCase__     )
        model.eval()

        _UpperCamelCase  :List[str]       =model(**lowerCAmelCase__     ).last_hidden_state

        self.parent.assertEqual(hidden_states.shape					,      (self.batch_size, self.seq_length, config.hidden_size)     )



   def  _UpperCamelCase		(    self					,      lowerCAmelCase__					,      lowerCAmelCase__					,      *lowerCAmelCase__     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase  :Optional[Any]       =CpmAntForCausalLM(lowerCAmelCase__     )
        model.to(lowerCAmelCase__     )
        _UpperCamelCase  :Any       =input_ids["""input_ids"""].to(lowerCAmelCase__     )
        model.eval()

        _UpperCamelCase  :Optional[int]       =model(**lowerCAmelCase__     )
        self.parent.assertEqual(
            model_output.logits.shape					,      (self.batch_size, self.seq_length, config.vocab_size + config.prompt_types * config.prompt_length)					,      )




   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :Dict       =self.prepare_config_and_inputs()
        return config, inputs_dict




@require_torch
class    lowerCamelCase__  (   __snake_case       ,				__snake_case       ,				unittest.TestCase     ):
   __UpperCAmelCase           =						(CpmAntModel, CpmAntForCausalLM) if is_torch_available() else ()
   __UpperCAmelCase           =						(
       {"""feature-extraction""": CpmAntModel, """text-generation""": CpmAntForCausalLM} if is_torch_available() else {}
   )

   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False



   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        _UpperCamelCase  :Optional[int]       =CpmAntModelTester(self     )
        _UpperCamelCase  :Dict       =ConfigTester(self					,      config_class=lowerCAmelCase__     )



   def  _UpperCamelCase		(    self     )				->     Dict:
        """simple docstring"""





        self.config_tester.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()



   def  _UpperCamelCase		(    self     )				->     str:
        """simple docstring"""





        unittest.skip("""CPMAnt doesn't support input_embeds."""     )(self.test_inputs_embeds     )



   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        unittest.skip(
            """CPMAnt doesn't support retain grad in hidden_states or attentions, because prompt management will peel off the output.hidden_states from graph.\
                 So is attentions. We strongly recommand you use loss to tune model."""     )(self.test_retain_grad_hidden_states_attentions     )



   def  _UpperCamelCase		(    self     )				->     List[str]:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :Optional[int]       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_cpmant_model(lowerCAmelCase__					,      lowerCAmelCase__     )




   def  _UpperCamelCase		(    self     )				->     Any:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :List[str]       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_lm_head_model(lowerCAmelCase__					,      lowerCAmelCase__     )




@require_torch
class    lowerCamelCase__  (   unittest.TestCase     ):



   @tooslow
   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase  :Dict       ="""今天天气真好！"""
        _UpperCamelCase  :Tuple       ="""openbmb/cpm-ant-10b"""
        _UpperCamelCase  :List[str]       =CpmAntModel.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :List[str]       =CpmAntTokenizer.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :Optional[Any]       =tokenizer(lowerCAmelCase__					,      return_tensors="""pt"""     )
        _UpperCamelCase  :Optional[Any]       =model(**lowerCAmelCase__     ).last_hidden_state

        _UpperCamelCase  :Optional[int]       =torch.tensor(
            [[[6.1708, 5.9244, 1.0835], [6.5207, 6.2893, -11.3324], [-1.0107, -0.0576, -5.9577]]]					,      )
        self.assertTrue(torch.allclose(hidden_states[:, :3, :3]					,      lowerCAmelCase__					,      atol=1e-2     )     )




@require_torch
class    lowerCamelCase__  (   unittest.TestCase     ):



   @tooslow
   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase  :List[Any]       ="""今天天气真好！"""
        _UpperCamelCase  :int       ="""openbmb/cpm-ant-10b"""
        _UpperCamelCase  :Optional[Any]       =CpmAntForCausalLM.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :Optional[Any]       =CpmAntTokenizer.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :List[Any]       =tokenizer(lowerCAmelCase__					,      return_tensors="""pt"""     )
        _UpperCamelCase  :Any       =model(**lowerCAmelCase__     ).logits

        _UpperCamelCase  :Optional[Any]       =torch.tensor(
            [[[-6.4267, -6.4083, -6.3958], [-5.8802, -5.9447, -5.7811], [-5.3896, -5.4820, -5.4295]]]					,      )
        self.assertTrue(torch.allclose(hidden_states[:, :3, :3]					,      lowerCAmelCase__					,      atol=1e-2     )     )



   @tooslow
   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        _UpperCamelCase  :Tuple       ="""openbmb/cpm-ant-10b"""
        _UpperCamelCase  :str       =CpmAntForCausalLM.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :int       =CpmAntTokenizer.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :str       ="""今天天气不错，"""
        _UpperCamelCase  :str       ="""今天天气不错，阳光明媚，我和妈妈一起去超市买东西。\n在超市里，我看到了一个很好玩的玩具，它的名字叫“机器人”。它有一个圆圆的脑袋，两只圆圆的眼睛，还有一个圆圆的"""
        _UpperCamelCase  :Dict       =tokenizer(lowerCAmelCase__					,      return_tensors="""pt"""     )
        _UpperCamelCase  :Dict       =model.generate(**lowerCAmelCase__     )
        _UpperCamelCase  :int       =tokenizer.batch_decode(lowerCAmelCase__     )
        self.assertEqual(lowerCAmelCase__					,      lowerCAmelCase__     )




   @tooslow
   def  _UpperCamelCase		(    self     )				->     Any:
        """simple docstring"""





        _UpperCamelCase  :List[Any]       ="""openbmb/cpm-ant-10b"""
        _UpperCamelCase  :List[str]       =CpmAntForCausalLM.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :List[Any]       =CpmAntTokenizer.from_pretrained(lowerCAmelCase__     )
        _UpperCamelCase  :Any       =["""今天天气不错，""", """新年快乐，万事如意！"""]
        _UpperCamelCase  :Optional[Any]       =[
            """今天天气不错，阳光明媚，我和妈妈一起去超市买东西。\n在超市里，我看到了一个很好玩的玩具，它的名字叫“机器人”。它有一个圆圆的脑袋，两只圆圆的眼睛，还有一个圆圆的""",
            """新年快乐，万事如意！在这辞旧迎新的美好时刻，我谨代表《农村新技术》杂志社全体同仁，向一直以来关心、支持《农村新技术》杂志发展的各级领导、各界朋友和广大读者致以最诚挚的""",
        ]
        _UpperCamelCase  :Tuple       =tokenizer(lowerCAmelCase__					,      return_tensors="""pt"""					,      padding=lowerCAmelCase__     )
        _UpperCamelCase  :List[Any]       =model.generate(**lowerCAmelCase__     )
        _UpperCamelCase  :str       =tokenizer.batch_decode(lowerCAmelCase__     )
        self.assertEqual(lowerCAmelCase__					,      lowerCAmelCase__     )
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import sys
import warnings
from os.path import abspath, dirname, join


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
snake_case__						      =			abspath(join(dirname(dirname(dirname(__file__))), 'src'))
sys.path.insert(1, git_repo_path)


# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='ignore', category=FutureWarning)
def    __magic_name__(	__UpperCAmelCase		)    ->     int:



      '''simple docstring'''

      from transformers.testing_utils import pytest_addoption_shared

      pytest_addoption_shared(__UpperCAmelCase		)




def    __magic_name__(	__UpperCAmelCase		)    ->     List[str]:



      '''simple docstring'''

      from transformers.testing_utils import pytest_terminal_summary_main

      _lowerCamelCase           =					terminalreporter.config.getoption('''--make-reports'''		)
      if make_reports:
            pytest_terminal_summary_main(__UpperCAmelCase			,    id=__UpperCAmelCase		)