Transformers.js 文件

pipeline API

您正在檢視的是需要從原始碼安裝。如果您想使用常規的 npm install,請檢視最新的穩定版本 (v3.0.0)。
Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

pipeline API

就像 transformers Python 庫一樣,Transformers.js 為使用者提供了一種利用 transformers 強大功能的簡單方法。pipeline() 函式是使用預訓練模型進行推理的最簡單、最快捷的方式。

要檢視可用任務/pipeline 的完整列表,請檢視此表格

基礎知識

首先,建立一個 pipeline() 例項並指定要使用的任務。例如,要建立一個情感分析 pipeline,您可以這樣做:

import { pipeline } from '@huggingface/transformers';

const classifier = await pipeline('sentiment-analysis');

首次執行時,pipeline 將下載並快取與該任務關聯的預設預訓練模型。這可能需要一些時間,但後續呼叫會快得多。

預設情況下,模型將從 Hugging Face Hub 下載並存儲在瀏覽器快取中,但也有方法可以指定自定義模型和快取位置。有關更多資訊,請參閱此處

現在,您可以透過將分類器作為函式呼叫來對目標文字進行處理:

const result = await classifier('I love transformers!');
// [{'label': 'POSITIVE', 'score': 0.9998}]

如果您有多個輸入,可以將其作為陣列傳遞:

const result = await classifier(['I love transformers!', 'I hate transformers!']);
// [{'label': 'POSITIVE', 'score': 0.9998}, {'label': 'NEGATIVE', 'score': 0.9982}]

您還可以透過將模型作為第二個引數傳遞給 pipeline() 函式來指定用於 pipeline 的不同模型。例如,要為情感分析使用不同的模型(比如一個被訓練用來預測評論情感作為1到5星級評分的模型),您可以這樣做:

const reviewer = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');

const result = await reviewer('The Shawshank Redemption is a true masterpiece of cinema.');
// [{label: '5 stars', score: 0.8167929649353027}]

Transformers.js 支援載入 Hugging Face Hub 上託管的任何模型,只要它具有 ONNX 權重(位於名為 onnx 的子資料夾中)。有關如何將您的 PyTorch、TensorFlow 或 JAX 模型轉換為 ONNX 的更多資訊,請參閱轉換部分

pipeline() 函式是快速使用預訓練模型進行推理的好方法,因為它為您處理了所有的預處理和後處理工作。例如,如果您想使用 OpenAI 的 Whisper 模型進行自動語音識別 (ASR),您可以這樣做:

// Create a pipeline for Automatic Speech Recognition
const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small.en');

// Transcribe an audio file, loaded from a URL.
const result = await transcriber('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac');
// {text: ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}

Pipeline 選項

載入

我們提供了多種選項來控制如何從 Hugging Face Hub(或本地)載入模型。預設情況下,在瀏覽器中執行時,會使用模型的*量化*版本,它更小更快,但通常精度較低。要覆蓋此行為(即使用未量化的模型),您可以將自定義的 PretrainedOptions 物件作為第三個引數傳遞給 pipeline 函式:

// Create a pipeline for feature extraction, using the full-precision model (fp32)
const pipe = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2', {
    dtype: "fp32",
});

請檢視關於量化的部分以瞭解更多資訊。

您還可以透過傳遞 revision 引數來指定要使用的模型版本。由於 Hugging Face Hub 使用基於 git 的版本控制系統,您可以使用任何有效的 git 版本說明符(例如,分支名稱或提交雜湊)。

const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en', {
    revision: 'output_attentions',
});

有關選項的完整列表,請檢視 PretrainedOptions 文件。

執行

許多 pipeline 都有可以指定的附加選項。例如,當使用支援多語言翻譯的模型時,您可以像這樣指定源語言和目標語言:

// Create a pipeline for translation
const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');

// Translate from English to Greek
const result = await translator('I like to walk my dog.', {
    src_lang: 'eng_Latn',
    tgt_lang: 'ell_Grek'
});
// [ { translation_text: 'Μου αρέσει να περπατάω το σκυλί μου.' } ]

// Translate back to English
const result2 = await translator(result[0].translation_text, {
    src_lang: 'ell_Grek',
    tgt_lang: 'eng_Latn'
});
// [ { translation_text: 'I like to walk my dog.' } ]

當使用支援自迴歸生成的模型時,您可以指定生成引數,如新詞元數量、取樣方法、溫度、重複懲罰等等。有關可用引數的完整列表,請參閱 GenerationConfig 類。

例如,要使用 LaMini-Flan-T5-783M 生成一首詩,您可以這樣做:

// Create a pipeline for text2text-generation
const poet = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');
const result = await poet('Write me a love poem about cheese.', {
    max_new_tokens: 200,
    temperature: 0.9,
    repetition_penalty: 2.0,
    no_repeat_ngram_size: 3,
});

result[0].generated_text 列印到控制檯,得到:

Cheese, oh cheese! You're the perfect comfort food.
Your texture so smooth and creamy you can never get old.
With every bite it melts in your mouth like buttery delights
that make me feel right at home with this sweet treat of mine. 

From classic to bold flavor combinations,
I love how versatile you are as an ingredient too?
Cheddar is my go-to for any occasion or mood; 
It adds depth and richness without being overpowering its taste buds alone

流式處理

一些 pipeline 如 text-generationautomatic-speech-recognition 支援流式輸出。這是透過 TextStreamer 類實現的。例如,當使用像 Qwen2.5-Coder-0.5B-Instruct 這樣的聊天模型時,您可以指定一個回撥函式,該函式將針對每個生成的詞元文字被呼叫(如果未設定,新詞元將被列印到控制檯)。

import { pipeline, TextStreamer } from "@huggingface/transformers";

// Create a text generation pipeline
const generator = await pipeline(
  "text-generation",
  "onnx-community/Qwen2.5-Coder-0.5B-Instruct",
  { dtype: "q4" },
);

// Define the list of messages
const messages = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content:  "Write a quick sort algorithm." },
];

// Create text streamer
const streamer = new TextStreamer(generator.tokenizer, {
  skip_prompt: true,
  // Optionally, do something with the text (e.g., write to a textbox)
  // callback_function: (text) => { /* Do something with text */ },
})

// Generate a response
const result = await generator(messages, { max_new_tokens: 512, do_sample: false, streamer });

result[0].generated_text 列印到控制檯,得到:

點選檢視控制檯輸出
Here's a simple implementation of the quick sort algorithm in Python:
```python
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)
# Example usage:
arr = [3, 6, 8, 10, 1, 2]
sorted_arr = quick_sort(arr)
print(sorted_arr)
```
### Explanation:
- **Base Case**: If the array has less than or equal to one element (i.e., `len(arr)` is less than or equal to `1`), it is already sorted and can be returned as is.
- **Pivot Selection**: The pivot is chosen as the middle element of the array.
- **Partitioning**: The array is partitioned into three parts: elements less than the pivot (`left`), elements equal to the pivot (`middle`), and elements greater than the pivot (`right`). These partitions are then recursively sorted.
- **Recursive Sorting**: The subarrays are sorted recursively using `quick_sort`.
This approach ensures that each recursive call reduces the problem size by half until it reaches a base case.

這種流式功能允許您在生成輸出時對其進行處理,而不是等待整個輸出生成完畢後再進行處理。

有關每個 pipeline 可用選項的更多資訊,請參閱 API 參考。如果您希望對推理過程有更多控制,可以使用 AutoModelAutoTokenizerAutoProcessor 類。

可用任務

任務

自然語言處理

任務 ID 描述 支援?
填充掩碼 fill-mask 掩蓋句子中的某些詞,並預測應該用哪些詞來替換這些掩碼。 (文件)
(模型)
問答 問題回答 從給定文字中檢索問題的答案。 (文件)
(模型)
句子相似度 sentence-similarity 判斷兩個文字的相似程度。 (文件)
(模型)
摘要 摘要 在保留重要資訊的同時,生成文件的較短版本。 (文件)
(模型)
表格問答 table-question-answering 回答關於給定表格資訊的問題。
文字分類 text-classificationsentiment-analysis 為給定的文字分配一個標籤或類別。 (文件)
(模型)
文字生成 文字生成 透過預測序列中的下一個詞來生成新文字。 (文件)
(模型)
文字到文字生成 text2text-generation 將一個文字序列轉換為另一個文字序列。 (文件)
(模型)
Token 分類 token-classificationner 為文字中的每個詞元分配一個標籤。 (文件)
(模型)
翻譯 翻譯 將文字從一種語言翻譯成另一種語言。 (文件)
(模型)
零樣本分類 zero-shot-classification 將文字分類到訓練期間未見過的類別中。 (文件)
(模型)
特徵提取 feature-extraction 將原始資料轉換為可以處理的數值特徵,同時保留原始資料集中的資訊。 (文件)
(模型)

視覺

任務 ID 描述 支援?
背景移除 background-removal 透過移除或使背景透明來分離影像的主體。 (文件)
(模型)
深度估計 depth-estimation 預測影像中物體的深度。 (文件)
(模型)
影像分類 image-classification 為整個影像分配一個標籤或類別。 (文件)
(模型)
影像分割 image-segmentation 將影像分割成多個片段,其中每個畫素都對映到一個物件。此任務有多種變體,如例項分割、全景分割和語義分割。 (文件)
(模型)
影像到影像 image-to-image 將源影像轉換為匹配目標影像或目標影像域的特徵。 (文件)
(模型)
掩碼生成 mask-generation 為影像中的物件生成掩碼。
物體檢測 object-detection 在影像中識別特定定義類別的物件。 (文件)
(模型)
影片分類 不適用 為整個影片分配一個標籤或類別。
無條件影像生成 不適用 在沒有任何上下文條件(如提示文字或其他影像)的情況下生成影像。
影像特徵提取 image-feature-extraction 將原始資料轉換為可以處理的數值特徵,同時保留原始影像中的資訊。 (文件)
(模型)

音訊

任務 ID 描述 支援?
音訊分類 音訊分類 為給定的音訊分配一個標籤或類別。 (文件)
(模型)
音訊到音訊 不適用 從輸入音訊源生成音訊。
自動語音識別 自動語音識別 將給定的音訊轉錄成文字。 (文件)
(模型)
文字到語音 text-to-speechtext-to-audio 根據文字輸入生成聽起來自然的語音。 (文件)
(模型)

表格

任務 ID 描述 支援?
表格分類 不適用 根據一組屬性對目標類別(一個組)進行分類。
表格迴歸 不適用 根據一組屬性預測一個數值。

多模態

任務 ID 描述 支援?
文件問答 document-question-answering 回答文件影像上的問題。 (文件)
(模型)
影像到文字 image-to-text 從給定影像中輸出文字。 (文件)
(模型)
文字到影像 text-to-image 從輸入文字生成影像。
視覺問答 視覺問答 基於影像回答開放式問題。
零樣本音訊分類 zero-shot-audio-classification 將音訊分類到訓練期間未見過的類別中。 (文件)
(模型)
零樣本影像分類 zero-shot-image-classification 將影像分類到訓練期間未見過的類別中。 (文件)
(模型)
零樣本物件檢測 zero-shot-object-detection 識別訓練期間未見過的類別的物件。 (文件)
(模型)

強化學習

任務 ID 描述 支援?
強化學習 不適用 透過與環境互動、試錯以及接收獎勵(正面或負面)作為反饋來從行動中學習。
< > 在 GitHub 上更新

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