GenAI Course · Module 7 · Session 23

Generative Modeling & Hugging Face

⏱ 12 min read🎯 Beginner friendly🖼 3 diagrams🧪 1 live demo🐍 Python code

So far we studied how transformers work inside. Now let us start using them. In this session you will understand the two main ways language models are trained, get to know Hugging Face (the “GitHub of AI models”), and run a real model on a free GPU.

In this session

  • Autoregressive vs autoencoding models, in simple words
  • The Hugging Face ecosystem: Hub, Transformers, Datasets, Pipelines
  • How to read a model card before you use a model
  • Loading a model and tokenizer, and running it on a Colab GPU
  • A calculator: will this model fit on my GPU?

01Autoregressive vs autoencoding

Language models learn by playing a prediction game on text. There are two main styles of game:

AR models write; AE models read.

In maths, an autoregressive model breaks the probability of a sentence into a chain of next-token probabilities:

P(sentence) = P(w₁) · P(w₂ | w₁) · P(w₃ | w₁, w₂) · …

That is why generative models are autoregressive: to write a sentence, they keep sampling the next token and feeding it back in (Session 21). Autoencoding models cannot do this naturally, because they need to see the whole sentence at once.

✍️

AR is like writing an essay: you write word by word, and each new word depends on what you already wrote. AE is like a fill-in-the-blanks test: you see the whole line and fill the gaps.

02The Hugging Face ecosystem

Hugging Face is the place where the AI community shares models, datasets and demos, plus the open-source libraries to use them. The Hub hosts well over a million models.

One account, one ecosystem: find a model, load it, fine-tune it, share a demo.

Read the model card first

Before you use any model, open its model card and check:

03Pipelines: the 3-line shortcut

A pipeline wraps the tokenizer, model and post-processing together. Just pick a task:

pipelines.py
# pip install transformers torch
from transformers import pipeline

sentiment = pipeline("sentiment-analysis")
print(sentiment("The new UPI app is super fast and easy to use!"))

ner = pipeline("ner", aggregation_strategy="simple")
print(ner("Priya Sharma opened an account at HDFC Bank in Pune."))
[{'label': 'POSITIVE', 'score': 0.99…}] [{'entity_group': 'PER', 'word': 'Priya Sharma', …}, {'entity_group': 'ORG', 'word': 'HDFC Bank', …}, {'entity_group': 'LOC', 'word': 'Pune', …}] (example output; default models and scores can change)

Other ready tasks include "summarization", "translation", "question-answering", "zero-shot-classification", "text-generation" and "automatic-speech-recognition". When you do not name a model, a default is downloaded; in real projects always pin the exact model name.

04Loading a model and tokenizer yourself

For more control, load the two parts directly. The Auto classes read the model’s config and pick the right architecture for you.

The tokenizer is used twice: once to encode, once to decode.
chat_with_small_llm.py
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "Qwen/Qwen2.5-0.5B-Instruct"                 # small, open, instruction-tuned
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.float16, device_map="auto")

messages = [{"role": "user", "content": "Explain UPI to a 10-year-old in 2 lines."}]
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)

out = model.generate(inputs, max_new_tokens=80)
print(tok.decode(out[0][inputs.shape[-1]:], skip_special_tokens=True))
Chat models need their chat template. apply_chat_template adds the special tokens the model was trained with (like the <|user|> markers from the SFT lesson). Skipping it gives poor answers.

05Running on a free Colab GPU

  1. Open Google Colab and create a new notebook.
  2. Go to Runtime → Change runtime type → T4 GPU and save.
  3. Check the GPU: import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0))
  4. Install libraries: !pip install -q transformers accelerate, then run the code above.

The free T4 has 16 GB of GPU memory. A quick rule: model weights need about parameters × bytes per parameter, plus some extra for activations and the KV cache. Try it:

Demo · Will it fit on a T4 (16 GB)?

06Summary

07Quick quiz

1. GPT-style models are…

2. Where do you check whether you can use a model commercially?

3. Roughly how much memory do a 7B model’s FP16 weights need?

4. Why use apply_chat_template with a chat model?

5. What does pipeline() do?

08References

Created by Ajeetkumar