zero_shot_classification.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import inspect
  2. from typing import List, Union
  3. import numpy as np
  4. from ..tokenization_utils import TruncationStrategy
  5. from ..utils import add_end_docstrings, logging
  6. from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args
  7. logger = logging.get_logger(__name__)
  8. class ZeroShotClassificationArgumentHandler(ArgumentHandler):
  9. """
  10. Handles arguments for zero-shot for text classification by turning each possible label into an NLI
  11. premise/hypothesis pair.
  12. """
  13. def _parse_labels(self, labels):
  14. if isinstance(labels, str):
  15. labels = [label.strip() for label in labels.split(",") if label.strip()]
  16. return labels
  17. def __call__(self, sequences, labels, hypothesis_template):
  18. if len(labels) == 0 or len(sequences) == 0:
  19. raise ValueError("You must include at least one label and at least one sequence.")
  20. if hypothesis_template.format(labels[0]) == hypothesis_template:
  21. raise ValueError(
  22. (
  23. 'The provided hypothesis_template "{}" was not able to be formatted with the target labels. '
  24. "Make sure the passed template includes formatting syntax such as {{}} where the label should go."
  25. ).format(hypothesis_template)
  26. )
  27. if isinstance(sequences, str):
  28. sequences = [sequences]
  29. sequence_pairs = []
  30. for sequence in sequences:
  31. sequence_pairs.extend([[sequence, hypothesis_template.format(label)] for label in labels])
  32. return sequence_pairs, sequences
  33. @add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
  34. class ZeroShotClassificationPipeline(ChunkPipeline):
  35. """
  36. NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural
  37. language inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a
  38. hardcoded number of potential classes, they can be chosen at runtime. It usually means it's slower but it is
  39. **much** more flexible.
  40. Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis
  41. pair and passed to the pretrained model. Then, the logit for *entailment* is taken as the logit for the candidate
  42. label being valid. Any NLI model can be used, but the id of the *entailment* label must be included in the model
  43. config's :attr:*~transformers.PretrainedConfig.label2id*.
  44. Example:
  45. ```python
  46. >>> from transformers import pipeline
  47. >>> oracle = pipeline(model="facebook/bart-large-mnli")
  48. >>> oracle(
  49. ... "I have a problem with my iphone that needs to be resolved asap!!",
  50. ... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
  51. ... )
  52. {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
  53. >>> oracle(
  54. ... "I have a problem with my iphone that needs to be resolved asap!!",
  55. ... candidate_labels=["english", "german"],
  56. ... )
  57. {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}
  58. ```
  59. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  60. This NLI pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  61. `"zero-shot-classification"`.
  62. The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list
  63. of available models on [huggingface.co/models](https://huggingface.co/models?search=nli).
  64. """
  65. def __init__(self, args_parser=ZeroShotClassificationArgumentHandler(), *args, **kwargs):
  66. self._args_parser = args_parser
  67. super().__init__(*args, **kwargs)
  68. if self.entailment_id == -1:
  69. logger.warning(
  70. "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to "
  71. "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."
  72. )
  73. @property
  74. def entailment_id(self):
  75. for label, ind in self.model.config.label2id.items():
  76. if label.lower().startswith("entail"):
  77. return ind
  78. return -1
  79. def _parse_and_tokenize(
  80. self, sequence_pairs, padding=True, add_special_tokens=True, truncation=TruncationStrategy.ONLY_FIRST, **kwargs
  81. ):
  82. """
  83. Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
  84. """
  85. return_tensors = self.framework
  86. if self.tokenizer.pad_token is None:
  87. # Override for tokenizers not supporting padding
  88. logger.error(
  89. "Tokenizer was not supporting padding necessary for zero-shot, attempting to use "
  90. " `pad_token=eos_token`"
  91. )
  92. self.tokenizer.pad_token = self.tokenizer.eos_token
  93. try:
  94. inputs = self.tokenizer(
  95. sequence_pairs,
  96. add_special_tokens=add_special_tokens,
  97. return_tensors=return_tensors,
  98. padding=padding,
  99. truncation=truncation,
  100. )
  101. except Exception as e:
  102. if "too short" in str(e):
  103. # tokenizers might yell that we want to truncate
  104. # to a value that is not even reached by the input.
  105. # In that case we don't want to truncate.
  106. # It seems there's not a really better way to catch that
  107. # exception.
  108. inputs = self.tokenizer(
  109. sequence_pairs,
  110. add_special_tokens=add_special_tokens,
  111. return_tensors=return_tensors,
  112. padding=padding,
  113. truncation=TruncationStrategy.DO_NOT_TRUNCATE,
  114. )
  115. else:
  116. raise e
  117. return inputs
  118. def _sanitize_parameters(self, **kwargs):
  119. if kwargs.get("multi_class", None) is not None:
  120. kwargs["multi_label"] = kwargs["multi_class"]
  121. logger.warning(
  122. "The `multi_class` argument has been deprecated and renamed to `multi_label`. "
  123. "`multi_class` will be removed in a future version of Transformers."
  124. )
  125. preprocess_params = {}
  126. if "candidate_labels" in kwargs:
  127. preprocess_params["candidate_labels"] = self._args_parser._parse_labels(kwargs["candidate_labels"])
  128. if "hypothesis_template" in kwargs:
  129. preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
  130. postprocess_params = {}
  131. if "multi_label" in kwargs:
  132. postprocess_params["multi_label"] = kwargs["multi_label"]
  133. return preprocess_params, {}, postprocess_params
  134. def __call__(
  135. self,
  136. sequences: Union[str, List[str]],
  137. *args,
  138. **kwargs,
  139. ):
  140. """
  141. Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
  142. information.
  143. Args:
  144. sequences (`str` or `List[str]`):
  145. The sequence(s) to classify, will be truncated if the model input is too large.
  146. candidate_labels (`str` or `List[str]`):
  147. The set of possible class labels to classify each sequence into. Can be a single label, a string of
  148. comma-separated labels, or a list of labels.
  149. hypothesis_template (`str`, *optional*, defaults to `"This example is {}."`):
  150. The template used to turn each label into an NLI-style hypothesis. This template must include a {} or
  151. similar syntax for the candidate label to be inserted into the template. For example, the default
  152. template is `"This example is {}."` With the candidate label `"sports"`, this would be fed into the
  153. model like `"<cls> sequence to classify <sep> This example is sports . <sep>"`. The default template
  154. works well in many cases, but it may be worthwhile to experiment with different templates depending on
  155. the task setting.
  156. multi_label (`bool`, *optional*, defaults to `False`):
  157. Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that
  158. the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered
  159. independent and probabilities are normalized for each candidate by doing a softmax of the entailment
  160. score vs. the contradiction score.
  161. Return:
  162. A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
  163. - **sequence** (`str`) -- The sequence for which this is the output.
  164. - **labels** (`List[str]`) -- The labels sorted by order of likelihood.
  165. - **scores** (`List[float]`) -- The probabilities for each of the labels.
  166. """
  167. if len(args) == 0:
  168. pass
  169. elif len(args) == 1 and "candidate_labels" not in kwargs:
  170. kwargs["candidate_labels"] = args[0]
  171. else:
  172. raise ValueError(f"Unable to understand extra arguments {args}")
  173. return super().__call__(sequences, **kwargs)
  174. def preprocess(self, inputs, candidate_labels=None, hypothesis_template="This example is {}."):
  175. sequence_pairs, sequences = self._args_parser(inputs, candidate_labels, hypothesis_template)
  176. for i, (candidate_label, sequence_pair) in enumerate(zip(candidate_labels, sequence_pairs)):
  177. model_input = self._parse_and_tokenize([sequence_pair])
  178. yield {
  179. "candidate_label": candidate_label,
  180. "sequence": sequences[0],
  181. "is_last": i == len(candidate_labels) - 1,
  182. **model_input,
  183. }
  184. def _forward(self, inputs):
  185. candidate_label = inputs["candidate_label"]
  186. sequence = inputs["sequence"]
  187. model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names}
  188. # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
  189. model_forward = self.model.forward if self.framework == "pt" else self.model.call
  190. if "use_cache" in inspect.signature(model_forward).parameters.keys():
  191. model_inputs["use_cache"] = False
  192. outputs = self.model(**model_inputs)
  193. model_outputs = {
  194. "candidate_label": candidate_label,
  195. "sequence": sequence,
  196. "is_last": inputs["is_last"],
  197. **outputs,
  198. }
  199. return model_outputs
  200. def postprocess(self, model_outputs, multi_label=False):
  201. candidate_labels = [outputs["candidate_label"] for outputs in model_outputs]
  202. sequences = [outputs["sequence"] for outputs in model_outputs]
  203. if self.framework == "pt":
  204. logits = np.concatenate([output["logits"].float().numpy() for output in model_outputs])
  205. else:
  206. logits = np.concatenate([output["logits"].numpy() for output in model_outputs])
  207. N = logits.shape[0]
  208. n = len(candidate_labels)
  209. num_sequences = N // n
  210. reshaped_outputs = logits.reshape((num_sequences, n, -1))
  211. if multi_label or len(candidate_labels) == 1:
  212. # softmax over the entailment vs. contradiction dim for each label independently
  213. entailment_id = self.entailment_id
  214. contradiction_id = -1 if entailment_id == 0 else 0
  215. entail_contr_logits = reshaped_outputs[..., [contradiction_id, entailment_id]]
  216. scores = np.exp(entail_contr_logits) / np.exp(entail_contr_logits).sum(-1, keepdims=True)
  217. scores = scores[..., 1]
  218. else:
  219. # softmax the "entailment" logits over all candidate labels
  220. entail_logits = reshaped_outputs[..., self.entailment_id]
  221. scores = np.exp(entail_logits) / np.exp(entail_logits).sum(-1, keepdims=True)
  222. top_inds = list(reversed(scores[0].argsort()))
  223. return {
  224. "sequence": sequences[0],
  225. "labels": [candidate_labels[i] for i in top_inds],
  226. "scores": scores[0, top_inds].tolist(),
  227. }