feature_extraction.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from typing import Any
  2. from ..utils import add_end_docstrings
  3. from .base import GenericTensor, Pipeline, build_pipeline_init_args
  4. @add_end_docstrings(
  5. build_pipeline_init_args(has_tokenizer=True, supports_binary_output=False),
  6. r"""
  7. tokenize_kwargs (`dict`, *optional*):
  8. Additional dictionary of keyword arguments passed along to the tokenizer.
  9. return_tensors (`bool`, *optional*):
  10. If `True`, returns a tensor according to the specified framework, otherwise returns a list.""",
  11. )
  12. class FeatureExtractionPipeline(Pipeline):
  13. """
  14. Feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
  15. transformer, which can be used as features in downstream tasks.
  16. Example:
  17. ```python
  18. >>> from transformers import pipeline
  19. >>> extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction")
  20. >>> result = extractor("This is a simple test.", return_tensors=True)
  21. >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string.
  22. torch.Size([1, 8, 768])
  23. ```
  24. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  25. This feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier:
  26. `"feature-extraction"`.
  27. All models may be used for this pipeline. See a list of all models, including community-contributed models on
  28. [huggingface.co/models](https://huggingface.co/models).
  29. """
  30. _load_processor = False
  31. _load_image_processor = False
  32. _load_feature_extractor = False
  33. _load_tokenizer = True
  34. def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, return_tensors=None, **kwargs):
  35. if tokenize_kwargs is None:
  36. tokenize_kwargs = {}
  37. if truncation is not None:
  38. if "truncation" in tokenize_kwargs:
  39. raise ValueError(
  40. "truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)"
  41. )
  42. tokenize_kwargs["truncation"] = truncation
  43. preprocess_params = tokenize_kwargs
  44. postprocess_params = {}
  45. if return_tensors is not None:
  46. postprocess_params["return_tensors"] = return_tensors
  47. return preprocess_params, {}, postprocess_params
  48. def preprocess(self, inputs, **tokenize_kwargs) -> dict[str, GenericTensor]:
  49. model_inputs = self.tokenizer(inputs, return_tensors="pt", **tokenize_kwargs)
  50. return model_inputs
  51. def _forward(self, model_inputs):
  52. model_outputs = self.model(**model_inputs)
  53. return model_outputs
  54. def postprocess(self, model_outputs, return_tensors=False):
  55. # [0] is the first available tensor, logits or last_hidden_state.
  56. if return_tensors:
  57. return model_outputs[0]
  58. return model_outputs[0].tolist()
  59. def __call__(self, *args: str | list[str], **kwargs: Any) -> Any | list[Any]:
  60. """
  61. Extract the features of the input(s) text.
  62. Args:
  63. args (`str` or `list[str]`): One or several texts (or one list of texts) to get the features of.
  64. Return:
  65. A nested list of `float`: The features computed by the model.
  66. """
  67. return super().__call__(*args, **kwargs)