




"""simple docstring"""




from typing import Optional

from torch import nn

from .transformer_ad import TransformeraDModel, TransformeraDModelOutput






class     __magic_name__							(       nn.Module				):






				'''simple docstring'''





				def __init__(       self		, _a = 16		, _a = 88		, _a = None		, _a = 1		, _a = 0.0		, _a = 32		, _a = None		, _a = False		, _a = None		, _a = None		, _a = "geglu"		, _a = None		, ):





							"""simple docstring"""
							super().__init__()
							lowerCamelCase			      =					nn.ModuleList(
							    [
							        TransformeraDModel(
							            num_attention_heads=__a		, attention_head_dim=__a		, in_channels=__a		, num_layers=__a		, dropout=__a		, norm_num_groups=__a		, cross_attention_dim=__a		, attention_bias=__a		, sample_size=__a		, num_vector_embeds=__a		, activation_fn=__a		, num_embeds_ada_norm=__a		, )
							        for _ in range(2 )
							    ] )

							# Variables that can be set by a pipeline:

							# The ratio of transformer1 to transformer2's output states to be combined during inference
							lowerCamelCase			      =					0.5

							# The shape of `encoder_hidden_states` is expected to be
							# `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)`
							lowerCamelCase			      =					[77, 257]

							# Which transformer to use to encode which condition.
							# E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])`
							lowerCamelCase			      =					[1, 0]





				def    _lowerCAmelCase				(       self		, _a		, _a		, _a=None		, _a=None		, _a=None		, _a = True		, ):





							"""simple docstring"""
							lowerCamelCase			      =					hidden_states

							lowerCamelCase			      =					[]
							lowerCamelCase			      =					0
							# attention_mask is not used yet
							for i in range(2 ):
										# for each of the two transformers, pass the corresponding condition tokens
										lowerCamelCase			      =					encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]]
										lowerCamelCase			      =					self.transformer_index_for_condition[i]
										lowerCamelCase			      =					self.transformers[transformer_index](
										    __a		, encoder_hidden_states=__a		, timestep=__a		, cross_attention_kwargs=__a		, return_dict=__a		, )[0]
										encoded_states.append(encoded_state - input_states )
										tokens_start += self.condition_lengths[i]

							lowerCamelCase			      =					encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio)
							lowerCamelCase			      =					output_states + input_states

							if not return_dict:
										return (output_states,)

							return TransformeraDModelOutput(sample=__a )




'''simple docstring'''





from typing import Dict

import numpy as np

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


if is_tf_available():
    import tensorflow as tf

    from ..tf_utils import stable_softmax


if is_torch_available():
    import torch


SCREAMING_SNAKE_CASE_:     Optional[int]  =logging.get_logger(__name__)




@add_end_docstrings(
    UpperCamelCase__		,	r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """		,	)
class        __A      ( UpperCamelCase__	):



    def 					_lowercase						(self    :    str   ,			__a    :    GenericTensor ):
         if self.framework == "tf":
              UpperCAmelCase_           =   tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
         elif self.framework == "pt":
              UpperCAmelCase_           =   torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,			as_tuple=__a )
         else:
              raise ValueError("Unsupported framework" )
         return masked_index



    def 					_lowercase						(self    :    Tuple   ,			__a    :    GenericTensor ):
         UpperCAmelCase_           =   self.get_masked_index(__a )
         UpperCAmelCase_           =   np.prod(masked_index.shape )
         if numel < 1:
              raise PipelineException(
                  "fill-mask"   ,			self.model.base_model_prefix   ,			f"""No mask_token ({self.tokenizer.mask_token}) found on the input"""   ,			)



    def 					_lowercase						(self    :    List[Any]   ,			__a    :    GenericTensor ):
         if isinstance(__a   ,			__a ):
              for model_input in model_inputs:
                   self._ensure_exactly_one_mask_token(model_input["input_ids"][0] )
         else:
              for input_ids in model_inputs["input_ids"]:
                   self._ensure_exactly_one_mask_token(__a )



    def 					_lowercase						(self    :    Tuple   ,			__a    :    Dict   ,			__a    :    List[str]=None   ,			**__a    :    Any ):
         if return_tensors is None:
              UpperCAmelCase_           =   self.framework
         UpperCAmelCase_           =   self.tokenizer(__a   ,			return_tensors=__a )
         self.ensure_exactly_one_mask_token(__a )
         return model_inputs



    def 					_lowercase						(self    :    str   ,			__a    :    Optional[int] ):
         UpperCAmelCase_           =   self.model(**__a )
         UpperCAmelCase_           =   model_inputs["input_ids"]
         return model_outputs



    def 					_lowercase						(self    :    List[str]   ,			__a    :    Tuple   ,			__a    :    int=5   ,			__a    :    Dict=None ):
         # Cap top_k if there are targets
         if target_ids is not None and target_ids.shape[0] < top_k:
              UpperCAmelCase_           =   target_ids.shape[0]
         UpperCAmelCase_           =   model_outputs["input_ids"][0]
         UpperCAmelCase_           =   model_outputs["logits"]

         if self.framework == "tf":
              UpperCAmelCase_           =   tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]

              UpperCAmelCase_           =   outputs.numpy()

              UpperCAmelCase_           =   outputs[0, masked_index, :]
              UpperCAmelCase_           =   stable_softmax(__a   ,			axis=-1 )
              if target_ids is not None:
                   UpperCAmelCase_           =   tf.gather_nd(tf.squeeze(__a   ,			0 )   ,			target_ids.reshape(-1   ,			1 ) )
                   UpperCAmelCase_           =   tf.expand_dims(__a   ,			0 )

              UpperCAmelCase_           =   tf.math.top_k(__a   ,			k=__a )
              UpperCAmelCase_    , UpperCAmelCase_           =   topk.values.numpy(), topk.indices.numpy()
         else:
              UpperCAmelCase_           =   torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,			as_tuple=__a ).squeeze(-1 )
              # Fill mask pipeline supports only one ${mask_token} per sample

              UpperCAmelCase_           =   outputs[0, masked_index, :]
              UpperCAmelCase_           =   logits.softmax(dim=-1 )
              if target_ids is not None:
                   UpperCAmelCase_           =   probs[..., target_ids]

              UpperCAmelCase_    , UpperCAmelCase_           =   probs.topk(__a )

         UpperCAmelCase_           =   []
         UpperCAmelCase_           =   values.shape[0] == 1
         for i, (_values, _predictions) in enumerate(zip(values.tolist()   ,			predictions.tolist() ) ):
              UpperCAmelCase_           =   []
              for v, p in zip(_values   ,			_predictions ):
                   # Copy is important since we're going to modify this array in place
                   UpperCAmelCase_           =   input_ids.numpy().copy()
                   if target_ids is not None:
                        UpperCAmelCase_           =   target_ids[p].tolist()

                   UpperCAmelCase_           =   p
                   # Filter padding out:
                   UpperCAmelCase_           =   tokens[np.where(tokens != self.tokenizer.pad_token_id )]
                   # Originally we skip special tokens to give readable output.
                   # For multi masks though, the other [MASK] would be removed otherwise
                   # making the output look odd, so we add them back
                   UpperCAmelCase_           =   self.tokenizer.decode(__a   ,			skip_special_tokens=__a )
                   UpperCAmelCase_           =   {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence}
                   row.append(__a )
              result.append(__a )
         if single_mask:
              return result[0]
         return result



    def 					_lowercase						(self    :    Dict   ,			__a    :    List[Any]   ,			__a    :    List[str]=None ):
         if isinstance(__a   ,			__a ):
              UpperCAmelCase_           =   [targets]
         try:
              UpperCAmelCase_           =   self.tokenizer.get_vocab()
         except Exception:
              UpperCAmelCase_           =   {}
         UpperCAmelCase_           =   []
         for target in targets:
              UpperCAmelCase_           =   vocab.get(__a   ,			__a )
              if id_ is None:
                   UpperCAmelCase_           =   self.tokenizer(
                       __a   ,			add_special_tokens=__a   ,			return_attention_mask=__a   ,			return_token_type_ids=__a   ,			max_length=1   ,			truncation=__a   ,			)["input_ids"]
                   if len(__a ) == 0:
                        logger.warning(
                            f"""The specified target token `{target}` does not exist in the model vocabulary. """
                            "We cannot replace it with anything meaningful, ignoring it" )
                        continue
                   UpperCAmelCase_           =   input_ids[0]
                   # XXX: If users encounter this pass
                   # it becomes pretty slow, so let's make sure
                   # The warning enables them to fix the input to
                   # get faster performance.
                   logger.warning(
                       f"""The specified target token `{target}` does not exist in the model vocabulary. """
                       f"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" )
              target_ids.append(id_ )
         UpperCAmelCase_           =   list(set(__a ) )
         if len(__a ) == 0:
              raise ValueError("At least one target must be provided when passed." )
         UpperCAmelCase_           =   np.array(__a )
         return target_ids



    def 					_lowercase						(self    :    Tuple   ,			__a    :    Dict=None   ,			__a    :    List[str]=None ):
         UpperCAmelCase_           =   {}

         if targets is not None:
              UpperCAmelCase_           =   self.get_target_ids(__a   ,			__a )
              UpperCAmelCase_           =   target_ids

         if top_k is not None:
              UpperCAmelCase_           =   top_k

         if self.tokenizer.mask_token_id is None:
              raise PipelineException(
                  "fill-mask"   ,			self.model.base_model_prefix   ,			"The tokenizer does not define a `mask_token`." )
         return {}, {}, postprocess_params






    def __call__(self    :    Union[str, Any]   ,			__a    :    str   ,			*__a    :    Any   ,			**__a    :    Tuple ):
         UpperCAmelCase_           =   super().__call__(__a   ,			**__a )
         if isinstance(__a   ,			__a ) and len(__a ) == 1:
              return outputs[0]
         return outputs




