



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


_lowerCAmelCase	:   Optional[Any]    =   logging.get_logger(__name__)


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







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







						"""simple docstring"""
						lowerCAmelCase__		  =  self.get_masked_index(a_						)
						lowerCAmelCase__		  =  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 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						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 						SCREAMING_SNAKE_CASE_					(							self    ,a_    ,a_=None    ,**a_						):







						"""simple docstring"""
						if return_tensors is None:
										lowerCAmelCase__		  =  self.framework
						lowerCAmelCase__		  =  self.tokenizer(a_    ,return_tensors=a_						)
						self.ensure_exactly_one_mask_token(a_						)
						return model_inputs
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  self.model(**a_						)
						lowerCAmelCase__		  =  model_inputs['input_ids']
						return model_outputs
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_    ,a_=5    ,a_=None						):







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

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

										lowerCAmelCase__		  =  outputs.numpy()

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

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

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

										lowerCAmelCase__  ,   lowerCAmelCase__		  =  probs.topk(a_						)

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

														lowerCAmelCase__		  =  p
														# Filter padding out:
														lowerCAmelCase__		  =  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
														lowerCAmelCase__		  =  self.tokenizer.decode(a_    ,skip_special_tokens=a_						)
														lowerCAmelCase__		  =  {'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 						SCREAMING_SNAKE_CASE_					(							self    ,a_    ,a_=None						):







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







						"""simple docstring"""
						lowerCAmelCase__		  =  {}

						if targets is not None:
										lowerCAmelCase__		  =  self.get_target_ids(a_    ,a_						)
										lowerCAmelCase__		  =  target_ids

						if top_k is not None:
										lowerCAmelCase__		  =  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    ,a_    ,*a_    ,**a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  super().__call__(a_    ,**a_						)
						if isinstance(a_    ,a_						) and len(a_						) == 1:
										return outputs[0]
						return outputs





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCAmelCase	:   List[str]    =   logging.get_logger(__name__)

_lowerCAmelCase	:   Tuple    =   {
    "microsoft/wavlm-base": "https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json",
    # See all WavLM models at https://huggingface.co/models?filter=wavlm
}


class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		SCREAMING_SNAKE_CASE__								=	'wavlm'
		def __init__(							self    ,a_=32    ,a_=768    ,a_=12    ,a_=12    ,a_=3072    ,a_="gelu"    ,a_=0.1    ,a_=0.1    ,a_=0.1    ,a_=0.0    ,a_=0.1    ,a_=0.1    ,a_=0.02    ,a_=1e-5    ,a_="group"    ,a_="gelu"    ,a_=(512, 512, 512, 512, 512, 512, 512)    ,a_=(5, 2, 2, 2, 2, 2, 2)    ,a_=(10, 3, 3, 3, 3, 2, 2)    ,a_=False    ,a_=128    ,a_=16    ,a_=320    ,a_=800    ,a_=False    ,a_=True    ,a_=0.05    ,a_=10    ,a_=2    ,a_=0.0    ,a_=10    ,a_=320    ,a_=2    ,a_=0.1    ,a_=100    ,a_=256    ,a_=256    ,a_=0.1    ,a_="mean"    ,a_=False    ,a_=False    ,a_=256    ,a_=(512, 512, 512, 512, 1500)    ,a_=(5, 3, 3, 1, 1)    ,a_=(1, 2, 3, 1, 1)    ,a_=512    ,a_=80    ,a_=0    ,a_=1    ,a_=2    ,a_=False    ,a_=3    ,a_=2    ,a_=3    ,a_=None    ,**a_    ,):







						"""simple docstring"""
						super().__init__(**a_    ,pad_token_id=a_    ,bos_token_id=a_    ,eos_token_id=a_						)
						lowerCAmelCase__		  =  hidden_size
						lowerCAmelCase__		  =  feat_extract_norm
						lowerCAmelCase__		  =  feat_extract_activation
						lowerCAmelCase__		  =  list(a_						)
						lowerCAmelCase__		  =  list(a_						)
						lowerCAmelCase__		  =  list(a_						)
						lowerCAmelCase__		  =  conv_bias
						lowerCAmelCase__		  =  num_buckets
						lowerCAmelCase__		  =  max_bucket_distance
						lowerCAmelCase__		  =  num_conv_pos_embeddings
						lowerCAmelCase__		  =  num_conv_pos_embedding_groups
						lowerCAmelCase__		  =  len(self.conv_dim						)
						lowerCAmelCase__		  =  num_hidden_layers
						lowerCAmelCase__		  =  intermediate_size
						lowerCAmelCase__		  =  hidden_act
						lowerCAmelCase__		  =  num_attention_heads
						lowerCAmelCase__		  =  hidden_dropout
						lowerCAmelCase__		  =  attention_dropout
						lowerCAmelCase__		  =  activation_dropout
						lowerCAmelCase__		  =  feat_proj_dropout
						lowerCAmelCase__		  =  final_dropout
						lowerCAmelCase__		  =  layerdrop
						lowerCAmelCase__		  =  layer_norm_eps
						lowerCAmelCase__		  =  initializer_range
						lowerCAmelCase__		  =  num_ctc_classes
						lowerCAmelCase__		  =  vocab_size
						lowerCAmelCase__		  =  do_stable_layer_norm
						lowerCAmelCase__		  =  use_weighted_layer_sum
						lowerCAmelCase__		  =  classifier_proj_size

						if (
						    (len(self.conv_stride						) != self.num_feat_extract_layers)
						    or (len(self.conv_kernel						) != self.num_feat_extract_layers)
						    or (len(self.conv_dim						) != self.num_feat_extract_layers)
						):
										raise ValueError(
										    'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='
										    ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='
										    f' {len(self.conv_dim						)}`, `len(config.conv_stride) = {len(self.conv_stride						)}`,'
										    f' `len(config.conv_kernel) = {len(self.conv_kernel						)}`.'						)

						# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
						lowerCAmelCase__		  =  apply_spec_augment
						lowerCAmelCase__		  =  mask_time_prob
						lowerCAmelCase__		  =  mask_time_length
						lowerCAmelCase__		  =  mask_time_min_masks
						lowerCAmelCase__		  =  mask_feature_prob
						lowerCAmelCase__		  =  mask_feature_length

						# parameters for pretraining with codevector quantized representations
						lowerCAmelCase__		  =  num_codevectors_per_group
						lowerCAmelCase__		  =  num_codevector_groups
						lowerCAmelCase__		  =  contrastive_logits_temperature
						lowerCAmelCase__		  =  num_negatives
						lowerCAmelCase__		  =  codevector_dim
						lowerCAmelCase__		  =  proj_codevector_dim
						lowerCAmelCase__		  =  diversity_loss_weight

						# ctc loss
						lowerCAmelCase__		  =  ctc_loss_reduction
						lowerCAmelCase__		  =  ctc_zero_infinity

						# adapter
						lowerCAmelCase__		  =  add_adapter
						lowerCAmelCase__		  =  adapter_kernel_size
						lowerCAmelCase__		  =  adapter_stride
						lowerCAmelCase__		  =  num_adapter_layers
						lowerCAmelCase__		  =  output_hidden_size or hidden_size

						# SequenceClassification-specific parameter. Feel free to ignore for other classes.
						lowerCAmelCase__		  =  classifier_proj_size

						# XVector-specific parameters. Feel free to ignore for other classes.
						lowerCAmelCase__		  =  list(a_						)
						lowerCAmelCase__		  =  list(a_						)
						lowerCAmelCase__		  =  list(a_						)
						lowerCAmelCase__		  =  xvector_output_dim



		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return functools.reduce(operator.mul    ,self.conv_stride    ,1						)
