Transformers 文件

管道 (Pipelines)

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

管道 (Pipelines)

管道是使用模型進行推理的一種極佳且簡便的方式。這些管道是封裝了庫中大部分複雜程式碼的物件,為多種任務提供了簡單的 API,包括命名實體識別、掩碼語言建模、情感分析、特徵提取和問答。有關使用示例,請參閱任務摘要

需要注意的管道抽象有兩個類別:

管道抽象

pipeline 抽象是所有其他可用管道的包裝器。它的例項化方式與任何其他管道一樣,但可以提供額外的便利性。

對單個專案的簡單呼叫

>>> pipe = pipeline("text-classification")
>>> pipe("This restaurant is awesome")
[{'label': 'POSITIVE', 'score': 0.9998743534088135}]

如果你想使用模型中心中的特定模型,如果該模型已經定義了任務,你可以忽略任務引數。

>>> pipe = pipeline(model="FacebookAI/roberta-large-mnli")
>>> pipe("This restaurant is awesome")
[{'label': 'NEUTRAL', 'score': 0.7313136458396912}]

要對多個專案呼叫管道,你可以用一個 list 來呼叫它。

>>> pipe = pipeline("text-classification")
>>> pipe(["This restaurant is awesome", "This restaurant is awful"])
[{'label': 'POSITIVE', 'score': 0.9998743534088135},
 {'label': 'NEGATIVE', 'score': 0.9996669292449951}]

要遍歷整個資料集,建議直接使用 `dataset`。這意味著你不需要一次性分配整個資料集,也不需要自己進行批處理。這應該和在 GPU 上的自定義迴圈一樣快。如果不是,請隨時建立 issue。

import datasets
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
from tqdm.auto import tqdm

pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0)
dataset = datasets.load_dataset("superb", name="asr", split="test")

# KeyDataset (only *pt*) will simply return the item in the dict returned by the dataset item
# as we're not interested in the *target* part of the dataset. For sentence pair use KeyPairDataset
for out in tqdm(pipe(KeyDataset(dataset, "file"))):
    print(out)
    # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"}
    # {"text": ....}
    # ....

為了方便使用,也可以使用生成器。

from transformers import pipeline

pipe = pipeline("text-classification")


def data():
    while True:
        # This could come from a dataset, a database, a queue or HTTP request
        # in a server
        # Caveat: because this is iterative, you cannot use `num_workers > 1` variable
        # to use multiple threads to preprocess data. You can still have 1 thread that
        # does the preprocessing while the main runs the big inference
        yield "This is a test"


for out in pipe(data()):
    print(out)
    # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"}
    # {"text": ....}
    # ....

transformers.pipeline

< >

( task: typing.Optional[str] = None model: typing.Union[str, ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel'), NoneType] = None config: typing.Union[str, transformers.configuration_utils.PretrainedConfig, NoneType] = None tokenizer: typing.Union[str, transformers.tokenization_utils.PreTrainedTokenizer, ForwardRef('PreTrainedTokenizerFast'), NoneType] = None feature_extractor: typing.Union[str, ForwardRef('SequenceFeatureExtractor'), NoneType] = None image_processor: typing.Union[str, transformers.image_processing_utils.BaseImageProcessor, NoneType] = None processor: typing.Union[str, transformers.processing_utils.ProcessorMixin, NoneType] = None framework: typing.Optional[str] = None revision: typing.Optional[str] = None use_fast: bool = True token: typing.Union[str, bool, NoneType] = None device: typing.Union[int, str, ForwardRef('torch.device'), NoneType] = None device_map: typing.Union[str, dict[str, typing.Union[int, str]], NoneType] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = 'auto' trust_remote_code: typing.Optional[bool] = None model_kwargs: typing.Optional[dict[str, typing.Any]] = None pipeline_class: typing.Optional[typing.Any] = None **kwargs: typing.Any ) Pipeline

引數

  • task (str) — 定義將返回哪個管道的任務。目前接受的任務有:

  • model (strPreTrainedModelTFPreTrainedModel, 可選) — 管道用於進行預測的模型。這可以是一個模型識別符號,也可以是一個繼承自 PreTrainedModel (適用於 PyTorch) 或 TFPreTrainedModel (適用於 TensorFlow) 的預訓練模型的實際例項。

    如果未提供,將載入 task 的預設模型。

  • config (strPretrainedConfig, 可選) — 管道用於例項化模型的配置。這可以是一個模型識別符號,也可以是一個繼承自 PretrainedConfig 的實際預訓練模型配置。

    如果未提供,將使用所請求模型的預設配置檔案。這意味著如果給定了 model,將使用其預設配置。但是,如果未提供 model,則會使用該 task 的預設模型的配置。

  • tokenizer (strPreTrainedTokenizer, 可選) — 管道用於為模型編碼資料的分詞器。這可以是一個模型識別符號,也可以是一個繼承自 PreTrainedTokenizer 的實際預訓練分詞器。

    如果未提供,將載入給定 model 的預設分詞器(如果它是一個字串)。如果 model 未指定或不是字串,則載入 config 的預設分詞器(如果它是一個字串)。然而,如果 config 也未給定或不是字串,則將載入給定 task 的預設分詞器。

  • feature_extractor (strPreTrainedFeatureExtractor, 可選) — 管道用於為模型編碼資料的特徵提取器。這可以是一個模型識別符號,也可以是一個繼承自 PreTrainedFeatureExtractor 的實際預訓練特徵提取器。

    特徵提取器用於非 NLP 模型,例如語音或視覺模型以及多模態模型。多模態模型還需要傳入一個分詞器。

    如果未提供,將載入給定 model 的預設特徵提取器(如果它是一個字串)。如果 model 未指定或不是字串,則載入 config 的預設特徵提取器(如果它是一個字串)。然而,如果 config 也未給定或不是字串,則將載入給定 task 的預設特徵提取器。

  • image_processor (strBaseImageProcessor, 可選) — 管道用於為模型預處理影像的影像處理器。這可以是一個模型識別符號,也可以是一個繼承自 BaseImageProcessor 的實際影像處理器。

    影像處理器用於視覺模型和需要影像輸入的多模態模型。多模態模型還需要傳入一個分詞器。

    如果未提供,將載入給定 model 的預設影像處理器(如果它是一個字串)。如果 model 未指定或不是字串,則載入 config 的預設影像處理器(如果它是一個字串)。

  • processor (strProcessorMixin, 可選) — 管道用於為模型預處理資料的處理器。這可以是一個模型識別符號,也可以是一個繼承自 ProcessorMixin 的實際處理器。

    處理器用於需要多模態輸入的多模態模型,例如,一個同時需要文字和影像輸入的模型。

    如果未提供,將載入給定 model 的預設處理器(如果它是一個字串)。如果 model 未指定或不是字串,則載入 config 的預設處理器(如果它是一個字串)。

  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,或者在未提供模型時預設為 PyTorch。

  • revision (str, 可選, 預設為 "main") — 當傳遞任務名稱或字串模型識別符號時:要使用的特定模型版本。它可以是分支名稱、標籤名稱或提交 ID,因為我們使用基於 git 的系統在 huggingface.co 上儲存模型和其他工件,所以 revision 可以是 git 允許的任何識別符號。
  • use_fast (bool, 可選, 預設為 True) — 是否儘可能使用快速分詞器(一個 PreTrainedTokenizerFast)。
  • use_auth_token (strbool, 可選) — 用於遠端檔案的 HTTP 持有者授權令牌。如果為 True,將使用執行 huggingface-cli login 時生成的令牌(儲存在 ~/.huggingface 中)。
  • device (intstrtorch.device) — 定義此管道將分配到的裝置(例如,"cpu", "cuda:1", "mps" 或 GPU 序號 1)。
  • device_map (strdict[str, Union[int, str, torch.device], 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式)。當存在 accelerate 庫時,設定 device_map="auto" 可自動計算最優的 device_map(更多資訊請參見此處)。

    不要同時使用 device_mapdevice,因為它們會衝突。

  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16, torch.bfloat16, … 或 "auto")。
  • trust_remote_code (bool, 可選, 預設為 False) — 是否允許在模型中心上定義的自定義程式碼在其自己的建模、配置、分詞甚至管道檔案中。此選項僅應為您信任且已閱讀其程式碼的倉庫設定為 True,因為它將在您的本地計算機上執行模型中心上的程式碼。
  • model_kwargs (dict[str, Any], 可選) — 傳遞給模型的 from_pretrained(..., **model_kwargs) 函式的額外關鍵字引數字典。
  • kwargs (dict[str, Any], 可選) — 傳遞給特定管道初始化的額外關鍵字引數(有關可能的值,請參閱相應管道類的文件)。

返回

流水線

適合該任務的管道。

用於構建 Pipeline 的實用工廠方法。

一個管道由以下部分組成:

儘管有諸如 `tokenizer`、`feature_extractor`、`image_processor` 和 `processor` 等可選引數,但不應一次性指定所有這些引數。如果未提供這些元件,`pipeline` 將嘗試自動載入所需的元件。如果您想顯式提供這些元件,請參考特定管道以獲取有關需要哪些元件的更多詳細資訊。

示例

>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer

>>> # Sentiment analysis pipeline
>>> analyzer = pipeline("sentiment-analysis")

>>> # Question answering pipeline, specifying the checkpoint identifier
>>> oracle = pipeline(
...     "question-answering", model="distilbert/distilbert-base-cased-distilled-squad", tokenizer="google-bert/bert-base-cased"
... )

>>> # Named entity recognition pipeline, passing in a specific model and tokenizer
>>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
>>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)

管道批處理

所有管道都可以使用批處理。這在管道使用其流式處理能力時(即傳遞列表、`Dataset` 或 `generator` 時)會起作用。

from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
import datasets

dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised")
pipe = pipeline("text-classification", device=0)
for out in pipe(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"):
    print(out)
    # [{'label': 'POSITIVE', 'score': 0.9998743534088135}]
    # Exactly the same output as before, but the content are passed
    # as batches to the model

然而,這並不一定能提升效能。根據硬體、資料和所使用的實際模型,它可能會帶來 10 倍的加速,也可能導致 5 倍的減速。

在大多數情況下能提速的例子

from transformers import pipeline
from torch.utils.data import Dataset
from tqdm.auto import tqdm

pipe = pipeline("text-classification", device=0)


class MyDataset(Dataset):
    def __len__(self):
        return 5000

    def __getitem__(self, i):
        return "This is a test"


dataset = MyDataset()

for batch_size in [1, 8, 64, 256]:
    print("-" * 30)
    print(f"Streaming batch_size={batch_size}")
    for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)):
        pass
# On GTX 970
------------------------------
Streaming no batching
100%|██████████████████████████████████████████████████████████████████████| 5000/5000 [00:26<00:00, 187.52it/s]
------------------------------
Streaming batch_size=8
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:04<00:00, 1205.95it/s]
------------------------------
Streaming batch_size=64
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:02<00:00, 2478.24it/s]
------------------------------
Streaming batch_size=256
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:01<00:00, 2554.43it/s]
(diminishing returns, saturated the GPU)

在大多數情況下會減速的例子

class MyDataset(Dataset):
    def __len__(self):
        return 5000

    def __getitem__(self, i):
        if i % 64 == 0:
            n = 100
        else:
            n = 1
        return "This is a test" * n

這是一個偶爾出現的與其他句子相比非常長的句子。在這種情況下,**整個**批次都需要是 400 個詞元長,所以整個批次的大小將是 [64, 400] 而不是 [64, 4],從而導致了嚴重的減速。更糟糕的是,在更大的批次上,程式會直接崩潰。

------------------------------
Streaming no batching
100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:05<00:00, 183.69it/s]
------------------------------
Streaming batch_size=8
100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:03<00:00, 265.74it/s]
------------------------------
Streaming batch_size=64
100%|██████████████████████████████████████████████████████████████████████| 1000/1000 [00:26<00:00, 37.80it/s]
------------------------------
Streaming batch_size=256
  0%|                                                                                 | 0/1000 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "/home/nicolas/src/transformers/test.py", line 42, in <module>
    for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)):
....
    q = q / math.sqrt(dim_per_head)  # (bs, n_heads, q_length, dim_per_head)
RuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch)

對於這個問題,沒有好的(通用的)解決方案,具體效果可能因您的使用情況而異。經驗法則如下:

對於使用者來說,一個經驗法則是:

  • 在你的負載和硬體上測量效能。測量,測量,再測量。真實資料是唯一的標準。

  • 如果你受延遲限制(即時產品進行推理),不要進行批處理。

  • 如果你使用 CPU,不要進行批處理。

  • 如果你關注吞吐量(你想在一堆靜態資料上執行你的模型),在 GPU 上,那麼:

    • 如果你對序列長度的大小沒有概念(“自然”資料),預設不要批處理,測量並嘗試性地新增它,並新增 OOM 檢查以便在失敗時恢復(如果你不控制序列長度,它遲早會失敗)。
    • 如果你的序列長度非常規整,那麼批處理很可能非常有效,測量並增加批處理大小直到出現 OOMs。
    • GPU 越大,批處理越有可能帶來更好的效果。
  • 一旦你啟用了批處理,請確保你能很好地處理 OOMs。

管道分塊批處理

zero-shot-classificationquestion-answering 有些特殊,因為單個輸入可能會導致模型的多次前向傳播。在正常情況下,這會與 batch_size 引數產生問題。

為了規避這個問題,這兩個管道都有點特殊,它們是 `ChunkPipeline` 而不是常規的 `Pipeline`。簡而言之:

preprocessed = pipe.preprocess(inputs)
model_outputs = pipe.forward(preprocessed)
outputs = pipe.postprocess(model_outputs)

現在變成

all_model_outputs = []
for preprocessed in pipe.preprocess(inputs):
    model_outputs = pipe.forward(preprocessed)
    all_model_outputs.append(model_outputs)
outputs = pipe.postprocess(all_model_outputs)

這對你的程式碼來說應該是透明的,因為管道的使用方式是相同的。

這是一個簡化的檢視,因為管道可以自動處理批處理!這意味著你不需要關心你的輸入實際上會觸發多少次前向傳播,你可以獨立於輸入來最佳化 `batch_size`。上一節的注意事項仍然適用。

管道 FP16 推理

模型可以在 FP16 模式下執行,這在 GPU 上可以顯著加快速度並節省記憶體。大多數模型不會因此遭受明顯的效能損失。模型越大,效能損失的可能性就越小。

要啟用 FP16 推理,您只需向管道建構函式傳遞 `torch_dtype=torch.float16` 或 `torch_dtype='float16'`。請注意,這僅適用於具有 PyTorch 後端的模型。您的輸入將在內部轉換為 FP16。

管道自定義程式碼

如果你想覆蓋一個特定的管道。

請隨時為你的任務建立一個 issue,管道的目標是易於使用並支援大多數情況,因此 `transformers` 也許可以支援你的用例。

如果你想簡單嘗試,可以:

  • 子類化您選擇的管道
class MyPipeline(TextClassificationPipeline):
    def postprocess():
        # Your code goes here
        scores = scores * 100
        # And here


my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...)
# or if you use *pipeline* function, then:
my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline)

這應該能讓你實現所有你想要的自定義程式碼。

實現一個管道

實現一個新的管道

音訊

可用於音訊任務的管道包括以下內容。

AudioClassificationPipeline

class transformers.AudioClassificationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 管道用於進行預測的模型。這需要是一個繼承自 PyTorch 的 PreTrainedModel 或 TensorFlow 的 TFPreTrainedModel 的模型。
  • feature_extractor (SequenceFeatureExtractor) — 管道用於為模型編碼資料的特徵提取器。該物件繼承自 SequenceFeatureExtractor
  • modelcard (strModelCard, 可選) — 歸屬於此管道模型的模型卡片。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,或者在未提供模型時預設為 PyTorch。

  • task (str, 預設為 "") — 管道的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當管道使用 DataLoader 時(傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的工作程序數。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應為序列化格式(即 pickle)或原始輸出資料(例如文字)的標誌。

使用任何 AutoModelForAudioClassification 的音訊分類流水線。此流水線可預測原始波形或音訊檔案的類別。對於音訊檔案,應安裝 ffmpeg 以支援多種音訊格式。

示例

>>> from transformers import pipeline

>>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks")
>>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
[{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此流水線目前可以使用以下任務識別符號從 pipeline() 載入:"audio-classification"

請參閱 huggingface.co/models 上的可用模型列表。

__call__

< >

( inputs: typing.Union[numpy.ndarray, bytes, str, dict] **kwargs: typing.Any ) 包含以下鍵的 `dict` 列表

引數

  • inputs (np.ndarraybytesstrdict) — 輸入可以是:
    • str:音訊檔案的檔名,將使用 ffmpeg 以正確的取樣率讀取檔案以獲取波形。這需要在系統上安裝 ffmpeg
    • bytes:被視作音訊檔案的內容,並由 ffmpeg 以相同的方式解釋。
    • (np.ndarray,形狀為 (n, ),型別為 np.float32np.float64):以正確取樣率提供的原始音訊(不會進行進一步檢查)。
    • dict 形式:可用於傳遞以任意 sampling_rate 取樣的原始音訊,並讓此流水線進行重取樣。字典格式必須為 {"sampling_rate": int, "raw": np.array}{"sampling_rate": int, "array": np.array},其中鍵 "raw""array" 用於表示原始音訊波形。
  • top_k (int, 可選, 預設為 None) — 流水線將返回的排名最高的標籤數量。如果提供的數字為 None 或高於模型配置中可用的標籤數量,它將預設為標籤的總數。
  • function_to_apply(str, 可選, 預設為 "softmax") — 應用於模型輸出的函式。預設情況下,流水線將對模型輸出應用 softmax 函式。有效選項:["softmax", "sigmoid", "none"]。請注意,傳遞 Python 內建的 None 將預設為 "softmax",因此您需要傳遞字串 "none" 來停用任何後處理。

返回

包含以下鍵的 `dict` 列表

  • label (str) — 預測的標籤。
  • score (float) — 對應的機率。

對作為輸入給定的序列進行分類。有關更多資訊,請參閱 AutomaticSpeechRecognitionPipeline 文件。

AutomaticSpeechRecognitionPipeline

class transformers.AutomaticSpeechRecognitionPipeline

< >

( model: PreTrainedModel feature_extractor: typing.Union[ForwardRef('SequenceFeatureExtractor'), str] = None tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None decoder: typing.Union[ForwardRef('BeamSearchDecoderCTC'), str, NoneType] = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線將用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,則是繼承自 TFPreTrainedModel 的模型。
  • feature_extractor (SequenceFeatureExtractor) — 流水線將用於為模型編碼波形的特徵提取器。
  • tokenizer (PreTrainedTokenizer) — 流水線將用於為模型編碼資料的分詞器。此物件繼承自 PreTrainedTokenizer
  • decoder (pyctcdecode.BeamSearchDecoderCTC, 可選) — PyCTCDecode 的 BeamSearchDecoderCTC 可用於語言模型增強的解碼。更多資訊請參閱 Wav2Vec2ProcessorWithLM
  • chunk_length_s (float, 可選, 預設為 0) — 每個塊的輸入長度。如果 chunk_length_s = 0,則停用分塊(預設)。

    有關如何有效使用 chunk_length_s 的更多資訊,請參閱 ASR 分塊部落格文章

  • stride_length_s (float, 可選, 預設為 chunk_length_s / 6) — 每個塊左右兩側的步幅長度。僅在 chunk_length_s > 0 時使用。這使模型能夠看到更多上下文並更好地推斷字母,但流水線會在末尾丟棄步幅部分,以使最終重構儘可能完美。

    有關如何有效使用 stride_length_s 的更多資訊,請參閱 ASR 分塊部落格文章

  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。必須安裝指定的框架。如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,如果未提供模型,則預設為 PyTorch。
  • device (Union[int, torch.device], 可選) — 用於 CPU/GPU 支援的裝置序號。將其設定為 None 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。
  • torch_dtype (Union[int, torch.dtype], 可選) — 計算的資料型別 (dtype)。將其設定為 None 將使用 float32 精度。設定為 torch.float16torch.bfloat16 以在相應的 dtype 中使用半精度。

旨在從音訊中提取口語文字的流水線。

輸入可以是原始波形或音訊檔案。對於音訊檔案,應安裝 ffmpeg 以支援多種音訊格式。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256
  • num_beams: 5

示例

>>> from transformers import pipeline

>>> transcriber = pipeline(model="openai/whisper-base")
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
{'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

__call__

< >

( inputs: typing.Union[numpy.ndarray, bytes, str, dict] **kwargs: typing.Any ) `Dict`

引數

  • inputs (np.ndarraybytesstrdict) — 輸入可以是:

    • str:可以是本地音訊檔案的檔名,也可以是下載音訊檔案的公共 URL 地址。將使用 ffmpeg 以正確的取樣率讀取檔案以獲取波形。這需要在系統上安裝 ffmpeg
    • bytes:被視作音訊檔案的內容,並由 ffmpeg 以相同的方式解釋。
    • (np.ndarray,形狀為 (n, ),型別為 np.float32np.float64):以正確取樣率提供的原始音訊(不會進行進一步檢查)。
    • dict 形式:可用於傳遞以任意 sampling_rate 取樣的原始音訊,並讓此流水線進行重取樣。字典格式必須為 {"sampling_rate": int, "raw": np.array},還可以可選地包含 "stride": (left: int, right: int),這可以要求流水線在解碼時忽略前 left 個樣本和後 right 個樣本(但在推理時會使用它們為模型提供更多上下文)。僅在 CTC 模型中使用 stride
  • return_timestamps (可選, strbool) — 僅適用於純 CTC 模型(Wav2Vec2、HuBERT 等)和 Whisper 模型。不適用於其他序列到序列模型。

    對於 CTC 模型,時間戳可以採用以下兩種格式之一:

    • "char":流水線將為文字中的每個字元返回帶時間戳的文字。例如,如果您得到 [{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7, 0.9)}],則表示模型預測字母“h”是在 0.5 秒之後和 0.6 秒之前說出的。
    • "word":流水線將為文字中的每個單詞返回帶時間戳的文字。例如,如果您得到 [{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}],則表示模型預測單詞“hi”是在 0.5 秒之後和 0.9 秒之前說出的。

    對於 Whisper 模型,時間戳可以採用以下兩種格式之一:

    • "word":與上述詞級 CTC 時間戳相同。詞級時間戳是透過動態時間規整(DTW)演算法預測的,這是一種透過檢查交叉注意力權重來近似詞級時間戳的方法。
    • True:流水線將為文字中的詞返回帶時間戳的文字。例如,如果您得到 [{"text": " Hi there!", "timestamp": (0.5, 1.5)}],則表示模型預測“Hi there!”這個片段是在 0.5 秒之後和 1.5 秒之前說出的。請注意,文字片段指的是一個或多個單詞的序列,而不是像詞級時間戳那樣的單個單詞。
  • generate_kwargs (dict, 可選) — 用於生成呼叫的 generate_config 的臨時引數化字典。有關 `generate` 的完整概述,請檢視以下指南

返回

字典

一個包含以下鍵的字典:

  • text (str): 識別出的文字。
  • chunks (可選,list[Dict]) 當使用 `return_timestamps` 時,`chunks` 將成為一個包含模型識別出的所有不同文字塊的列表,例如 `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]`。可以透過執行 `"".join(chunk["text"] for chunk in output["chunks"])` 來大致恢復原始全文。

將作為輸入給出的音訊序列轉錄為文字。有關更多資訊,請參閱 AutomaticSpeechRecognitionPipeline 文件。

TextToAudioPipeline

class transformers.TextToAudioPipeline

< >

( *args vocoder = None sampling_rate = None no_processor = True **kwargs )

使用任何 AutoModelForTextToWaveformAutoModelForTextToSpectrogram 的文字到音訊生成流水線。此流水線根據輸入文字和可選的其他條件輸入生成音訊檔案。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256

示例

>>> from transformers import pipeline

>>> pipe = pipeline(model="suno/bark-small")
>>> output = pipe("Hey it's HuggingFace on the phone!")

>>> audio = output["audio"]
>>> sampling_rate = output["sampling_rate"]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

您可以使用 TextToAudioPipeline.__call__.forward_paramsTextToAudioPipeline.__call__.generate_kwargs 指定傳遞給模型的引數。

示例

>>> from transformers import pipeline

>>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt")

>>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length
>>> generate_kwargs = {
...     "do_sample": True,
...     "temperature": 0.7,
...     "max_new_tokens": 35,
... }

>>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs)

此流水線目前可以使用以下任務識別符號從 pipeline() 載入:"text-to-speech""text-to-audio"

請參閱 huggingface.co/models 上的可用模型列表。

__call__

< >

( text_inputs: typing.Union[str, list[str]] **forward_params ) `dict` 或 `dict` 列表

引數

  • text_inputs (strlist[str]) — 要生成的文字。
  • forward_params (dict, 可選) — 傳遞給模型生成/前向方法的引數。forward_params 總是傳遞給底層模型。
  • generate_kwargs (dict, 可選) — 用於生成呼叫的 generate_config 的臨時引數化字典。有關 `generate` 的完整概述,請檢視以下指南。僅當底層模型是生成模型時,`generate_kwargs` 才傳遞給它。

返回

一個 `dict` 或一個 `dict` 列表

字典有兩個鍵:

  • audio (np.ndarray,形狀為 (nb_channels, audio_length)) — 生成的音訊波形。
  • sampling_rate (int) — 生成的音訊波形的取樣率。

根據輸入生成語音/音訊。有關更多資訊,請參閱 TextToAudioPipeline 文件。

ZeroShotAudioClassificationPipeline

class transformers.ZeroShotAudioClassificationPipeline

< >

( **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線將用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,則是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 流水線將用於為模型編碼資料的分詞器。此物件繼承自 PreTrainedTokenizer
  • feature_extractor (SequenceFeatureExtractor) — 流水線將用於為模型編碼資料的特徵提取器。此物件繼承自 SequenceFeatureExtractor
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。必須安裝指定的框架。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應為序列化格式(即 pickle)或原始輸出資料(例如文字)的標誌。

使用 ClapModel 的零樣本音訊分類流水線。當您提供一個音訊和一組 candidate_labels 時,此流水線可預測該音訊的類別。

預設的 hypothesis_template 是:"This is a sound of {}."。請確保根據您的用途更新它。

示例

>>> from transformers import pipeline
>>> from datasets import load_dataset

>>> dataset = load_dataset("ashraq/esc50")
>>> audio = next(iter(dataset["train"]["audio"]))["array"]
>>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused")
>>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"])
[{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vaccum cleaner'}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。此音訊分類流水線目前可以使用以下任務識別符號從 pipeline() 載入:"zero-shot-audio-classification"。請參閱 huggingface.co/models 上的可用模型列表。

__call__

< >

( audios: typing.Union[numpy.ndarray, bytes, str, dict] **kwargs: typing.Any )

引數

  • audios (str, list[str], np.arraylist[np.array]) — 流水線處理三種類型的輸入:
    • 包含指向音訊的 http 連結的字串
    • 包含音訊本地路徑的字串
    • 載入到 numpy 中的音訊
  • candidate_labels (list[str]) — 此音訊的候選標籤。它們將使用 hypothesis_template 進行格式化。
  • hypothesis_template (str, 可選, 預設為 "This is a sound of {}") — 與 candidate_labels 結合使用的格式,透過將佔位符替換為 candidate_labels 來嘗試進行音訊分類。如果 candidate_labels 已經格式化,則傳遞 ”{}”。

為作為輸入傳遞的音訊分配標籤。

計算機視覺

可用於計算機視覺任務的流水線包括以下內容。

DepthEstimationPipeline

class transformers.DepthEstimationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將由流水線用於進行預測的模型。對於PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於TensorFlow,則需要是繼承自 TFPreTrainedModel 的模型。
  • image_processor (BaseImageProcessor) — 將由流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (str or ModelCard, 可選) — 歸屬於此流水線模型的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,或者在未提供模型時預設使用PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader (當傳遞資料集,在GPU上使用Pytorch模型時),要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader (當傳遞資料集,在GPU上使用Pytorch模型時) 時,要使用的批次大小,對於推理而言,這並不總是有益的,請閱讀 使用流水線進行批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 用於CPU/GPU支援的裝置序號。將其設定為-1將使用CPU,正數將在相應的CUDA裝置ID上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(即 pickle)或作為原始輸出資料(例如文字)進行的標誌。

使用任何 AutoModelForDepthEstimation 的深度估計流水線。此流水線預測影像的深度。

示例

>>> from transformers import pipeline

>>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf")
>>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg")
>>> # This is a tensor with the values being the depth expressed in meters for each pixel
>>> output["predicted_depth"].shape
torch.Size([1, 384, 384])

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

目前可以使用以下任務識別符號從 pipeline() 載入此深度估計流水線:"depth-estimation"

請在 huggingface.co/models 上檢視可用模型的列表。

__call__

< >

( inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs: typing.Any )

引數

  • inputs (str, list[str], PIL.Image or list[PIL.Image]) — 流水線處理三種類型的影像:

    • 包含指向影像的 http 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入在 PIL 中的影像

    流水線接受單個影像或一批影像,批處理時必須以字串形式傳遞。批處理中的影像必須都是相同格式:全部為 http 連結,全部為本地路徑,或全部為 PIL 影像。

  • parameters (Dict, 可選) — 引數名稱到引數值的字典,用於控制流水線行為。目前唯一可用的引數是 timeout,即流水線在放棄嘗試下載影像之前應等待的時間長度(以秒為單位)。
  • timeout (float, 可選, 預設為 None) — 從網頁獲取影像時等待的最大時間(以秒為單位)。如果為 None,則不設定超時,呼叫可能會永遠阻塞。

預測作為輸入傳遞的影像的深度。

ImageClassificationPipeline

class transformers.ImageClassificationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將由流水線用於進行預測的模型。對於PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於TensorFlow,則需要是繼承自 TFPreTrainedModel 的模型。
  • image_processor (BaseImageProcessor) — 將由流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (str or ModelCard, 可選) — 歸屬於此流水線模型的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,或者在未提供模型時預設使用PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader (當傳遞資料集,在GPU上使用Pytorch模型時),要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader (當傳遞資料集,在GPU上使用Pytorch模型時) 時,要使用的批次大小,對於推理而言,這並不總是有益的,請閱讀 使用流水線進行批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 用於CPU/GPU支援的裝置序號。將其設定為-1將使用CPU,正數將在相應的CUDA裝置ID上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(即 pickle)或作為原始輸出資料(例如文字)進行的標誌。
  • function_to_apply (str, 可選, 預設為 "default") — 應用於模型輸出以檢索分數的函式。接受四個不同的值:

    • "default": 如果模型只有一個標籤,將對輸出應用 sigmoid 函式。如果模型有多個標籤,將對輸出應用 softmax 函式。
    • "sigmoid": 對輸出應用 sigmoid 函式。
    • "softmax": 對輸出應用 softmax 函式。
    • "none": 不對輸出應用任何函式。

使用任何 AutoModelForImageClassification 的影像分類流水線。此流水線預測影像的類別。

示例

>>> from transformers import pipeline

>>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k")
>>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

目前可以使用以下任務識別符號從 pipeline() 載入此影像分類流水線:"image-classification"

請在 huggingface.co/models 上檢視可用模型的列表。

__call__

< >

( inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs: typing.Any )

引數

  • inputs (str, list[str], PIL.Image or list[PIL.Image]) — 流水線處理三種類型的影像:

    • 包含指向影像的 http 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入在 PIL 中的影像

    流水線接受單個影像或一批影像,批處理時必須以字串形式傳遞。批處理中的影像必須都是相同格式:全部為 http 連結,全部為本地路徑,或全部為 PIL 影像。

  • function_to_apply (str, 可選, 預設為 "default") — 應用於模型輸出以檢索分數的函式。接受四個不同的值:

    如果未指定此引數,則將根據標籤數量應用以下函式:

    • 如果模型只有一個標籤,將對輸出應用 sigmoid 函式。
    • 如果模型有多個標籤,將對輸出應用 softmax 函式。

    可能的值為:

    • "sigmoid": 對輸出應用 sigmoid 函式。
    • "softmax": 對輸出應用 softmax 函式。
    • "none": 不對輸出應用任何函式。
  • top_k (int, 可選, 預設為 5) — 流水線將返回的排名靠前的標籤數量。如果提供的數量高於模型配置中可用的標籤數量,則將預設為標籤的數量。
  • timeout (float, 可選, 預設為 None) — 從網頁獲取影像時等待的最大時間(以秒為單位)。如果為 None,則不設定超時,呼叫可能會永遠阻塞。

為作為輸入傳遞的影像分配標籤。

ImageSegmentationPipeline

class transformers.ImageSegmentationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將由流水線用於進行預測的模型。對於PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於TensorFlow,則需要是繼承自 TFPreTrainedModel 的模型。
  • image_processor (BaseImageProcessor) — 將由流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (str or ModelCard, 可選) — 歸屬於此流水線模型的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,或者在未提供模型時預設使用PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader (當傳遞資料集,在GPU上使用Pytorch模型時),要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader (當傳遞資料集,在GPU上使用Pytorch模型時) 時,要使用的批次大小,對於推理而言,這並不總是有益的,請閱讀 使用流水線進行批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 用於CPU/GPU支援的裝置序號。將其設定為-1將使用CPU,正數將在相應的CUDA裝置ID上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(即 pickle)或作為原始輸出資料(例如文字)進行的標誌。

使用任何 AutoModelForXXXSegmentation 的影像分割流水線。此流水線預測物件的掩碼及其類別。

示例

>>> from transformers import pipeline

>>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic")
>>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
>>> len(segments)
2

>>> segments[0]["label"]
'bird'

>>> segments[1]["label"]
'bird'

>>> type(segments[0]["mask"])  # This is a black and white mask showing where is the bird on the original image.
<class 'PIL.Image.Image'>

>>> segments[0]["mask"].size
(768, 512)

目前可以使用以下任務識別符號從 pipeline() 載入此影像分割流水線:"image-segmentation"

請在 huggingface.co/models 上檢視可用模型的列表。

__call__

< >

( inputs: typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']] **kwargs: typing.Any )

引數

  • inputs (str, list[str], PIL.Image or list[PIL.Image]) — 流水線處理三種類型的影像:

    • 包含指向影像的 HTTP(S) 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入在 PIL 中的影像

    流水線接受單個影像或一批影像。批處理中的影像必須都是相同格式:全部為 HTTP(S) 連結,全部為本地路徑,或全部為 PIL 影像。

  • subtask (str, 可選) — 要執行的分割任務,根據模型能力選擇 [semantic, instance, panoptic]。如果未設定,流水線將嘗試按以下順序解析:panoptic, instance, semantic
  • threshold (float, 可選, 預設為 0.9) — 用於過濾預測掩碼的機率閾值。
  • mask_threshold (float, 可選, 預設為 0.5) — 將預測掩碼轉換為二進位制值時使用的閾值。
  • overlap_mask_area_threshold (float, 可選, 預設為 0.5) — 掩碼重疊閾值,用於消除小的、不連貫的片段。
  • timeout (float, 可選, 預設為 None) — 從網頁獲取影像時等待的最大時間(以秒為單位)。如果為 None,則不設定超時,呼叫可能會永遠阻塞。

在作為輸入傳遞的影像中執行分割(檢測掩碼和類別)。

ImageToImagePipeline

class transformers.ImageToImagePipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線用於進行預測的模型。對於 PyTorch,該模型需要繼承自 PreTrainedModel;對於 TensorFlow,則需要繼承自 TFPreTrainedModel
  • image_processor (BaseImageProcessor) — 流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前已安裝的框架。如果未指定框架但兩個框架都已安裝,將預設使用 `model` 的框架,或者在未提供模型時預設使用 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀 流水線批處理
  • args_parser (ArgumentHandler, 可選) — 負責解析提供的流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 `torch.device` 或 `str`。
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 `model_kwargs` 傳送(僅為簡便的快捷方式),以使用此模型可用的精度(`torch.float16`、`torch.bfloat16`... 或 `"auto"`)。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(例如 pickle)或原始輸出資料(例如文字)形式出現的標誌。

使用任何 `AutoModelForImageToImage` 的影像到影像流水線。此流水線基於先前的影像輸入生成新影像。

示例

>>> from PIL import Image
>>> import requests

>>> from transformers import pipeline

>>> upscaler = pipeline("image-to-image", model="caidas/swin2SR-classical-sr-x2-64")
>>> img = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
>>> img = img.resize((64, 64))
>>> upscaled_img = upscaler(img)
>>> img.size
(64, 64)

>>> upscaled_img.size
(144, 144)

目前,可以使用以下任務識別符號從 pipeline() 載入此影像到影像流水線:`"image-to-image"`。

請在 huggingface.co/models 檢視可用模型列表。

__call__

< >

( images: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs: typing.Any )

引數

  • images (str, list[str], PIL.Imagelist[PIL.Image]) — 流水線處理三種類型的影像:

    • 包含指向影像的 http 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入的 PIL 影像

    流水線接受單個影像或一批影像,後者必須作為字串傳遞。批次中的影像必須全部採用相同格式:全部為 http 連結、全部為本地路徑或全部為 PIL 影像。

  • timeout (float, 可選, 預設為 None) — 從網路獲取影像的最大等待時間(秒)。如果為 None,則不使用超時,呼叫可能會永久阻塞。

轉換作為輸入傳遞的影像。

ObjectDetectionPipeline

class transformers.ObjectDetectionPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線用於進行預測的模型。對於 PyTorch,該模型需要繼承自 PreTrainedModel;對於 TensorFlow,則需要繼承自 TFPreTrainedModel
  • image_processor (BaseImageProcessor) — 流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前已安裝的框架。如果未指定框架但兩個框架都已安裝,將預設使用 `model` 的框架,或者在未提供模型時預設使用 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀 流水線批處理
  • args_parser (ArgumentHandler, 可選) — 負責解析提供的流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 `torch.device` 或 `str`。
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 `model_kwargs` 傳送(僅為簡便的快捷方式),以使用此模型可用的精度(`torch.float16`、`torch.bfloat16`... 或 `"auto"`)。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(例如 pickle)或原始輸出資料(例如文字)形式出現的標誌。

使用任何 `AutoModelForObjectDetection` 的目標檢測流水線。此流水線預測物件的邊界框及其類別。

示例

>>> from transformers import pipeline

>>> detector = pipeline(model="facebook/detr-resnet-50")
>>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]

>>> # x, y  are expressed relative to the top left hand corner.

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

目前,可以使用以下任務識別符號從 pipeline() 載入此目標檢測流水線:`"object-detection"`。

請在 huggingface.co/models 檢視可用模型列表。

__call__

< >

( *args **kwargs )

引數

  • inputs (str, list[str], PIL.Imagelist[PIL.Image]) — 流水線處理三種類型的影像:

    • 包含指向影像的 HTTP(S) 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入的 PIL 影像

    流水線接受單個影像或一批影像。批次中的影像必須全部採用相同格式:全部為 HTTP(S) 連結、全部為本地路徑或全部為 PIL 影像。

  • threshold (float, 可選, 預設為 0.5) — 進行預測所需的機率閾值。
  • timeout (float, 可選, 預設為 None) — 從網路獲取影像的最大等待時間(秒)。如果為 None,則不設定超時,呼叫可能會永久阻塞。

檢測作為輸入傳遞的影像中的物件(邊界框和類別)。

VideoClassificationPipeline

class transformers.VideoClassificationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線用於進行預測的模型。對於 PyTorch,該模型需要繼承自 PreTrainedModel;對於 TensorFlow,則需要繼承自 TFPreTrainedModel
  • image_processor (BaseImageProcessor) — 流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前已安裝的框架。如果未指定框架但兩個框架都已安裝,將預設使用 `model` 的框架,或者在未提供模型時預設使用 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀 流水線批處理
  • args_parser (ArgumentHandler, 可選) — 負責解析提供的流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 `torch.device` 或 `str`。
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 `model_kwargs` 傳送(僅為簡便的快捷方式),以使用此模型可用的精度(`torch.float16`、`torch.bfloat16`... 或 `"auto"`)。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(例如 pickle)或原始輸出資料(例如文字)形式出現的標誌。

使用任何 `AutoModelForVideoClassification` 的影片分類流水線。此流水線預測影片的類別。

目前,可以使用以下任務識別符號從 pipeline() 載入此影片分類流水線:`"video-classification"`。

請在 huggingface.co/models 檢視可用模型列表。

__call__

< >

( inputs: typing.Union[str, list[str], NoneType] = None **kwargs )

引數

  • inputs (str, list[str]) — 流水線處理三種類型的影片:

    • 包含指向影片的 http 連結的字串
    • 包含本地影片路徑的字串

    流水線接受單個影片或一批影片,後者必須作為字串傳遞。批次中的影片必須全部採用相同格式:全部為 http 連結或全部為本地路徑。

  • top_k (int, 可選, 預設為 5) — 流水線將返回的最高標籤數量。如果提供的數量高於模型配置中可用的標籤數量,則將預設為標籤數量。
  • num_frames (int, 可選, 預設為 self.model.config.num_frames) — 從影片中取樣用於分類的幀數。如果未提供,則將預設為模型配置中指定的幀數。
  • frame_sampling_rate (int, 可選, 預設為 1) — 用於從影片中選擇幀的取樣率。如果未提供,則預設為 1,即使用每一幀。
  • function_to_apply(str, 可選, 預設為 “softmax”) — 應用於模型輸出的函式。預設情況下,流水線將對模型輸出應用 softmax 函式。有效選項:[“softmax”, “sigmoid”, “none”]。注意,傳遞 Python 內建的 `None` 將預設為 “softmax”,因此需要傳遞字串 “none” 來停用任何後處理。

為作為輸入傳遞的影片分配標籤。

ZeroShotImageClassificationPipeline

class transformers.ZeroShotImageClassificationPipeline

< >

( **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線用於進行預測的模型。對於 PyTorch,該模型需要繼承自 PreTrainedModel;對於 TensorFlow,則需要繼承自 TFPreTrainedModel
  • image_processor (BaseImageProcessor) — 流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型使用的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 PyTorch 的 "pt" 或 TensorFlow 的 "tf"。指定的框架必須已安裝。

    如果未指定框架,則預設為當前已安裝的框架。如果未指定框架且兩個框架都已安裝,則預設為 model 所使用的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(這只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16, ... 或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(例如 pickle)或作為原始輸出資料(例如文字)進行的標誌。

使用 CLIPModel 的零樣本影像分類流水線。當您提供一張影像和一組 candidate_labels 時,此流水線可以預測影像的類別。

示例

>>> from transformers import pipeline

>>> classifier = pipeline(model="google/siglip-so400m-patch14-384")
>>> classifier(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
...     candidate_labels=["animals", "humans", "landscape"],
... )
[{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]

>>> classifier(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
...     candidate_labels=["black and white", "photorealist", "painting"],
... )
[{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此影像分類流水線目前可以使用以下任務識別符號從 pipeline() 載入:"zero-shot-image-classification"

請在 huggingface.co/models 上檢視可用模型列表。

__call__

< >

( image: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] candidate_labels: list **kwargs: typing.Any )

引數

  • image (str, list[str], PIL.Imagelist[PIL.Image]) — 流水線處理三種類型的影像:

    • 指向影像的 http 連結字串
    • 指向影像的本地路徑字串
    • 直接載入的 PIL 影像
  • candidate_labels (list[str]) — 此影像的候選標籤。它們將使用 hypothesis_template 進行格式化。
  • hypothesis_template (str, 可選, 預設為 "This is a photo of {}") — 與 candidate_labels 一起使用的格式,透過用 candidate_labels 替換佔位符來嘗試進行影像分類。如果 candidate_labels 已經格式化,請傳遞 ”{}”。
  • timeout (float, 可選, 預設為 None) — 從網路獲取影像的最大等待時間(秒)。如果為 None,則不設定超時,呼叫可能會永遠阻塞。

為作為輸入傳遞的影像分配標籤。

ZeroShotObjectDetectionPipeline

class transformers.ZeroShotObjectDetectionPipeline

< >

( **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線將用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • image_processor (BaseImageProcessor) — 流水線將用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型使用的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 PyTorch 的 "pt" 或 TensorFlow 的 "tf"。指定的框架必須已安裝。

    如果未指定框架,則預設為當前已安裝的框架。如果未指定框架且兩個框架都已安裝,則預設為 model 所使用的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(這只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16, ... 或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(例如 pickle)或作為原始輸出資料(例如文字)進行的標誌。

使用 OwlViTForObjectDetection 的零樣本目標檢測流水線。當您提供一張影像和一組 candidate_labels 時,此流水線可以預測物體的邊界框。

示例

>>> from transformers import pipeline

>>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
>>> detector(
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
...     candidate_labels=["cat", "couch"],
... )
[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]

>>> detector(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
...     candidate_labels=["head", "bird"],
... )
[{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此目標檢測流水線目前可以使用以下任務識別符號從 pipeline() 載入:"zero-shot-object-detection"

請在 huggingface.co/models 上檢視可用模型列表。

__call__

< >

( image: typing.Union[str, ForwardRef('Image.Image'), list[dict[str, typing.Any]]] candidate_labels: typing.Union[str, list[str], NoneType] = None **kwargs: typing.Any )

引數

  • image (str, PIL.Imagelist[dict[str, Any]]) — 流水線處理三種類型的影像:

    • 包含指向影像的 http url 的字串
    • 包含指向影像的本地路徑的字串
    • 直接載入的 PIL 影像

    您可以使用此引數直接傳送影像列表、資料集或生成器,如下所示:

檢測作為輸入傳遞的影像中的物件(邊界框和類別)。

自然語言處理

可用於自然語言處理任務的流水線包括以下幾種。

FillMaskPipeline

class transformers.FillMaskPipeline

< >

( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線將用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 流水線將用於為模型編碼資料的分詞器。此物件繼承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型使用的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 PyTorch 的 "pt" 或 TensorFlow 的 "tf"。指定的框架必須已安裝。

    如果未指定框架,則預設為當前已安裝的框架。如果未指定框架且兩個框架都已安裝,則預設為 model 所使用的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, 可選) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(這只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16, ... 或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線輸出是否應以序列化格式(例如 pickle)或作為原始輸出資料(例如文字)進行的標誌。
  • top_k (int, 可選, 預設為 5) — 要返回的預測數量。
  • targets (strlist[str], 可選) — 當傳遞此引數時,模型將把分數限制在傳遞的目標上,而不是在整個詞彙表中查詢。如果提供的目標不在模型詞彙表中,它們將被分詞,並使用第一個生成的分詞(會有一個警告,並且可能會變慢)。
  • tokenizer_kwargs (dict, 可選) — 傳遞給分詞器的額外關鍵字引數字典。

使用任何 ModelWithLMHead 的掩碼語言建模預測流水線。有關更多資訊,請參閱掩碼語言建模示例

示例

>>> from transformers import pipeline

>>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
>>> fill_masker("This is a simple [MASK].")
[{'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.'}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此掩碼填充流水線目前可以使用以下任務識別符號從 pipeline() 載入:"fill-mask"

此流水線可以使用的模型是那些使用掩碼語言建模目標進行訓練的模型,其中包括庫中的雙向模型。請在 huggingface.co/models 上檢視最新的可用模型列表。

此流水線僅適用於只有一個標記被掩碼的輸入。實驗性功能:我們添加了對多個掩碼的支援。返回的值是原始模型輸出,對應於離散機率,而人們可能期望的是聯合機率(參見討論)。

此流水線現在支援 tokenizer_kwargs。例如,可以嘗試:

>>> from transformers import pipeline

>>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
>>> tokenizer_kwargs = {"truncation": True}
>>> fill_masker(
...     "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100,
...     tokenizer_kwargs=tokenizer_kwargs,
... )

__call__

< >

( inputs: typing.Union[str, list[str]] **kwargs: typing.Any ) dict 的列表或列表的列表

引數

  • inputs (strlist[str]) — 一個或多個帶有掩碼標記的文字(或一個提示列表)。
  • targets (strlist[str], 可選) — 當傳遞此引數時,模型將把分數限制在傳遞的目標上,而不是在整個詞彙表中查詢。如果提供的目標不在模型詞彙表中,它們將被分詞,並使用第一個生成的分詞(會有一個警告,並且可能會變慢)。
  • top_k (int, 可選) — 當傳遞此引數時,將覆蓋要返回的預測數量。

返回

dict 的列表或列表的列表

每個結果都以字典列表的形式出現,包含以下鍵:

  • sequence (str) — 帶有掩碼標記預測的相應輸入。
  • score (float) — 對應的機率。
  • token (int) — 預測的標記 ID(用於替換掩碼標記)。
  • token_str (str) — 預測的標記(用於替換掩碼標記)。

填充作為輸入給出的文字中的掩碼標記。

QuestionAnsweringPipeline

class transformers.QuestionAnsweringPipeline

< >

( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: PreTrainedTokenizer modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線將用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 流水線將用於為模型編碼資料的分詞器。此物件繼承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型使用的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。必須已安裝指定的框架。

    如果未指定框架,則將預設使用當前已安裝的框架。如果未指定框架但兩種框架都已安裝,則將預設使用 model 的框架,如果未提供模型,則預設使用 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, 可選) — 負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線的輸出應為序列化格式(即 pickle)還是原始輸出資料(例如文字)的標誌。

使用任何 ModelForQuestionAnswering 的問答流水線。有關更多資訊,請參閱問答示例

示例

>>> from transformers import pipeline

>>> oracle = pipeline(model="deepset/roberta-base-squad2")
>>> oracle(question="Where do I live?", context="My name is Wolfgang and I live in Berlin")
{'score': 0.9191, 'start': 34, 'end': 40, 'answer': 'Berlin'}

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

目前可以使用以下任務識別符號從 pipeline() 載入此問答流水線:"question-answering"

此流水線可以使用的模型是已經在問答任務上進行了微調的模型。請參閱 huggingface.co/models 上可用的最新模型列表。

__call__

< >

( *args **kwargs ) 一個 dictdict 列表

引數

  • question (strlist[str]) — 一個或多個問題(必須與 context 引數一起使用)。
  • context (strlist[str]) — 與問題相關的一個或多個上下文(必須與 question 引數一起使用)。
  • top_k (int, 可選, 預設為 1) — 要返回的答案數量(將按可能性順序選擇)。請注意,如果上下文中沒有足夠的可用選項,我們將返回少於 top_k 個答案。
  • doc_stride (int, 可選, 預設為 128) — 如果上下文太長,無法與模型的問題相適應,它將被分割成幾個帶有重疊的塊。此引數控制重疊的大小。
  • max_answer_len (int, 可選, 預設為 15) — 預測答案的最大長度(例如,只考慮長度較短的答案)。
  • max_seq_len (int, 可選, 預設為 384) — 傳遞給模型的每個塊的總句子(上下文 + 問題)的最大長度(以詞元為單位)。如果需要,上下文將被分割成幾個塊(使用 doc_stride 作為重疊)。
  • max_question_len (int, 可選, 預設為 64) — 標記化後問題的最大長度。如果需要,它將被截斷。
  • handle_impossible_answer (bool, 可選, 預設為 False) — 是否接受無法回答的答案。
  • align_to_words (bool, 可選, 預設為 True) — 嘗試將答案與實際單詞對齊。在以空格分隔的語言上可以提高質量。在非空格分隔的語言(如日語或中文)上可能會有負面影響。

返回

一個 `dict` 或一個 `dict` 列表

每個結果都以字典形式返回,包含以下鍵:

  • score (float) — 與答案相關的機率。
  • start (int) — 答案的字元起始索引(在輸入的標記化版本中)。
  • end (int) — 答案的字元結束索引(在輸入的標記化版本中)。
  • answer (str) — 問題的答案。

透過使用上下文來回答作為輸入給出的問題。

create_sample

< >

( question: typing.Union[str, list[str]] context: typing.Union[str, list[str]] ) 一個或一個 SquadExample 列表

引數

  • question (strlist[str]) — 提出的問題。
  • context (strlist[str]) — 我們將在其中尋找答案的上下文。

返回

一個或一個 SquadExample 列表

相應的 SquadExample,將問題和上下文分組。

QuestionAnsweringPipeline 內部利用 SquadExample。這個輔助方法封裝了將問題和上下文轉換為 SquadExample 的所有邏輯。

我們目前支援抽取式問答。

span_to_answer

< >

( text: str start: int end: int ) 類似 `{‘answer’` 的字典

引數

  • text (str) — 用於提取答案的實際上下文。
  • start (int) — 答案的起始詞元索引。
  • end (int) — 答案的結束詞元索引。

返回

類似 `{‘answer’` 的字典

str, ‘start’: int, ‘end’: int}`

當從詞元機率解碼時,此方法將詞元索引對映到初始上下文中的實際單詞。

SummarizationPipeline

class transformers.SummarizationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 流水線用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型使用的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。必須已安裝指定的框架。

    如果未指定框架,則將預設使用當前已安裝的框架。如果未指定框架但兩種框架都已安裝,則將預設使用 model 的框架,如果未提供模型,則預設使用 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, 可選, 預設為 1) — 當流水線使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並不總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, 可選) — 負責解析所提供流水線引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示流水線的輸出應為序列化格式(即 pickle)還是原始輸出資料(例如文字)的標誌。

對新聞文章和其他文件進行摘要。

目前可以使用以下任務識別符號從 pipeline() 載入此摘要流水線:"summarization"

此流水線可以使用的模型是已經在摘要任務上進行了微調的模型,目前包括:’bart-large-cnn’、’google-t5/t5-small’、’google-t5/t5-base’、’google-t5/t5-large’、’google-t5/t5-3b’、’google-t5/t5-11b’。請參閱 huggingface.co/models 上可用的最新模型列表。有關可用引數的列表,請參閱以下文件

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256
  • num_beams: 4

用法

# use bart in pytorch
summarizer = pipeline("summarization")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)

# use t5 in tf
summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)

__call__

< >

( *args **kwargs ) 一個列表或一個 dict 的列表的列表

引數

  • documents (strlist[str]) — 一篇或多篇文章(或一個文章列表)用於摘要。
  • return_text (bool, 可選, 預設為 True) — 是否在輸出中包含解碼後的文字
  • return_tensors (bool, 可選, 預設為 False) — 是否在輸出中包含預測的張量(作為詞元索引)。
  • clean_up_tokenization_spaces (bool, 可選, 預設為 False) — 是否清理文字輸出中可能存在的多餘空格。
  • generate_kwargs — 傳遞給模型 generate 方法的額外關鍵字引數(請參見與您的框架對應的 generate 方法此處)。

返回

dict 的列表或列表的列表

每個結果都以字典形式返回,包含以下鍵:

  • summary_text (str,當 return_text=True 時存在) — 相應輸入的摘要。
  • summary_token_ids (torch.Tensortf.Tensor,當 return_tensors=True 時存在) — 摘要的詞元 ID。

對作為輸入給出的文字進行摘要。

TableQuestionAnsweringPipeline

class transformers.TableQuestionAnsweringPipeline

< >

( args_parser = <transformers.pipelines.table_question_answering.TableQuestionAnsweringArgumentHandler object at 0x7eff9573bdf0> *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — 流水線用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 流水線用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可選) — 歸屬於此流水線模型使用的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。必須已安裝指定的框架。

    如果未指定框架,則將預設使用當前已安裝的框架。如果未指定框架但兩種框架都已安裝,則將預設使用 model 的框架,如果未提供模型,則預設使用 PyTorch。

  • task (str, 預設為 "") — 流水線的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當流水線使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當 pipeline 使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批處理大小。對於推理,這並非總是有益的,請閱讀使用 pipeline 進行批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供 pipeline 引數的物件的引用。
  • device (int, optional, defaults to -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16, torch.bfloat16, … 或 "auto")。
  • binary_output (bool, optional, defaults to False) — 指示 pipeline 的輸出應該是序列化格式(例如 pickle)還是原始輸出資料(例如文字)的標誌。

使用 ModelForTableQuestionAnswering 的表格問答 pipeline。此 pipeline 僅在 PyTorch 中可用。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256

示例

>>> from transformers import pipeline

>>> oracle = pipeline(model="google/tapas-base-finetuned-wtq")
>>> table = {
...     "Repository": ["Transformers", "Datasets", "Tokenizers"],
...     "Stars": ["36542", "4512", "3934"],
...     "Contributors": ["651", "77", "34"],
...     "Programming language": ["Python", "Python", "Rust, Python and NodeJS"],
... }
>>> oracle(query="How many stars does the transformers repository have?", table=table)
{'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此表格問答 pipeline 目前可以透過 pipeline() 使用以下任務識別符號載入:"table-question-answering"

此 pipeline 可以使用的模型是那些在表格問答任務上進行微調的模型。請參閱 huggingface.co/models 上可用的最新模型列表。

__call__

< >

( *args **kwargs ) 包含結果的字典或字典列表

引數

  • table (pd.DataFrame or Dict) — Pandas DataFrame 或將被轉換為包含所有表格值的 DataFrame 的字典。有關字典示例,請參見上文。
  • query (str or list[str]) — 將與表格一起傳送到模型的查詢或查詢列表。
  • sequential (bool, optional, defaults to False) — 是按順序進行推理還是批次進行。批次處理速度更快,但像 SQA 這樣的模型,由於其對話性質,需要按順序進行推理以提取序列內的關係。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — 啟用和控制填充。接受以下值:

    • True'longest':填充到批處理中最長的序列(如果只提供單個序列,則不填充)。
    • 'max_length':填充到由 max_length 引數指定的最大長度,如果未提供該引數,則填充到模型可接受的最大輸入長度。
    • False'do_not_pad'(預設):不填充(即,可以輸出具有不同長度序列的批處理)。
  • truncation (bool, str or TapasTruncationStrategy, optional, defaults to False) — 啟用和控制截斷。接受以下值:

    • True'drop_rows_to_fit':截斷到由 max_length 引數指定的最大長度,如果未提供該引數,則截斷到模型可接受的最大輸入長度。這將逐行截斷,從表格中移除行。
    • False'do_not_truncate'(預設):不截斷(即,可以輸出序列長度大於模型最大可接受輸入大小的批處理)。

返回

包含結果的字典或字典列表

每個結果都是一個包含以下鍵的字典

  • answer (str) — 給定表格的查詢答案。如果存在聚合器,答案前將加上 AGGREGATOR >
  • coordinates (list[tuple[int, int]]) — 答案單元格的座標。
  • cells (list[str]) — 由答案單元格值組成的字串列表。
  • aggregator (str) — 如果模型有聚合器,則返回該聚合器。

根據表格回答查詢。pipeline 接受下面詳述的幾種輸入型別

  • pipeline(table, query)
  • pipeline(table, [query])
  • pipeline(table=table, query=query)
  • pipeline(table=table, query=[query])
  • pipeline({"table": table, "query": query})
  • pipeline({"table": table, "query": [query]})
  • pipeline([{"table": table, "query": query}, {"table": table, "query": query}])

table 引數應該是一個字典或從該字典構建的 DataFrame,包含整個表格

示例

data = {
    "actors": ["brad pitt", "leonardo di caprio", "george clooney"],
    "age": ["56", "45", "59"],
    "number of movies": ["87", "53", "69"],
    "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"],
}

這個字典可以按原樣傳遞,也可以轉換為 pandas DataFrame

示例

import pandas as pd

table = pd.DataFrame.from_dict(data)

TextClassificationPipeline

class transformers.TextClassificationPipeline

< >

( **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — pipeline 用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,則是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — pipeline 用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (str or ModelCard, optional) — 歸屬於此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 表示 PyTorch,"tf" 表示 TensorFlow。必須安裝指定的框架。

    如果未指定框架,將預設使用當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, defaults to "") — pipeline 的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當 pipeline 使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當 pipeline 使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批處理大小。對於推理,這並非總是有益的,請閱讀使用 pipeline 進行批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供 pipeline 引數的物件的引用。
  • device (int, optional, defaults to -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16, torch.bfloat16, … 或 "auto")。
  • binary_output (bool, optional, defaults to False) — 指示 pipeline 的輸出應該是序列化格式(例如 pickle)還是原始輸出資料(例如文字)的標誌。
  • return_all_scores (bool, optional, defaults to False) — 是返回所有預測分數,還是隻返回預測類別的分數。
  • function_to_apply (str, optional, defaults to "default") — 應用於模型輸出以檢索分數的函式。接受四種不同的值:

    • "default":如果模型只有一個標籤,將對輸出應用 sigmoid 函式。如果模型有多個標籤,將對輸出應用 softmax 函式。對於迴歸任務,不會對輸出應用任何函式。
    • "sigmoid":對輸出應用 sigmoid 函式。
    • "softmax":對輸出應用 softmax 函式。
    • "none":不對輸出應用任何函式。

使用任何 ModelForSequenceClassification 的文字分類 pipeline。有關更多資訊,請參閱序列分類示例

示例

>>> from transformers import pipeline

>>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
>>> classifier("This movie is disgustingly good !")
[{'label': 'POSITIVE', 'score': 1.0}]

>>> classifier("Director tried too much.")
[{'label': 'NEGATIVE', 'score': 0.996}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此文字分類 pipeline 目前可以透過 pipeline() 使用以下任務識別符號載入:"sentiment-analysis"(用於根據正面或負面情緒對序列進行分類)。

如果有多個分類標籤可用(model.config.num_labels >= 2),pipeline 將對結果執行 softmax。如果只有一個標籤,pipeline 將對結果執行 sigmoid。對於迴歸任務(model.config.problem_type == "regression"),不會對輸出應用任何函式。

此 pipeline 可以使用的模型是那些在序列分類任務上進行微調的模型。請參閱 huggingface.co/models 上可用的最新模型列表。

__call__

< >

( inputs: typing.Union[str, list[str], dict[str, str], list[dict[str, str]]] **kwargs: typing.Any ) 一個 dict 列表

引數

  • inputs (str or list[str] or dict[str], or list[dict[str]]) — 一個或多個要分類的文字。為了使用文字對進行分類,您可以傳送一個包含 {"text", "text_pair"} 鍵的字典,或這些字典的列表。
  • top_k (int, optional, defaults to 1) — 返回多少個結果。
  • function_to_apply (str, optional, defaults to "default") — 應用於模型輸出以檢索分數的函式。接受四種不同的值:

    如果未指定此引數,則將根據標籤數量應用以下函式:

    • 如果問題型別是迴歸,將不對輸出應用任何函式。
    • 如果模型只有一個標籤,將對輸出應用 sigmoid 函式。
    • 如果模型有多個標籤,將對輸出應用 softmax 函式。

    可能的值為:

    • "sigmoid":對輸出應用 sigmoid 函式。
    • "softmax":對輸出應用 softmax 函式。
    • "none":不對輸出應用任何函式。

返回

一個 dict 列表

每個結果都以字典列表的形式出現,包含以下鍵:

  • label (str) — 預測的標籤。
  • score (float) — 對應的機率。

如果使用 top_k,則每個標籤返回一個這樣的字典。

對給定的輸入文字進行分類。

TextGenerationPipeline

class transformers.TextGenerationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — pipeline 用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,則是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — pipeline 用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (str or ModelCard, optional) — 歸屬於此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 表示 PyTorch,"tf" 表示 TensorFlow。必須安裝指定的框架。

    如果未指定框架,將預設使用當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, defaults to "") — pipeline 的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當 pipeline 使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當 pipeline 使用 DataLoader 時(例如在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批處理大小。對於推理,這並非總是有益的,請閱讀使用 pipeline 進行批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供 pipeline 引數的物件的引用。
  • device (int, optional, defaults to -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16, torch.bfloat16, … 或 "auto")。
  • binary_output (bool, optional, defaults to False) — 指示 pipeline 的輸出應該是序列化格式(例如 pickle)還是原始輸出資料(例如文字)的標誌。

使用任何 ModelWithLMHeadModelForCausalLM 的語言生成 pipeline。此 pipeline 預測將跟隨指定文字提示的詞語。當底層模型是對話模型時,它也可以接受一個或多個聊天,在這種情況下,pipeline 將以聊天模式執行,並透過新增其響應來繼續聊天。每個聊天都採用字典列表的形式,其中每個字典都包含“role”和“content”鍵。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256
  • do_sample: True
  • temperature: 0.7

示例

>>> from transformers import pipeline

>>> generator = pipeline(model="openai-community/gpt2")
>>> generator("I can't believe you did such a ", do_sample=False)
[{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}]

>>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.
>>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False)
>>> from transformers import pipeline

>>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta")
>>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string
>>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2)
[{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]

pipeline 教程中瞭解更多關於使用 pipeline 的基礎知識。您可以將文字生成引數傳遞給此 pipeline 以控制停止標準、解碼策略等。在文字生成策略文字生成中瞭解更多關於文字生成引數的資訊。

此語言生成 pipeline 目前可以透過 pipeline() 使用以下任務識別符號載入:"text-generation"

此 pipeline 可以使用的模型是那些使用自迴歸語言建模目標訓練的模型。請參閱 [huggingface.co/models] 上的可用文字補全模型列表和對話模型列表。

__call__

< >

( text_inputs **kwargs ) 一個列表或列表的列表,其中包含 dict

引數

  • text_inputs (str, list[str], list[dict[str, str]] 或 list[list[dict[str, str]]]) — 一個或多個待補全的提示(或一個提示列表)。如果傳入字串或字串列表,此 pipeline 將延續每個提示。或者,也可以傳入“聊天”形式,即一個包含“role”和“content”鍵的字典列表,或多個此類聊天記錄的列表。當傳入聊天記錄時,將使用模型的聊天模板對其進行格式化,然後再傳遞給模型。
  • return_tensors (bool, 可選, 預設為 False) — 在輸出中返回預測的張量(作為 token 索引)。如果設定為 True,則不返回解碼後的文字。
  • return_text (bool, 可選) — 在輸出中返回解碼後的文字。
  • return_full_text (bool, 可選, 預設為 True) — 如果設定為 False,則只返回新增的文字,否則返回完整文字。不能與 return_text 同時指定。
  • clean_up_tokenization_spaces (bool, 可選, 預設為 True) — 是否清理文字輸出中可能出現的額外空格。
  • continue_final_message( bool, 可選) — 這表示您希望模型繼續輸入聊天中的最後一條訊息,而不是開始一條新訊息,從而允許您“預填充”其響應。預設情況下,當輸入聊天中的最後一條訊息角色為 assistant 時,此值為 True,否則為 False,但您可以透過設定此標誌來手動覆蓋該行為。
  • prefix (str, 可選) — 新增到提示的字首。
  • handle_long_generation (str, 可選) — 預設情況下,此 pipeline 不處理長文字生成(即以某種形式超過模型最大長度的生成)。沒有完美的方法來解決這個問題(更多資訊:https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227)。這裡提供了根據您的用例來解決該問題的常用策略。

    • None:預設策略,不進行特殊處理
    • "hole":從輸入的左側截斷,並留出足夠的空間讓生成發生(可能會截斷大量提示,並且不適用於生成超過模型容量的情況)
  • generate_kwargs (dict, 可選) — 傳遞給模型 generate 方法的額外關鍵字引數(請參閱與您的框架對應的 generate 方法此處)。

返回

一個列表或列表的列表,元素為 dict

返回以下字典之一(不能同時返回 generated_textgenerated_token_ids

  • generated_text (str,當 return_text=True 時存在) — 生成的文字。
  • generated_token_ids (torch.Tensortf.Tensor,當 return_tensors=True 時存在) — 生成文字的 token ID。

補全作為輸入給出的提示。

Text2TextGenerationPipeline

class transformers.Text2TextGenerationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 將用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,這需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — pipeline 將用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可選) — 歸屬於此 pipeline 模型 的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設為當前已安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,或者如果未提供模型,則預設為 PyTorch。

  • task (str, 預設為 "") — pipeline 的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當 pipeline 使用 DataLoader(在 GPU 上為 Pytorch 模型傳遞資料集時)時,要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當 pipeline 使用 DataLoader(在 GPU 上為 Pytorch 模型傳遞資料集時)時,要使用的批次大小,對於推理而言,這並不總是有益的,請閱讀 Pipeline 批處理
  • args_parser (ArgumentHandler, 可選) — 負責解析提供的 pipeline 引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16, torch.bfloat16, ... 或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示 pipeline 的輸出是否應以序列化格式(例如 pickle)或原始輸出資料(例如文字)進行的標誌。

使用 seq2seq 模型進行文字到文字生成的 Pipeline。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256
  • num_beams: 4

示例

>>> from transformers import pipeline

>>> generator = pipeline(model="mrm8488/t5-base-finetuned-question-generation-ap")
>>> generator(
...     "answer: Manuel context: Manuel has created RuPERTa-base with the support of HF-Transformers and Google"
... )
[{'generated_text': 'question: Who created the RuPERTa-base?'}]

pipeline 教程中瞭解更多關於使用 pipeline 的基礎知識。您可以將文字生成引數傳遞給此 pipeline 以控制停止標準、解碼策略等。在文字生成策略文字生成中瞭解更多關於文字生成引數的資訊。

此 Text2TextGenerationPipeline 目前可以從 pipeline() 使用以下任務識別符號載入:"text2text-generation"

此 pipeline 可以使用的模型是那些在翻譯任務上進行了微調的模型。請在 huggingface.co/models 上檢視最新的可用模型列表。有關可用引數的列表,請參閱以下文件

用法

text2text_generator = pipeline("text2text-generation")
text2text_generator("question: What is 42 ? context: 42 is the answer to life, the universe and everything")

__call__

< >

( *args: typing.Union[str, list[str]] **kwargs: typing.Any ) 一個列表或列表的列表,元素為 dict

引數

  • args (strlist[str]) — 編碼器的輸入文字。
  • return_tensors (bool, 可選, 預設為 False) — 是否在輸出中包含預測的張量(作為 token 索引)。
  • return_text (bool, 可選, 預設為 True) — 是否在輸出中包含解碼後的文字。
  • clean_up_tokenization_spaces (bool, 可選, 預設為 False) — 是否清理文字輸出中可能出現的額外空格。
  • truncation (TruncationStrategy, 可選, 預設為 TruncationStrategy.DO_NOT_TRUNCATE) — pipeline 內部分詞的截斷策略。TruncationStrategy.DO_NOT_TRUNCATE (預設) 永遠不會截斷,但有時為了適應模型的 max_length 而截斷輸入比後續丟擲錯誤更可取。
  • generate_kwargs — 傳遞給模型 generate 方法的額外關鍵字引數(請參閱與您的框架對應的 generate 方法此處)。

返回

dict 的列表或列表的列表

每個結果都以字典形式返回,包含以下鍵:

  • generated_text (str,當 return_text=True 時存在) — 生成的文字。
  • generated_token_ids (torch.Tensortf.Tensor,當 return_tensors=True 時存在) — 生成文字的 token ID。

使用作為輸入給出的文字生成輸出文字。

check_inputs

< >

( input_length: int min_length: int max_length: int )

檢查給定輸入相對於模型是否存在潛在問題。

TokenClassificationPipeline

class transformers.TokenClassificationPipeline

< >

( args_parser = <transformers.pipelines.token_classification.TokenClassificationArgumentHandler object at 0x7eff957a1a80> *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 將用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,這需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — pipeline 將用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可選) — 歸屬於此 pipeline 模型 的模型卡。
  • framework (str, 可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設為當前已安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,或者如果未提供模型,則預設為 PyTorch。

  • task (str, 預設為 "") — pipeline 的任務識別符號。
  • num_workers (int, 可選, 預設為 8) — 當 pipeline 使用 DataLoader(在 GPU 上為 Pytorch 模型傳遞資料集時)時,要使用的工作程序數量。
  • batch_size (int, 可選, 預設為 1) — 當 pipeline 使用 DataLoader(在 GPU 上為 Pytorch 模型傳遞資料集時)時,要使用的批次大小,對於推理而言,這並不總是有益的,請閱讀 Pipeline 批處理
  • args_parser (ArgumentHandler, 可選) — 負責解析提供的 pipeline 引數的物件的引用。
  • device (int, 可選, 預設為 -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16, torch.bfloat16, ... 或 "auto")。
  • binary_output (bool, 可選, 預設為 False) — 指示 pipeline 的輸出是否應以序列化格式(例如 pickle)或原始輸出資料(例如文字)進行的標誌。
  • ignore_labels (list[str], 預設為 ["O"]) — 要忽略的標籤列表。
  • grouped_entities (bool, 可選, 預設為 False) — 已棄用,請改用 aggregation_strategy。是否在預測中將對應同一實體的 token 組合在一起。
  • stride (int, 可選) — 如果提供 stride,pipeline 將應用於所有文字。文字被分割成大小為 model_max_length 的塊。僅適用於 fast tokenizer 且 aggregation_strategy 不同於 NONE 的情況。此引數的值定義了塊之間重疊 token 的數量。換句話說,模型每一步將向前移動 tokenizer.model_max_length - stride 個 token。
  • aggregation_strategy (str, 可選, 預設為 "none") — 根據模型預測融合(或不融合)token 的策略。

    • “none”:不進行任何聚合,僅返回模型的原始結果。
    • “simple”:嘗試按照預設模式對實體進行分組。(A, B-TAG), (B, I-TAG), (C, I-TAG), (D, B-TAG2) (E, B-TAG2) 最終將變為 [{“word”: ABC, “entity”: “TAG”}, {“word”: “D”, “entity”: “TAG2”}, {“word”: “E”, “entity”: “TAG2”}]。請注意,兩個連續的 B 標籤將最終成為不同的實體。在基於詞的語言中,我們可能會不希望地分割詞:想象一下 Microsoft 被標記為 [{“word”: “Micro”, “entity”: “ENTERPRISE”}, {“word”: “soft”, “entity”: “NAME”}]。請檢視 FIRST, MAX, AVERAGE 以尋找緩解這種情況並消除詞語歧義的方法(在支援該含義的語言中,基本上是空格分隔的 token)。這些緩解措施僅對真實詞語有效,“New York” 可能仍會被標記為兩個不同的實體。
    • “first”:(僅適用於基於詞的模型)將使用 SIMPLE 策略,但詞語不能最終帶有不同的標籤。當存在歧義時,詞語將簡單地使用該詞第一個 token 的標籤。
    • “average”:(僅適用於基於詞的模型)將使用 SIMPLE 策略,但詞語不能最終帶有不同的標籤。分數將首先在 token 之間取平均,然後應用最大標籤。
    • “max”:(僅適用於基於詞的模型)將使用 SIMPLE 策略,但詞語不能最終帶有不同的標籤。詞語實體將簡單地是得分最高的 token。

使用任何 ModelForTokenClassification 的命名實體識別 pipeline。有關更多資訊,請參閱命名實體識別示例

示例

>>> from transformers import pipeline

>>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple")
>>> sentence = "Je m'appelle jean-baptiste et je vis à montréal"
>>> tokens = token_classifier(sentence)
>>> tokens
[{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}]

>>> token = tokens[0]
>>> # Start and end provide an easy way to highlight words in the original text.
>>> sentence[token["start"] : token["end"]]
' jean-baptiste'

>>> # Some models use the same idea to do part of speech.
>>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple")
>>> syntaxer("My name is Sarah and I live in London")
[{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此 token 識別 pipeline 目前可以從 pipeline() 使用以下任務識別符號載入:"ner"(用於預測序列中 token 的類別:person, organisation, location 或 miscellaneous)。

此 pipeline 可以使用的模型是那些在 token 分類任務上進行了微調的模型。請在 huggingface.co/models 上檢視最新的可用模型列表。

__call__

< >

( inputs: typing.Union[str, list[str]] **kwargs: typing.Any ) dict 的列表或列表的列表

引數

  • inputs (strList[str]) — 用於 token 分類的一個或多個文字(或一個文字列表)。當 is_split_into_words=True 時,可以是預分詞的。

返回

dict 的列表或列表的列表

每個結果都以字典列表的形式出現(對應輸入中的每個 token 一個,或者如果此 pipeline 使用 aggregation_strategy 例項化,則為每個實體一個),具有以下鍵:

  • word (str) — 被分類的 token/詞。這是透過解碼所選 token 獲得的。如果您想獲得原始句子中的確切字串,請使用 startend
  • score (float) — 對應於 entity 的機率。
  • entity (str) — 為該 token/詞預測的實體(當 aggregation_strategy 不為 "none" 時,名為 entity_group)。
  • index (int, 僅當 aggregation_strategy="none" 時存在) — 句子中相應 token 的索引。
  • start (int, 可選) — 句子中相應實體開始的索引。僅當分詞器中存在偏移量時才存在。
  • end (int, 可選) — 句子中相應實體結束的索引。僅當分詞器中存在偏移量時才存在。

對作為輸入給出的文字的每個 token 進行分類。

aggregate_words

< >

( entities: list aggregation_strategy: AggregationStrategy )

覆蓋給定詞中不一致的 token,以強制在詞邊界上達成一致。

例如:micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT 使用 first 策略將被重寫為 microsoft| company| B-ENT I-ENT

gather_pre_entities

< >

( sentence: str input_ids: ndarray scores: ndarray offset_mapping: typing.Optional[list[tuple[int, int]]] special_tokens_mask: ndarray aggregation_strategy: AggregationStrategy word_ids: typing.Optional[list[typing.Optional[int]]] = None word_to_chars_map: typing.Optional[list[tuple[int, int]]] = None )

將各種 numpy 陣列融合成包含聚合所需所有資訊的字典。

group_entities

< >

( entities: list )

引數

  • entities (dict) — pipeline 預測的實體。

查詢並組合具有相同實體預測的相鄰 token。

group_sub_entities

< >

( entities: list )

引數

  • entities (dict) — 由管道預測的實體。

將具有相同預測實體的相鄰詞元(token)組合在一起。

TranslationPipeline

class transformers.TranslationPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 管道將用於進行預測的模型。對於 PyTorch,它必須是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它必須是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 管道將用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (str or ModelCard, optional) — 歸屬於此管道模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前已安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,或者在未提供模型時預設使用 PyTorch。

  • task (str, defaults to "") — 管道的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當管道使用 DataLoader 時(例如,在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當管道使用 DataLoader 時(例如,在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的批大小。對於推理來說,這並不總是有益的,請閱讀使用管道進行批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供管道引數的物件的引用。
  • device (int, optional, defaults to -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳遞(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, optional, defaults to False) — 指示管道的輸出是應該以序列化格式(即 pickle)還是以原始輸出資料(例如文字)的形式進行的標誌。

將一種語言翻譯成另一種語言。

當前可以使用任務識別符號 "translation_xx_to_yy"pipeline() 載入此翻譯管道。

此管道可以使用的模型是那些已經在翻譯任務上進行了微調的模型。請在 huggingface.co/models 上檢視最新的可用模型列表。有關可用引數的列表,請參閱以下文件

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256
  • num_beams: 4

用法

en_fr_translator = pipeline("translation_en_to_fr")
en_fr_translator("How old are you?")

__call__

< >

( *args **kwargs ) 一個列表或一個 dict 的列表的列表

引數

  • args (str or list[str]) — 要翻譯的文字。
  • return_tensors (bool, optional, defaults to False) — 是否在輸出中包含預測的張量(作為詞元索引)。
  • return_text (bool, optional, defaults to True) — 是否在輸出中包含解碼後的文字。
  • clean_up_tokenization_spaces (bool, optional, defaults to False) — 是否清除文字輸出中可能存在的多餘空格。
  • src_lang (str, optional) — 輸入文字的語言。對於多語言模型可能是必需的。對於單語對翻譯模型沒有影響。
  • tgt_lang (str, optional) — 期望輸出的語言。對於多語言模型可能是必需的。對於單語對翻譯模型沒有影響。
  • generate_kwargs — 要傳遞給模型生成方法的附加關鍵字引數(請參閱與您的框架對應的生成方法 此處)。

返回

dict 的列表或列表的列表

每個結果都以字典形式返回,包含以下鍵:

  • translation_text (str, 僅當 return_text=True 時存在) — 翻譯結果。
  • translation_token_ids (torch.Tensortf.Tensor, 僅當 return_tensors=True 時存在) — 翻譯結果的詞元 ID。

翻譯作為輸入給定的文字。

ZeroShotClassificationPipeline

class transformers.ZeroShotClassificationPipeline

< >

( args_parser = <transformers.pipelines.zero_shot_classification.ZeroShotClassificationArgumentHandler object at 0x7eff957a35e0> *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 管道將用於進行預測的模型。對於 PyTorch,它必須是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它必須是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 管道將用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • modelcard (str or ModelCard, optional) — 歸屬於此管道模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前已安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,或者在未提供模型時預設使用 PyTorch。

  • task (str, defaults to "") — 管道的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當管道使用 DataLoader 時(例如,在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當管道使用 DataLoader 時(例如,在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的批大小。對於推理來說,這並不總是有益的,請閱讀使用管道進行批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供管道引數的物件的引用。
  • device (int, optional, defaults to -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳遞(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, optional, defaults to False) — 指示管道的輸出是應該以序列化格式(即 pickle)還是以原始輸出資料(例如文字)的形式進行的標誌。

基於自然語言推理(NLI)的零樣本分類管道,使用在 NLI 任務上訓練的 `ModelForSequenceClassification`。等同於 `text-classification` 管道,但這些模型不需要硬編碼數量的潛在類別,它們可以在執行時選擇。這通常意味著它會更慢,但靈活性**要大得多**。

可以傳遞序列和標籤的任意組合,每個組合將被構造成一個前提/假設對並傳遞給預訓練模型。然後,*蘊含(entailment)* 的 logit 被視為候選標籤有效的 logit。可以使用任何 NLI 模型,但*蘊含*標籤的 ID 必須包含在模型配置的 :attr:`~transformers.PretrainedConfig.label2id` 中。

示例

>>> from transformers import pipeline

>>> oracle = pipeline(model="facebook/bart-large-mnli")
>>> oracle(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'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]}

>>> oracle(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["english", "german"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

當前可以使用任務識別符號 "zero-shot-classification"pipeline() 載入此 NLI 管道。

此管道可以使用的模型是那些已經在 NLI 任務上進行了微調的模型。請在 huggingface.co/models 上檢視最新的可用模型列表。

__call__

< >

( sequences: typing.Union[str, list[str]] *args **kwargs ) dictdict 列表

引數

  • sequences (str or list[str]) — 要分類的序列。如果模型輸入太大,將被截斷。
  • candidate_labels (str or list[str]) — 用於對每個序列進行分類的可能類別標籤集。可以是一個單一標籤、一個逗號分隔的標籤字串或一個標籤列表。
  • hypothesis_template (str, optional, defaults to "This example is {}.") — 用於將每個標籤轉換為 NLI 風格假設的模板。此模板必須包含一個 {} 或類似的語法,以便將候選標籤插入模板中。例如,預設模板是 `"This example is {}."`。對於候選標籤 `"sports"`,它將被輸入到模型中,形式為 `"<cls> 要分類的序列 <sep> This example is sports . <sep>"`。預設模板在許多情況下效果很好,但根據任務設定,嘗試不同的模板可能值得一試。
  • multi_label (bool, optional, defaults to False) — 是否允許多個候選標籤為真。如果為 `False`,則對得分進行歸一化,使得每個序列的標籤似然之和為 1。如果為 `True`,則標籤被視為獨立的,並透過對蘊含分數與矛盾分數進行 softmax 來對每個候選標籤的機率進行歸一化。

返回

一個 `dict` 或一個 `dict` 列表

每個結果都以字典形式返回,包含以下鍵:

  • sequence (str) — 此輸出所對應的序列。
  • labels (list[str]) — 按似然順序排序的標籤。
  • scores (list[float]) — 每個標籤的機率。

對作為輸入給定的序列進行分類。更多資訊請參閱 ZeroShotClassificationPipeline 文件。

多模態

可用於多模態任務的管道包括以下幾種。

DocumentQuestionAnsweringPipeline

class transformers.DocumentQuestionAnsweringPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 管道將用於進行預測的模型。對於 PyTorch,它必須是繼承自 PreTrainedModel 的模型;對於 TensorFlow,它必須是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 管道將用於為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • image_processor (BaseImageProcessor) — 管道將用於為模型編碼資料的影像處理器。該物件繼承自 BaseImageProcessor
  • modelcard (str or ModelCard, optional) — 歸屬於此管道模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設使用當前已安裝的框架。如果未指定框架且兩個框架都已安裝,將預設使用 model 的框架,或者在未提供模型時預設使用 PyTorch。

  • task (str, defaults to "") — 管道的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當管道使用 DataLoader 時(例如,在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當管道使用 DataLoader 時(例如,在 GPU 上為 PyTorch 模型傳遞資料集時),要使用的批大小。對於推理來說,這並不總是有益的,請閱讀使用管道進行批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供管道引數的物件的引用。
  • device (int, optional, defaults to -1) — 支援 CPU/GPU 的裝置序號。設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳遞(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, optional, defaults to False) — 指示管道的輸出是應該以序列化格式(即 pickle)還是以原始輸出資料(例如文字)的形式進行的標誌。

文件問答管道使用任何 AutoModelForDocumentQuestionAnswering 模型。其輸入/輸出與(抽取式)問答管道類似;但是,該管道接受影像(以及可選的 OCR 識別的單詞/邊界框)作為輸入,而不是文字上下文。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256

示例

>>> from transformers import pipeline

>>> document_qa = pipeline(model="impira/layoutlm-document-qa")
>>> document_qa(
...     image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
...     question="What is the invoice number?",
... )
[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

當前可以使用任務識別符號 "document-question-answering"pipeline() 載入此文件問答管道。

此管道可以使用的模型是那些已經在文件問答任務上進行了微調的模型。請在 huggingface.co/models 上檢視最新的可用模型列表。

__call__

< >

( image: typing.Union[ForwardRef('Image.Image'), str, list[dict[str, typing.Any]]] question: typing.Optional[str] = None word_boxes: typing.Optional[tuple[str, list[float]]] = None **kwargs: typing.Any ) dictdict 列表

引數

  • image (str or PIL.Image) — 管道處理三種類型的影像:

    • 指向影像的 http 連結的字串
    • 指向本地影像路徑的字串
    • 直接在 PIL 中載入的影像

    管道接受單個影像或一批影像。如果給定單個影像,它可以被廣播到多個問題上。

  • question (str) — 向文件提出的問題。
  • word_boxes (list[str, tuple[float, float, float, float]], optional) — 單詞及其邊界框(歸一化到 0->1000)的列表。如果您提供此可選輸入,對於需要它們的模型(例如 LayoutLM),流水線將使用這些單詞和框,而不是在影像上執行 OCR 來派生它們。這允許您在多次呼叫流水線時重用 OCR 結果,而無需每次都重新執行。
  • top_k (int, optional, defaults to 1) — 要返回的答案數量(將按可能性順序選擇)。請注意,如果上下文中沒有足夠的可用選項,我們將返回少於 top_k 個答案。
  • doc_stride (int, optional, defaults to 128) — 如果文件中的單詞太長,無法與模型的問題相匹配,它將被分成幾個有重疊的塊。此引數控制重疊的大小。
  • max_answer_len (int, optional, defaults to 15) — 預測答案的最大長度(例如,只考慮長度較短的答案)。
  • max_seq_len (int, optional, defaults to 384) — 傳遞給模型的每個塊的總句子(上下文 + 問題)的最大長度(以詞元為單位)。如果需要,上下文將被分成幾個塊(使用 doc_stride 作為重疊)。
  • max_question_len (int, optional, defaults to 64) — 標記化後問題的最大長度。如果需要,它將被截斷。
  • handle_impossible_answer (bool, optional, defaults to False) — 是否接受“不可能”作為答案。
  • lang (str, optional) — 執行 OCR 時使用的語言。預設為英語。
  • tesseract_config (str, optional) — 執行 OCR 時傳遞給 tesseract 的附加標誌。
  • timeout (float, optional, defaults to None) — 從網頁獲取圖片的最長等待時間(秒)。如果為 None,則不設定超時,呼叫可能會永遠阻塞。

返回

一個 `dict` 或一個 `dict` 列表

每個結果都以字典形式返回,包含以下鍵:

  • score (float) — 與答案相關的機率。
  • start (int) — 答案的起始單詞索引(在輸入的 OCR 版本或提供的 word_boxes 中)。
  • end (int) — 答案的結束單詞索引(在輸入的 OCR 版本或提供的 word_boxes 中)。
  • answer (str) — 問題的答案。
  • words (list[int]) — 答案中每個單詞/框對的索引。

透過使用文件來回答作為輸入給出的問題。文件被定義為一個影像和一個可選的(單詞,框)元組列表,表示文件中的文字。如果未提供 word_boxes,它將使用 Tesseract OCR 引擎(如果可用)為需要它們作為輸入的 LayoutLM 類模型自動提取單詞和框。對於 Donut 模型,不執行 OCR。

您可以透過多種方式呼叫流水線

  • pipeline(image=image, question=question)
  • pipeline(image=image, question=question, word_boxes=word_boxes)
  • pipeline([{"image": image, "question": question}])
  • pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])

FeatureExtractionPipeline

class transformers.FeatureExtractionPipeline

< >

( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將被流水線用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型,對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 將被流水線用於為模型編碼資料的分詞器。此物件繼承自 PreTrainedTokenizer
  • modelcard (str or ModelCard, optional) — 歸屬於此流水線模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt"(PyTorch)或 "tf"(TensorFlow)。必須安裝指定的框架。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, defaults to "") — 流水線的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當流水線將使用 DataLoader 時(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當流水線將使用 DataLoader 時(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的批次大小,對於推理而言,這並非總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, optional, defaults to -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在關聯的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16 等或 "auto")。
  • tokenize_kwargs (dict, optional) — 傳遞給分詞器的額外關鍵字引數字典。
  • return_tensors (bool, optional) — 如果為 True,則根據指定的框架返回一個張量,否則返回一個列表。

特徵提取流水線不使用模型頭部。此流水線從基礎 Transformer 中提取隱藏狀態,這些狀態可用作下游任務中的特徵。

示例

>>> from transformers import pipeline

>>> extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction")
>>> result = extractor("This is a simple test.", return_tensors=True)
>>> result.shape  # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string.
torch.Size([1, 8, 768])

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

當前可以使用任務識別符號 "feature-extraction"pipeline() 載入此特徵提取流水線。

所有模型都可以用於此流水線。在 huggingface.co/models 上檢視所有模型列表,包括社群貢獻的模型。

__call__

< >

( *args: typing.Union[str, list[str]] **kwargs: typing.Any ) float 的巢狀列表

引數

  • args (str or list[str]) — 一個或多個要獲取其特徵的文字(或一個文字列表)。

返回

float 的巢狀列表

模型計算的特徵。

提取輸入文字的特徵。

ImageFeatureExtractionPipeline

class transformers.ImageFeatureExtractionPipeline

< >

( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將被流水線用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型,對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • image_processor (BaseImageProcessor) — 將被流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (str or ModelCard, optional) — 歸屬於此流水線模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt"(PyTorch)或 "tf"(TensorFlow)。必須安裝指定的框架。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, defaults to "") — 流水線的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當流水線將使用 DataLoader 時(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的工作程序數。
  • batch_size (int, optional, defaults to 1) — 當流水線將使用 DataLoader 時(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的批次大小,對於推理而言,這並非總是有益的,請閱讀流水線批處理
  • args_parser (ArgumentHandler, optional) — 對負責解析所提供流水線引數的物件的引用。
  • device (int, optional, defaults to -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在關聯的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype, optional) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool, optional, defaults to False) — 指示流水線的輸出是應以序列化格式(例如 pickle)還是作為原始輸出資料(例如文字)進行的標誌。
  • image_processor_kwargs (dict, optional) — 傳遞給影像處理器的額外關鍵字引數字典,例如 {“size”: {“height”: 100, “width”: 100}‌}。
  • pool (bool, optional, defaults to False) — 是否返回池化輸出。如果為 False,模型將返回原始隱藏狀態。

影像特徵提取流水線不使用模型頭部。此流水線從基礎 Transformer 中提取隱藏狀態,這些狀態可用作下游任務中的特徵。

示例

>>> from transformers import pipeline

>>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction")
>>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True)
>>> result.shape  # This is a tensor of shape [1, sequence_lenth, hidden_dimension] representing the input image.
torch.Size([1, 197, 768])

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

當前可以使用任務識別符號 "image-feature-extraction"pipeline() 載入此影像特徵提取流水線。

所有視覺模型都可以用於此流水線。在 huggingface.co/models 上檢視所有模型列表,包括社群貢獻的模型。

__call__

< >

( *args: typing.Union[str, ForwardRef('Image.Image'), list['Image.Image'], list[str]] **kwargs: typing.Any ) float 的巢狀列表

引數

  • images (str, list[str], PIL.Image or list[PIL.Image]) — 流水線處理三種類型的影像:

    • 包含指向影像的 http 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入到 PIL 中的影像

    流水線接受單個影像或一批影像,後者必須作為字串傳遞。批處理中的影像必須都具有相同的格式:全部為 http 連結、全部為本地路徑或全部為 PIL 影像。

  • timeout (float, optional, defaults to None) — 從網頁獲取圖片的最長等待時間(秒)。如果為 None,則不使用超時,呼叫可能會永遠阻塞。

返回

float 的巢狀列表

模型計算的特徵。

提取輸入的特徵。

ImageToTextPipeline

class transformers.ImageToTextPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將被流水線用於進行預測的模型。對於 PyTorch,它需要是繼承自 PreTrainedModel 的模型,對於 TensorFlow,它需要是繼承自 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 將被流水線用於為模型編碼資料的分詞器。此物件繼承自 PreTrainedTokenizer
  • image_processor (BaseImageProcessor) — 將被流水線用於為模型編碼資料的影像處理器。此物件繼承自 BaseImageProcessor
  • modelcard (str or ModelCard, optional) — 歸屬於此流水線模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt"(PyTorch)或 "tf"(TensorFlow)。必須安裝指定的框架。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 model 的框架,如果未提供模型,則預設為 PyTorch。

  • task (str, defaults to "") — 流水線的任務識別符號。
  • num_workers (int, optional, defaults to 8) — 當流水線將使用 DataLoader 時(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的工作程序數。
  • batch_size (int可選,預設為 1) — 當 pipeline 使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並非總是有益的,請閱讀使用 pipeline 進行批處理
  • args_parser (ArgumentHandler可選) — 負責解析所提供的 pipeline 引數的物件的引用。
  • device (int可選,預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool可選,預設為 False) — 指示 pipeline 的輸出是否應以序列化格式(如 pickle)或原始輸出資料(如文字)進行的標誌。

使用 AutoModelForVision2Seq 的影像到文字 pipeline。此 pipeline 為給定影像預測標題。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256

示例

>>> from transformers import pipeline

>>> captioner = pipeline(model="ydshieh/vit-gpt2-coco-en")
>>> captioner("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'generated_text': 'two birds are standing next to each other '}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此影像到文字 pipeline 目前可以使用以下任務識別符號從 pipeline() 載入:“image-to-text”。

請參閱 huggingface.co/models 上的可用模型列表。

__call__

< >

( inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs ) dict 的列表或列表的列表

引數

  • inputs (strlist[str]PIL.Imagelist[PIL.Image]) — pipeline 處理三種類型的影像:

    • 包含指向影像的 HTTP(s) 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入到 PIL 中的影像

    pipeline 接受單個影像或一批影像。

  • max_new_tokens (int可選) — 要生成的最大詞元數。預設情況下,它將使用 generate 的預設值。
  • generate_kwargs (Dict可選) — 傳遞它以將所有這些引數直接傳送到 generate,從而實現對此函式的完全控制。
  • timeout (float可選,預設為 None) — 從 Web 獲取影像的最長等待時間(秒)。如果為 None,則不設定超時,呼叫可能會永遠阻塞。

返回

dict 的列表或列表的列表

每個結果都以字典形式返回,包含以下鍵:

  • generated_text (str) — 生成的文字。

為作為輸入傳遞的影像分配標籤。

ImageTextToTextPipeline

class transformers.ImageTextToTextPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,則是繼承自 TFPreTrainedModel 的模型。
  • processor (ProcessorMixin) — pipeline 用於為模型編碼資料的處理器。該物件繼承自 ProcessorMixin。處理器是一個複合物件,可能包含 `tokenizer`、`feature_extractor` 和 `image_processor`。
  • modelcard (strModelCard可選) — 歸屬於此 pipeline 模型的模型卡。
  • framework (str可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 `model` 的框架,或者在未提供模型時預設為 PyTorch。

  • task (str,預設為 "") — pipeline 的任務識別符號。
  • num_workers (int可選,預設為 8) — 當 pipeline 使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int可選,預設為 1) — 當 pipeline 使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並非總是有益的,請閱讀使用 pipeline 進行批處理
  • args_parser (ArgumentHandler可選) — 負責解析所提供的 pipeline 引數的物件的引用。
  • device (int可選,預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool可選,預設為 False) — 指示 pipeline 的輸出是否應以序列化格式(如 pickle)或原始輸出資料(如文字)進行的標誌。

使用 `AutoModelForImageTextToText` 的圖文到文字 pipeline。此 pipeline 根據影像和文字生成文字。當底層模型是對話模型時,它還可以接受一個或多個聊天,在這種情況下,pipeline 將以聊天模式執行,並透過新增其響應來繼續聊天。每個聊天都採用字典列表的形式,其中每個字典包含“role”和“content”鍵。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256

示例

>>> from transformers import pipeline

>>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base")
>>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
[{'generated_text': 'a photo of two birds'}]
>>> from transformers import pipeline

>>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")
>>> messages = [
>>>     {
>>>         "role": "user",
>>>         "content": [
>>>             {
>>>                 "type": "image",
>>>                 "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
>>>             },
>>>             {"type": "text", "text": "Describe this image."},
>>>         ],
>>>     },
>>>     {
>>>         "role": "assistant",
>>>         "content": [
>>>             {"type": "text", "text": "There is a dog and"},
>>>         ],
>>>     },
>>> ]
>>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
[{'input_text': [{'role': 'user',
    'content': [{'type': 'image',
    'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
    {'type': 'text', 'text': 'Describe this image.'}]},
{'role': 'assistant',
    'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此圖文到文字 pipeline 目前可以使用以下任務識別符號從 pipeline() 載入:“image-text-to-text”。

請參閱 huggingface.co/models 上的可用模型列表。

__call__

< >

( images: typing.Union[str, list[str], list[list[str]], ForwardRef('Image.Image'), list['Image.Image'], list[list['Image.Image']], list[dict], NoneType] = None text: typing.Union[str, list[str], list[dict], NoneType] = None **kwargs ) dict 的列表或列表的列表

引數

  • images (strlist[str]PIL.Image、`list[PIL.Image]`、`list[dict[str, Union[str, PIL.Image]]]` ) — pipeline 處理三種類型的影像:

    • 包含指向影像的 HTTP(s) 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入到 PIL 中的影像

    pipeline 接受單個影像或一批影像。最後,此 pipeline 還支援此引數中包含影像和文字的聊天格式(請參閱 `text`)。

  • text (str, list[str], list[dict[str, Union[str, PIL.Image]]]) — 用於生成的文字。如果傳遞了字串列表,則列表的長度應與影像數量相同。文字也可以遵循聊天格式:一個字典列表,其中每個字典代表對話中的一條訊息。每個字典應有兩個鍵:‘role’ 和 ‘content’。‘role’ 應該是 ‘user’、‘system’ 或 ‘assistant’ 之一。‘content’ 應該是一個包含訊息文字和訊息型別的字典列表。訊息型別可以是 ‘text’ 或 ‘image’。如果型別是 ‘image’,則不需要文字。
  • return_tensors (bool可選,預設為 False) — 在輸出中返回預測的張量(作為詞元索引)。如果設定為 True,則不返回解碼後的文字。
  • return_text (bool可選) — 在輸出中返回解碼後的文字。
  • return_full_text (bool可選,預設為 True) — 如果設定為 False,則只返回新增的文字;否則返回全文。不能與 return_text 同時指定。
  • clean_up_tokenization_spaces (bool可選,預設為 True) — 是否清理文字輸出中潛在的多餘空格。
  • continue_final_message( bool可選) — 這表示您希望模型繼續輸入聊天中的最後一條訊息,而不是開始一條新訊息,從而允許您“預填充”其響應。預設情況下,當輸入聊天中的最後一條訊息角色為 `assistant` 時,此值為 `True`,否則為 `False`,但您可以透過設定此標誌手動覆蓋該行為。

返回

dict 的列表或列表的列表

每個結果都以字典形式返回,包含以下鍵(不能同時返回 generated_textgenerated_token_ids 的組合):

  • generated_text (str,當 return_text=True 時存在) — 生成的文字。
  • generated_token_ids (torch.Tensor,當 return_tensors=True 時存在) — 生成文字的詞元 ID。
  • input_text (str) — 輸入文字。

根據作為輸入傳遞的文字和影像生成文字。

MaskGenerationPipeline

class transformers.MaskGenerationPipeline

< >

( **kwargs )

引數

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 用於進行預測的模型。對於 PyTorch,這需要是繼承自 PreTrainedModel 的模型;對於 TensorFlow,則是繼承自 TFPreTrainedModel 的模型。
  • image_processor (BaseImageProcessor) — pipeline 用於為模型編碼資料的影像處理器。該物件繼承自 BaseImageProcessor
  • modelcard (strModelCard可選) — 歸屬於此 pipeline 模型的模型卡。
  • framework (str可選) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必須已安裝。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩個框架都已安裝,將預設為 `model` 的框架,或者在未提供模型時預設為 PyTorch。

  • task (str,預設為 "") — pipeline 的任務識別符號。
  • num_workers (int可選,預設為 8) — 當 pipeline 使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的工作程序數。
  • batch_size (int可選,預設為 1) — 當 pipeline 使用 DataLoader 時(例如,在 GPU 上為 Pytorch 模型傳遞資料集時),要使用的批次大小。對於推理,這並非總是有益的,請閱讀使用 pipeline 進行批處理
  • args_parser (ArgumentHandler可選) — 負責解析所提供的 pipeline 引數的物件的引用。
  • device (int可選,預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 ID 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (strtorch.dtype可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型可用的精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool可選,預設為 False) — 指示 pipeline 的輸出是否應以序列化格式(如 pickle)或原始輸出資料(如文字)進行的標誌。
  • points_per_batch (可選,int,預設為 64) — 設定模型同時執行的點數。更高的數值可能更快,但會使用更多 GPU 記憶體。
  • output_bboxes_mask (bool可選,預設為 False) — 是否輸出邊界框預測。
  • output_rle_masks (bool可選,預設為 False) — 是否以 `RLE` 格式輸出掩碼。

使用 `SamForMaskGeneration` 對影像進行自動掩碼生成。此 pipeline 為給定影像預測二元掩碼。它是一個 `ChunkPipeline`,因為您可以將點分成小批次以避免記憶體不足(OOM)問題。使用 `points_per_batch` 引數控制將同時處理的點數。預設為 `64`。

該 pipeline 分三步工作:

  1. `preprocess`:生成一個由 1024 個均勻分佈的點組成的網格,以及邊界框和點標籤。有關如何建立點和邊界框的更多詳細資訊,請檢視 `_generate_crop_boxes` 函式。影像也使用 `image_processor` 進行預處理。此函式 `yields` 一個 `points_per_batch` 大小的小批次。

  2. `forward`:將 `preprocess` 的輸出饋送到模型。影像嵌入只計算一次。呼叫 `self.model.get_image_embeddings` 並確保不計算梯度,並且張量和模型在同一裝置上。

  3. `postprocess`:自動掩碼生成的最重要部分發生在這裡。包括三個步驟:

    • image_processor.postprocess_masks(在每個小批次迴圈中執行):接收原始輸出掩碼,根據影像大小調整其大小,並將其轉換為二元掩碼。
    • image_processor.filter_masks(在每個小批次迴圈中):同時使用 `pred_iou_thresh` 和 `stability_scores`。還應用各種基於非極大值抑制的過濾器來移除不良掩碼。
    • image_processor.postprocess_masks_for_amg 在掩碼上應用 NSM 以僅保留相關的掩碼。

示例

>>> from transformers import pipeline

>>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation")
>>> outputs = generator(
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
... )

>>> outputs = generator(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128
... )

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

此分割 pipeline 目前可以使用以下任務識別符號從 pipeline() 載入:`"mask-generation"`。

請參閱 huggingface.co/models 上的可用模型列表。

__call__

< >

( image: typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']] *args: typing.Any **kwargs: typing.Any ) Dict

引數

  • image (strList[str]PIL.ImageList[PIL.Image]) — 影像或影像列表。
  • mask_threshold (float可選,預設為 0.0) — 將預測掩碼轉換為二元值時使用的閾值。
  • pred_iou_thresh (float可選,預設為 0.88) — 應用於模型預測掩碼質量的過濾閾值,範圍在 `[0,1]` 之間。
  • stability_score_thresh (float可選,預設為 0.95) — 一個在 `[0,1]` 範圍內的過濾閾值,使用掩碼在二值化模型掩碼預測的截止值變化下的穩定性。
  • stability_score_offset (int可選,預設為 1) — 計算穩定性分數時移動截止值的量。
  • crops_nms_thresh (float可選,預設為 0.7) — 非極大值抑制用於過濾重複掩碼的框 IoU 截止值。
  • crops_n_layers (int可選,預設為 0) — 如果 `crops_n_layers>0`,將在影像的裁剪塊上再次執行掩碼預測。設定要執行的層數,其中每層有 2**i_layer 個影像裁剪塊。
  • crop_overlap_ratio (float可選,預設為 `512 / 1500`) — 設定裁剪塊的重疊程度。在第一個裁剪層中,裁剪塊將按影像長度的這個比例重疊。後面具有更多裁剪塊的層會相應縮小此重疊。
  • crop_n_points_downscale_factor (int可選,預設為 1) — 第 n 層中每邊取樣的點數將按 crop_n_points_downscale_factor**n 的比例縮小。
  • timeout (float可選,預設為 None) — 從網頁獲取圖片的最長等待時間(秒)。如果為 None,則不設定超時,呼叫可能會永遠阻塞。

返回

字典

一個包含以下鍵的字典:

  • mask (PIL.Image) — 檢測到的物體的二進位制掩碼,形式為與原始影像形狀相同的 PIL 影像 (width, height)。如果未找到物體,則返回一個填充為零的掩碼。
  • score (可選 float) — 可選。當模型能夠估算由標籤和掩碼描述的“物體”的置信度時提供。

生成二進位制分割掩碼

VisualQuestionAnsweringPipeline

class transformers.VisualQuestionAnsweringPipeline

< >

( *args **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將被 pipeline 用來進行預測的模型。對於 PyTorch,該模型需要繼承自 PreTrainedModel;對於 TensorFlow,則需要繼承自 TFPreTrainedModel
  • tokenizer (PreTrainedTokenizer) — 將被 pipeline 用來為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • image_processor (BaseImageProcessor) — 將被 pipeline 用來為模型編碼資料的影像處理器。該物件繼承自 BaseImageProcessor
  • modelcard (str or ModelCard可選) — 歸屬於此 pipeline 模型的模型卡。
  • framework (str可選) — 要使用的框架,"pt" 表示 PyTorch,"tf" 表示 TensorFlow。指定的框架必須已安裝。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩種框架都已安裝,將預設為 model 的框架,或者在未提供模型時預設為 PyTorch。

  • task (str,預設為 "") — pipeline 的任務識別符號。
  • num_workers (int可選,預設為 8) — 當 pipeline 使用 DataLoader(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的工作程序數。
  • batch_size (int可選,預設為 1) — 當 pipeline 使用 DataLoader(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的批處理大小。對於推理,這並不總是有益的,請閱讀 使用 pipeline 進行批處理
  • args_parser (ArgumentHandler可選) — 負責解析提供的 pipeline 引數的物件的引用。
  • device (int可選,預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 id 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool可選,預設為 False) — 指示 pipeline 的輸出是否應以序列化格式(即 pickle)進行,或作為原始輸出資料(例如文字)。

使用 AutoModelForVisualQuestionAnswering 的視覺問答 pipeline。此 pipeline 目前僅在 PyTorch 中可用。

除非您使用的模型在其配置檔案(generation_config.json)中明確設定了這些生成引數,否則將使用以下預設值:

  • max_new_tokens: 256

示例

>>> from transformers import pipeline

>>> oracle = pipeline(model="dandelin/vilt-b32-finetuned-vqa")
>>> image_url = "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/lena.png"
>>> oracle(question="What is she wearing ?", image=image_url)
[{'score': 0.948, 'answer': 'hat'}, {'score': 0.009, 'answer': 'fedora'}, {'score': 0.003, 'answer': 'clothes'}, {'score': 0.003, 'answer': 'sun hat'}, {'score': 0.002, 'answer': 'nothing'}]

>>> oracle(question="What is she wearing ?", image=image_url, top_k=1)
[{'score': 0.948, 'answer': 'hat'}]

>>> oracle(question="Is this a person ?", image=image_url, top_k=1)
[{'score': 0.993, 'answer': 'yes'}]

>>> oracle(question="Is this a man ?", image=image_url, top_k=1)
[{'score': 0.996, 'answer': 'no'}]

流水線教程中瞭解有關使用流水線基礎知識的更多資訊。

這個視覺問答 pipeline 目前可以透過使用以下任務識別符號從 pipeline() 載入:"visual-question-answering", "vqa"

此 pipeline 可以使用的模型是那些在視覺問答任務上進行過微調的模型。請在 huggingface.co/models 上檢視最新的可用模型列表。

__call__

< >

( image: typing.Union[ForwardRef('Image.Image'), str, list['Image.Image'], list[str], ForwardRef('KeyDataset')] question: typing.Union[str, list[str], NoneType] = None **kwargs ) 包含結果的字典或字典列表。字典包含以下鍵

引數

  • image (str, list[str], PIL.Image, list[PIL.Image] or KeyDataset) — pipeline 處理三種類型的影像:

    • 包含指向影像的 http 連結的字串
    • 包含本地影像路徑的字串
    • 直接載入到 PIL 中的影像

    pipeline 接受單個影像或一批影像。如果給定單個影像,它可以廣播到多個問題。對於資料集:傳入的資料集必須是 transformers.pipelines.pt_utils.KeyDataset 型別。例如:

返回

包含結果的字典或字典列表。字典包含以下鍵

  • label (str) — 模型識別的標籤。
  • score (int) — 模型為該標籤賦予的分數。

回答關於影像的開放式問題。pipeline 接受多種型別的輸入,詳情如下

  • pipeline(image=image, question=question)
  • pipeline({"image": image, "question": question})
  • pipeline([{"image": image, "question": question}])
  • pipeline([{"image": image, "question": question}, {"image": image, "question": question}])

父類:Pipeline

class transformers.Pipeline

< >

( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )

引數

  • model (PreTrainedModel or TFPreTrainedModel) — 將被 pipeline 用來進行預測的模型。對於 PyTorch,該模型需要繼承自 PreTrainedModel;對於 TensorFlow,則需要繼承自 TFPreTrainedModel
  • tokenizer (PreTrainedTokenizer) — 將被 pipeline 用來為模型編碼資料的分詞器。該物件繼承自 PreTrainedTokenizer
  • feature_extractor (SequenceFeatureExtractor) — 將被 pipeline 用來為模型編碼資料的特徵提取器。該物件繼承自 SequenceFeatureExtractor
  • image_processor (BaseImageProcessor) — 將被 pipeline 用來為模型編碼資料的影像處理器。該物件繼承自 BaseImageProcessor
  • processor (ProcessorMixin) — 將被 pipeline 用來為模型編碼資料的處理器。該物件繼承自 ProcessorMixin。處理器是一個複合物件,可能包含 tokenizerfeature_extractorimage_processor
  • modelcard (str or ModelCard可選) — 歸屬於此 pipeline 模型的模型卡。
  • framework (str可選) — 要使用的框架,"pt" 表示 PyTorch,"tf" 表示 TensorFlow。指定的框架必須已安裝。

    如果未指定框架,將預設為當前安裝的框架。如果未指定框架且兩種框架都已安裝,將預設為 model 的框架,或者在未提供模型時預設為 PyTorch。

  • task (str,預設為 "") — pipeline 的任務識別符號。
  • num_workers (int可選,預設為 8) — 當 pipeline 使用 DataLoader(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的工作程序數。
  • batch_size (int可選,預設為 1) — 當 pipeline 使用 DataLoader(當傳遞資料集,在 GPU 上使用 Pytorch 模型時),要使用的批處理大小。對於推理,這並不總是有益的,請閱讀 使用 pipeline 進行批處理
  • args_parser (ArgumentHandler可選) — 負責解析提供的 pipeline 引數的物件的引用。
  • device (int可選,預設為 -1) — 用於 CPU/GPU 支援的裝置序號。將其設定為 -1 將使用 CPU,正數將在相應的 CUDA 裝置 id 上執行模型。您也可以傳遞原生的 torch.devicestr
  • torch_dtype (str or torch.dtype可選) — 直接作為 model_kwargs 傳送(只是一個更簡單的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16 等或 "auto")。
  • binary_output (bool可選,預設為 False) — 指示 pipeline 的輸出是否應以序列化格式(即 pickle)進行,或作為原始輸出資料(例如文字)。

Pipeline 類是所有 pipeline 繼承的基類。有關不同 pipeline 共享的方法,請參考此類。

實現流水線操作的基類。Pipeline 的工作流程定義為以下操作序列

輸入 -> 分詞 -> 模型推理 -> 後處理 (依賴於任務) -> 輸出

Pipeline 透過 device 引數支援在 CPU 或 GPU 上執行(見下文)。

某些 pipeline,例如 FeatureExtractionPipeline ('feature-extraction'),會以巢狀列表的形式輸出大型張量物件。為避免將如此大的結構作為文字資料轉儲,我們提供了 binary_output 建構函式引數。如果設定為 True,輸出將以 pickle 格式儲存。

check_model_type

< >

( supported_models: typing.Union[list[str], dict] )

引數

  • supported_models (list[str] or dict) — pipeline 支援的模型列表,或帶有模型類值的字典。

檢查模型類是否受 pipeline 支援。

device_placement

< >

( )

上下文管理器,以框架無關的方式允許在使用者指定的裝置上分配張量。

示例

# Explicitly ask for tensor allocation on CUDA device :0
pipe = pipeline(..., device=0)
with pipe.device_placement():
    # Every framework specific tensor allocation will be done on the request device
    output = pipe(...)

ensure_tensor_on_device

< >

( **inputs ) dict[str, torch.Tensor]

引數

  • inputs (應為 torch.Tensor 的關鍵字引數,其餘將被忽略) — 要放置在 self.device 上的張量。
  • Recursive 對列表有效。—

返回

dict[str, torch.Tensor]

inputs 相同,但在正確的裝置上。

確保 PyTorch 張量在指定的裝置上。

postprocess

< >

( model_outputs: ModelOutput **postprocess_parameters: dict )

後處理將接收 _forward 方法的原始輸出(通常是張量),並將其重新格式化為更友好的形式。通常它會輸出一個結果列表或字典(僅包含字串和數字)。

predict

< >

( X )

Scikit / Keras 介面,用於 transformers 的 pipeline。此方法將轉發到 call()。

preprocess

< >

( input_: typing.Any **preprocess_parameters: dict )

預處理將接收特定 pipeline 的 `input_`,並返回一個包含所有 `_forward` 正常執行所需內容的字典。它應至少包含一個張量,但可能包含任意其他項。

push_to_hub

< >

( repo_id: str use_temp_dir: typing.Optional[bool] = None commit_message: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None max_shard_size: typing.Union[str, int, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: typing.Optional[str] = None commit_description: typing.Optional[str] = None tags: typing.Optional[list[str]] = None **deprecated_kwargs )

引數

  • repo_id (str) — 您想要將 pipeline 推送到的儲存庫的名稱。在推送到給定組織時,它應包含您的組織名稱。
  • use_temp_dir (bool可選) — 是否使用臨時目錄儲存儲存的檔案,然後再推送到 Hub。如果不存在名為 repo_id 的目錄,則預設為 True,否則為 False
  • commit_message (str, optional) — 推送時要提交的訊息。預設為 "Upload pipe"
  • private (bool, optional) — 是否將倉庫設為私有。如果為 None(預設值),倉庫將是公開的,除非組織的預設設定是私有。如果倉庫已存在,則此值將被忽略。
  • token (bool or str, optional) — 用作遠端檔案 HTTP bearer 授權的 token。如果為 True,將使用執行 huggingface-cli login 時生成的 token(儲存在 ~/.huggingface 中)。如果未指定 repo_url,則預設為 True
  • max_shard_size (int or str, optional, defaults to "5GB") — 僅適用於模型。檢查點在分片之前的最大大小。檢查點分片的大小將小於此大小。如果表示為字串,則需要是數字後跟一個單位(如 "5MB")。我們預設為 "5GB",以便使用者可以在免費的 Google Colab 例項上輕鬆載入模型,而不會出現任何 CPU OOM 問題。
  • create_pr (bool, optional, defaults to False) — 是否為上傳的檔案建立一個 PR(拉取請求)或直接提交。
  • safe_serialization (bool, optional, defaults to True) — 是否將模型權重轉換為 safetensors 格式以進行更安全的序列化。
  • revision (str, optional) — 要將上傳檔案推送到的分支。
  • commit_description (str, optional) — 將要建立的提交的描述
  • tags (list[str], optional) — 要推送到 Hub 的標籤列表。

將 pipeline 檔案上傳到 🤗 Model Hub。

示例

from transformers import pipeline

pipe = pipeline("google-bert/bert-base-cased")

# Push the pipe to your namespace with the name "my-finetuned-bert".
pipe.push_to_hub("my-finetuned-bert")

# Push the pipe to an organization with the name "my-finetuned-bert".
pipe.push_to_hub("huggingface/my-finetuned-bert")

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] safe_serialization: bool = True **kwargs )

引數

  • save_directory (str or os.PathLike) — 要儲存到的目錄路徑。如果不存在,則會建立該目錄。
  • safe_serialization (str) — 是使用 safetensors 還是傳統的 PyTorch 或 Tensorflow 方式儲存模型。
  • kwargs (dict[str, Any], optional) — 傳遞給 push_to_hub() 方法的附加關鍵字引數。

儲存 pipeline 的模型和 tokenizer。

transform

< >

( X )

Scikit / Keras 介面,用於 transformers 的 pipeline。此方法將轉發到 call()。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.