# Pipeline

[Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) adalah API inferensi yang sederhana namun kuat, yang dapat langsung digunakan untuk berbagai tugas machine learning dengan model apa pun dari [Hub](https://hf.co/models) Hugging Face.

Sesuaikan [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) untuk tugas Anda dengan parameter khusus tugas, seperti menambahkan timestamp ke pipeline automatic speech recognition (ASR) untuk mentranskrip catatan rapat. [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) mendukung GPU, Apple Silicon, dan bobot half-precision untuk mempercepat inferensi dan menghemat memori.

Transformers memiliki dua kelas pipeline, yaitu [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) yang bersifat umum dan banyak pipeline khusus tugas seperti [TextGenerationPipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.TextGenerationPipeline). Muat pipeline-pipeline individual ini dengan mengatur pengenal tugas pada parameter `task` di [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline). Anda dapat menemukan pengenal tugas untuk setiap pipeline di dokumentasi API mereka.

Setiap tugas dikonfigurasi untuk menggunakan model dan preprocessor pretrained bawaan, tetapi ini dapat ditimpa dengan parameter `model` jika Anda ingin menggunakan model lain.

Sebagai contoh, untuk menggunakan [TextGenerationPipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.TextGenerationPipeline) dengan [Gemma 2](./model_doc/gemma2), atur `task="text-generation"` dan `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'}]
```

Ketika Anda memiliki lebih dari satu input, berikan sebagai sebuah list.

```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%'}]]
```

Panduan ini akan memperkenalkan Anda pada [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline), mendemonstrasikan fiturnya, dan menunjukkan cara mengonfigurasi berbagai parameternya.

## Tugas

[Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) kompatibel dengan banyak tugas machine learning di berbagai modalitas. Berikan input yang sesuai ke pipeline, dan ia akan menangani sisanya.

Berikut adalah beberapa contoh cara menggunakan [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) untuk berbagai tugas dan modalitas.

```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="image-text-to-text", model="HuggingFaceTB/SmolVLM-256M-Instruct")
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg"},
            {"type": "text", "text": "What is in the image?"},
        ],
    }
]
pipeline(messages, max_new_tokens=50, return_full_text=False)
[{'input_text': [{'role': 'user', 'content': [{'type': 'image', 'image': 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg'}, {'type': 'text', 'text': 'What is in the image?'}]}],
  'generated_text': ' There is a statue in the image.'}]
```

## Parameter

Secara minimal, [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) hanya memerlukan pengidentifikasi tugas, model, dan input yang sesuai. Namun, terdapat banyak parameter yang tersedia untuk mengonfigurasi pipeline, mulai dari parameter yang spesifik untuk tugas tertentu hingga optimasi kinerja.

Bagian ini memperkenalkan beberapa parameter yang lebih penting.

### Perangkat

[Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) kompatibel dengan banyak jenis perangkat keras, termasuk GPU, CPU, Apple Silicon, dan lainnya. Konfigurasikan jenis perangkat keras dengan parameter `device`. Secara default, ketika `device` tidak disetel, [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) secara otomatis menempatkan model pada akselerator pertama yang tersedia (GPU CUDA, Apple Silicon MPS, XPU, ...) dan hanya beralih ke CPU jika tidak ada yang tersedia. Sampaikan `device="cpu"` untuk memaksanya berjalan di CPU.

Untuk menjalankan [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) pada GPU, atur `device` ke id perangkat CUDA yang terkait. Sebagai contoh, `device=0` akan dijalankan pada GPU pertama.

```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 ")
```

Anda juga dapat membiarkan [Accelerate](https://hf.co/docs/accelerate/index), sebuah pustaka untuk pelatihan terdistribusi, secara otomatis memilih cara memuat dan menyimpan bobot model pada perangkat yang sesuai. Hal ini sangat berguna jika Anda memiliki beberapa perangkat. Accelerate memuat dan menyimpan bobot model pada perangkat tercepat terlebih dahulu, lalu memindahkan bobot ke perangkat lain (CPU, hard drive) sesuai kebutuhan. Atur `device_map="auto"` agar Accelerate memilih perangkatnya.

> [!TIP]
> Pastikan [Accelerate](https://hf.co/docs/accelerate/basic_tutorials/install) sudah terinstal.
>
> ```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 ")
```

Untuk menjalankan [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) pada Apple silicon, atur `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 ")
```

### Inferensi batch

[Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) juga dapat memproses batch input dengan parameter `batch_size`. Inferensi batch dapat meningkatkan kecepatan, terutama pada GPU, tetapi tidak dijamin. Variabel lain seperti perangkat keras, data, dan model itu sendiri dapat memengaruhi apakah inferensi batch meningkatkan kecepatan. Karena alasan ini, inferensi batch dinonaktifkan secara default.

Pada contoh di bawah, ketika ada 4 input dan `batch_size` diatur ke 2, [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) meneruskan batch berisi 2 input ke model pada satu waktu.

```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'}]]
```

Kasus penggunaan lain yang baik untuk inferensi batch adalah untuk streaming data di [Pipeline](/docs/transformers/main/id/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)
```

Perhatikan aturan umum berikut untuk menentukan apakah inferensi batch dapat membantu meningkatkan kinerja.

1. Satu-satunya cara untuk memastikan adalah dengan mengukur kinerja pada model, data, dan perangkat keras Anda.
2. Jangan lakukan inferensi secara batch jika Anda dibatasi oleh latensi (misalnya, produk inferensi langsung).
3. Jangan lakukan inferensi batch jika Anda menggunakan CPU.
4. Jangan lakukan inferensi batch jika Anda tidak mengetahui `sequence_length` dari data Anda. Ukur kinerjanya, tambahkan secara iteratif ke `sequence_length`, dan sertakan pemeriksaan out-of-memory (OOM) untuk memulihkan diri dari kegagalan.
5. Lakukan batch inference jika `sequence_length` Anda teratur, dan terus tingkatkan hingga muncul error OOM. Semakin besar GPU, semakin bermanfaat batch inference.
6. Pastikan Anda dapat menangani error OOM jika Anda memutuskan untuk melakukan inferensi batch.

### Parameter khusus tugas

[Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) menerima parameter apa pun yang didukung oleh pipeline tugas individual. Pastikan untuk memeriksa setiap pipeline tugas individual untuk melihat jenis parameter apa yang tersedia. Jika Anda tidak dapat menemukan parameter yang berguna untuk kasus penggunaan Anda, silakan buka [issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml) GitHub untuk memintanya!

Contoh di bawah ini mendemonstrasikan beberapa parameter khusus tugas yang tersedia.

Lewatkan parameter `return_timestamps="word"` ke [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) untuk mengembalikan kapan setiap kata diucapkan.

```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)}]}
```

Lewati `return_full_text=False` ke [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) untuk hanya mengembalikan teks yang dihasilkan, bukan teks lengkap (prompt dan teks yang dihasilkan).

[__call__()](/docs/transformers/main/id/main_classes/pipelines#transformers.TextGenerationPipeline.__call__) juga mendukung argumen kata kunci tambahan dari metode [generate()](/docs/transformers/main/id/main_classes/text_generation#transformers.GenerationMixin.generate). Untuk mengembalikan lebih dari satu urutan yang dihasilkan, atur `num_return_sequences` ke nilai yang lebih besar dari 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'}]
```

## Batching chunk

Terdapat beberapa kasus di mana Anda perlu memproses data dalam bentuk chunk.

- untuk beberapa tipe data, satu input (misalnya, file audio yang sangat panjang) mungkin perlu dipecah menjadi beberapa bagian sebelum dapat diproses
- untuk beberapa tugas, seperti klasifikasi zero-shot atau question answering, satu input mungkin memerlukan beberapa forward pass yang dapat menyebabkan masalah dengan parameter `batch_size`

Kelas [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) dirancang untuk menangani kasus penggunaan ini. Kedua kelas pipeline digunakan dengan cara yang sama, tetapi karena [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) dapat menangani batching secara otomatis, Anda tidak perlu khawatir tentang jumlah forward pass yang dipicu oleh input Anda. Sebagai gantinya, Anda dapat mengoptimalkan `batch_size` secara independen dari input.

Contoh di bawah ini menunjukkan bagaimana perbedaannya dengan [Pipeline](/docs/transformers/main/id/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)
```

## Dataset besar

Untuk inferensi dengan dataset besar, Anda dapat mengiterasi langsung pada dataset itu sendiri. Hal ini menghindari alokasi memori untuk seluruh dataset secara langsung, dan Anda tidak perlu khawatir membuat batch sendiri. Coba [Batch inference](#batch-inference) dengan parameter `batch_size` untuk melihat apakah hal ini meningkatkan kinerja.

```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)
```

Cara lain untuk menjalankan inferensi pada dataset besar dengan [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) adalah dengan menggunakan iterator atau generator.

```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"])
```

## Model besar

[Accelerate](https://hf.co/docs/accelerate/index) memungkinkan beberapa optimasi untuk menjalankan model besar dengan [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline). Pastikan Accelerate sudah terpasang terlebih dahulu.

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

Pengaturan `device_map="auto"` berguna untuk mendistribusikan model secara otomatis ke perangkat tercepat (GPU) terlebih dahulu sebelum mengalokasikannya ke perangkat lain yang lebih lambat jika tersedia (CPU, hard drive).

[Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) mendukung bobot presisi setengah (torch.float16), yang dapat jauh lebih cepat dan menghemat memori. Penurunan kinerja dapat diabaikan untuk sebagian besar model, terutama model yang lebih besar. Jika perangkat keras Anda mendukungnya, Anda dapat mengaktifkan torch.bfloat16 sebagai gantinya untuk rentang yang lebih luas.

> [!TIP]
> Input secara internal dikonversi ke torch.float16 dan hanya berfungsi untuk model dengan backend PyTorch.

Terakhir, [Pipeline](/docs/transformers/main/id/main_classes/pipelines#transformers.Pipeline) juga menerima model terkuantisasi untuk mengurangi penggunaan memori lebih lanjut. Pastikan Anda telah menginstal pustaka [bitsandbytes](https://hf.co/docs/bitsandbytes/installation) terlebih dahulu, lalu tambahkan `quantization_config` ke `model_kwargs` di 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'}]
```

