


'''simple docstring'''







import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
   from transformers.models.esm.modeling_esm import (
       ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
       EsmEmbeddings,
       create_position_ids_from_input_ids,
   )


class 			__lowerCamelCase			:
    """simple docstring"""


    def __init__(  self      :							str				,							SCREAMING_SNAKE_CASE      :							str				,							SCREAMING_SNAKE_CASE      :							List[str]=13				,							SCREAMING_SNAKE_CASE      :							Optional[Any]=7				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=False				,							SCREAMING_SNAKE_CASE      :							Optional[int]=True				,							SCREAMING_SNAKE_CASE      :							str=False				,							SCREAMING_SNAKE_CASE      :							Tuple=True				,							SCREAMING_SNAKE_CASE      :							Optional[int]=33				,							SCREAMING_SNAKE_CASE      :							Any=32				,							SCREAMING_SNAKE_CASE      :							Any=5				,							SCREAMING_SNAKE_CASE      :							Tuple=4				,							SCREAMING_SNAKE_CASE      :							List[Any]=37				,							SCREAMING_SNAKE_CASE      :							Optional[Any]="gelu"				,							SCREAMING_SNAKE_CASE      :							Optional[int]=0.1				,							SCREAMING_SNAKE_CASE      :							Dict=0.1				,							SCREAMING_SNAKE_CASE      :							List[str]=512				,							SCREAMING_SNAKE_CASE      :							Tuple=16				,							SCREAMING_SNAKE_CASE      :							List[Any]=2				,							SCREAMING_SNAKE_CASE      :							List[Any]=0.02				,							SCREAMING_SNAKE_CASE      :							Any=3				,							SCREAMING_SNAKE_CASE      :							List[str]=4				,							SCREAMING_SNAKE_CASE      :							str=None				,							):
           _A					:     Optional[int]     = parent
           _A					:     List[Any]     = batch_size
           _A					:     Any     = seq_length
           _A					:     List[str]     = is_training
           _A					:     List[str]     = use_input_mask
           _A					:     str     = use_token_type_ids
           _A					:     Tuple     = use_labels
           _A					:     Union[str, Any]     = vocab_size
           _A					:     Dict     = hidden_size
           _A					:     Tuple     = num_hidden_layers
           _A					:     Dict     = num_attention_heads
           _A					:     Any     = intermediate_size
           _A					:     Union[str, Any]     = hidden_act
           _A					:     Any     = hidden_dropout_prob
           _A					:     Optional[int]     = attention_probs_dropout_prob
           _A					:     Optional[Any]     = max_position_embeddings
           _A					:     str     = type_vocab_size
           _A					:     List[Any]     = type_sequence_label_size
           _A					:     List[Any]     = initializer_range
           _A					:     Optional[int]     = num_labels
           _A					:     Union[str, Any]     = num_choices
           _A					:     str     = scope


    def        A   (  self      :							Any):
           _A					:     Union[str, Any]     = ids_tensor([self.batch_size, self.seq_length]				,							self.vocab_size)

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

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

           _A					:     Union[str, Any]     = self.get_config()

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


    def        A   (  self      :							Optional[Any]):
           return EsmConfig(
               vocab_size=self.vocab_size				,							hidden_size=self.hidden_size				,							pad_token_id=1				,							num_hidden_layers=self.num_hidden_layers				,							num_attention_heads=self.num_attention_heads				,							intermediate_size=self.intermediate_size				,							hidden_act=self.hidden_act				,							hidden_dropout_prob=self.hidden_dropout_prob				,							attention_probs_dropout_prob=self.attention_probs_dropout_prob				,							max_position_embeddings=self.max_position_embeddings				,							type_vocab_size=self.type_vocab_size				,							initializer_range=self.initializer_range				,							)


    def        A   (  self      :							int				,							SCREAMING_SNAKE_CASE      :							int				,							SCREAMING_SNAKE_CASE      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							str				,							SCREAMING_SNAKE_CASE      :							int				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							List[str]):
           _A					:     List[Any]     = EsmModel(config=SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           _A					:     Optional[int]     = model(SCREAMING_SNAKE_CASE				,							attention_mask=SCREAMING_SNAKE_CASE)
           _A					:     Union[str, Any]     = model(SCREAMING_SNAKE_CASE)
           _A					:     Union[str, Any]     = model(SCREAMING_SNAKE_CASE)

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


    def        A   (  self      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]):
           _A					:     Optional[Any]     = EsmForMaskedLM(config=SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           _A					:     str     = model(SCREAMING_SNAKE_CASE				,							attention_mask=SCREAMING_SNAKE_CASE				,							labels=SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.seq_length, self.vocab_size))


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							Tuple				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Tuple				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]):
           _A					:     Any     = self.num_labels
           _A					:     Union[str, Any]     = EsmForTokenClassification(config=SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           _A					:     Optional[Any]     = model(SCREAMING_SNAKE_CASE				,							attention_mask=SCREAMING_SNAKE_CASE				,							labels=SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.seq_length, self.num_labels))


    def        A   (  self      :							Optional[Any]):
           _A					:     Any     = self.prepare_config_and_inputs()
           (
               (
               _A
           )  ,			(
               _A
           )  ,			(
               _A
           )  ,			(
               _A
           )  ,			(
               _A
           )  ,			(
               _A
           )  ,			
           )					:     Any     = config_and_inputs
           _A					:     Tuple     = {'input_ids': input_ids, 'attention_mask': input_mask}
           return config, inputs_dict




@require_torch
class 			__lowerCamelCase			(	a_    , a_    , unittest.TestCase	):
    """simple docstring"""
    a													=   False

    a													=   (
        (
            EsmForMaskedLM,
            EsmModel,
            EsmForSequenceClassification,
            EsmForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    a													=   ()
    a													=   (
        {
            "feature-extraction": EsmModel,
            "fill-mask": EsmForMaskedLM,
            "text-classification": EsmForSequenceClassification,
            "token-classification": EsmForTokenClassification,
            "zero-shot": EsmForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    a													=   True


    def        A   (  self      :							Union[str, Any]):
           _A					:     Dict     = EsmModelTester(self)
           _A					:     str     = ConfigTester(self				,							config_class=SCREAMING_SNAKE_CASE				,							hidden_size=37)


    def        A   (  self      :							int):
           self.config_tester.run_common_tests()


    def        A   (  self      :							Tuple):
           _A					:     List[str]     = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Optional[int]):
           _A					:     Union[str, Any]     = self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
                  _A					:     Any     = type
                  self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Optional[int]):
           _A					:     str     = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Any):
           _A					:     Any     = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE)


    @slow
    def        A   (  self      :							Tuple):
           for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _A					:     Dict     = EsmModel.from_pretrained(SCREAMING_SNAKE_CASE)
                  self.assertIsNotNone(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Any):
           _A					:     Union[str, Any]     = self.model_tester.prepare_config_and_inputs()[0]
           _A					:     Dict     = EsmEmbeddings(config=SCREAMING_SNAKE_CASE)

           _A					:     int     = torch.as_tensor([[12, 31, 13, model.padding_idx]])
           _A					:     int     = torch.as_tensor(
               [
                   [
                       0 + model.padding_idx + 1,
                       1 + model.padding_idx + 1,
                       2 + model.padding_idx + 1,
                       model.padding_idx,
                   ]
               ])
           _A					:     Tuple     = create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE				,							model.padding_idx)
           self.assertEqual(position_ids.shape				,							expected_positions.shape)
           self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE)))


    def        A   (  self      :							Tuple):
           _A					:     Optional[Any]     = self.model_tester.prepare_config_and_inputs()[0]
           _A					:     List[str]     = EsmEmbeddings(config=SCREAMING_SNAKE_CASE)

           _A					:     int     = torch.empty(2				,							4				,							30)
           _A					:     Union[str, Any]     = [
               0 + embeddings.padding_idx + 1,
               1 + embeddings.padding_idx + 1,
               2 + embeddings.padding_idx + 1,
               3 + embeddings.padding_idx + 1,
           ]
           _A					:     str     = torch.as_tensor([expected_single_positions, expected_single_positions])
           _A					:     Any     = embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE)
           self.assertEqual(position_ids.shape				,							expected_positions.shape)
           self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE)))


    @unittest.skip('Esm does not support embedding resizing')
    def        A   (  self      :							Dict):
           pass


    @unittest.skip('Esm does not support embedding resizing')
    def        A   (  self      :							Optional[int]):
           pass


    @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
    def        A   (  self      :							Dict):
           pass




@require_torch
class 			__lowerCamelCase			(	a_	):
    """simple docstring"""


    @slow
    def        A   (  self      :							Any):
           with torch.no_grad():
                  _A					:     List[str]     = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D')
                  model.eval()
                  _A					:     Any     = torch.tensor([[0, 1, 2, 3, 4, 5]])
                  _A					:     Optional[int]     = model(SCREAMING_SNAKE_CASE)[0]

                  _A					:     Any     = 33

                  _A					:     Optional[int]     = torch.Size((1, 6, vocab_size))
                  self.assertEqual(output.shape				,							SCREAMING_SNAKE_CASE)

                  _A					:     List[Any]     = torch.tensor(
                      [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]])
                  self.assertTrue(torch.allclose(output[:, :3, :3]				,							SCREAMING_SNAKE_CASE				,							atol=1e-4))


    @slow
    def        A   (  self      :							List[Any]):
           with torch.no_grad():
                  _A					:     Dict     = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D')
                  model.eval()

                  _A					:     Dict     = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
                  _A					:     Optional[int]     = model(SCREAMING_SNAKE_CASE)[0]
                  # compare the actual values for a slice.
                  _A					:     List[Any]     = torch.tensor(
                      [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]])
                  self.assertTrue(torch.allclose(output[:, :3, :3]				,							SCREAMING_SNAKE_CASE				,							atol=1e-4))










'''simple docstring'''







import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
   import tensorflow as tf

if is_torch_available():
   import torch


A				:					Any    						=			logging.get_logger(__name__)


class 			__lowerCamelCase			:
    """simple docstring"""


    def __init__(  self      :							Dict				,							SCREAMING_SNAKE_CASE      :							str = None				,							SCREAMING_SNAKE_CASE      :							uuid.UUID = None				,							SCREAMING_SNAKE_CASE      :							List[Any]=None				,							SCREAMING_SNAKE_CASE      :							Optional[int]=None):
           if not conversation_id:
                  _A					:     str     = uuid.uuida()
           if past_user_inputs is None:
                  _A					:     List[Any]     = []
           if generated_responses is None:
                  _A					:     Union[str, Any]     = []

           _A					:     uuid.UUID     = conversation_id
           _A					:     List[str]     = past_user_inputs
           _A					:     List[str]     = generated_responses
           _A					:     Optional[str]     = text


    def __eq__(  self      :							List[str]				,							SCREAMING_SNAKE_CASE      :							Optional[int]):
           if not isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE):
                  return False
           if self.uuid == other.uuid:
                  return True
           return (
               self.new_user_input == other.new_user_input
               and self.past_user_inputs == other.past_user_inputs
               and self.generated_responses == other.generated_responses
           )


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							str				,							SCREAMING_SNAKE_CASE      :							bool = False):
           if self.new_user_input:
                  if overwrite:
                         logger.warning(
                             F'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '
                             F'with: "{text}".')
                         _A					:     Optional[Any]     = text
                  else:
                         logger.warning(
                             F'User input added while unprocessed input was existing: "{self.new_user_input}" new input '
                             F'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input')
           else:
                  _A					:     Optional[Any]     = text


    def        A   (  self      :							Optional[int]):
           if self.new_user_input:
                  self.past_user_inputs.append(self.new_user_input)
           _A					:     Optional[Any]     = None


    def        A   (  self      :							List[Any]				,							SCREAMING_SNAKE_CASE      :							str):
           self.generated_responses.append(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							str):
           for user_input, generated_response in zip(self.past_user_inputs				,							self.generated_responses):
                  yield True, user_input
                  yield False, generated_response
           if self.new_user_input:
                  yield True, self.new_user_input


    def __repr__(  self      :							Dict):
           _A					:     Any     = F'Conversation id: {self.uuid} \n'
           for is_user, text in self.iter_texts():
                  _A					:     Optional[int]     = 'user' if is_user else 'bot'
                  output += F'{name} >> {text} \n'
           return output




@add_end_docstrings(
    a_    , R"\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    "    , )
class 			__lowerCamelCase			(	a_	):
    """simple docstring"""


    def __init__(  self      :							Optional[int]				,							*SCREAMING_SNAKE_CASE      :							Any				,							**SCREAMING_SNAKE_CASE      :							str):
           super().__init__(*SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)
           if self.tokenizer.pad_token_id is None:
                  _A					:     Any     = self.tokenizer.eos_token


    def        A   (  self      :							Optional[Any]				,							SCREAMING_SNAKE_CASE      :							List[Any]=None				,							SCREAMING_SNAKE_CASE      :							Optional[int]=None				,							SCREAMING_SNAKE_CASE      :							Optional[Any]=None				,							**SCREAMING_SNAKE_CASE      :							str):
           _A					:     str     = {}
           _A					:     Union[str, Any]     = {}
           _A					:     List[str]     = {}

           if min_length_for_response is not None:
                  _A					:     Optional[Any]     = min_length_for_response
           if minimum_tokens is not None:
                  _A					:     Tuple     = minimum_tokens

           if "max_length" in generate_kwargs:
                  _A					:     List[Any]     = generate_kwargs['max_length']
                  # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
           if clean_up_tokenization_spaces is not None:
                  _A					:     List[str]     = clean_up_tokenization_spaces

           if generate_kwargs:
                  forward_params.update(SCREAMING_SNAKE_CASE)
           return preprocess_params, forward_params, postprocess_params


    def __call__(  self      :							Any				,							SCREAMING_SNAKE_CASE      :							Union[Conversation, List[Conversation]]				,							SCREAMING_SNAKE_CASE      :							Any=0				,							**SCREAMING_SNAKE_CASE      :							Tuple):
           _A					:     Any     = super().__call__(SCREAMING_SNAKE_CASE				,							num_workers=SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)
           if isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE) and len(SCREAMING_SNAKE_CASE) == 1:
                  return outputs[0]
           return outputs


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							Conversation				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=32):
           if not isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE):
                  raise ValueError('ConversationalPipeline, expects Conversation as inputs')
           if conversation.new_user_input is None:
                  raise ValueError(
                      F'Conversation with UUID {type(conversation.uuid)} does not contain new user input to process. '
                      'Add user inputs with the conversation\'s `add_user_input` method')
           if hasattr(self.tokenizer				,							'_build_conversation_input_ids'):
                  _A					:     Optional[Any]     = self.tokenizer._build_conversation_input_ids(SCREAMING_SNAKE_CASE)
           else:
                  # If the tokenizer cannot handle conversations, we default to only the old version
                  _A					:     Dict     = self._legacy_parse_and_tokenize(SCREAMING_SNAKE_CASE)

           if self.framework == "pt":
                  _A					:     Union[str, Any]     = torch.LongTensor([input_ids])
           elif self.framework == "tf":
                  _A					:     Optional[Any]     = tf.constant([input_ids])
           return {"input_ids": input_ids, "conversation": conversation}


    def        A   (  self      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Dict				,							SCREAMING_SNAKE_CASE      :							List[str]=10				,							**SCREAMING_SNAKE_CASE      :							Tuple):
           _A					:     str     = generate_kwargs.get('max_length'				,							self.model.config.max_length)

           _A					:     Any     = model_inputs['input_ids'].shape[1]
           if max_length - minimum_tokens < n:
                  logger.warning(F'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})')
                  _A					:     Dict     = max_length - minimum_tokens
                  _A					:     int     = model_inputs['input_ids'][:, -trim:]
                  if "attention_mask" in model_inputs:
                         _A					:     str     = model_inputs['attention_mask'][:, -trim:]
           _A					:     Any     = model_inputs.pop('conversation')
           _A					:     Optional[Any]     = max_length
           _A					:     int     = self.model.generate(**SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)
           if self.model.config.is_encoder_decoder:
                  _A					:     int     = 1
           else:
                  _A					:     List[Any]     = n
           return {"output_ids": output_ids[:, start_position:], "conversation": conversation}


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							str				,							SCREAMING_SNAKE_CASE      :							List[Any]=True):
           _A					:     Optional[Any]     = model_outputs['output_ids']
           _A					:     Optional[int]     = self.tokenizer.decode(
               output_ids[0]				,							skip_special_tokens=SCREAMING_SNAKE_CASE				,							clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE				,							)
           _A					:     Any     = model_outputs['conversation']
           conversation.mark_processed()
           conversation.append_response(SCREAMING_SNAKE_CASE)
           return conversation


    def        A   (  self      :							str				,							SCREAMING_SNAKE_CASE      :							Conversation):
           _A					:     Optional[Any]     = self.tokenizer.eos_token_id
           _A					:     List[Any]     = []
           for is_user, text in conversation.iter_texts():
                  if eos_token_id is not None:
                         input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE				,							add_special_tokens=SCREAMING_SNAKE_CASE) + [eos_token_id])
                  else:
                         input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE				,							add_special_tokens=SCREAMING_SNAKE_CASE))

           if len(SCREAMING_SNAKE_CASE) > self.tokenizer.model_max_length:
                  _A					:     Dict     = input_ids[-self.tokenizer.model_max_length :]
           return input_ids






