# Pipeline

[Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) là một API suy luận đơn giản nhưng mạnh mẽ, có sẵn cho nhiều tác vụ học máy khác nhau với bất kỳ mô hình nào từ [Hub](https://hf.co/models) của Hugging Face.

Tùy chỉnh [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) cho tác vụ của bạn bằng các tham số cụ thể cho từng tác vụ, chẳng hạn như thêm dấu thời gian vào pipeline nhận dạng giọng nói tự động (ASR) để chuyển văn bản ghi chú cuộc họp. [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) hỗ trợ GPU, Apple Silicon và trọng số độ chính xác nửa (half-precision) để tăng tốc suy luận và tiết kiệm bộ nhớ.

Transformers có hai lớp pipeline, một lớp [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) tổng quát và nhiều pipeline riêng cho từng tác vụ cụ thể như [TextGenerationPipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.TextGenerationPipeline). Hãy nạp các pipeline riêng này bằng cách đặt bộ định danh tác vụ trong tham số `task` của [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline). Bạn có thể tìm thấy bộ định danh tác vụ cho từng pipeline trong tài liệu API của chúng.

Mỗi tác vụ được cấu hình để sử dụng một mô hình và bộ tiền xử lý được huấn luyện trước mặc định, nhưng bạn có thể ghi đè điều này bằng tham số `model` nếu muốn sử dụng một mô hình khác.

Ví dụ, để sử dụng [TextGenerationPipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.TextGenerationPipeline) với [Gemma 2](./model_doc/gemma2), hãy đặt `task="text-generation"` và `model="google/gemma-2-2b"`.

```py
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="google/gemma-2-2b")
pipeline("the secret to baking a really good cake is ")
[{'generated_text': 'the secret to baking a really good cake is 1. the right ingredients 2. the'}]
```

Khi bạn có nhiều hơn một đầu vào, hãy truyền chúng dưới dạng một danh sách.

```py
from transformers import pipeline
from accelerate import Accelerator

device = Accelerator().device

pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device=device)
pipeline(["the secret to baking a really good cake is ", "a baguette is "])
[[{'generated_text': 'the secret to baking a really good cake is 1. the right ingredients 2. the'}],
 [{'generated_text': 'a baguette is 100% bread.\n\na baguette is 100%'}]]
```

Hướng dẫn này sẽ giới thiệu cho bạn về [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline), trình bày các tính năng của nó và cho thấy cách cấu hình các tham số khác nhau.

## Nhiệm vụ

[Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) tương thích với nhiều tác vụ học máy trên các phương thức khác nhau. Truyền vào pipeline một đầu vào phù hợp và nó sẽ xử lý phần còn lại.

Dưới đây là một số ví dụ về cách sử dụng [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) cho các tác vụ và chế độ dữ liệu khác nhau.

```py
from transformers import pipeline

pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
pipeline("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.'}
```

```py
from transformers import pipeline

pipeline = pipeline(task="image-classification", model="google/vit-base-patch16-224")
pipeline(images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
[{'label': 'lynx, catamount', 'score': 0.43350091576576233},
 {'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
  'score': 0.034796204417943954},
 {'label': 'snow leopard, ounce, Panthera uncia',
  'score': 0.03240183740854263},
 {'label': 'Egyptian cat', 'score': 0.02394474856555462},
 {'label': 'tiger cat', 'score': 0.02288915030658245}]
```

```py
from transformers import pipeline

pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
pipeline(
    image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
    question="What is in the image?",
)
[{'answer': 'statue of liberty'}]
```

## Tham số

Tối thiểu, [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) chỉ yêu cầu một định danh tác vụ, mô hình và đầu vào phù hợp. Tuy nhiên, có nhiều tham số có sẵn để cấu hình pipeline, từ các tham số cụ thể cho từng tác vụ đến tối ưu hóa hiệu suất.

Phần này giới thiệu với bạn một số tham số quan trọng hơn.

### Thiết bị

[Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) tương thích với nhiều loại phần cứng, bao gồm GPU, CPU, Apple Silicon và nhiều hơn nữa. Cấu hình loại phần cứng bằng tham số `device`. Mặc định, khi `device` không được đặt, [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) tự động đặt mô hình lên bộ tăng tốc đầu tiên khả dụng (GPU CUDA, Apple Silicon MPS, XPU, ...) và chỉ chuyển sang CPU khi không có bộ tăng tốc nào khả dụng. Truyền `device="cpu"` để buộc chạy trên CPU.

Để chạy [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) trên GPU, hãy đặt `device` thành id thiết bị CUDA tương ứng. Ví dụ, `device=0` sẽ chạy trên GPU đầu tiên.

```py
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device=0)
pipeline("the secret to baking a really good cake is ")
```

Bạn cũng có thể để [Accelerate](https://hf.co/docs/accelerate/index), một thư viện cho huấn luyện phân tán, tự động chọn cách tải và lưu trữ trọng số mô hình trên thiết bị phù hợp. Điều này đặc biệt hữu ích nếu bạn có nhiều thiết bị. Accelerate sẽ tải và lưu trữ trọng số mô hình trên thiết bị nhanh nhất trước, sau đó di chuyển trọng số sang các thiết bị khác (CPU, ổ cứng) khi cần. Đặt `device_map="auto"` để Accelerate chọn thiết bị.

> [!TIP]
> Hãy đảm bảo rằng [Accelerate](https://hf.co/docs/accelerate/basic_tutorials/install) đã được cài đặt.
>
> ```py
> !pip install -U accelerate
> ```

```py
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device_map="auto")
pipeline("the secret to baking a really good cake is ")
```

Để chạy [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) trên Apple silicon, hãy đặt `device="mps"`.

```py
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device="mps")
pipeline("the secret to baking a really good cake is ")
```

### Suy luận theo lô

[Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) cũng có thể xử lý các lô đầu vào với tham số `batch_size`. Suy luận theo lô có thể cải thiện tốc độ, đặc biệt là trên GPU, nhưng không được đảm bảo. Các biến khác như phần cứng, dữ liệu và chính mô hình có thể ảnh hưởng đến việc suy luận theo lô có cải thiện tốc độ hay không. Vì lý do này, suy luận theo lô bị tắt theo mặc định.

Trong ví dụ dưới đây, khi có 4 đầu vào và `batch_size` được đặt thành 2, [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) sẽ truyền một lô gồm 2 đầu vào cho mô hình mỗi lần.

```py
from transformers import pipeline
from accelerate import Accelerator

device = Accelerator().device

pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device=device, batch_size=2)
pipeline(["the secret to baking a really good cake is", "a baguette is", "paris is the", "hotdogs are"])
[[{'generated_text': 'the secret to baking a really good cake is to use a good cake mix.\n\ni’'}],
 [{'generated_text': 'a baguette is'}],
 [{'generated_text': 'paris is the most beautiful city in the world.\n\ni’ve been to paris 3'}],
 [{'generated_text': 'hotdogs are a staple of the american diet. they are a great source of protein and can'}]]
```

Một trường hợp sử dụng tốt khác của suy luận theo lô là cho dữ liệu dạng luồng trong [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline).

```py
from transformers import pipeline
from accelerate import Accelerator
from transformers.pipelines.pt_utils import KeyDataset
import datasets

device = Accelerator().device

# KeyDataset is a utility that returns the item in the dict returned by the dataset
dataset = load_dataset("stanfordnlp/imdb", name="plain_text", split="unsupervised")
pipeline = pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", device=device)
for out in pipeline(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"):
    print(out)
```

Hãy ghi nhớ các nguyên tắc chung sau đây khi xác định xem suy luận theo lô (batch inference) có thể giúp cải thiện hiệu suất hay không.

1. Cách duy nhất để chắc chắn là đo hiệu suất trên mô hình, dữ liệu và phần cứng của bạn.
2. Không nên thực hiện suy luận theo lô (batch inference) nếu bạn bị ràng buộc bởi độ trễ (ví dụ: một sản phẩm suy luận trực tiếp).
3. Không thực hiện suy luận theo lô (batch inference) nếu bạn đang sử dụng CPU.
4. Không nên thực hiện suy luận theo lô (batch inference) nếu bạn không biết `sequence_length` của dữ liệu. Hãy đo lường hiệu suất, tăng dần `sequence_length` và bao gồm các kiểm tra hết bộ nhớ (OOM) để khôi phục sau các sự cố.
5. Thực hiện suy luận theo lô (batch inference) nếu `sequence_length` của bạn đều đặn, và tiếp tục tăng kích thước lô cho đến khi gặp lỗi OOM. GPU càng lớn thì suy luận theo lô càng hữu ích.
6. Hãy đảm bảo bạn có thể xử lý các lỗi OOM nếu bạn quyết định thực hiện suy luận theo lô (batch inference).

### Tham số cụ thể cho tác vụ

[Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) chấp nhận bất kỳ tham số nào được hỗ trợ bởi từng pipeline tác vụ riêng lẻ. Hãy kiểm tra từng pipeline tác vụ để xem loại tham số nào có sẵn. Nếu bạn không tìm thấy tham số hữu ích cho trường hợp sử dụng của mình, hãy thoải mái mở một [issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml) trên GitHub để yêu cầu!

Các ví dụ dưới đây minh họa một số tham số dành riêng cho từng tác vụ có sẵn.

Truyền tham số `return_timestamps="word"` vào [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) để trả về thời điểm mỗi từ được phát ra.

```py
from transformers import pipeline

pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
pipeline(audio="https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac", return_timestamps="word")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.',
 'chunks': [{'text': ' I', 'timestamp': (0.0, 1.1)},
  {'text': ' have', 'timestamp': (1.1, 1.44)},
  {'text': ' a', 'timestamp': (1.44, 1.62)},
  {'text': ' dream', 'timestamp': (1.62, 1.92)},
  {'text': ' that', 'timestamp': (1.92, 3.7)},
  {'text': ' one', 'timestamp': (3.7, 3.88)},
  {'text': ' day', 'timestamp': (3.88, 4.24)},
  {'text': ' this', 'timestamp': (4.24, 5.82)},
  {'text': ' nation', 'timestamp': (5.82, 6.78)},
  {'text': ' will', 'timestamp': (6.78, 7.36)},
  {'text': ' rise', 'timestamp': (7.36, 7.88)},
  {'text': ' up', 'timestamp': (7.88, 8.46)},
  {'text': ' and', 'timestamp': (8.46, 9.2)},
  {'text': ' live', 'timestamp': (9.2, 10.34)},
  {'text': ' out', 'timestamp': (10.34, 10.58)},
  {'text': ' the', 'timestamp': (10.58, 10.8)},
  {'text': ' true', 'timestamp': (10.8, 11.04)},
  {'text': ' meaning', 'timestamp': (11.04, 11.4)},
  {'text': ' of', 'timestamp': (11.4, 11.64)},
  {'text': ' its', 'timestamp': (11.64, 11.8)},
  {'text': ' creed.', 'timestamp': (11.8, 12.3)}]}
```

Truyền `return_full_text=False` vào [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) để chỉ trả về văn bản được tạo ra thay vì toàn bộ văn bản (prompt và văn bản được tạo ra).

[__call__()](/docs/transformers/main/vi/main_classes/pipelines#transformers.TextGenerationPipeline.__call__) cũng hỗ trợ các đối số từ khóa bổ sung từ phương thức [generate()](/docs/transformers/main/vi/main_classes/text_generation#transformers.GenerationMixin.generate). Để trả về nhiều hơn một chuỗi được tạo, hãy đặt `num_return_sequences` thành một giá trị lớn hơn 1.

```py
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="openai-community/gpt2")
pipeline("the secret to baking a good cake is", num_return_sequences=4, return_full_text=False)
[{'generated_text': ' how easy it is for me to do it with my hands. You must not go nuts, or the cake is going to fall out.'},
 {'generated_text': ' to prepare the cake before baking. The key is to find the right type of icing to use and that icing makes an amazing frosting cake.\n\nFor a good icing cake, we give you the basics'},
 {'generated_text': " to remember to soak it in enough water and don't worry about it sticking to the wall. In the meantime, you could remove the top of the cake and let it dry out with a paper towel.\n"},
 {'generated_text': ' the best time to turn off the oven and let it stand 30 minutes. After 30 minutes, stir and bake a cake in a pan until fully moist.\n\nRemove the cake from the heat for about 12'}]
```

## Gom nhóm theo chunk

Có một số trường hợp bạn cần xử lý dữ liệu theo từng khối.

- đối với một số kiểu dữ liệu, một đầu vào duy nhất (ví dụ, một tệp âm thanh rất dài) có thể cần được chia thành nhiều phần trước khi có thể được xử lý
- đối với một số tác vụ, như phân loại zero-shot hoặc trả lời câu hỏi, một đầu vào duy nhất có thể cần nhiều lần truyền tiến (forward pass), điều này có thể gây ra vấn đề với tham số `batch_size`

Lớp [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) được thiết kế để xử lý các trường hợp sử dụng này. Cả hai lớp pipeline đều được sử dụng theo cùng một cách, nhưng vì [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) có thể tự động xử lý batching, bạn không cần lo lắng về số lần truyền tiến mà các đầu vào của bạn kích hoạt. Thay vào đó, bạn có thể tối ưu hóa `batch_size` độc lập với các đầu vào.

Ví dụ dưới đây cho thấy cách nó khác với [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline).

```py
# ChunkPipeline
all_model_outputs = []
for preprocessed in pipeline.preprocess(inputs):
    model_outputs = pipeline.model_forward(preprocessed)
    all_model_outputs.append(model_outputs)
outputs =pipeline.postprocess(all_model_outputs)

# Pipeline
preprocessed = pipeline.preprocess(inputs)
model_outputs = pipeline.forward(preprocessed)
outputs = pipeline.postprocess(model_outputs)
```

## Bộ dữ liệu lớn

Để suy luận với các bộ dữ liệu lớn, bạn có thể lặp trực tiếp trên chính bộ dữ liệu. Cách này tránh việc cấp phát bộ nhớ ngay lập tức cho toàn bộ bộ dữ liệu, và bạn không cần phải lo lắng về việc tự tạo các lô (batch). Hãy thử [Suy luận theo lô](#batch-inference) với tham số `batch_size` để xem liệu nó có cải thiện hiệu suất hay không.

```py
from transformers.pipelines.pt_utils import KeyDataset
from transformers import pipeline
from accelerate import Accelerator
from datasets import load_dataset

device = Accelerator().device

dataset = load_dataset("stanfordnlp/imdb", name="plain_text", split="unsupervised")
pipeline = pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", device=device)
for out in pipeline(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"):
    print(out)
```

Các cách khác để chạy suy luận trên các bộ dữ liệu lớn với [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) bao gồm việc sử dụng một trình lặp hoặc trình tạo.

```py
def data():
    for i in range(1000):
        yield f"My example {i}"

pipeline = pipeline(model="openai-community/gpt2", device=0)
generated_characters = 0
for out in pipeline(data()):
    generated_characters += len(out[0]["generated_text"])
```

## Các mô hình lớn

[Accelerate](https://hf.co/docs/accelerate/index) cho phép một số tối ưu hóa để chạy các mô hình lớn với [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline). Hãy đảm bảo rằng Accelerate đã được cài đặt trước.

```py
!pip install -U accelerate
```

Cài đặt `device_map="auto"` hữu ích để tự động phân phối mô hình lên các thiết bị nhanh nhất (GPU) trước, sau đó mới chuyển sang các thiết bị chậm hơn nếu có (CPU, ổ cứng).

[Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) hỗ trợ trọng số độ chính xác nửa (torch.float16), có thể nhanh hơn đáng kể và tiết kiệm bộ nhớ. Mất hiệu suất là không đáng kể đối với hầu hết các mô hình, đặc biệt là các mô hình lớn hơn. Nếu phần cứng của bạn hỗ trợ, bạn có thể bật torch.bfloat16 thay thế để có phạm vi rộng hơn.

> [!TIP]
> Inputs được chuyển đổi nội bộ sang torch.float16 và chỉ hoạt động với các model có backend PyTorch.

Cuối cùng, [Pipeline](/docs/transformers/main/vi/main_classes/pipelines#transformers.Pipeline) cũng chấp nhận các mô hình đã lượng tử hóa để giảm thêm mức sử dụng bộ nhớ. Hãy đảm bảo bạn đã cài đặt thư viện [bitsandbytes](https://hf.co/docs/bitsandbytes/installation) trước, sau đó thêm `quantization_config` vào `model_kwargs` trong pipeline.

```py
import torch
from transformers import pipeline, BitsAndBytesConfig

pipeline = pipeline(model="google/gemma-7b", dtype=torch.bfloat16, device_map="auto", model_kwargs={"quantization_config": BitsAndBytesConfig(load_in_8bit=True)})
pipeline("the secret to baking a good cake is ")
[{'generated_text': 'the secret to baking a good cake is 1. the right ingredients 2. the right'}]
```

