




'''simple docstring'''





from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block




@dataclass
class  _snake_case		(	A__							):
			lowerCAmelCase_     :      Optional[int]						       =    42




class  _snake_case		(	A__						,						A__							):




			@register_to_config
			def __init__(					self				,							a__ = 65_536				,							a__ = None				,							a__ = 2				,							a__ = 2				,							a__ = 0				,							a__ = "fourier"				,							a__ = True				,							a__ = False				,							a__ = 0.0				,							a__ = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")				,							a__ = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")				,							a__ = "UNetMidBlock1D"				,							a__ = None				,							a__ = (32, 32, 64)				,							a__ = None				,							a__ = 8				,							a__ = 1				,							a__ = False				,							)				->				List[Any]:

										'''simple docstring'''




										super().__init__()
										snake_case_						=      sample_size

										# time
										if time_embedding_type == "fourier":
																	snake_case_						=      GaussianFourierProjection(
																	    embedding_size=8				,							set_W_to_weight=a__				,							log=a__				,							flip_sin_to_cos=a__							)
																	snake_case_						=      2 * block_out_channels[0]
										elif time_embedding_type == "positional":
																	snake_case_						=      Timesteps(
																	    block_out_channels[0]				,							flip_sin_to_cos=a__				,							downscale_freq_shift=a__							)
																	snake_case_						=      block_out_channels[0]

										if use_timestep_embedding:
																	snake_case_						=      block_out_channels[0] * 4
																	snake_case_						=      TimestepEmbedding(
																	    in_channels=a__				,							time_embed_dim=a__				,							act_fn=a__				,							out_dim=block_out_channels[0]				,							)

										snake_case_						=      nn.ModuleList([]							)
										snake_case_						=      None
										snake_case_						=      nn.ModuleList([]							)
										snake_case_						=      None

										# down
										snake_case_						=      in_channels
										for i, down_block_type in enumerate(a__							):
																	snake_case_						=      output_channel
																	snake_case_						=      block_out_channels[i]

																	if i == 0:
																								input_channel += extra_in_channels

																	snake_case_						=      i == len(a__							) - 1

																	snake_case_						=      get_down_block(
																	    a__				,							num_layers=a__				,							in_channels=a__				,							out_channels=a__				,							temb_channels=block_out_channels[0]				,							add_downsample=not is_final_block or downsample_each_block				,							)
																	self.down_blocks.append(a__							)

										# mid
										snake_case_						=      get_mid_block(
										    a__				,							in_channels=block_out_channels[-1]				,							mid_channels=block_out_channels[-1]				,							out_channels=block_out_channels[-1]				,							embed_dim=block_out_channels[0]				,							num_layers=a__				,							add_downsample=a__				,							)

										# up
										snake_case_						=      list(reversed(a__							)							)
										snake_case_						=      reversed_block_out_channels[0]
										if out_block_type is None:
																	snake_case_						=      out_channels
										else:
																	snake_case_						=      block_out_channels[0]

										for i, up_block_type in enumerate(a__							):
																	snake_case_						=      output_channel
																	snake_case_						=      (
																	    reversed_block_out_channels[i + 1] if i < len(a__							) - 1 else final_upsample_channels
																	)

																	snake_case_						=      i == len(a__							) - 1

																	snake_case_						=      get_up_block(
																	    a__				,							num_layers=a__				,							in_channels=a__				,							out_channels=a__				,							temb_channels=block_out_channels[0]				,							add_upsample=not is_final_block				,							)
																	self.up_blocks.append(a__							)
																	snake_case_						=      output_channel

										# out
										snake_case_						=      norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4				,							32							)
										snake_case_						=      get_out_block(
										    out_block_type=a__				,							num_groups_out=a__				,							embed_dim=block_out_channels[0]				,							out_channels=a__				,							act_fn=a__				,							fc_dim=block_out_channels[-1] // 4				,							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__ = True				,							)				->				Optional[int]:

										'''simple docstring'''




										snake_case_						=      timestep
										if not torch.is_tensor(a__							):
																	snake_case_						=      torch.tensor([timesteps]				,							dtype=torch.long				,							device=sample.device							)
										elif torch.is_tensor(a__							) and len(timesteps.shape							) == 0:
																	snake_case_						=      timesteps[None].to(sample.device							)

										snake_case_						=      self.time_proj(a__							)
										if self.config.use_timestep_embedding:
																	snake_case_						=      self.time_mlp(a__							)
										else:
																	snake_case_						=      timestep_embed[..., None]
																	snake_case_						=      timestep_embed.repeat([1, 1, sample.shape[2]]							).to(sample.dtype							)
																	snake_case_						=      timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:])							)

										# 2. down
										snake_case_						=      ()
										for downsample_block in self.down_blocks:
																	snake_case_					,      snake_case_						=      downsample_block(hidden_states=a__				,							temb=a__							)
																	down_block_res_samples += res_samples

										# 3. mid
										if self.mid_block:
																	snake_case_						=      self.mid_block(a__				,							a__							)

										# 4. up
										for i, upsample_block in enumerate(self.up_blocks							):
																	snake_case_						=      down_block_res_samples[-1:]
																	snake_case_						=      down_block_res_samples[:-1]
																	snake_case_						=      upsample_block(a__				,							res_hidden_states_tuple=a__				,							temb=a__							)

										# 5. post-process
										if self.out_block:
																	snake_case_						=      self.out_block(a__				,							a__							)

										if not return_dict:
																	return (sample,)

										return UNetaDOutput(sample=a__							)












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


A__	:			Dict			   = logging.get_logger(__name__)
@add_end_docstrings(
    A__		,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       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				def 				lowercase__   (     self						:    Optional[int],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if self.framework == "tf":
												lowercase__    =			tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
								elif self.framework == "pt":
												lowercase__    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id,  as_tuple=lowerCamelCase  )
								else:
												raise ValueError('''Unsupported framework'''  )
								return masked_index




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								lowercase__    =			self.get_masked_index(lowerCamelCase  )
								lowercase__    =			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						:    Optional[Any],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												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(lowerCamelCase  )




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Optional[int]=None,  **lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								if return_tensors is None:
												lowercase__    =			self.framework
								lowercase__    =			self.tokenizer(lowerCamelCase,  return_tensors=lowerCamelCase  )
								self.ensure_exactly_one_mask_token(lowerCamelCase  )
								return model_inputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    int  ):

								'''simple docstring'''
								lowercase__    =			self.model(**lowerCamelCase  )
								lowercase__    =			model_inputs['''input_ids''']
								return model_outputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    List[str],  lowerCamelCase						:    Tuple=5,  lowerCamelCase						:    List[Any]=None  ):

								'''simple docstring'''
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
												lowercase__    =			target_ids.shape[0]
								lowercase__    =			model_outputs['''input_ids'''][0]
								lowercase__    =			model_outputs['''logits''']

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

												lowercase__    =			outputs.numpy()

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

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

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

												lowercase__ ,						lowercase__    =			probs.topk(lowerCamelCase  )

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

																lowercase__    =			p
																# Filter padding out:
																lowercase__    =			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
																lowercase__    =			self.tokenizer.decode(lowerCamelCase,  skip_special_tokens=lowerCamelCase  )
																lowercase__    =			{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]  ), '''sequence''': sequence}
																row.append(lowerCamelCase  )
												result.append(lowerCamelCase  )
								if single_mask:
												return result[0]
								return result




				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    Dict=None  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												lowercase__    =			[targets]
								try:
												lowercase__    =			self.tokenizer.get_vocab()
								except Exception:
												lowercase__    =			{}
								lowercase__    =			[]
								for target in targets:
												lowercase__    =			vocab.get(lowerCamelCase,  lowerCamelCase  )
												if id_ is None:
																lowercase__    =			self.tokenizer(
																    lowerCamelCase,  add_special_tokens=lowerCamelCase,  return_attention_mask=lowerCamelCase,  return_token_type_ids=lowerCamelCase,  max_length=1,  truncation=lowerCamelCase,  )['''input_ids''']
																if len(lowerCamelCase  ) == 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
																lowercase__    =			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_  )
								lowercase__    =			list(set(lowerCamelCase  )  )
								if len(lowerCamelCase  ) == 0:
												raise ValueError('''At least one target must be provided when passed.'''  )
								lowercase__    =			np.array(lowerCamelCase  )
								return target_ids




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    int=None,  lowerCamelCase						:    Any=None  ):

								'''simple docstring'''
								lowercase__    =			{}

								if targets is not None:
												lowercase__    =			self.get_target_ids(lowerCamelCase,  lowerCamelCase  )
												lowercase__    =			target_ids

								if top_k is not None:
												lowercase__    =			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						:    List[Any],  lowerCamelCase						:    Optional[Any],  *lowerCamelCase						:    Optional[Any],  **lowerCamelCase						:    Optional[Any]  ):

								'''simple docstring'''
								lowercase__    =			super().__call__(lowerCamelCase,  **lowerCamelCase  )
								if isinstance(lowerCamelCase,  lowerCamelCase  ) and len(lowerCamelCase  ) == 1:
												return outputs[0]
								return outputs




