transformers-tutorials

This repository contains demos I made with the Transformers library by HuggingFace.

https://github.com/nielsrogge/transformers-tutorials

Science Score: 46.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: arxiv.org
  • Committers with academic emails
    1 of 8 committers (12.5%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (6.1%) to scientific vocabulary

Keywords

bert gpt-2 layoutlm pytorch transformers vision-transformer

Keywords from Contributors

cryptocurrency cryptography jax transformer
Last synced: 6 months ago · JSON representation

Repository

This repository contains demos I made with the Transformers library by HuggingFace.

Basic Info
  • Host: GitHub
  • Owner: NielsRogge
  • License: mit
  • Language: Jupyter Notebook
  • Default Branch: master
  • Homepage:
  • Size: 226 MB
Statistics
  • Stars: 10,943
  • Watchers: 143
  • Forks: 1,624
  • Open Issues: 318
  • Releases: 0
Topics
bert gpt-2 layoutlm pytorch transformers vision-transformer
Created over 5 years ago · Last pushed 9 months ago
Metadata Files
Readme License Citation

README.md

Transformers-Tutorials

Hi there!

This repository contains demos I made with the Transformers library by HuggingFace. Currently, all of them are implemented in PyTorch.

NOTE: if you are not familiar with HuggingFace and/or Transformers, I highly recommend to check out our free course, which introduces you to several Transformer architectures (such as BERT, GPT-2, T5, BART, etc.), as well as an overview of the HuggingFace libraries, including Transformers, Tokenizers, Datasets, Accelerate and the hub.

For an overview of the ecosystem of HuggingFace for computer vision (June 2022), refer to this notebook with corresponding video.

Currently, it contains the following demos: * Audio Spectrogram Transformer (paper): - performing inference with ASTForAudioClassification to classify audio. Open In Colab * BERT (paper): - fine-tuning BertForTokenClassification on a named entity recognition (NER) dataset. Open In Colab - fine-tuning BertForSequenceClassification for multi-label text classification. Open In Colab * BEiT (paper): - understanding BeitForMaskedImageModeling Open In Colab * CANINE (paper): - fine-tuning CanineForSequenceClassification on IMDb Open In Colab * CLIPSeg (paper): - performing zero-shot image segmentation with CLIPSeg Open In Colab * Conditional DETR (paper): - performing inference with ConditionalDetrForObjectDetection Open In Colab - fine-tuning ConditionalDetrForObjectDetection on a custom dataset (balloon) Open In Colab * ConvNeXT (paper): - fine-tuning (and performing inference with) ConvNextForImageClassification Open In Colab * DINO (paper): - visualize self-attention of Vision Transformers trained using the DINO method Open In Colab * DETR (paper): - performing inference with DetrForObjectDetection Open In Colab - fine-tuning DetrForObjectDetection on a custom object detection dataset Open In Colab - evaluating DetrForObjectDetection on the COCO detection 2017 validation set Open In Colab - performing inference with DetrForSegmentation Open In Colab - fine-tuning DetrForSegmentation on COCO panoptic 2017 Open In Colab * DPT (paper): - performing inference with DPT for monocular depth estimation Open In Colab - performing inference with DPT for semantic segmentation Open In Colab * Deformable DETR (paper): - performing inference with DeformableDetrForObjectDetection Open In Colab * DiT (paper): - performing inference with DiT for document image classification Open In Colab * Donut (paper): - performing inference with Donut for document image classification Open In Colab - fine-tuning Donut for document image classification Open In Colab - performing inference with Donut for document visual question answering (DocVQA) Open In Colab - performing inference with Donut for document parsing Open In Colab - fine-tuning Donut for document parsing with PyTorch Lightning Open In Colab * GIT (paper): - performing inference with GIT for image/video captioning and image/video question-answering Open In Colab - fine-tuning GIT on a custom image captioning dataset Open In Colab * GLPN (paper): - performing inference with GLPNForDepthEstimation to illustrate monocular depth estimation Open In Colab * GPT-J-6B (repository): - performing inference with GPTJForCausalLM to illustrate few-shot learning and code generation Open In Colab * GroupViT (repository): - performing inference with GroupViTModel to illustrate zero-shot semantic segmentation Open In Colab * ImageGPT (blog post): - (un)conditional image generation with ImageGPTForCausalLM Open In Colab - linear probing with ImageGPT Open In Colab * LUKE (paper): - fine-tuning LukeForEntityPairClassification on a custom relation extraction dataset using PyTorch Lightning Open In Colab * LayoutLM (paper): - fine-tuning LayoutLMForTokenClassification on the FUNSD dataset Open In Colab - fine-tuning LayoutLMForSequenceClassification on the RVL-CDIP dataset Open In Colab - adding image embeddings to LayoutLM during fine-tuning on the FUNSD dataset Open In Colab * LayoutLMv2 (paper): - fine-tuning LayoutLMv2ForSequenceClassification on RVL-CDIP Open In Colab - fine-tuning LayoutLMv2ForTokenClassification on FUNSD Open In Colab - fine-tuning LayoutLMv2ForTokenClassification on FUNSD using the Trainer Open In Colab - performing inference with LayoutLMv2ForTokenClassification on FUNSD Open In Colab - true inference with LayoutLMv2ForTokenClassification (when no labels are available) + Gradio demo Open In Colab - fine-tuning LayoutLMv2ForTokenClassification on CORD Open In Colab - fine-tuning LayoutLMv2ForQuestionAnswering on DOCVQA Open In Colab * LayoutLMv3 (paper): - fine-tuning LayoutLMv3ForTokenClassification on the FUNSD dataset Open In Colab * LayoutXLM (paper): - fine-tuning LayoutXLM on the XFUND benchmark for token classification Open In Colab - fine-tuning LayoutXLM on the XFUND benchmark for relation extraction Open In Colab * MarkupLM (paper): - inference with MarkupLM to perform question answering on web pages Open In Colab - fine-tuning MarkupLMForTokenClassification on a toy dataset for NER on web pages Open In Colab * Mask2Former (paper): - performing inference with Mask2Former for universal image segmentation: Open In Colab * MaskFormer (paper): - performing inference with MaskFormer (both semantic and panoptic segmentation): Open In Colab - fine-tuning MaskFormer on a custom dataset for semantic segmentation Open In Colab * OneFormer (paper): - performing inference with OneFormer for universal image segmentation: Open In Colab * Perceiver IO (paper): - showcasing masked language modeling and image classification with the Perceiver Open In Colab - fine-tuning the Perceiver for image classification Open In Colab - fine-tuning the Perceiver for text classification Open In Colab - predicting optical flow between a pair of images with PerceiverForOpticalFlowOpen In Colab - auto-encoding a video (images, audio, labels) with PerceiverForMultimodalAutoencoding Open In Colab * SAM (paper): - performing inference with MedSAM Open In Colab - fine-tuning SamModel on a custom dataset Open In Colab * SegFormer (paper): - performing inference with SegformerForSemanticSegmentation Open In Colab - fine-tuning SegformerForSemanticSegmentation on custom data using native PyTorch Open In Colab * T5 (paper): - fine-tuning T5ForConditionalGeneration on a Dutch summarization dataset on TPU using HuggingFace Accelerate Open In Colab - fine-tuning T5ForConditionalGeneration (CodeT5) for Ruby code summarization using PyTorch Lightning Open In Colab * TAPAS (paper):
- fine-tuning TapasForQuestionAnswering on the Microsoft Sequential Question Answering (SQA) dataset Open In Colab - evaluating TapasForSequenceClassification on the Table Fact Checking (TabFact) dataset Open In Colab * Table Transformer (paper): - using the Table Transformer for table detection and table structure recognition Open In Colab * TrOCR (paper): - performing inference with TrOCR to illustrate optical character recognition with Transformers, as well as making a Gradio demo Open In Colab - fine-tuning TrOCR on the IAM dataset using the Seq2SeqTrainer Open In Colab - fine-tuning TrOCR on the IAM dataset using native PyTorch Open In Colab - evaluating TrOCR on the IAM test set Open In Colab * UPerNet (paper): - performing inference with UperNetForSemanticSegmentation Open In Colab * VideoMAE (paper): - performing inference with VideoMAEForVideoClassification Open In Colab * ViLT (paper): - fine-tuning ViLT for visual question answering (VQA) Open In Colab - performing inference with ViLT to illustrate visual question answering (VQA) Open In Colab - masked language modeling (MLM) with a pre-trained ViLT model Open In Colab - performing inference with ViLT for image-text retrieval Open In Colab - performing inference with ViLT to illustrate natural language for visual reasoning (NLVR) Open In Colab * ViTMAE (paper): - reconstructing pixel values with ViTMAEForPreTraining Open In Colab * Vision Transformer (paper): - performing inference with ViTForImageClassification Open In Colab - fine-tuning ViTForImageClassification on CIFAR-10 using PyTorch Lightning Open In Colab - fine-tuning ViTForImageClassification on CIFAR-10 using the Trainer Open In Colab * X-CLIP (paper): - performing zero-shot video classification with X-CLIP Open In Colab - zero-shot classifying a YouTube video with X-CLIP Open In Colab * YOLOS (paper): - fine-tuning YolosForObjectDetection on a custom dataset Open In Colab - inference with YolosForObjectDetection Open In Colab

... more to come!

If you have any questions regarding these demos, feel free to open an issue on this repository.

Btw, I was also the main contributor to add the following algorithms to the library: - TAbular PArSing (TAPAS) by Google AI - Vision Transformer (ViT) by Google AI - DINO by Facebook AI - Data-efficient Image Transformers (DeiT) by Facebook AI - LUKE by Studio Ousia - DEtection TRansformers (DETR) by Facebook AI - CANINE by Google AI - BEiT by Microsoft Research - LayoutLMv2 (and LayoutXLM) by Microsoft Research - TrOCR by Microsoft Research - SegFormer by NVIDIA - ImageGPT by OpenAI - Perceiver by Deepmind - MAE by Facebook AI - ViLT by NAVER AI Lab - ConvNeXT by Facebook AI - DiT By Microsoft Research - GLPN by KAIST - DPT by Intel Labs - YOLOS by School of EIC, Huazhong University of Science & Technology - TAPEX by Microsoft Research - LayoutLMv3 by Microsoft Research - VideoMAE by Multimedia Computing Group, Nanjing University - X-CLIP by Microsoft Research - MarkupLM by Microsoft Research

All of them were an incredible learning experience. I can recommend anyone to contribute an AI algorithm to the library!

Data preprocessing

Regarding preparing your data for a PyTorch model, there are a few options: - a native PyTorch dataset + dataloader. This is the standard way to prepare data for a PyTorch model, namely by subclassing torch.utils.data.Dataset, and then creating a corresponding DataLoader (which is a Python generator that allows to loop over the items of a dataset). When subclassing the Dataset class, one needs to implement 3 methods: __init__, __len__ (which returns the number of examples of the dataset) and __getitem__ (which returns an example of the dataset, given an integer index). Here's an example of creating a basic text classification dataset (assuming one has a CSV that contains 2 columns, namely "text" and "label"):

```python from torch.utils.data import Dataset

class CustomTrainDataset(Dataset): def init(self, df, tokenizer): self.df = df self.tokenizer = tokenizer

def __len__(self):
    return len(self.df)

def __getitem__(self, idx):
    # get item
    item = df.iloc[idx]
    text = item['text']
    label = item['label']
    # encode text
    encoding = self.tokenizer(text, padding="max_length", max_length=128, truncation=True, return_tensors="pt")
    # remove batch dimension which the tokenizer automatically adds
    encoding = {k:v.squeeze() for k,v in encoding.items()}
    # add label
    encoding["label"] = torch.tensor(label)

    return encoding

```

Instantiating the dataset then happens as follows:

```python from transformers import BertTokenizer import pandas as pd

tokenizer = BertTokenizer.frompretrained("bert-base-uncased") df = pd.readcsv("pathtoyour_csv")

train_dataset = CustomTrainDataset(df=df, tokenizer=tokenizer) ```

Accessing the first example of the dataset can then be done as follows:

python encoding = train_dataset[0]

In practice, one creates a corresponding DataLoader, that allows to get batches from the dataset:

```python from torch.utils.data import DataLoader

traindataloader = DataLoader(traindataset, batchsize=4, shuffle=True) ``` I often check whether the data is created correctly by fetching the first batch from the data loader, and then printing out the shapes of the tensors, decoding the inputids back to text, etc.

```python batch = next(iter(train_dataloader)) for k,v in batch.items(): print(k, v.shape)

decode the input_ids of the first example of the batch

print(tokenizer.decode(batch['input_ids'][0].tolist()) ``` - HuggingFace Datasets. Datasets is a library by HuggingFace that allows to easily load and process data in a very fast and memory-efficient way. It is backed by Apache Arrow, and has cool features such as memory-mapping, which allow you to only load data into RAM when it is required. It only has deep interoperability with the HuggingFace hub, allowing to easily load well-known datasets as well as share your own with the community.

Loading a custom dataset as a Dataset object can be done as follows (you can install datasets using pip install datasets): ```python from datasets import load_dataset

dataset = loaddataset('csv', datafiles={'train': ['mytrainfile1.csv', 'mytrainfile2.csv'] 'test': 'mytestfile.csv'}) ``` Here I'm loading local CSV files, but there are other formats supported (including JSON, Parquet, txt) as well as loading data from a local Pandas dataframe or dictionary for instance. You can check out the docs for all details.

Training frameworks

Regarding fine-tuning Transformer models (or more generally, PyTorch models), there are a few options: - using native PyTorch. This is the most basic way to train a model, and requires the user to manually write the training loop. The advantage is that this is very easy to debug. The disadvantage is that one needs to implement training him/herself, such as setting the model in the appropriate mode (model.train()/model.eval()), handle device placement (model.to(device)), etc. A typical training loop in PyTorch looks as follows (inspired by this great PyTorch intro tutorial):

```python import torch from transformers import BertForSequenceClassification

Instantiate pre-trained BERT model with randomly initialized classification head

model = BertForSequenceClassification.from_pretrained("bert-base-uncased")

I almost always use a learning rate of 5e-5 when fine-tuning Transformer based models

optimizer = torch.optim.Adam(model.parameters(), lr=5e-5)

put model on GPU, if available

device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device)

for epoch in range(epochs): model.train() trainloss = 0.0 for batch in traindataloader: # put batch on device batch = {k:v.to(device) for k,v in batch.items()}

    # forward pass
    outputs = model(**batch)
    loss = outputs.loss

    train_loss += loss.item()

    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

print("Loss after epoch {epoch}:", train_loss/len(train_dataloader))

model.eval()
val_loss = 0.0
with torch.no_grad():
    for batch in eval_dataloader:
        # put batch on device
        batch = {k:v.to(device) for k,v in batch.items()}

        # forward pass
        outputs = model(**batch)
        loss = outputs.logits

        val_loss += loss.item()

print("Validation loss after epoch {epoch}:", val_loss/len(eval_dataloader))

```

  • PyTorch Lightning (PL). PyTorch Lightning is a framework that automates the training loop written above, by abstracting it away in a Trainer object. Users don't need to write the training loop themselves anymore, instead they can just do trainer = Trainer() and then trainer.fit(model). The advantage is that you can start training models very quickly (hence the name lightning), as all training-related code is handled by the Trainer object. The disadvantage is that it may be more difficult to debug your model, as the training and evaluation is now abstracted away.
  • HuggingFace Trainer. The HuggingFace Trainer API can be seen as a framework similar to PyTorch Lightning in the sense that it also abstracts the training away using a Trainer object. However, contrary to PyTorch Lightning, it is not meant not be a general framework. Rather, it is made especially for fine-tuning Transformer-based models available in the HuggingFace Transformers library. The Trainer also has an extension called Seq2SeqTrainer for encoder-decoder models, such as BART, T5 and the EncoderDecoderModel classes. Note that all PyTorch example scripts of the Transformers library make use of the Trainer.
  • HuggingFace Accelerate: Accelerate is a new project, that is made for people who still want to write their own training loop (as shown above), but would like to make it work automatically irregardless of the hardware (i.e. multiple GPUs, TPU pods, mixed precision, etc.).

Citation

Feel free to cite me when you use some of my tutorials :)

bibtex @misc{rogge2025transformerstutorials, author = {Rogge, Niels}, title = {Tutorials}, url = {[https://github.com/NielsRogge/tutorials](https://github.com/NielsRogge/Transformers-Tutorials)}, year = {2025} }

Owner

  • Login: NielsRogge
  • Kind: user
  • Location: Belgium
  • Company: HuggingFace

ML @HuggingFace. Interested in deep learning, NLP. Contributed 40+ models to HuggingFace Transformers

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 436
  • Total Committers: 8
  • Avg Commits per committer: 54.5
  • Development Distribution Score (DDS): 0.053
Past Year
  • Commits: 25
  • Committers: 3
  • Avg Commits per committer: 8.333
  • Development Distribution Score (DDS): 0.12
Top Committers
Name Email Commits
NielsRogge 4****e 413
fra f****i@g****m 9
Rogge Niels n****e@h****e 6
raushan r****n@h****o 3
Eduardo Pacheco 6****h 2
sergiopaniego s****o@g****m 1
graham g****t@g****m 1
Niels Rogge n****e@N****l 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 125
  • Total pull requests: 18
  • Average time to close issues: 2 months
  • Average time to close pull requests: 3 months
  • Total issue authors: 119
  • Total pull request authors: 14
  • Average comments per issue: 2.62
  • Average comments per pull request: 1.83
  • Merged pull requests: 6
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 34
  • Pull requests: 3
  • Average time to close issues: 2 days
  • Average time to close pull requests: 2 minutes
  • Issue authors: 33
  • Pull request authors: 2
  • Average comments per issue: 0.85
  • Average comments per pull request: 2.33
  • Merged pull requests: 2
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • tzktz (4)
  • AbdulDD (3)
  • DhruvAwasthi (2)
  • piegu (2)
  • Arjunexperion (2)
  • arvisioncode (2)
  • AnasLahmar (2)
  • nk-alex (2)
  • spydaz (1)
  • nisyad-ms (1)
  • DrVictorBenjamin (1)
  • lombardata (1)
  • sanakashgouli (1)
  • boris-lok-pentadoc (1)
  • aditya11ad (1)
Pull Request Authors
  • zucchini-nlp (6)
  • PierreMesure (2)
  • qiisziilbash (2)
  • sergiopaniego (2)
  • zinccat (2)
  • thariq-nugrohotomo (1)
  • cdreetz (1)
  • EduardoPach (1)
  • sufianj (1)
  • salman-moh (1)
  • Yazangthb (1)
  • eltociear (1)
  • amtam0 (1)
Top Labels
Issue Labels
Pull Request Labels