Loading an LLM in 4 bits using bitsandbytes

Overview
This tutorial demonstrates loading a causal language model in 4-bit
precision in a resource-constrained environment such as free Google
Colab. The example model is facebook/opt-350m.
Install dependencies
1!pip install transformers bitsandbytes accelerate peft
- Transformers provides pretrained models, tokenizers, and generation utilities.
- bitsandbytes provides quantization.
- Accelerate helps manage execution and device placement.
- PEFT provides parameter-efficient fine-tuning techniques.
Import model utilities
1from transformers import AutoModelForCausalLM, AutoTokenizer
AutoModelForCausalLM selects a causal language-model architecture.
AutoTokenizer loads the matching tokenizer, which converts text into
token IDs.
Load the model in 4-bit precision
1model_id = "facebook/opt-350m"23model = AutoModelForCausalLM.from_pretrained(4 model_id,5 load_in_4bit=True,6 device_map="auto"7)89tokenizer = AutoTokenizer.from_pretrained(model_id)
load_in_4bit=True requests 4-bit loading. device_map="auto" asks the
Transformers/Accelerate stack to place model components on available
hardware.
Model architecture
The article inspects the resulting OPTForCausalLM architecture:
- Token embeddings: shown as
Embedding(50272, 512, padding_idx=1), representing a vocabulary of 50,272 tokens and embedding width 512. - Positional embeddings: shown as
OPTLearnedPositionalEmbedding(2050, 1024), supplying token-position information. - Projection layers: includes 4-bit
project_inandproject_outlayers. - Decoder layers: a stack of 24 decoder layers, with self-attention, normalization, activation, and feed-forward components.
- Language-modeling head: maps hidden representations to vocabulary logits for next-token prediction.
Run inference
1text = "Hello my name is"2device = "cuda:0"34inputs = tokenizer(text, return_tensors="pt").to(device)56outputs = model.generate(**inputs, max_new_tokens=20)
The tokenizer returns a dictionary containing values such as input_ids
and attention_mask. The max_new_tokens argument limits the number of
generated tokens.
The article also expands the generation call:
1outputs = model.generate(2 input_ids=inputs["input_ids"],3 attention_mask=inputs["attention_mask"],4 max_new_tokens=205)
Scope and takeaway
The article describes itself as an introductory explanation of the first part of a notebook and links to a Colab notebook for the remaining material.
Workflow: install dependencies, load the quantized model and tokenizer, inspect the architecture, tokenize a prompt, and generate text.
Source coverage note: This file reflects the publicly accessible article text, not every cell in the linked notebook.
Related Posts

Quantization using bitsandbytes
A beginner level introduction to LLM quantization using the libraries bitsandbytes, accelerate and transformers.