


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			=				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  lowerCamelCase_					(				self:      int       ,		UpperCamelCase_:      GenericTensor				)     ->  np.ndarray:





									"""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=UpperCamelCase_				)
									else:
											raise ValueError('''Unsupported framework'''				)
									return masked_index

							def  lowerCamelCase_					(				self:      str       ,		UpperCamelCase_:      GenericTensor				)     ->  np.ndarray:





									"""simple docstring"""







									lowercase__				= self.get_masked_index(UpperCamelCase_				)
									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  lowerCamelCase_					(				self:      str       ,		UpperCamelCase_:      GenericTensor				)     ->  Dict:





									"""simple docstring"""







									if isinstance(UpperCamelCase_       ,		UpperCamelCase_				):
											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(UpperCamelCase_				)

							def  lowerCamelCase_					(				self:      List[str]       ,		UpperCamelCase_:      str       ,		UpperCamelCase_:      str=None       ,		**UpperCamelCase_:      Any				)     ->  Dict[str, GenericTensor]:





									"""simple docstring"""







									if return_tensors is None:
											lowercase__				= self.framework
									lowercase__				= self.tokenizer(UpperCamelCase_       ,		return_tensors=UpperCamelCase_				)
									self.ensure_exactly_one_mask_token(UpperCamelCase_				)
									return model_inputs

							def  lowerCamelCase_					(				self:      Any       ,		UpperCamelCase_:      Any				)     ->  int:





									"""simple docstring"""







									lowercase__				= self.model(**UpperCamelCase_				)
									lowercase__				= model_inputs['''input_ids''']
									return model_outputs

							def  lowerCamelCase_					(				self:      Dict       ,		UpperCamelCase_:      List[Any]       ,		UpperCamelCase_:      Optional[int]=5       ,		UpperCamelCase_:      Optional[int]=None				)     ->  Optional[int]:





									"""simple docstring"""







									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(UpperCamelCase_       ,		axis=-1				)
											if target_ids is not None:
													lowercase__				= tf.gather_nd(tf.squeeze(UpperCamelCase_       ,		0				)       ,		target_ids.reshape(-1       ,		1				)				)
													lowercase__				= tf.expand_dims(UpperCamelCase_       ,		0				)

											lowercase__				= tf.math.top_k(UpperCamelCase_       ,		k=UpperCamelCase_				)
											lowercase__	,						lowercase__				= topk.values.numpy(), topk.indices.numpy()
									else:
											lowercase__				= torch.nonzero(input_ids == self.tokenizer.mask_token_id       ,		as_tuple=UpperCamelCase_				).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(UpperCamelCase_				)

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

							def  lowerCamelCase_					(				self:      Any       ,		UpperCamelCase_:      int       ,		UpperCamelCase_:      int=None				)     ->  Dict:





									"""simple docstring"""







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

							def  lowerCamelCase_					(				self:      List[str]       ,		UpperCamelCase_:      int=None       ,		UpperCamelCase_:      List[Any]=None				)     ->  Union[str, Any]:





									"""simple docstring"""







									lowercase__				= {}

									if targets is not None:
											lowercase__				= self.get_target_ids(UpperCamelCase_       ,		UpperCamelCase_				)
											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]       ,		UpperCamelCase_:      Optional[Any]       ,		*UpperCamelCase_:      Tuple       ,		**UpperCamelCase_:      List[Any]				)     ->  Union[str, Any]:





									"""simple docstring"""







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







'''simple docstring'''

import qiskit







def a_     (    __UpperCAmelCase				,							__UpperCAmelCase					)				->					qiskit.result.counts.Counts:





			"""simple docstring"""







			snake_case:    Union[str, Any]      							=qiskit.Aer.get_backend('aer_simulator'					)

			# Create a Quantum Circuit acting on the q register
			snake_case:    Dict      							=qiskit.QuantumCircuit(__UpperCAmelCase				,							__UpperCAmelCase					)

			# Map the quantum measurement to the classical bits
			circuit.measure([0]				,							[0]					)

			# Execute the circuit on the simulator
			snake_case:    Dict      							=qiskit.execute(__UpperCAmelCase				,							__UpperCAmelCase				,							shots=10_00					)

			# Return the histogram data of the results of the experiment.
			return job.result().get_counts(__UpperCAmelCase					)


if __name__ == "__main__":
	print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")




