transformers/docs/source/en/quicktour.md
Steven Liu c0f8d055ce
[docs] Redesign (#31757)
* toctree

* not-doctested.txt

* collapse sections

* feedback

* update

* rewrite get started sections

* fixes

* fix

* loading models

* fix

* customize models

* share

* fix link

* contribute part 1

* contribute pt 2

* fix toctree

* tokenization pt 1

* Add new model (#32615)

* v1 - working version

* fix

* fix

* fix

* fix

* rename to correct name

* fix title

* fixup

* rename files

* fix

* add copied from on tests

* rename to `FalconMamba` everywhere and fix bugs

* fix quantization + accelerate

* fix copies

* add `torch.compile` support

* fix tests

* fix tests and add slow tests

* copies on config

* merge the latest changes

* fix tests

* add few lines about instruct

* Apply suggestions from code review

Co-authored-by: Arthur <48595927+ArthurZucker@users.noreply.github.com>

* fix

* fix tests

---------

Co-authored-by: Arthur <48595927+ArthurZucker@users.noreply.github.com>

* "to be not" -> "not to be" (#32636)

* "to be not" -> "not to be"

* Update sam.md

* Update trainer.py

* Update modeling_utils.py

* Update test_modeling_utils.py

* Update test_modeling_utils.py

* fix hfoption tag

* tokenization pt. 2

* image processor

* fix toctree

* backbones

* feature extractor

* fix file name

* processor

* update not-doctested

* update

* make style

* fix toctree

* revision

* make fixup

* fix toctree

* fix

* make style

* fix hfoption tag

* pipeline

* pipeline gradio

* pipeline web server

* add pipeline

* fix toctree

* not-doctested

* prompting

* llm optims

* fix toctree

* fixes

* cache

* text generation

* fix

* chat pipeline

* chat stuff

* xla

* torch.compile

* cpu inference

* toctree

* gpu inference

* agents and tools

* gguf/tiktoken

* finetune

* toctree

* trainer

* trainer pt 2

* optims

* optimizers

* accelerate

* parallelism

* fsdp

* update

* distributed cpu

* hardware training

* gpu training

* gpu training 2

* peft

* distrib debug

* deepspeed 1

* deepspeed 2

* chat toctree

* quant pt 1

* quant pt 2

* fix toctree

* fix

* fix

* quant pt 3

* quant pt 4

* serialization

* torchscript

* scripts

* tpu

* review

* model addition timeline

* modular

* more reviews

* reviews

* fix toctree

* reviews reviews

* continue reviews

* more reviews

* modular transformers

* more review

* zamba2

* fix

* all frameworks

* pytorch

* supported model frameworks

* flashattention

* rm check_table

* not-doctested.txt

* rm check_support_list.py

* feedback

* updates/feedback

* review

* feedback

* fix

* update

* feedback

* updates

* update

---------

Co-authored-by: Younes Belkada <49240599+younesbelkada@users.noreply.github.com>
Co-authored-by: Arthur <48595927+ArthurZucker@users.noreply.github.com>
Co-authored-by: Quentin Gallouédec <45557362+qgallouedec@users.noreply.github.com>
2025-03-03 10:33:46 -08:00

13 KiB
Executable File
Raw Blame History

Quickstart

open-in-colab

Transformers is designed to be fast and easy to use so that everyone can start learning or building with transformer models.

The number of user-facing abstractions is limited to only three classes for instantiating a model, and two APIs for inference or training. This quickstart introduces you to Transformers' key features and shows you how to:

  • load a pretrained model
  • run inference with [Pipeline]
  • fine-tune a model with [Trainer]

Set up

To start, we recommend creating a Hugging Face account. An account lets you host and access version controlled models, datasets, and Spaces on the Hugging Face Hub, a collaborative platform for discovery and building.

Create a User Access Token and log in to your account.

from huggingface_hub import notebook_login

notebook_login()

Install a machine learning framework.

!pip install torch
!pip install tensorflow

Then install an up-to-date version of Transformers and some additional libraries from the Hugging Face ecosystem for accessing datasets and vision models, evaluating training, and optimizing training for large models.

!pip install -U transformers datasets evaluate accelerate timm

Pretrained models

Each pretrained model inherits from three base classes.

Class Description
[PretrainedConfig] A file that specifies a models attributes such as the number of attention heads or vocabulary size.
[PreTrainedModel] A model (or architecture) defined by the model attributes from the configuration file. A pretrained model only returns the raw hidden states. For a specific task, use the appropriate model head to convert the raw hidden states into a meaningful result (for example, [LlamaModel] versus [LlamaForCausalLM]).
Preprocessor A class for converting raw inputs (text, images, audio, multimodal) into numerical inputs to the model. For example, [PreTrainedTokenizer] converts text into tensors and [ImageProcessingMixin] converts pixels into tensors.

We recommend using the AutoClass API to load models and preprocessors because it automatically infers the appropriate architecture for each task and machine learning framework based on the name or path to the pretrained weights and configuration file.

Use [~PreTrainedModel.from_pretrained] to load the weights and configuration file from the Hub into the model and preprocessor class.

When you load a model, configure the following parameters to ensure the model is optimally loaded.

  • device_map="auto" automatically allocates the model weights to your fastest device first, which is typically the GPU.
  • torch_dtype="auto" directly initializes the model weights in the data type they're stored in, which can help avoid loading the weights twice (PyTorch loads weights in torch.float32 by default).
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype="auto", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")

Tokenize the text and return PyTorch tensors with the tokenizer. Move the model to a GPU if it's available to accelerate inference.

model_inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="pt").to("cuda")

The model is now ready for inference or training.

For inference, pass the tokenized inputs to [~GenerationMixin.generate] to generate text. Decode the token ids back into text with [~PreTrainedTokenizerBase.batch_decode].

generated_ids = model.generate(**model_inputs, max_length=30)
tokenizer.batch_decode(generated_ids)[0]
'<s> The secret to baking a good cake is 100% in the preparation. There are so many recipes out there,'
from transformers import TFAutoModelForCausalLM, AutoTokenizer

model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2-xl")
tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2-xl")

Tokenize the text and return TensorFlow tensors with the tokenizer.

model_inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="tf")

The model is now ready for inference or training.

For inference, pass the tokenized inputs to [~GenerationMixin.generate] to generate text. Decode the token ids back into text with [~PreTrainedTokenizerBase.batch_decode].

generated_ids = model.generate(**model_inputs, max_length=30)
tokenizer.batch_decode(generated_ids)[0]
'The secret to baking a good cake is \xa0to use the right ingredients. \xa0The secret to baking a good cake is to use the right'

Tip

Skip ahead to the Trainer section to learn how to fine-tune a model.

Pipeline

The [Pipeline] class is the most convenient way to inference with a pretrained model. It supports many tasks such as text generation, image segmentation, automatic speech recognition, document question answering, and more.

Tip

Refer to the Pipeline API reference for a complete list of available tasks.

Create a [Pipeline] object and select a task. By default, [Pipeline] downloads and caches a default pretrained model for a given task. Pass the model name to the model parameter to choose a specific model.

Set device="cuda" to accelerate inference with a GPU.

from transformers import pipeline

pipeline = pipeline("text-generation", model="meta-llama/Llama-2-7b-hf", device="cuda")

Prompt [Pipeline] with some initial text to generate more text.

pipeline("The secret to baking a good cake is ", max_length=50)
[{'generated_text': 'The secret to baking a good cake is 100% in the batter. The secret to a great cake is the icing.\nThis is why weve created the best buttercream frosting reci'}]

Set device="cuda" to accelerate inference with a GPU.

from transformers import pipeline

pipeline = pipeline("image-segmentation", model="facebook/detr-resnet-50-panoptic", device="cuda")

Pass an image - a URL or local path to the image - to [Pipeline].

segments = pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
segments[0]["label"]
'bird'
segments[1]["label"]
'bird'

Set device="cuda" to accelerate inference with a GPU.

from transformers import pipeline

pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", device="cuda")

Pass an audio file to [Pipeline].

pipeline("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.'}

Trainer

[Trainer] is a complete training and evaluation loop for PyTorch models. It abstracts away a lot of the boilerplate usually involved in manually writing a training loop, so you can start training faster and focus on training design choices. You only need a model, dataset, a preprocessor, and a data collator to build batches of data from the dataset.

Use the [TrainingArguments] class to customize the training process. It provides many options for training, evaluation, and more. Experiment with training hyperparameters and features like batch size, learning rate, mixed precision, torch.compile, and more to meet your training needs. You could also use the default training parameters to quickly produce a baseline.

Load a model, tokenizer, and dataset for training.

from transformers import AutoModelForSequenceClassification, AutoTokenizer
from datasets import load_dataset

model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
dataset = load_dataset("rotten_tomatoes")

Create a function to tokenize the text and convert it into PyTorch tensors. Apply this function to the whole dataset with the [~datasets.Dataset.map] method.

def tokenize_dataset(dataset):
    return tokenizer(dataset["text"])
dataset = dataset.map(tokenize_dataset, batched=True)

Load a data collator to create batches of data and pass the tokenizer to it.

from transformers import DataCollatorWithPadding

data_collator = DataCollatorWithPadding(tokenizer=tokenizer)

Next, set up [TrainingArguments] with the training features and hyperparameters.

from transformers import TrainingArguments

training_args = TrainingArguments(
    output_dir="distilbert-rotten-tomatoes",
    learning_rate=2e-5,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    num_train_epochs=2,
    push_to_hub=True,
)

Finally, pass all these separate components to [Trainer] and call [~Trainer.train] to start.

from transformers import Trainer

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=dataset["train"],
    eval_dataset=dataset["test"],
    tokenizer=tokenizer,
    data_collator=data_collator,
)

trainer.train()

Share your model and tokenizer to the Hub with [~Trainer.push_to_hub].

trainer.push_to_hub()

Congratulations, you just trained your first model with Transformers!

TensorFlow

Warning

Not all pretrained models are available in TensorFlow. Refer to a models API doc to check whether a TensorFlow implementation is supported.

[Trainer] doesn't work with TensorFlow models, but you can still train a Transformers model implemented in TensorFlow with Keras. Transformers TensorFlow models are a standard tf.keras.Model, which is compatible with Keras' compile and fit methods.

Load a model, tokenizer, and dataset for training.

from transformers import TFAutoModelForSequenceClassification, AutoTokenizer

model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")

Create a function to tokenize the text and convert it into TensorFlow tensors. Apply this function to the whole dataset with the [~datasets.Dataset.map] method.

def tokenize_dataset(dataset):
    return tokenizer(dataset["text"])
dataset = dataset.map(tokenize_dataset)

Transformers provides the [~TFPreTrainedModel.prepare_tf_dataset] method to collate and batch a dataset.

tf_dataset = model.prepare_tf_dataset(
    dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer
)

Finally, call compile to configure the model for training and fit to start.

from tensorflow.keras.optimizers import Adam

model.compile(optimizer="adam")
model.fit(tf_dataset)

Next steps

Now that you have a better understanding of Transformers and what it offers, it's time to keep exploring and learning what interests you the most.

  • Base classes: Learn more about the configuration, model and processor classes. This will help you understand how to create and customize models, preprocess different types of inputs (audio, images, multimodal), and how to share your model.
  • Inference: Explore the [Pipeline] further, inference and chatting with LLMs, agents, and how to optimize inference with your machine learning framework and hardware.
  • Training: Study the [Trainer] in more detail, as well as distributed training and optimizing training on specific hardware.
  • Quantization: Reduce memory and storage requirements with quantization and speed up inference by representing weights with fewer bits.
  • Resources: Looking for end-to-end recipes for how to train and inference with a model for a specific task? Check out the task recipes!