fill_mask.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. from typing import Any, overload
  2. import numpy as np
  3. from ..utils import add_end_docstrings, is_torch_available, logging
  4. from .base import GenericTensor, Pipeline, PipelineException, build_pipeline_init_args
  5. if is_torch_available():
  6. import torch
  7. logger = logging.get_logger(__name__)
  8. @add_end_docstrings(
  9. build_pipeline_init_args(has_tokenizer=True),
  10. r"""
  11. top_k (`int`, *optional*, defaults to 5):
  12. The number of predictions to return.
  13. targets (`str` or `list[str]`, *optional*):
  14. When passed, the model will limit the scores to the passed targets instead of looking up in the whole
  15. vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
  16. token will be used (with a warning, and that might be slower).
  17. tokenizer_kwargs (`dict`, *optional*):
  18. Additional dictionary of keyword arguments passed along to the tokenizer.""",
  19. )
  20. class FillMaskPipeline(Pipeline):
  21. _load_processor = False
  22. _load_image_processor = False
  23. _load_feature_extractor = False
  24. _load_tokenizer = True
  25. """
  26. Masked language modeling prediction pipeline using any `ModelWithLMHead`. See the [masked language modeling
  27. examples](../task_summary#masked-language-modeling) for more information.
  28. Example:
  29. ```python
  30. >>> from transformers import pipeline
  31. >>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
  32. >>> fill_masker("This is a simple [MASK].")
  33. [{'score': 0.042, 'token': 3291, 'token_str': 'problem', 'sequence': 'this is a simple problem.'}, {'score': 0.031, 'token': 3160, 'token_str': 'question', 'sequence': 'this is a simple question.'}, {'score': 0.03, 'token': 8522, 'token_str': 'equation', 'sequence': 'this is a simple equation.'}, {'score': 0.027, 'token': 2028, 'token_str': 'one', 'sequence': 'this is a simple one.'}, {'score': 0.024, 'token': 3627, 'token_str': 'rule', 'sequence': 'this is a simple rule.'}]
  34. ```
  35. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  36. This mask filling pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  37. `"fill-mask"`.
  38. The models that this pipeline can use are models that have been trained with a masked language modeling objective,
  39. which includes the bi-directional models in the library. See the up-to-date list of available models on
  40. [huggingface.co/models](https://huggingface.co/models?filter=fill-mask).
  41. <Tip>
  42. This pipeline only works for inputs with exactly one token masked. Experimental: We added support for multiple
  43. masks. The returned values are raw model output, and correspond to disjoint probabilities where one might expect
  44. joint probabilities (See [discussion](https://github.com/huggingface/transformers/pull/10222)).
  45. </Tip>
  46. <Tip>
  47. This pipeline now supports tokenizer_kwargs. For example try:
  48. ```python
  49. >>> from transformers import pipeline
  50. >>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
  51. >>> tokenizer_kwargs = {"truncation": True}
  52. >>> fill_masker(
  53. ... "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100,
  54. ... tokenizer_kwargs=tokenizer_kwargs,
  55. ... )
  56. ```
  57. </Tip>
  58. """
  59. def get_masked_index(self, input_ids: GenericTensor) -> np.ndarray:
  60. masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False)
  61. return masked_index
  62. def _ensure_exactly_one_mask_token(self, input_ids: GenericTensor) -> np.ndarray:
  63. masked_index = self.get_masked_index(input_ids)
  64. numel = np.prod(masked_index.shape)
  65. if numel < 1:
  66. raise PipelineException(
  67. "fill-mask",
  68. self.model.base_model_prefix,
  69. f"No mask_token ({self.tokenizer.mask_token}) found on the input",
  70. )
  71. def ensure_exactly_one_mask_token(self, model_inputs: GenericTensor):
  72. if isinstance(model_inputs, list):
  73. for model_input in model_inputs:
  74. self._ensure_exactly_one_mask_token(model_input["input_ids"][0])
  75. else:
  76. for input_ids in model_inputs["input_ids"]:
  77. self._ensure_exactly_one_mask_token(input_ids)
  78. def preprocess(
  79. self, inputs, return_tensors=None, tokenizer_kwargs=None, **preprocess_parameters
  80. ) -> dict[str, GenericTensor]:
  81. if return_tensors is None:
  82. return_tensors = "pt"
  83. if tokenizer_kwargs is None:
  84. tokenizer_kwargs = {}
  85. model_inputs = self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
  86. self.ensure_exactly_one_mask_token(model_inputs)
  87. return model_inputs
  88. def _forward(self, model_inputs):
  89. model_outputs = self.model(**model_inputs)
  90. model_outputs["input_ids"] = model_inputs["input_ids"]
  91. return model_outputs
  92. def postprocess(self, model_outputs, top_k=5, target_ids=None):
  93. # Cap top_k if there are targets
  94. if target_ids is not None and target_ids.shape[0] < top_k:
  95. top_k = target_ids.shape[0]
  96. input_ids = model_outputs["input_ids"][0]
  97. outputs = model_outputs["logits"]
  98. masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False).squeeze(-1)
  99. # Fill mask pipeline supports only one ${mask_token} per sample
  100. logits = outputs[0, masked_index, :]
  101. probs = logits.softmax(dim=-1)
  102. if target_ids is not None:
  103. probs = probs[..., target_ids]
  104. values, predictions = probs.topk(top_k)
  105. result = []
  106. single_mask = values.shape[0] == 1
  107. for i, (_values, _predictions) in enumerate(zip(values.tolist(), predictions.tolist())):
  108. row = []
  109. for v, p in zip(_values, _predictions):
  110. # Copy is important since we're going to modify this array in place
  111. tokens = input_ids.numpy().copy()
  112. if target_ids is not None:
  113. p = target_ids[p].tolist()
  114. tokens[masked_index[i]] = p
  115. # Filter padding out:
  116. tokens = tokens[np.where(tokens != self.tokenizer.pad_token_id)]
  117. # Originally we skip special tokens to give readable output.
  118. # For multi masks though, the other [MASK] would be removed otherwise
  119. # making the output look odd, so we add them back
  120. sequence = self.tokenizer.decode(tokens, skip_special_tokens=single_mask)
  121. proposition = {"score": v, "token": p, "token_str": self.tokenizer.decode([p]), "sequence": sequence}
  122. row.append(proposition)
  123. result.append(row)
  124. if single_mask:
  125. return result[0]
  126. return result
  127. def get_target_ids(self, targets):
  128. if isinstance(targets, str):
  129. targets = [targets]
  130. try:
  131. vocab = self.tokenizer.get_vocab()
  132. except Exception:
  133. vocab = {}
  134. target_ids = []
  135. for target in targets:
  136. id_ = vocab.get(target)
  137. if id_ is None:
  138. input_ids = self.tokenizer(
  139. target,
  140. add_special_tokens=False,
  141. return_attention_mask=False,
  142. return_token_type_ids=False,
  143. max_length=1,
  144. truncation=True,
  145. )["input_ids"]
  146. if len(input_ids) == 0:
  147. logger.warning(
  148. f"The specified target token `{target}` does not exist in the model vocabulary. "
  149. "We cannot replace it with anything meaningful, ignoring it"
  150. )
  151. continue
  152. id_ = input_ids[0]
  153. # XXX: If users encounter this pass
  154. # it becomes pretty slow, so let's make sure
  155. # The warning enables them to fix the input to
  156. # get faster performance.
  157. logger.warning(
  158. f"The specified target token `{target}` does not exist in the model vocabulary. "
  159. f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`."
  160. )
  161. target_ids.append(id_)
  162. target_ids = list(set(target_ids))
  163. if len(target_ids) == 0:
  164. raise ValueError("At least one target must be provided when passed.")
  165. target_ids = np.array(target_ids)
  166. return target_ids
  167. def _sanitize_parameters(self, top_k=None, targets=None, tokenizer_kwargs=None):
  168. preprocess_params = {}
  169. if tokenizer_kwargs is not None:
  170. preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs
  171. postprocess_params = {}
  172. if targets is not None:
  173. target_ids = self.get_target_ids(targets)
  174. postprocess_params["target_ids"] = target_ids
  175. if top_k is not None:
  176. postprocess_params["top_k"] = top_k
  177. if self.tokenizer.mask_token_id is None:
  178. raise PipelineException(
  179. "fill-mask", self.model.base_model_prefix, "The tokenizer does not define a `mask_token`."
  180. )
  181. return preprocess_params, {}, postprocess_params
  182. @overload
  183. def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ...
  184. @overload
  185. def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
  186. def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
  187. """
  188. Fill the masked token in the text(s) given as inputs.
  189. Args:
  190. inputs (`str` or `list[str]`):
  191. One or several texts (or one list of prompts) with masked tokens.
  192. targets (`str` or `list[str]`, *optional*):
  193. When passed, the model will limit the scores to the passed targets instead of looking up in the whole
  194. vocab. If the provided targets are not in the model vocab, they will be tokenized and the first
  195. resulting token will be used (with a warning, and that might be slower).
  196. top_k (`int`, *optional*):
  197. When passed, overrides the number of predictions to return.
  198. Return:
  199. A list or a list of list of `dict`: Each result comes as list of dictionaries with the following keys:
  200. - **sequence** (`str`) -- The corresponding input with the mask token prediction.
  201. - **score** (`float`) -- The corresponding probability.
  202. - **token** (`int`) -- The predicted token id (to replace the masked one).
  203. - **token_str** (`str`) -- The predicted token (to replace the masked one).
  204. """
  205. outputs = super().__call__(inputs, **kwargs)
  206. if isinstance(inputs, list) and len(inputs) == 1:
  207. return outputs[0]
  208. return outputs