Skip to content

Lesson 8 ยท Running Llama Locally

Run Llama with Hugging Face Transformers

Request access to gated Llama weights, log in with the hf command, download files safely and generate replies in Python with the Transformers library.

Ollama and llama.cpp hide many details. The Transformers library from Hugging Face lets you load Llama directly in Python. That is the usual route to fine-tuning and research code. It typically needs more memory than a quantized GGUF file, and a GPU makes a large difference.

Get access to the weights

Official Llama repositories on Hugging Face are gated. You create an account, open the model page, review the license and use policy, agree to share the requested information and get access. Meta also describes a second route in its llama-models repository: request access on Meta's site, receive a signed download link by email and use its download tool. According to that repository, the link expires after 24 hours.

After you have access, authenticate your computer with the Hugging Face command line, called hf:

Terminal
pip install -U huggingface_hub transformers torch accelerate
hf auth login
hf download meta-llama/Llama-3.2-1B-Instruct --local-dir ./llama-1b

An access token is a password. Never paste it into code, notebooks or chat messages, and never commit it to Git. Use the login command or a protected environment variable.

Prefer safe file formats

Model repositories contain weight files, a configuration and tokenizer files. Prefer the safetensors format. Older pickle-based formats can run code when loaded. Also be careful with the option trust_remote_code=True, which lets code from a repository run on your machine. Do not turn it on unless you have read that code and trust its source.

Generate a reply

This is real code for your computer. It cannot run in the browser:

Python
import torch
from transformers import pipeline

generator = pipeline(
    "text-generation",
    model="meta-llama/Llama-3.2-1B-Instruct",
    dtype=torch.bfloat16,       # older library versions call this torch_dtype
    device_map="auto",
)

messages = [
    {"role": "system", "content": "You answer in two short sentences."},
    {"role": "user", "content": "Why do leaves change color in autumn?"},
]

result = generator(messages, max_new_tokens=120)
print(result[0]["generated_text"][-1]["content"])

The pipeline accepts a list of messages and applies the model's chat template for you. The output holds the whole conversation, so the last item is the new reply.

The lower-level route

When you need control over tokens, load the tokenizer and model separately:

Python
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "meta-llama/Llama-3.2-1B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", dtype="auto")

inputs = tokenizer.apply_chat_template(
    messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
).to(model.device)

output = model.generate(**inputs, max_new_tokens=120, do_sample=False)
new_tokens = output[0][inputs["input_ids"].shape[-1]:]
print(tokenizer.decode(new_tokens, skip_special_tokens=True))

Two details matter. add_generation_prompt=True adds the header that tells the model to start answering. And the slice after generation removes your prompt from the output. With do_sample=False, the model takes the most likely token each time, which is useful for tests.

See the shape of the work

Python Stand-in: follow the steps of generate()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When a reply stops in the middle of a sentence, check max_new_tokens first.

Save memory

  • Use the smallest model that works.
  • Load in 16-bit instead of 32-bit.
  • Load in 8-bit or 4-bit with a quantization library such as bitsandbytes (check that your platform supports it).
  • Reduce batch size and prompt length.

device_map="auto" (which needs the accelerate package) can place layers across devices. If some end up on the CPU or disk, generation becomes much slower.

Pin versions

Record library versions and the model revision (a commit hash on the repository). Pass revision= when loading. This protects you from surprising changes in files or behavior. Library arguments also change over time, so when an example fails, compare it with the documentation for your installed version.

What lives in the model folder

After a download you see several kinds of files. The configuration file describes the architecture, such as the number of layers and attention heads. The weight files hold the parameters, often split into several parts with an index file. The tokenizer files hold the vocabulary and the chat template. There may also be a generation configuration with default settings such as stop tokens. Copy the whole folder when you move a model, because a missing tokenizer or template file leads to errors or strange output.

Choosing where the model runs

On a machine with a supported NVIDIA GPU, you install a PyTorch build that matches your driver. On Apple silicon, PyTorch can use the Metal backend. On a CPU only, small models work but generate slowly. Verify which device your code actually uses instead of assuming it, for example by printing model.device after loading.

Handling errors

Common messages and their usual causes:

  • 401 or 403 while downloading: you are not logged in, or access to the gated repository has not been granted.
  • Out of memory: the model or batch is too large for the device. Use a smaller model, a lower precision or a shorter input.
  • A warning about the padding token: many Llama tokenizers have none by default. For batched generation, set one deliberately and check the documentation of your version.
  • Unexpected argument: your library version differs from the example.

Read the full error text before searching for a fix. It usually names the file, argument or device involved.

Generation settings

In Transformers, do_sample=False chooses the most likely token at each step. With do_sample=True, you can also set values such as temperature and top_p. A repository may ship its own generation configuration with default values, so print or set the settings you care about instead of assuming them. For tests, keep sampling off or fix the random seed. For creative work, turn sampling on and compare several outputs.

Wrap your model call in a small function with explicit arguments. It makes your experiments repeatable, and you can later swap the local model for a server call without changing the rest of your program.

When to move to a server

Loading a model inside your script is convenient for experiments, but every script that starts must load it again. When several programs or users need the same model, run it once in a server and call it over HTTP, as the next lesson shows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a first download of an official Llama model fail with an access error?

    You must accept the license, get access and authenticate.
  2. 2. Which format is the safer choice for loading weights?

    safetensors stores tensors without running code during loading.
  3. 3. A reply stops mid-sentence. What should you check first?

    A low token limit cuts the output before the end-of-turn token.
  4. 4. What does apply_chat_template do?

    Each model family has its own markers, and the template inserts them.

Summary

  • Official Llama weights are gated; accept the license and log in with hf auth login.
  • Prefer safetensors and avoid running unknown remote code.
  • The pipeline is the shortest route; Auto classes give more control.
  • Pin revisions and library versions.

Next: Call a Local Llama Server from Python

Your progress is saved in this browser. No account needed.