Hugging Face Transformers Python Tutorial: Run a Small Model Locally

Hugging Face Transformers Python Tutorial: Run a Small Model Locally

Hugging Face Transformers lets you load pretrained models directly in Python. Unlike a separate local model server, the model runs inside your Python process, giving you control over tokenization, generation, devices, and application logic.

This tutorial uses SmolLM2-135M-Instruct, a compact instruction model suitable for learning the API. Its small size keeps the example approachable, but it should not be mistaken for a highly capable production assistant.

Reproducibility note: Record your Python, package, model, and operating-system versions before comparing results. Capture both the successful output and the first error when troubleshooting.

Quick fix: Create a venv, install torch and transformers, load HuggingFaceTB/SmolLM2-135M-Instruct with AutoModelForCausalLM, format the prompt with apply_chat_template, and slice the prompt tokens off before decoding. On a CPU-only Linux box the first run took about 15 seconds and the second about 4.

1. Create an isolated environment

Use a current Python version supported by the installed PyTorch and Transformers releases. On Ubuntu or Debian, install Python and virtual-environment support if necessary, then create a project:

sudo apt update
sudo apt install -y python3 python3-venv
mkdir transformers-demo
cd transformers-demo
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install torch transformers

This is a general installation example. For GPU acceleration, use the official PyTorch installation selector to choose packages appropriate for your operating system and accelerator. Installing a package does not replace a compatible GPU driver.

The first model load requires internet access to download its files. Public, unrestricted repositories generally do not require signing in; gated or private repositories may require authentication and license acceptance.

2. Load the model and tokenizer

Create generate.py with the following code. The tokenizer converts messages into model inputs, while the causal language model predicts continuation tokens.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
device = "cuda" if torch.cuda.is_available() else "cpu"

tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
model.to(device)
model.eval()

messages = [
    {
        "role": "user",
        "content": "Explain a Python virtual environment in two sentences.",
    }
]

prompt = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)
inputs = tokenizer(
    prompt,
    return_tensors="pt",
    add_special_tokens=False,
).to(device)

with torch.inference_mode():
    output = model.generate(
        **inputs,
        max_new_tokens=80,
        do_sample=False,
        pad_token_id=tokenizer.eos_token_id,
    )

new_tokens = output[0, inputs["input_ids"].shape[1]:]
print(tokenizer.decode(new_tokens, skip_special_tokens=True))

Run the script from the activated environment:

source .venv/bin/activate
python generate.py

I ran it on Debian 13 with Python 3.13, torch 2.15.0+cpu and transformers 5.24.1, wrapped in /usr/bin/time:

$ /usr/bin/time -f 'wall %e s, max RSS %M KB' python generate.py
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
Loading weights: 100%|██████████| 272/272 [00:00<00:00, 8052.08it/s]
A Python virtual environment is a way to create and manage multiple Python environments on a single machine, allowing you to isolate your project's dependencies and dependencies from other Python projects.
wall 15.21 s, max RSS 710096 KB

The answer is roughly right but clumsy (“dependencies and dependencies”), which is normal for a 135M-parameter model. The HF_TOKEN warning is harmless for public models; set a token only if downloads get rate limited.

3. Understand the generation settings

The chat template formats roles and message boundaries in the way the instruction model expects. Simply concatenating “User:” and “Assistant:” can produce poorer behavior when it differs from the model’s training format.

Because the template already supplies special tokens, the subsequent tokenizer call disables adding another set. The output slicing removes input tokens so the printed result contains only the generated continuation.

max_new_tokens limits newly generated tokens rather than the combined input and output length. Tokens are not identical to words. do_sample=False uses a non-sampling generation path; it does not guarantee identical results across all hardware and software combinations.

model.eval() selects evaluation behavior, while torch.inference_mode() avoids unnecessary gradient tracking. Neither operation fine-tunes the model.

dtype and device_map notes

For tiny models on a laptop, the default load plus model.to(device) is enough. As models grow, explicit dtype and device placement matter:

  • dtype: Prefer documenting what you load (for example float16 or bfloat16 on capable GPUs, float32 on CPU). Mixed choices affect memory and numerical behavior; do not assume identical text across dtypes.
  • device_map: For multi-GPU or large checkpoints, from_pretrained(..., device_map="auto") can place layers across devices. Combining an automatic map with a later blanket model.to("cuda") is a common footgun—pick one placement strategy.
  • CPU fallback: When CUDA is unavailable, the example runs on CPU. Expect slower generation; keep max_new_tokens modest while learning.
  • Quantization: Bits-and-bytes or other quantized loads are optional next steps with their own dependency and hardware constraints—introduce them only after the plain path works.

An automatic map on a GPU host looks like this. It needs the accelerate package installed:

model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    torch_dtype=torch.float16,
    device_map="auto",
)
# Do not also call model.to("cuda") when device_map already placed the weights.

4. Troubleshoot common failures

  • Import errors: Confirm the virtual environment is active and use python -m pip to install into the same interpreter.
  • CUDA unavailable: The example falls back to CPU. Check your driver and PyTorch build before expecting GPU acceleration.
  • Out of memory: Shorten prompts and output, use a smaller model, or investigate supported quantization methods.
  • Template errors: Confirm the chosen tokenizer includes a chat template. Different models need different prompting conventions.
  • Download or access errors: Check connectivity, repository permissions, and available storage.
  • Odd repetition or empty decode: Verify pad/eos settings, that you sliced away prompt tokens, and that the chat template matches the model card.

5. Make the project reproducible

Once your environment works, record package versions and the model revision used. Model names alone do not freeze repository contents. Pin revisions in code or lock files when you need stable demos.

python -c "import torch, transformers; print(torch.__version__, transformers.__version__)"
pip freeze > requirements.txt

Review the model card, license, and intended uses before distributing an application. SmolLM2 primarily targets English and can generate inaccurate or biased content. Treat its answers as suggestions, verify important claims, and never automatically execute generated code.

6. Tradeoffs versus a local server

In-process Transformers is excellent for learning, research scripts, and custom generation loops. A dedicated server (Ollama, vLLM, and similar) is often better when multiple clients share one GPU, when you want OpenAI-compatible HTTP without embedding weights in every process, or when you need operational controls around concurrency.

7. Minimal multi-turn loop (still in-process)

Once single-shot generation works, extend the same pattern to a short conversation without standing up a server. Keep history in a Python list and re-apply the chat template each turn.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID).eval()


def reply(history):
    prompt = tokenizer.apply_chat_template(
        history, tokenize=False, add_generation_prompt=True
    )
    inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
    with torch.inference_mode():
        out = model.generate(**inputs, max_new_tokens=60, do_sample=False,
                             pad_token_id=tokenizer.eos_token_id)
    new_tokens = out[0, inputs["input_ids"].shape[1]:]
    return tokenizer.decode(new_tokens, skip_special_tokens=True).strip()


history = [{"role": "user",
            "content": "Explain a Python virtual environment in one sentence."}]
a1 = reply(history)
print("assistant 1:", a1)
history += [{"role": "assistant", "content": a1},
            {"role": "user", "content": "How do I activate it on Linux?"}]
print("assistant 2:", reply(history))

Rebuilding the prompt each turn is intentional. It matches how many instruction models were trained and avoids hand-rolled “User:/Assistant:” formats that drift from the template. Cap history length the same way you would in a remote chatbot so context growth stays predictable on CPU.

What I ran into

Running the multi-turn script exposed the main limit of a model this small. The second answer was wrong:

assistant 2: To activate a Python virtual environment on Linux, you can use the following command:

```bash
python -m venv myenv
```

python -m venv creates an environment; source myenv/bin/activate activates it. The template and history handling worked, and the model still answered the wrong question. This is why the code above never executes model output and why a 135M model is a tool for learning the API, not an assistant.

The second surprise was that do_sample=False did not give the same text twice. Two back-to-back runs of generate.py on the same CPU produced different second halves of the sentence (“isolate your project’s dependencies…” and “run multiple Python applications in a single environment”). Greedy decoding removes sampling randomness, but CPU kernels can still pick different threads and summation order. If you need repeatable demos, pin the model revision and compare outputs with a tolerance, not exact string matches.

RunResult on CPU (torch 2.15.0+cpu)
First generate.py (includes download)15.21 s wall, about 710 MB peak RSS
Second generate.py (weights cached)3.97 s wall
Greedy output stable across runs?No, the second half of the sentence differed
Multi-turn answer to “How do I activate it?”Wrong: suggested python -m venv myenv

8. When to stop using in-process Transformers

Stay in-process while you are learning tokenization, templates, and generation knobs. Move to a local server when any of the following become true:

  • Multiple applications need the same loaded weights.
  • You want HTTP clients in languages other than Python without embedding PyTorch everywhere.
  • Cold start inside every CLI invocation wastes too much time.
  • You need serving features such as continuous batching or centralized GPU scheduling.

Those are product and ops reasons, not a claim that Transformers is obsolete. The library remains the foundation underneath many higher-level tools. Understanding a small local generate script makes later server choices easier to evaluate.

Cache and disk notes

Downloaded weights and tokenizer files land in the Hugging Face cache (typically under your home directory unless HF_HOME or related variables override it). Plan disk space before switching to larger checkpoints. Clearing the cache deletes downloads you may need again, so prefer documenting which revision you use over repeatedly wiping storage during experimentation.

FAQ

Do I need a GPU to run SmolLM2-135M?

No. It ran on CPU in about 4 seconds once the weights were cached. Larger models are where a GPU starts to matter.

Why does the output change when do_sample=False?

Greedy decoding removes sampling, but floating-point results can still differ between runs, threads, and hardware. Small differences in logits change which token wins.

Should I call model.to(“cuda”) after device_map=”auto”?

No. Pick one placement strategy. device_map already places the weights.

Where are the downloaded weights stored?

In the Hugging Face cache under your home directory unless HF_HOME points elsewhere.

Related guides

Official references: Transformers quickstart, SmolLM2 model card, and PyTorch installation selector.

Leave a Reply