Bookmarks
ReferenceData & AIVerified

AI models

AI models are trained neural networks that write text, draw images and recognise speech. This reference covers parameters, LoRA fine-tuning, FP8 and FP4, quantisation and diffusion.

checked 17 Nov · next check 24 Nov · 73 min read

Sections
14
Reading
73 min
Current version
0.21.3
Written from
huggingface.co/docs/peft/index

Check status of the reference

Verified 17 Nov · next check 24 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What AI models are and how they work

An AI model is a neural networkneural networkA machine learning model made of layers of simple calculations that adjusts its weights on examples and so learns to find patterns in data.Read more: neural network: an architecture (how numbers flow through the layers) plus weights (numbers found during training). Training fits the weights to data; inferenceinferenceRunning a trained model: on new data it makes predictions or generates text, while the weights stay unchanged.Read more: inference only reads them to produce an answer.

Architecture and weights

The architecture is the skeleton of a model: which layers it has and which operations they perform. The weights are the numbers loaded into that architecture; a set of weights is called a checkpoint. BERT is an architecture, while bert-base-cased is a checkpoint: the weights trained for the original BERT release. The word “model” can mean either, so this reference says which when it matters.

Training changes the weights so that the model’s errors on the data shrink. Fine-tuning continues training a ready-made model on a small dataset for your task, and needs less data, time and compute than training from scratch. During inference the weights do not change: the model receives an input and computes an output.

Three meanings of “parameters”

In talk about AI, “parameters” means three different things. Mixing them up is a common source of confusion.

WhatExampleWhere it is set
Model parametersmodel parameters (weights)The numbers inside a neural network that training fits to data and that are stored in the model file; their count determines size and memory use.Read more: model parameters (weights) are its weights9B means 9 billion weightsDetermined by training; the count is fixed by the architecture
Generation parameterstemperature, top_pIn the request to a ready-made model; see the “LLMs and RAG” reference, section “Generation and its parameters”
Training hyperparametershyperparameterA training or model setting that a person chooses in advance: unlike weights, training does not find it.Read more: hyperparameterlearning rate, LoRA rankIn the training or fine-tuning settings; see the section “Fine-tuning: full, LoRA and QLoRA”

What depends on what

Choosing a model is a chain of dependencies. The task determines the type of model; the type and the quality you need determine the size in parameters; the size together with the number format determines memory; memory determines the hardware; and the hardware determines speed and cost. Of all these links, only the size and the number format (compression losses) affect quality, along with the data and the training and fine-tuning stages.

Top: the selection chain, where each link sets the next. Bottom: what quality depends on.

Five decisions in order

  1. Task and model type: text, images, speech, embeddings; see the section “Types of models”.
  2. Size: how many parameters you need and whether the model is dense or MoE; see the section “Parameters and model sizes”.
  3. Number format and quantisation: how many bytes each weight takes; see the sections “Number formats: FP32, BF16, FP8, FP4” and “Quantisation: methods and losses”.
  4. Training or fine-tuning: you either take a ready-made model or change its weights; see the sections “How a model is trained” and “Fine-tuning: full, LoRA and QLoRA”.
  5. Choosing a specific model: language, licence, hardware; see the section “How to choose a model”.

The main formula

Weight memory equals the number of parameters multiplied by the bytes per parameter. A 27B model (27 billion parameters) in BF16 takes about 54 GB (2 bytes per weight), and in FP4 about 13.5 GB (0.5 bytes). Here GB means 10⁹ bytes. A table for other sizes and formats is in the “Cheat sheet” section, and where the parameter count comes from is explained in “Parameters and model sizes”.

Open and closed models

Open-weight models can be downloaded and run yourself. Closed models are available only through a service’s API. This reference is about how models work, not about services, so it deals with open models, and their names serve as examples.

Related topics

  • Working with a ready-made LLM (tokens, prompts, embeddings, RAG): the “LLMs and RAG” reference.
  • GPUs, inference servers, memory sizing with the KV cache, distributed training: the “AI infrastructure (GPU)” reference.
  • Classical models without neural networks: the “Machine learning basics” reference.

Section sources

the section is written from these pages

Cheat sheet

Weight memory is the number of parameters times the bytes per parameter: 27 billion in BF16 take 54 GB. Below are the formulas, a key to names such as 30B-A3B, and short examples for Transformers, PEFTPEFTparameter-efficient fine-tuningA family of methods for fine-tuning a large model by training only a small number of parameters, often added to it, while keeping the original weights frozen.Read more: PEFT and Diffusers.

Weight memory by size and format

SizeFP32 (4 bytes)BF16/FP16 (2)FP8/INT8 (1)FP4/INT4 (0.5)
1B4 GB2 GB1 GB0.5 GB
9B36 GB18 GB9 GB4.5 GB
27B108 GB54 GB27 GB13.5 GB
70B280 GB140 GB70 GB35 GB
122B488 GB244 GB122 GB61 GB

Formulas

What we calculateFormula
Weight memoryparameters × bytes per parameter
Full fine-tuning (Adam, mixed precision)≈ 16 bytes per parameter, that is 16 GB per 1B
LoRALoRALoRA methodA way of further training language models in which the weights of the base model are frozen and only small low-rank adapter matrices are trained.Read more: LoRAbase weights in BF16 + a small adapter
QLoRA≈ 0.5 bytes per base parameter + a small adapter
Generation speed for a single streamat most memory bandwidth ÷ bytes of active weights

For a mixture of experts (MoE) model, all parameters sit in memory, but only the active ones are read during generation. More in the section “Parameters and model sizes”.

How to read a model name

Part of the nameWhat it meansExample
8B, 27Bnumber of parameters, in billionsQwen/Qwen3-8B
30B-A3B30 billion parameters in total, about 3 billion activeQwen/Qwen3-30B-A3B
8x7Bmixture of experts: 8 experts in each layermistralai/Mixtral-8x7B-Instruct-v0.1
Base, ptbase model after pre-trainingpretrainingThe first and most expensive stage of training a language model: it starts from scratch on a huge text corpus so that the model learns to predict the next token.Read more: pretrainingQwen/Qwen3-8B-Base, google/gemma-3-27b-pt
Instruct, -it, Chattrained to follow instructions and hold a dialoguegoogle/gemma-3-27b-it, Qwen/Qwen1.5-7B-Chat
Thinkinga variant that reasons before answeringQwen/Qwen3-30B-A3B-Thinking-2507
FP8weights are stored in 8 bitsQwen/Qwen3-30B-A3B-FP8
AWQ, GPTQ-Int4quantisation method and bit widthQwen/Qwen2.5-7B-Instruct-AWQ, Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4
GGUF, Q4_K_Mformat for llama.cpp and one of its compression levelsQwen/Qwen3-8B-GGUF
Qwen3, v0.1, 2507model family generation, version number or update date: 2507 means July 2025Qwen/Qwen3-30B-A3B-Instruct-2507

There are no universal naming rules: each author names models in their own way. The most reliable approach is to open the model cardmodel cardA short document accompanying a machine learning model: what it is intended for, what data it was trained on, how it was evaluated, and what its limitations and licence are.Read more: model card and read the parameter count, format and licence.

Installation

bashon the host
pip install transformers peft accelerate bitsandbytes diffusers

Load a model in 4 bits

Quantisation at load time is set through BitsAndBytesConfig. The documentation recommends the nf4 type for training a 4-bit base (QLoRA).

pythonPython, Transformers
import torchfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig config = BitsAndBytesConfig(    load_in_4bit=True,    bnb_4bit_quant_type="nf4",    bnb_4bit_compute_dtype=torch.bfloat16,)model = AutoModelForCausalLM.from_pretrained(    "Qwen/Qwen3-8B",    quantization_config=config,    device_map="auto",)print(model.get_memory_footprint() / 1e9, "GB")

Count parameters and estimate memory

The num_parameters() method returns the number of parameters of the loaded model. The accelerate estimate-memory command reads only config.json, creates the model on the meta device and does not download the weights.

pythonPython, after loading
total = model.num_parameters()print(f"{total / 1e9:.1f}B parameters")
bashon the host
accelerate estimate-memory Qwen/Qwen3-8B --library_name transformers

The result table shows the model size in float32, float16, int8 and int4, as well as an estimate for training with Adam. The estimate covers only loading the weights, not generation.

Add a LoRA adapter

pythonPython, PEFT
from peft import LoraConfig, TaskType, get_peft_modelfrom transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-8B")config = LoraConfig(    r=8,    lora_alpha=32,    lora_dropout=0.1,    target_modules=["q_proj", "v_proj"],    task_type=TaskType.CAUSAL_LM,)peft_model = get_peft_model(model, config)peft_model.print_trainable_parameters()

The print_trainable_parameters() method shows the share of trainable weights: for LoRA it is a fraction of a percent. The adapter is saved with peft_model.save_pretrained("my-adapter"). Training is covered in the section “Fine-tuning: full, LoRA and QLoRA”.

Generate an image from a text description

pythonPython, Diffusers
import torchfrom diffusers import DiffusionPipeline pipe = DiffusionPipeline.from_pretrained(    "stabilityai/stable-diffusion-xl-base-1.0",    dtype=torch.float16,    device_map="cuda",)image = pipe(    "a lighthouse at dawn, watercolor",    num_inference_steps=30,    guidance_scale=5.0,).images[0]image.save("lighthouse.png")

The num_inference_steps parameter sets the number of denoising steps: more steps usually mean higher quality but a longer wait. The guidance_scale parameter strengthens adherence to the prompt, but too high a value usually makes the image worse. How diffusion works is covered in the section “Diffusion models”.

Section sources

the section is written from these pages

How the transformer works

A modern language model is a decoder-only transformertransformerA neural network architecture that processes a whole sequence at once and relates its elements through an attention mechanism rather than one by one.Read more: transformer: tokens are turned into vectors, pass through N identical blocks of attention and an MLP (a fully connected network), and come out as probabilities for the next token. Most of the parameters sit in the matrices of these blocks.

The path of a token

The tokeniser first splits the text (see the “Tokenization” section of the “LLMs and RAG” reference); after that, the model works with token IDs. An embedding is a table that replaces an ID with a vector of hidden_size numbers. The vectors pass through num_hidden_layers identical blocks, then the output layer lm_head turns the vector of the last token into a score for every token in the vocabulary. How the next token is chosen from these scores is covered in the “Generation and its parameters” section of the “LLMs and RAG” reference.

The same block is repeated N times; the dashed lines are residual connections.

Inside a block, each step first normalises the vector, then computes a result and adds it to the original vector. This is a residual connection: the block appends a correction to what is already there, which is why a deep network trains stably.

Attention

Attentionattention mechanismAn operation in a neural network that decides, for each token, which other tokens in the sequence to look at and how strongly, and builds a new representation from them.Read more: attention mechanism lets each token pick up what it needs from the earlier ones. Three vectors are derived from a token’s vector: a query, which is what the token is looking for; a key, which is what the token can be found by; and a value, which is what it hands over. The better a query matches a key, the more weight the value gets. Several “heads” do this in parallel and look at different things, and the O matrix combines their results. A decoder uses a causal mask: a token sees only the previous tokens and itself, which is why the model can be trained to predict the next token.

During generation, the keys and values of tokens that have already been processed are kept; this is the KV cache. To make it take up less memory, models use grouped-query attention (GQA): several query heads share one pair of keys and values. The extreme case is multi-query attention (MQA), with a single pair. The authors of GQA (Ainslie et al., 2023) showed that quality stays close to full multi-head attention while speed stays close to MQA. For how to calculate the KV cache size, see the “Sizing: memory and GPU count” section of the “AI infrastructure (GPU)” reference.

Where the parameters are

In each block, the parameters are the attention matrices (Q, K, V, O) and the MLP matrices. A classic block has four attention matrices of size hidden_size × hidden_size and an MLP of width 4 × hidden_size (2048 for a width of 512 in the original paper). Such a block holds about 12 × hidden_size² parameters, so N blocks hold about 12 × N × hidden_size², and two thirds of that is the MLP. In modern models the split is different: GQA shrinks the K and V matrices, and an MLP with three matrices instead of two and its own width intermediate_size takes up about four fifths of the block. Beyond the blocks there is the embedding table and lm_head: with a large vocabulary, that is more than a billion parameters even for an 8B model.

How to read config.json

The config.json file in a model repository describes its shape. The values below are from Qwen3-8B; you can use them to recompute the model size.

FieldMeaningQwen3-8B
num_hidden_layersnumber of blocks, N36
hidden_sizelength of a token’s vector4096
intermediate_sizewidth of the MLP inside a block12288
num_attention_headsnumber of query heads32
num_key_value_headsnumber of key and value heads (fewer means GQA)8
vocab_sizevocabulary size, rows in the embedding151936
max_position_embeddingsposition length set in the config40960
torch_dtype / dtypedata type of the stored weightsbfloat16

In older repositories the weight type field is called torch_dtype, while in Transformers 5 the configuration class uses the name dtype. Checking against Qwen3-8B: the attention matrices give 2 × 4096 × 4096 + 2 × 4096 × 1024 ≈ 42 million, the three-matrix MLP gives 3 × 4096 × 12288 ≈ 151 million, so about 193 million per block and about 6.95 billion for 36 blocks, which is the “non-embedding” figure from the model card. The embedding and lm_head (tie_word_embeddings is false, so there are two tables) add 151936 × 4096 ≈ 0.62 billion each.

pythonPython, no weights are downloaded
from accelerate import init_empty_weightsfrom transformers import AutoConfig, AutoModelForCausalLM config = AutoConfig.from_pretrained("Qwen/Qwen3-8B")# a model with no memory allocated for weights: shape onlywith init_empty_weights():    model = AutoModelForCausalLM.from_config(config) total = sum(p.numel() for p in model.parameters())print(f"{total / 1e9:.2f}B parameters")

The script downloads only config.json; the result is about 8.19 billion, matching the “8.2B” on the model card.

Length of context and origins

The model learns the order of tokenslanguage model tokenA chunk of text that the tokenizer splits the input and output of a language model into; context, limits and API pricing are measured in tokens.Read more: language model token from positional encoding; most modern models use rotary encoding, RoPE (rope_theta in the config, which in Transformers 5 sits inside rope_parameters). The actual context length depends on training: the max_position_embeddings field only sets an upper bound (40960 for Qwen3-8B, while the native context length on the model card is 32,768 tokens), and the context windowcontext windowThe amount of text, in tokens, that a language model takes in with a single request: the system instruction, the conversation and the reply all count against it.Read more: context window as a limit on a request is covered in the “LLMs and RAG” reference. The architecture itself comes from the paper “Attention Is All You Need” (Vaswani et al., 2017): originally an encoder–decoder for machine translation. For the kinds of models by design, see the “Types of models” section.

Section sources

the section is written from these pages

Parameters and model sizes

The number in a model’s name is its parameter countmodel parameters (weights)The numbers inside a neural network that training fits to data and that are stored in the model file; their count determines size and memory use.Read more: model parameters (weights) (weights), in billions: 9B means about 9 billion numbers the model has learned. It determines memory use, speed and, all else being equal, the model’s capabilities.

Where the number comes from

Parameters are the entries of the weight matrices: in each transformer layer they sit in the attention matrices and the MLP block, plus the embeddingembedding (vector representation)A fixed-length vector in which a model encodes the meaning of a text or another object: fragments with similar meaning get similar vectors.Read more: embedding (vector representation) tables at the input and output. The number of layers and the width (hidden_size) set the size, which is why the total is rarely a round number. According to the Qwen3-8B model card, it has 8.2 billion parameters (6.95 billion without embeddings) and 36 layers. Check the exact value in the model card or in config.json; the structure of a block is described in the section “How the transformer works”.

What grows with size and what does not

Knowledge and quality on hard tasks grow with size. Other things do not grow on their own: how up to date the knowledge is (it is limited by the date of the data), the context length (it is set during training: for Qwen3-8B it is 32,768 tokens, or 131,072 with YaRN) and support for languages that were not in the data.

A new small model can outperform an older large one: quality is set by the data and the training stages, not only by the parameter count (scaling laws are covered in the section “How a model is trained”). Small language models (SLMs) are often produced by distillationknowledge distillationA training method in which a small student model picks up the behaviour of a large teacher model by imitating its outputs.Read more: knowledge distillation, training on the outputs of a large model, which is covered in the same section.

Dense models and MoE

In a dense model, every token passes through all of the parameters. In a mixture of experts (MoEMoEmixture of expertsA neural network architecture in which only individual “experts” work on each token: a router decides whose weights to use, so the model is large but the computation per token is small.Read more: MoE) model, the MLP block is replaced by a set of experts, and a router picks one or several of them for each token. The Switch Transformers paper (2021) showed how to scale such sparse models to a trillion parameters.

Experts E2 and E6 are selected for this token; for the next one the router may pick others.

An MoE model has two numbers: total parameters and parameters active per token. Mixtral 8x7B has 47 billion parameters in total and 13 billion active. It is not 8 × 7 = 56: only the MLP blocks are replaced, while attention and embeddings are shared.

ModelExpertsPer tokenTotalActive
Mixtral 8x7B8247 billion13 billion
Qwen3-30B-A3B128830.5 billion3.3 billion

Memory is determined by all the parameters, because all the experts must be held in it. Speed is determined by the active ones, because only the selected experts are computed.

Why generation is limited by memory

For every new token, the processor reads all of the active weights from memory. So the speed of a single stream cannot exceed the memory bandwidth divided by the size of the active weights in bytes. This is an upper bound: real speed is lower. An example for a hypothetical graphics card with 1,000 GB/s of bandwidth:

Model and formatRead per tokenCeiling, tokens/s
Dense 27B, BF1654 GBabout 18
Dense 27B, FP413.5 GBabout 74
Qwen3-30B-A3B, BF166.6 GBabout 150

The last row shows the benefit of MoE: 3.3 billion parameters are read, although all 30.5 billion are held in memory (about 61 GB in BF16). The effect of batching and of the key-value cache (KV cache) is covered in the reference “AI infrastructure (GPU)”, in the section “Serving models: inference servers”.

Which model will fit

The weights take parameters × bytes per parameter: 2 bytes in BF16, 1 in FP8, 0.5 in FP4 or INT4. The rule from the Transformers documentation: loading the weights of a model with X billion parameters in BF16 needs about 2 × X GB of GPU memory. The formats are described in the section “Number formats: FP32, BF16, FP8, FP4”.

ClassMemoryIn FP4 or INT4In BF16
Phone, laptop4–8 GBup to 4B (2 GB)up to 2B (4 GB)
Single gaming graphics card16–24 GBup to 27–30B (13.5–15 GB)up to 8B (16 GB)
Workstation48–96 GBup to 122B (61 GB)up to 27–30B (54–60 GB)
Server with 4–8 GPUs of 80 GB each320–640 GBup to 800B (400 GB)up to 200B (400 GB)
Cluster of several serversmore than 640 GBmore than 800Bmore than 200B

You can estimate memory with three lines of Python or with the accelerate estimate-memory command, which creates the model on the meta device without downloading the weights.

pythoncalculation on the host
params_b = 27  # billions of parametersfor fmt, nbytes in [("BF16", 2), ("FP8", 1), ("FP4", 0.5)]:    print(fmt, params_b * nbytes, "GB")
bashon the host
accelerate estimate-memory Qwen/Qwen3-8B

Section sources

the section is written from these pages

Types of models

AI models differ in architecture (encoder, decoder, encoder-decoder), purpose (base, instruct, reasoning, embeddings) and modality — the kind of data going in and out: text, images, audio. Choose the type for the task first; size and number format come later.

By architecture

Most transformers follow one of three designs: they use the encoder, the decoder or both blocks together. The difference is what the attention mechanism can see while reading text.

ArchitectureHow it reads textExamplesTasks
Encoder onlyevery word sees the whole text, left and rightBERT, DistilBERT, ModernBERTclassification, named-entity recognition, extracting an answer from text, embeddings
Decoder onlya word sees only what comes before it; text is written one token at a timeGPT-style: Llama, Gemma, Qwen, DeepSeektext generation, chat, code
Encoder-decoder (seq2seq)the encoder reads the whole input, the decoder writes the output token by tokenT5, BART, Whispertranslation, summarisation, speech recognition

Most modern large language models (LLMs) are decoders. Encoders are much smaller (BERT has 110 and 340 million parameters) and handle text understanding: BERT was trained by masking words in a text and making the model restore them. T5 casts any text task as a pair of “text in, text out”.

By purpose

  • Base modelbase model and instruct modelTwo stages of one language model: after pretraining the base model continues text; after fine-tuning the instruct model answers requests in a conversation.Read more: base model and instruct model — the result of pre-training. It continues text and cannot hold a conversation: to it, a question is just the start of a text to be completed. Base models are what you take for fine-tuning. Example: Qwen/Qwen3-30B-A3B-Base (the model card lists a “Pretraining” stage).
  • Instruct model (-it, chat) — a base model that has gone through supervised fine-tuning and preference alignment. It answers in a conversation and expects a request formatted with the chat template. Example: google/gemma-3-4b-it versus the base google/gemma-3-4b-pt.
  • Reasoning modelreasoning modelA language model that writes a long chain of reasoning before answering: it tries out options, checks its own work and only then gives the result.Read more: reasoning model — writes out its reasoning before the answer, so it replies more slowly but does better at maths, code and logic. In Qwen3 the same set of weights works in two modes, with and without reasoning; the chat template parameter enable_thinking switches the mode.
  • Code model — a decoder trained on a large amount of source code in addition. Example: Qwen/Qwen2.5-Coder-7B-Instruct.
  • Embedding and reranking models return numbers, not text, for search by meaning — see the “LLMs and RAG” reference, section “Embeddings”.

How an instruct model is made from a base model is covered in the section “How a model is trained”. For questions and conversation use an instruct model; use a base model only if you plan to fine-tune.

By modality

Modality is the kind of data. Text-only models take and return text. Image-text-to-text models, or VLMsmultimodal modelA model that takes in or produces several kinds of data at once — text, images, audio, video — and links them in a single response.Read more: multimodal model (vision language models), take a picture together with a question and answer in text: they describe an image or answer a question about it. The Transformers documentation splits VLMs into base, chat and instruct versions, just like text models.

Whisper handles speech recognition. It is an encoder-decoder model trained on 680,000 hours of labelled audio. Its tokens control the task: transcribe for recognition, translate for translating speech into English. Images are generated by diffusion modelsdiffusion modelA generative model that creates an image (or audio, or video) from random noise by removing the noise step by step.Read more: diffusion model — see the section “Diffusion models”. A multimodal model takes or returns several kinds of data at once.

Summary table

The class in the library determines what loading returns: it decides which inputs the model accepts and which methods it has.

TypeInputOutputExample taskClass
Decoder language modeltexttextchat, code, summarisationAutoModelForCausalLM
Masked encodertextprobabilities of words at the masked positionsfilling gaps, fine-tuning for classificationAutoModelForMaskedLM
Encoder-decodertexttexttranslation, summarisationAutoModelForSeq2SeqLM
VLMimage and texttexta question about a pictureAutoModelForImageTextToText
Speech to textaudiotexttranscribing a recordingAutoModelForSpeechSeq2Seq
Text to speechtextaudio waveformvoice-overAutoModelForTextToWaveform (for some models)
Diffusion modeltext, sometimes an imageimageimage generationDiffusionPipeline (Diffusers)

How to choose a type for the task

  • Chatbot or assistant — an instruct decoder model; for hard tasks, one with a reasoning mode.
  • Search over documents — an embedding model, with an instruct model composing the answer (RAG).
  • Transcribing recordings — Whisper or another speech recognition model.
  • Pictures from a description — a diffusion model; questions about an existing picture — a VLM.
  • Labelling texts by class — a small encoder such as BERT, fine-tuned for the task.

How to match the type with size, language, licence and hardware is covered in the section “How to choose a model”.

How to load an instruct model

An instruct model receives the request as messages, and the chat template turns them into text with the required special tokens. For Qwen3, reasoning is also switched off here.

pythonPython, Transformers 5
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer name = "Qwen/Qwen3-8B"tokenizer = AutoTokenizer.from_pretrained(name)model = AutoModelForCausalLM.from_pretrained(    name, dtype=torch.bfloat16, device_map="auto") messages = [{"role": "user", "content": "What is a token?"}]text = tokenizer.apply_chat_template(    messages,    tokenize=False,    add_generation_prompt=True,    # no reasoning block    enable_thinking=False,)# special tokens are already in the template textinputs = tokenizer(    [text], return_tensors="pt", add_special_tokens=False).to(model.device)out = model.generate(**inputs, max_new_tokens=200)answer = out[0][inputs.input_ids.shape[1]:]print(tokenizer.decode(answer, skip_special_tokens=True))

If a model has both a base and an instruct version, the suffix in the repository name tells you which one you have: -Base and -pt mean base, -Instruct and -it mean instruct. For Qwen3 the instruct version has no suffix: Qwen/Qwen3-8B from the example above is the counterpart of the base Qwen/Qwen3-8B-Base.

Section sources

the section is written from these pages

Diffusion models

A diffusion modeldiffusion modelA generative model that creates an image (or audio, or video) from random noise by removing the noise step by step.Read more: diffusion model learns to remove noise from images. To generate, it starts from pure noise and, over a few dozen steps, cleans it into a picture that matches the text prompt.

How a model learns to remove noise

The foundation is the 2020 work by Ho, Jain and Abbeel (DDPM, denoising diffusion probabilistic models). Training images are corrupted with noise of varying strength, and the network learns to predict that noise from the noisy image. The trained model does the reverse: it takes random noise the size of the future image and passes it through the network many times. At each step the network predicts the noise residual, and the scheduler uses it to compute a slightly cleaner image.

The three parts of a latent model

Denoising directly in pixels is expensive. In late 2021 Rombach and colleagues proposed latent diffusion: denoising happens in a compressed representation of the image, the latent space of a pre-trained autoencoder. Stable Diffusion is built on this idea. To handle text, cross-attention layers are added to the network, linking the image to the prompt.

  • The text encoder turns the prompt into vectors. Stable Diffusion 1.5 uses a CLIP encoder; Stable Diffusion 3 uses three: two CLIP encoders and T5-XXL.
  • The denoiser predicts the noise at each step. It used to be a U-Net; newer models use a diffusion transformertransformerA neural network architecture that processes a whole sequence at once and relates its elements through an attention mechanism rather than one by one.Read more: transformer (DiT), which in Stable Diffusion 3 is MMDiT (multimodal diffusion transformer).
  • The VAE (variational autoencoder) converts an image to a latent and back. Generation needs only its decoder, which turns the finished latent into pixels.
Denoising happens in the latent: in Stable Diffusion it is eight times smaller than the image in height and width.

In the Diffusers documentation example, for a 512×512 image the initial noise is 64×64, eight times smaller. That is why both height and width must be multiples of 8.

Generation settings

ParameterWhat it doesTypical value
num_inference_stepsThe number of denoising steps. More steps mean slower generation25 in the Stable Diffusion example, 28 for Stable Diffusion 3
guidance_scaleHow strictly to follow the text (classifier-free guidance). A low value gives freedom; too high a value causes artefacts7.5 in the same example, 7.0 for Stable Diffusion 3
negative_promptDescribes what the image should not containan empty string or a list such as “low resolution”
height, widthSize in pixels, a multiple of 8. Below the training size, quality drops512×512 for Stable Diffusion 1.5, 1024×1024 for SDXL
generatorThe source of the initial noise. With the same seed the model produces the same imagetorch.Generator(...).manual_seed(31)
schedulerHow to get the image at the previous step from the predicted noisethe one shipped with the checkpoint

Classifier-free guidance works like this: at each step the network predicts the noise twice, for your prompt and for an empty one, and amplifies the difference between them. In the documentation the empty prompt is encoded separately and the vectors are combined into one batch.

How to get the same image again

AutoPipelineForText2Image picks the pipeline class from the checkpoint itself. Loading in half precision (float16) halves memory use compared with float32.

pythonDiffusers 0.43, needs an NVIDIA GPU
import torchfrom diffusers import AutoPipelineForText2Image pipe = AutoPipelineForText2Image.from_pretrained(    "stabilityai/stable-diffusion-xl-base-1.0",    dtype=torch.float16,    variant="fp16",).to("cuda") generator = torch.Generator("cuda").manual_seed(31)image = pipe(    "Astronaut in a jungle, cold color palette, detailed",    negative_prompt="low resolution, bad details",    num_inference_steps=30,    guidance_scale=7.5,    height=1024,    width=1024,    generator=generator,).images[0]image.save("astronaut.png")

The scheduler and the parts of the pipeline

A scheduler has no weights: it is only settings, so you can swap it on a loaded pipeline. The documentation advises starting with the default scheduler. For flow matching models (Flux and similar) it recommends FlowMatchEulerDiscreteScheduler or FlowMatchHeunDiscreteScheduler; the first is their default.

pythonDiffusers 0.43
import torchfrom diffusers import (    AutoPipelineForText2Image,    DPMSolverMultistepScheduler,) pipe = AutoPipelineForText2Image.from_pretrained(    "stabilityai/stable-diffusion-xl-base-1.0",    dtype=torch.float16,    variant="fp16",)pipe.scheduler = DPMSolverMultistepScheduler.from_config(    pipe.scheduler.config)# instead of .to("cuda"): parts move to the GPU one at a timepipe.enable_model_cpu_offload()

Flow matching, transformers and video

Stable Diffusion 3 is trained as rectified flow, a variant of flow matching: the model learns to move noise towards data along a straight line. Its denoiser is a transformer, not a U-Net. Diffusion models create more than images: video is generated the same way.

Memory and fine-tuning

Memory is calculated as for language models: parameters multiplied by bytes per parameter. This covers only the weights; activations need memory on top. Add up the denoiser, the text encoders and the VAE. The single T5-XXL encoder in Stable Diffusion 3 has 4.7 billion parameters, about 9.4 GB in half precision. The documentation warns that the model is hard to run on a GPU with less than 24 GB of memory even in fp16, and suggests offloading parts to the CPU (enable_model_cpu_offload) at the cost of a small loss in speed.

A diffusion model can be fine-tuned with LoRALoRALoRA methodA way of further training language models in which the weights of the base model are frozen and only small low-rank adapter matrices are trained.Read more: LoRA adapters, just like a language model: see “Fine-tuning: full, LoRA and QLoRA” for details. Licences and the safety of weight files are covered in “Model files, licences and safety”.

Section sources

the section is written from these pages

How a model is trained

A model is trained in several stages. Pre-trainingpretrainingThe first and most expensive stage of training a language model: it starts from scratch on a huge text corpus so that the model learns to predict the next token.Read more: pretraining on a huge corpus produces a base model, and post-training — supervised fine-tuning, preference alignment and reasoning training — turns it into an assistant.

Developers release base and instruct versions; everything in the dashed frame is up to you.

Pre-training: predicting the next token

Starting from random weights, the model is taught a single task: to predict the next token from the beginning of a text. The error is computed for every token of the corpus, so no labelled data is needed — raw text and code are enough. This is how the model picks up language and knowledge of the world, but not the ability to hold a conversation: a base model continues a text rather than answering a question.

The data runs to trillions of tokens, and the training cost is estimated at about 6 × parameters × tokens operations (as in Kaplan et al., 2020, on scaling laws). The Chinchilla paper showed that for a given compute budget, model size and the number of training tokens should grow in proportion: when the model size doubles, the data doubles too. Chinchilla itself has 70 billion parameters and was trained on 1.4 trillion tokens, which is 20 tokens per parameter, and it outperformed Gopher (280 billion parameters) on the same budget. The paper’s estimates for other sizes also give about 20 tokens per parameter: for example, 20.2 billion tokens for a model with 1 billion parameters. This is work for large GPU clusters; how they are built is explained in the “AI infrastructure (GPU)” reference, in the “Distributed training” section.

Supervised fine-tuning (SFT)

Supervised fine-tuning (SFTSFTsupervised fine-tuningA training stage in which a model learns from ready-made pairs of a prompt and a model answer, turning a base model into an instruction-following one.Read more: SFT) shows the base model pairs of “request — model answer” written in a chat template. The loss function stays the same — cross-entropy over tokens — but the data is different, and the model learns to answer in the required form. The result is an instruct model.

pythonPython, TRL
from datasets import load_datasetfrom trl import SFTConfig, SFTTrainer trainer = SFTTrainer(    model="Qwen/Qwen3-0.6B-Base",    args=SFTConfig(        output_dir="Qwen3-0.6B-Instruct",        # the chat template and the end-of-reply token are taken from SmolLM3        chat_template_path="HuggingFaceTB/SmolLM3-3B",    ),    train_dataset=load_dataset("trl-lib/Capybara", split="train"),)trainer.train()

Preference alignment: RLHF and DPO

After SFT the answers are acceptable, but not always what people want. Preference alignment adjusts the model using comparisons of answers. In RLHFRLHFreinforcement learning from human feedbackA way to fine-tune a language model so that its answers appeal to people: human ratings are turned into a reward, and the model is trained to maximise it.Read more: RLHF (reinforcement learning from human feedback), people rank the model’s answers, a reward model is trained on their ratings, and then the language model is fine-tuned with reinforcement learning (RL) so that the reward grows. In the InstructGPT paper (Ouyang et al., 2022), people preferred the answers of a 1.3-billion-parameter model to those of GPT-3 with 175 billion.

DPODPOdirect preference optimisationA method of fine-tuning a language model on pairs of “better” and “worse” responses that needs neither a separate reward model nor reinforcement learning.Read more: DPO (direct preference optimization, Rafailov et al., 2023) solves the same problem without a separate reward model and without generating answers during training: the model is trained directly on “better — worse” pairs with a simple classification loss. This makes DPO simpler and more stable. In TRL, a pair for it looks like this:

jsona pair for DPO and RewardTrainer
{"prompt": [{"role": "user", "content": "What colour is the sky?"}], "chosen": [{"role": "assistant", "content": "Blue."}], "rejected": [{"role": "assistant", "content": "Green."}]}

Reasoning training

Reasoning models are taught to think step by step before answering. DeepSeek-R1-Zero applied reinforcement learning with verifiable answers and no preliminary SFT: the reward came from rules — whether the final answer to the problem is correct (for code, a compiler checks the answer against tests) and whether the format with <think> tags is followed. The algorithm is GRPO: it samples a group of answers to one question and compares them with each other. The model developed checking and revision of its solutions on its own, but its reasoning was hard to read and mixed languages; so DeepSeek-R1 added stages with SFT and answer selection.

Distillation

Distillation transfers the knowledge of a large teacher model to a small student model. In the work of Hinton et al. (2015), the student learns from the probabilities the teacher outputs, not only from the correct answer. For language models it is often simpler: the student is trained with SFT on the teacher’s answers. This is how the DeepSeek-R1 authors passed reasoning on to small models: open Qwen2.5 and Llama models were fine-tuned on 800,000 examples generated with R1, using SFT alone, without reinforcement learning.

What gets released and what it is used for

A developer usually publishes base and instruct versions, and sometimes intermediate checkpoints too. For fine-tuning, the base version gives more freedom, while the instruct version gives a ready-made answer style. The post-training stages can be reproduced with the TRL library.

StageDataResultTRL tool
Pre-trainingtrillions of tokens of text and codebase modeloutside TRL
SFT“request — answer” pairsinstruct modelSFTTrainer
Reward model“better — worse” pairsanswer scorer for RLHFRewardTrainer
Preferences (DPO)“better — worse” pairsaligned instruct modelDPOTrainer
Reasoning (RL)problems with a verifiable answerreasoning modelGRPOTrainer

Section sources

the section is written from these pages

Fine-tuning: full, LoRA and QLoRA

Fine-tuningfine-tuningFurther training of an existing model on your own data so that it handles a specific task better: style, answer format, domain terminology.Read more: fine-tuning adapts a ready-made model to a task, a style or a response format. Full fine-tuning changes all the weights and needs a lot of memory; LoRALoRALoRA methodA way of further training language models in which the weights of the base model are frozen and only small low-rank adapter matrices are trained.Read more: LoRA and QLoRAQLoRAQLoRA methodA method of fine-tuning language models in which the frozen base model is stored in 4 bits and LoRA adapters are trained in 16-bit format.Read more: QLoRA train small adapters and often fit on a single graphics card.

When to fine-tune

Fine-tuning suits cases where you need to fix a response format, a style, a language or a narrow task: parsing emails into fields, answering in JSON, a support tone of voice. New and frequently changing knowledge is better supplied to the model through document retrieval (RAG): the choice between the two is covered in the “LLMs and RAG” reference, in the section “What LLMs and RAG are and how they work”.

Full fine-tuning: how much memory

Full fine-tuning updates every parameter, so memory holds the weights, the gradients and the Adam optimiser states. With mixed precision that is about 16 bytes per parameter: according to the ZeRO paper, 2 bytes for the weights in FP16, 2 for the gradients and 12 for the optimiser states (an FP32 copy of the weights, the momentum and the variance). For a 9-billion-parameter model this gives 9 × 16 = 144 GB, without activations. The Transformers page “GPU memory usage” counts the gradients in FP32 and gives 18 bytes.

LoRA: training a small correction

LoRA (Low-Rank Adaptation, Hu et al., 2021) freezes the model weights and trains only a correction to selected matrices. The product of two narrow matrices, B·A, is added to the frozen matrix W, where A has size r × d and B has size d × r. The rank r is much smaller than d, so there are few trainable parameters: for a 4096 × 4096 matrix and r = 16 that is 2 × 4096 × 16 = 131,072 numbers instead of 16,777,216, less than 1%. B starts at zero, so training begins exactly from the original model.

The adapter adds a correction B·A to the output of W; the rank r is much smaller than d.

Four main LoraConfig parameters configure the adapter. The default values come from the PEFTPEFTparameter-efficient fine-tuningA family of methods for fine-tuning a large model by training only a small number of parameters, often added to it, while keeping the original weights frozen.Read more: PEFT documentation.

ParameterWhat it setsDefault
rrank: a higher rank means more capacity and more trainable parameters8
lora_alphacorrection scale: the correction is multiplied by lora_alpha / r8
lora_dropoutshare of values dropped inside the adapter to guard against overfitting0.0
target_moduleswhich layers get an adapter; "all-linear" means all linear layersdepends on architecture

According to the PEFT documentation, an adapter on all linear layers, as in QLoRA, can reach the quality of full fine-tuning; by default, adapters are added only to the query and value attention layers in many architectures.

QLoRA: the same on a 4-bit base

QLoRA (Dettmers et al., 2023) keeps the frozen base model in 4 bits and trains the LoRA adapters in BF16. The weight format is NF4 (4-bit NormalFloat), designed for normally distributed weights. Double quantisation compresses the quantisation constants as well. A paged optimiser offloads its states to system memory when the graphics card runs out of memory. Gradients flow through the 4-bit weights into the adapters. For more on quantisation methods, see the section “Quantisation: methods and losses”.

The arithmetic for 9 billion parameters: in BF16 the weights take 9 × 2 = 18 GB, in 4 bits 9 × 0.5 = 4.5 GB, about 5 GB with the quantisation constants. According to the QLoRA paper, a 65B model can be fine-tuned on a single 48 GB graphics card, whereas full 16-bit fine-tuning would need more than 780 GB.

MethodWhat is trainedMemory for 9BResult
Fullall parametersabout 144 GBa new full copy of the model
LoRAadapters, BF16 baseabout 18 GB + adaptersa small adapter file
QLoRAadapters, NF4 baseabout 5 GB + adaptersa small adapter file

Training data

Conversations are written in the messages format: a list of turns with the roles user and assistant. SFTTrainer from the TRL library applies the model’s chat template to them itself, so you do not need to write token markup by hand. Data quality matters more than volume: in the QLoRA paper, a set of 9 thousand examples (OASST1) beat a set of 450 thousand (a FLAN v2 subsample) on chat quality. The number of examples you need depends on the task — check on a held-out set.

QLoRA on a small model

The example trains an adapter for Qwen/Qwen3-1.7B on the conversational dataset trl-lib/Capybara. The TRL documentation recommends raising the learning rate for adapters to around 1e-4. You need a graphics card supported by bitsandbytes.

pythontrain.py
import torchfrom datasets import load_datasetfrom peft import LoraConfigfrom transformers import BitsAndBytesConfigfrom trl import SFTConfig, SFTTrainer bnb = BitsAndBytesConfig(    load_in_4bit=True,    bnb_4bit_quant_type="nf4",    bnb_4bit_use_double_quant=True,    bnb_4bit_compute_dtype=torch.bfloat16,)lora = LoraConfig(    r=16,    lora_alpha=32,    lora_dropout=0.05,    target_modules="all-linear",    task_type="CAUSAL_LM",)args = SFTConfig(    output_dir="qwen3-qlora",    learning_rate=1e-4,    num_train_epochs=1,    per_device_train_batch_size=2,    gradient_accumulation_steps=8,    gradient_checkpointing=True,    bf16=True,)dataset = load_dataset("trl-lib/Capybara", split="train")trainer = SFTTrainer(    model="Qwen/Qwen3-1.7B",    args=args,    train_dataset=dataset,    peft_config=lora,    quantization_config=bnb,)trainer.train()# only the adapter is saved, not the whole modeltrainer.save_model("qwen3-qlora")

Merging and multiple adapters

An adapter can be kept separate from the base: one set of base weights serves many adapters for different tasks. For fast inference, merge the adapter into the base with merge_and_unload(): after that the model works as an ordinary one, with no separate adapter loading.

pythonmerging into the BF16 base
import torchfrom peft import PeftModelfrom transformers import AutoModelForCausalLM base = AutoModelForCausalLM.from_pretrained(    "Qwen/Qwen3-1.7B", dtype=torch.bfloat16)model = PeftModel.from_pretrained(base, "qwen3-qlora")merged = model.merge_and_unload()merged.save_pretrained("qwen3-merged")

Risks

  • Catastrophic forgetting: after learning a narrow task, the model copes worse with everything else. None of the methods rules out this risk: test the model on tasks outside your dataset too.
  • Overfitting on a small set: the model memorises the examples and repeats them. Keep a held-out set and watch its loss.
  • Data leakage: the model may memorise part of the training texts, and individual examples can be extracted verbatim by querying it. Do not include personal data or secrets in the set.

Section sources

the section is written from these pages

Number formats: FP32, BF16, FP8, FP4

A number format determines how many bytes each model parameter takes and which values it can represent. The shorter the format, the less memory and the faster the computation, but the coarser the numbers.

A floating-point number has three parts: a sign, an exponent (which sets the range) and a mantissa (which sets the precision). E4M3 reads as 4 exponent bits and 3 mantissa bits, plus a sign bit. The bit layout of the formats is covered in detail in the “AI infrastructure (GPU)” reference, section “GPUs: architecture, memory and precision”.

Available formats

FormatBitsExponent / mantissaWhere it is used
FP32328 / 23master copy of weights in training, error-sensitive calculations
TF3232 in memory8 / 10inside NVIDIA tensor cores: multiplication with 10 mantissa bits, data stored as FP32
BF16BF16BF16 formatA 16-bit floating-point number format with the same range as FP32 but lower precision. It is used to store and compute neural network weights.Read more: BF16168 / 7training and inference; same range as FP32
FP16165 / 10inference, training with loss scaling; maximum 65,504
FP8 E4M3FP8 and FP4 formats8- and 4-bit number formats (FP8, FP4) used to store neural network weights and activations so that models take less memory and train and run faster.Read more: FP8 and FP4 formats84 / 3weights and activations; maximum 448
FP8 E5M285 / 2gradients; maximum 57,344
FP4 E2M142 / 1weights and activations in MXFP4 and NVFP4; maximum 6
INT8, INT48, 4integer, no exponentquantised weights, see the section “Quantisation: methods and losses”

BF16 or FP16

Both use 16 bits, but the bits are split differently. FP16 gives 10 mantissa bits but only 5 exponent bits, so numbers above 65,504 overflow. BF16 takes its exponent from FP32 (8 bits), so the range is the same, but precision is lower: 7 mantissa bits.

In training, range matters more: gradients are sometimes very small and sometimes very large. With FP16 you have to scale the loss (multiply it by a power of two so that gradients do not underflow to zero), whereas BF16 does not need this. The PyTorch documentation warns that most models pre-trained in BF16 do not fit in the FP16 range and produce gradient overflow.

Mixed precision

In mixed precision, the main computations run in 16 bits, while a master copy of the weights is kept in FP32 and accumulates the updates; this is what the authors of the paper “Mixed Precision Training” proposed in 2017. In PyTorch, torch.autocast chooses the type for each operation: it wraps only the forward pass and the loss computation.

pythontraining in BF16
import torch with torch.autocast("cuda", dtype=torch.bfloat16):    loss = model(**batch).lossloss.backward()optimizer.step()optimizer.zero_grad()

With FP16, autocast is combined with torch.amp.GradScaler, which handles loss scaling; with BF16 it is not needed.

FP8

FP8 has two encodings, each suited to its own part of training. E4M3 is more precise but has a narrow range (up to 448): it is used for weights and forward-pass activations. E5M2 is coarser but reaches 57,344: it stores backward-pass gradients. This is how the format is described by the authors of the 2022 paper and in the Transformer Engine documentation.

The FP8 range is not enough for all tensors at once, so each tensor is given its own scaling factor: values are multiplied by it before being stored and divided by it after being read.

FP4 and block scaling

Four bits give only 16 combinations, and E2M1 can represent numbers only up to ±6. To make the format usable, values are divided into blocks, and each block has its own shared multiplier. This comes to about 4 bits per value plus a small overhead for the multipliers.

FormatElementBlockBlock scale
MXFP4 (OCP MX specification)FP4 E2M132 valuesE8M0: power of two, 8 bits
NVFP4 (NVIDIA)FP4 E2M116 valuesFP8 E4M3, plus a shared FP32 per tensor

An NVFP4 block is half the size and its scale is more precise, so values land closer to the originals, but there are more multipliers: the overhead is higher than in MXFP4.

What a format does to a model

FormatBytes per parameterMemory for 27BQuality risk
FP324108 GBnone, the reference
BF16, FP16254 GBpractically none
FP8, INT8127 GBsmall, depends on the model and method
FP4, INT40.513.5 GBnoticeable, needs blocks and calibration

A short format can speed up the computation itself only on hardware that computes it natively: FP8 on NVIDIA GPUs from the Ada and Hopper generations onwards, FP4 from Blackwell onwards. On an older card, the weights are unpacked to 16 bits before each multiplication: memory is saved, but the computation is not faster. For ways to obtain 8- and 4-bit weights from an existing model, and their losses, see the section “Quantisation: methods and losses”.

Section sources

the section is written from these pages

Quantisation: methods and losses

QuantisationquantisationCompressing the weights and computations of a trained model into lower-precision numbers — integers or short floats — to reduce memory use and speed up inference.Read more: quantisation stores the weights of a finished model, and sometimes the activations too, in a shorter format: 8 or 4 bits instead of 16. The model takes 2–4 times less memory, and quality usually drops only slightly. The fewer the bits, the bigger the loss.

How compression works

A low-precision number can take only a few values: 256 in int8 and 16 in int4. So every weight is rounded, which produces a rounding error. The methods differ in how they stop this error from spoiling the output. Weights are split into groups, for example of 128, and each group has its own scale, so an outlier in one group does not stretch the range of the others.

Memory is simple arithmetic: parameters × bytes per parameter. For a 27B model in BF16 the weights take 54 GB, at 8 bits 27 GB and at 4 bits 13.5 GB. That is the weights only: the KV cache and activations come on top. For the formats, see the section “Number formats: FP32, BF16, FP8, FP4”; for sizing with the KV cache, see the reference “AI infrastructure (GPU)”, section “Sizing: memory and GPU count”.

After training or during it

PTQ (post-training quantisation) compresses a model that is already trained, which is how the methods in the table below work. Some need no data and compress at load time; others run a small calibration set through the model and use the activations to decide how to compress each layer. That takes longer, but at 4 bits and below it is usually more accurate. QAT (quantisation-aware training) trains the model with quantisation in mind, so the loss is smaller. Developers sometimes release such versions themselves: Gemma 3 has a QAT version in Q4_0, and according to its model card the quality is close to bfloat16.

What gets compressed: weights, or activations too

Weight-only methods (GPTQ, AWQ, bitsandbytes at 4 bits) keep activations in BF16 or FP16. Before each matrix multiplication the kernel unpacks the weights. This saves memory and speeds up generation when it is limited by reading weights from memory: 4-bit weights are a quarter of the data compared with BF16.

Weight-and-activation methods (the W8A8 scheme: FP8 or INT8) multiply directly in the short format. They speed up processing of long prompts and large batches, but need suitable hardware: FP8 multiplication is available on NVIDIA with compute capability 8.9 and above (Ada, Hopper, Blackwell), on AMD Instinct MI300 and on Intel XPU. Where the right kernels are missing, vLLM by default runs such a checkpointmodel checkpointA saved state of a model at a given training step: the weights and, as a rule, everything needed to resume training from that point.Read more: model checkpoint as W8A16: the weights stay compressed and accuracy does not suffer, but activations and multiplication are in 16 bits.

Methods

MethodBitsCalibrationWhere it runs
bitsandbytes (INT8, NF4)8 and 4not needed: compresses at load timeTransformers: NVIDIA, Intel XPU, CPU; vLLM: NVIDIA only
GPTQ (Frantar et al., 2022)2, 3, 4, 8needed: a dataset at compression timeNVIDIA, Intel XPU, CPU; AMD only in Transformers
AWQ (Lin et al., 2023)4needed: a datasetready-made checkpoint: NVIDIA, Intel XPU, CPU; AMD only in Transformers
FP8, NVFP4FP8 and FP4 formats8- and 4-bit number formats (FP8, FP4) used to store neural network weights and activations so that models take less memory and train and run faster.Read more: FP8 and FP4 formats8 and 4not needed with on-the-fly compressionFP8: NVIDIA from Ada, AMD, Intel XPU; NVFP4: Blackwell
GGUFGGUFGGUF formatA binary file format that stores a model’s weights and everything needed to load it: llama.cpp and other GGML-based runtimes read the model from a single file.Read more: GGUF (llama.cpp)1–8optional (--imatrix)llama.cpp: CPU, GPU, Apple silicon

AWQ finds about 1% of important weights in the model from the distribution of activations and protects them by scaling. GPTQ chooses the rounding using approximate second-order information. In Transformers benchmarks on Llama 3.1 at 4 bits, AWQ and GPTQ often lead on accuracy, but need calibration. At 8 bits models stay close to the original; below 4 bits the loss is noticeable, especially at 2 bits. Ready-made FP8 and NVFP4 checkpoints for vLLM are produced with NVIDIA Model Optimizer or LLM Compressor, and Transformers can also compress to both formats itself, at load time.

GGUF types

GGUF is a single file with the weights, configuration and tokenizer for llama.cpp. The type name shows the bit width and variant: Q4 is about 4 bits, K is k-quantisation, S, M and L are the small, medium and large variants (Q4_K_M is larger than Q4_K_S), and IQ are i-quants, including from 2 bits. When compressing, you can pass an importance matrix (--imatrix). Bits per weight, from the llama-quantize README table for Llama 3.1 8B:

TypeBits per weight8B model size
Q8_08.507.95 GiB
Q6_K6.566.14 GiB
Q5_K_M5.705.33 GiB
Q4_K_M4.894.58 GiB
IQ4_XS4.464.17 GiB
IQ2_XXS2.382.23 GiB

Bits per weight are higher than the nominal figure: group scales are stored too, and k-types are mixed by default, so some tensors are stored in a different type (the --pure flag turns this off). For Llama 3.1 8B the README gives 4.9 GB in Q4_K_M against 32.1 GB in F32. First convert the model to a high-precision GGUF, then compress it:

bashin the llama.cpp directory
python convert_hf_to_gguf.py \  --outfile qwen3-8b-bf16.gguf \  --outtype bf16 \  --remote Qwen/Qwen3-8B./build/bin/llama-quantize \  qwen3-8b-bf16.gguf \  qwen3-8b-Q4_K_M.gguf \  Q4_K_M

Loading at 4 bits with Transformers

For bitsandbytes it is enough to pass a config at load time: the weights are compressed straight away. For 8 bits, set only load_in_8bit=True in BitsAndBytesConfig. NF4 (normal float 4) is a 4-bit type from the QLoRA paper; its values are denser near zero, where most weights lie. It is also used to fine-tune a model (section “Fine-tuning: full, LoRA and QLoRA”).

pythonPython, Transformers
import torchfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig bnb = BitsAndBytesConfig(    load_in_4bit=True,    bnb_4bit_quant_type="nf4",    bnb_4bit_compute_dtype=torch.bfloat16,)model = AutoModelForCausalLM.from_pretrained(    "Qwen/Qwen3-8B",    quantization_config=bnb,    device_map="auto",)

Ready-made quantised versions

Often you do not need to compress anything yourself: popular models have ready-made versions on Hugging Face. The method shows in the repository name and on the model card: -AWQ, -GPTQ-Int4, -FP8, -GGUF. For a ready-made checkpoint no config is needed: Transformers reads the method from config.json, and for GGUF you pass the file in gguf_file. Most GGUF models are dequantised to full precision when loaded this way and take as much memory as an uncompressed model, so to save memory run GGUF in llama.cpp. In vLLM a ready-made version is a single command (servers are covered in the reference “AI infrastructure (GPU)”, section “Serving models: inference servers”):

bashon a server with a GPU
vllm serve Qwen/Qwen3-8B-AWQ

Where quality drops noticeably

  • Below 4 bits: the loss is noticeable, especially at 2 bits, and AQLM and VPTQ also take a long time to compress.
  • Small models: at the same bit width they lose more than large ones.
  • Hard tasks: mathematical reasoning degrades earlier and more than anything else.
  • Languages: the loss is spread unevenly across them, and languages with non-Latin scripts suffer most, while automated tests understate it. Check Uzbek separately, on real examples.

There is no general figure for the loss: it depends on the model, the method and the task. Test on your own examples by comparing the answers of the compressed and original models (section “How to choose a model”).

Section sources

the section is written from these pages

Model files, licences and safety

A model on Hugging Face is a repository: a configuration, a tokenizer, the weights in parts and a card with the licence. Weights in the safetensors format load without running any code, while older .bin files (pickle) can run it.

What a repository contains

Open the “Files and versions” tab of any model: it holds a set of files, each with its own job. Below is a typical layout, using Qwen/Qwen3-30B-A3B as the example; other models differ in tokenizer file names and the number of parts.

FileWhat it holds
config.jsonthe architecture: number of layers, hidden size, number of attention heads, model type
generation_config.jsondefault generation parameters
tokenizer.json, tokenizer_config.jsonthe tokenizer vocabulary and its settings, including the chat template
model-00001-of-00016.safetensorsone part of the weights (a shard); large models have dozens
model.safetensors.index.jsonthe index: which shard holds each parameter (weight_map) and the total size
README.mdthe model card: description, limitations, metadata and licence
LICENSEthe licence text, if the developer put it in the repository

A chat template is a rule for turning a list of messages into text with special tokens. How to use it in requests is explained in the “LLMs and RAG” reference, in the section “Prompts and chat templates”. Shards keep large weights from sitting in a single file: save_pretrained() in Transformers splits a checkpoint larger than 50 GB into parts (the limit is set by max_shard_size) and writes an index.

Weight file formats

FormatExtensionWhat matters
safetensors formatsafetensors formatA simple file format for storing tensors, such as model weights, safely: loading only reads the data and never executes code, unlike pickle.Read more: safetensors format.safetensorstensors only, no code; fast loading; the recommended format on the Hub; PyTorch uses pickle by default
PyTorch pickle.bin, .ptpickle serialisation: arbitrary code can run on loading
GGUFGGUFGGUF formatA binary file format that stores a model’s weights and everything needed to load it: llama.cpp and other GGML-based runtimes read the model from a single file.Read more: GGUF.ggufone file for llama.cpp and other runtimes: tensors and metadata together
ONNX.onnxa model in a portable format for third-party runtimes

Unlike safetensors, which holds only tensors, GGUF stores both the weights and a standard set of metadata, so a single file is enough to run a model in llama.cpp. For how quantised GGUF files are made, see the section “Quantisation: methods and losses”.

Model card

A model cardmodel cardA short document accompanying a machine learning model: what it is intended for, what data it was trained on, how it was evaluated, and what its limitations and licence are.Read more: model card is the repository’s README.md: plain Markdown with a YAML metadata block at the top. It describes the model, its intended use and limitations (including biases), the training parameters and the data. Read it before downloading the weights.

yamlmetadata of a derived model
license: apache-2.0base_model: Qwen/Qwen3-30B-A3Blanguage:  - en  - rupipeline_tag: text-generation

The license field is shown on the model page and works as a filter. base_model links a fine-tuned or quantised model to the original, and language lists the languages. If you need Uzbek, look for uz in the metadata and for a description of quality in the card text: the author fills in the metadata, and it does not prove that the model knows the language well.

What an “open” model means

“Open weightsopen-weight modelAn AI model whose trained weights have been published: they can be downloaded, run on your own hardware, fine-tuned and built into your own product under the terms of the licence.Read more: open-weight model” means the files can be downloaded. That is not the same as open source. The Open Source AI Definition from the OSI requires the freedoms to use, study, modify and share the system, and for that, access to three things: information about the training data, the complete code for training and running, and the model parameters.

If only the weights and the inference code are open, or the licence forbids some uses, the model does not meet this definition. In practice it matters more to read the licence. Terms vary:

  • permissive licences (Apache 2.0, MIT): allow commercial use, modification and redistribution with minimal conditions, such as keeping the attribution notice;
  • licences with use restrictions: the developer’s own licence, which may set limits on the number of users, forbid some uses or set requirements for naming derived models;
  • gated repositories: the files are available only after you submit a request and accept the terms; your username and email are passed to the author, unless they chose not to collect them.

In the metadata, license: other means a custom licence: its name and link are given in the license_name and license_link fields. Check the text: the terms may differ for a commercial product, and for fine-tuning and redistributing a derived model.

How to download someone else’s model safely

Pickle is a set of instructions, and unpacking it can call any Python function. So a malicious .bin can run code on your machine at load time, before the first request to the model. The Hub scans every uploaded file with the ClamAV antivirus and shows the list of imports from the pickle, flagging suspicious ones. The documentation states plainly that scanning is not a 100% guarantee and that responsibility for security lies with the user.

The second danger is trust_remote_code=True. For models with their own architecture, the code lives in the repository, and this parameter allows Transformers to run it. The Hub scans repositories for malware, but the Transformers documentation still advises caution: read the code and pin the revision (revision) so the code cannot change after you have checked it.

  • take weights in safetensors; use .bin and .pt only from a source you trust;
  • keep trust_remote_code off until you have read the model’s code;
  • pin revision to a commit hash, not to the main branch;
  • look at the file list and the card before downloading.
pythonlisting files without downloading the weights
from huggingface_hub import list_repo_files repo = "Qwen/Qwen3-30B-A3B"for name in list_repo_files(repo):    print(name)
pythonloading with a pinned revision
from transformers import AutoModelForCausalLM # full commit hash from the history on the model pagecommit = "ad44e777bcd18fa416d9da3bd8f70d33ebb85d39" model = AutoModelForCausalLM.from_pretrained(    "Qwen/Qwen3-30B-A3B",    revision=commit,    use_safetensors=True,)

With use_safetensors=True, loading fails if the repository has no safetensors files, instead of silently falling back to pickle. By default (None), safetensors files are used, and if there are none, .bin. Copy the commit hash from the commit history on the model page.

Section sources

the section is written from these pages

How to choose a model

Choose an open model in this order: task and model type, languages, licence, memory and hardware, speed, context length. Then test two or three candidates on your own examples: a benchmark score is no substitute for your task.

Six questions, in order

  1. Task. What must the model do: answer in a chat, classify texts, search by meaning, draw, recognise speech? This determines the model type: instruct, an encoder such as BERT, an embeddingembedding (vector representation)A fixed-length vector in which a model encodes the meaning of a text or another object: fragments with similar meaning get similar vectors.Read more: embedding (vector representation) model, a diffusion model, a speech recognition model. The types are described in the section “Types of models”.
  2. Languages. Is the language you need, including Uzbek, listed in the model cardmodel cardA short document accompanying a machine learning model: what it is intended for, what data it was trained on, how it was evaluated, and what its limitations and licence are.Read more: model card? If a language is not listed, do not count on its quality: test it on your own examples.
  3. Licence. Are you allowed to do what you intend: commercial use, fine-tuning, distributing derivative models? Read the terms in the licence itself, not in its name: “open weightsopen-weight modelAn AI model whose trained weights have been published: they can be downloaded, run on your own hardware, fine-tuned and built into your own product under the terms of the licence.Read more: open-weight model” does not mean “permissive licence”. More in the section “Model files, licences and safety”.
  4. Memory and hardware. The weights take parameters × bytes per parameter, plus the KV cache and activations. A 27-billion-parameter model at 4 bits is about 13.5 GB for the weights alone. The formulas are in the section “Parameters and model sizes”.
  5. Speed. A mixture of experts (MoE) model computes only some of its parameters: Qwen3-30B-A3B has 3.3 billion of 30.5 billion active (hence A3B in the name), but all of them sit in memory. With fewer bits per weight, less data is read from memory for each token. Inference servers are covered in the reference “AI infrastructure (GPU)”, section “Serving models: inference servers”.
  6. Context length. The maximum is stated in the model card; in config.json it usually corresponds to the max_position_embeddings field, but the number there does not always match the stated one, and then the card is the one to trust. A long context uses memory for the KV cache, and quality at the limit of the length can be lower.

Where to look

Open models are hosted on the Hugging Face Hub. The huggingface.co/models page filters them by model card metadata: task, library, language, licence. The author enters the language and licence in the metadata (the Hub can detect the task and library itself), so the language filter finds only what the author declared: an empty “language” field does not mean the language is unsupported, only that the author did not state it.

A model card (a README.md file with a YAML header) describes the intended use, limitations and biases, training data and evaluation results. Read the sections on limitations and usage: they hold what a benchmark table does not.

Some repositories are gated: to download the files you must submit a request, and your username and email are sent to the authors unless they opted out of collecting them. Access is granted to a specific user, not to an organisation, and approval can be automatic or manual.

What to trust in benchmarks

A benchmark is a set of tasks with reference answers and a metric over them. It is useful for rough screening, but the score has limits:

  • It does not measure your task: a good result on school exams says nothing about your support emails.
  • Test questions can end up in the training data (leakage), and then the model answers from memory.
  • Authors measure differently: a different number of examples in the prompt, a different prompt template, different generation settings. Scores from different cards are not always comparable.
  • Leaderboards and tables go out of date quickly: new models and new versions of the tasks keep appearing.

Test on your own examples

Collect 20–50 examples from your task, including difficult and awkward ones: typos, mixed languages, empty or overly long input. Run each candidate with the same generation settings and compare the answers against criteria written down beforehand: is it correct, is it complete, is it in the right language, is the format respected.

pythonthe same questions and settings
from transformers import pipeline questions = ["Parolni qanday tiklayman?", "How do I return an item?"]models = ["Qwen/Qwen3-30B-A3B-Instruct-2507", "Qwen/Qwen3-4B-Instruct-2507"] for name in models:    chat = pipeline("text-generation", model=name, device_map="auto")    for q in questions:        msgs = [{"role": "user", "content": q}]        out = chat(msgs, max_new_tokens=200, do_sample=False)        print(name, "|", q)        print(out[0]["generated_text"][-1]["content"])

do_sample=False turns off randomness, so that differences in the answers come from the model rather than luck. The models in the example have no reasoning mode: in hybrid Qwen3 models it is on by default, and 200 tokens can all go on “thinking”. In BF16 the weights of a 30B model take about 61 GB (30.5 billion × 2 bytes), so on a graphics card with 24 GB it is run quantised. Generation parameters are covered in the reference “LLMs and RAG”, section “Generation and its parameters”. For bulk testing on ready-made sets there is Lighteval, the Hugging Face library for evaluating models. It runs from the command line and can work through accelerate, vllm, sglang and other backends.

bashexample from the Lighteval documentation
lighteval accelerate \  "model_name=openai-community/gpt2" \  truthfulqa:mc

Evaluating RAG quality is a separate task: it is covered in the reference “LLMs and RAG”, section “Evaluating RAG quality”.

Worked example

Task: a support chatbot in Uzbek, one graphics card with 24 GB of memory.

StepConclusion
Model typeinstruct: it answers questions, while a base model only continues the text
Languagelook for Uzbek in the candidate’s card; whether or not it is declared, we test the quality ourselves
Licencepermissive, allowing commercial use
Memory27–30B at 4 bits: 13.5–15 GB of weights, leaving headroom for the KV cache and activations
Speedan MoE model with few active parameters answers faster than a dense one of the same size
Testing30 real customer questions, two or three candidates, the same settings

Section sources

the section is written from these pages

Common mistakes

Most mistakes with open-weight modelsopen-weight modelAn AI model whose trained weights have been published: they can be downloaded, run on your own hardware, fine-tuned and built into your own product under the terms of the licence.Read more: open-weight model come from three places: miscounting memory and mixing up parameter counts, compressing without checking, and fine-tuning where RAG is needed. Below are the common misconceptions, why they fail and what to do instead.

“More parameters is always better”

Quality depends on size, data volume and training stages together. In the Chinchilla paper (Hoffmann et al., 2022), a 70B-parameter model was trained on four times more data with the same compute budget as the 280B Gopher. Chinchilla outperformed Gopher. A 9B model fine-tuned for your task can do as well as a general-purpose 27B one. It has a third of the weights, so it is faster and cheaper to run.

Start with the smallest model that fits your hardware, test it on your own examples and scale up only if the result falls short.

Confusing total and active parameters in MoE

A mixture of experts (MoE)MoEmixture of expertsA neural network architecture in which only individual “experts” work on each token: a router decides whose weights to use, so the model is large but the computation per token is small.Read more: MoE model has two numbers: total parameters and parameters active per token. Mixtral 8x7B has 47B in total and 13B active. Active parameters determine the compute per token, while memory is determined by all of them: every expert must be held in memory, even if a token never reaches it.

ModelTotalActiveWeights in BF16
Mixtral 8x7B47B13Babout 94 GB
Qwen3-30B-A3B30.5B3.3Babout 61 GB

So 30B-A3B needs about the compute per token of a 3B model, but as much GPU memory as a 30B one.

Counting memory from the weights alone

Parameters × bytes per parameter gives only the weights. A 27B model in BF16 takes 54 GB for weights, and running it needs more. On top come the KV cache (which grows with context length and the number of concurrent requests) and activations. For a calculation that includes the KV cache, see the “AI infrastructure (GPU)” reference, section “Sizing: memory and GPU count”. Leave some headroom.

Squeezing a small model down to 2–3 bits

QuantisationquantisationCompressing the weights and computations of a trained model into lower-precision numbers — integers or short floats — to reduce memory use and speed up inference.Read more: quantisation rounds weights to a small set of values, and the fewer the bits, the greater the loss. According to the method comparison in the Transformers documentation, 8 bits are almost indistinguishable from BF16 in accuracy, and 4 bits keep it high. Below 4 bits the loss is noticeable, especially at 2 bits. Small models compress worse than large ones. In the GPTQ paper (Frantar et al., 2022), larger models generally tolerate quantisation better, and at 3 bits it is they that preserve accuracy best. That makes 2–3 bits for a small model the riskiest option.

Start with 8 or 4 bits. If memory is short, compare a smaller model at 4 bits with the model you want at 2–3 bits on your own tasks. The Transformers documentation advises measuring accuracy and speed on your own task and hardware before choosing a method. For the methods and their losses, see the section “Quantisation: methods and losses”.

Fine-tuning for new knowledge

Fine-tuning changes a model’s style, response format and behaviour, but it absorbs new facts poorly. In the experiments of Gekhman et al. (2024), the model learned examples containing facts new to it noticeably more slowly than the rest, and once it had learned them, it hallucinated more often. For up-to-date documents and a closed knowledge base you need retrieval over them (RAG): knowledge is updated without training, and an answer can be backed by a link to the document. For choosing between the two, see the “LLMs and RAG” reference, section “What LLMs and RAG are and how they work”.

Fine-tuning without the chat template

A chat model continues a sequence of tokens, and the roles system, user and assistant are turned into special tokens. Different models use different ones: Mistral-7B-Instruct marks user turns with [INST] and [/INST], while Zephyr-7B uses <|user|> and <|assistant|>. With the wrong tokens, quality drops sharply. Take the template from the tokenizer of the very model you are fine-tuning, and use it to build both the training examples and the requests at run time.

pythonTransformers 5
from transformers import AutoTokenizer tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")messages = [{"role": "user", "content": "Hello!"}]text = tok.apply_chat_template(    messages,    tokenize=False,    add_generation_prompt=True,)# if you tokenise yourself, do not add special tokens againinputs = tok(text, add_special_tokens=False)

add_generation_prompt=True appends a marker for the start of the reply: without it, the model may continue the user’s turn instead of answering. Training examples do not need the marker, so use add_generation_prompt=False there. The template already contains all the required special tokens, while the tokenizer, when called normally, may add <bos> or <eos> on top. According to the documentation, extra or duplicated tokens degrade the result; with tokenize=True there are no duplicates.

The adapter was not picked up

If after LoRA fine-tuning the model behaves like the base model, or answers differently after every load, check three common causes. First: the trained model was loaded through get_peft_model(). It creates a new, untrained adapter; you need PeftModel.from_pretrained. Second: the names in target_modules do not match the model’s modules. PEFTPEFTparameter-efficient fine-tuningA family of methods for fine-tuning a large model by training only a small number of parameters, often added to it, while keeping the original weights frozen.Read more: PEFT reports an error only if no name matches at all, and silently skips the unmatched ones among the matched.

pythonloading an adapter
from peft import PeftModel # load the base model the same way as for trainingmodel = PeftModel.from_pretrained(base_model, "./my-adapter")model.eval()

Check print_trainable_parameters() right after get_peft_model(), before training: if the number of trainable parameters is much smaller than expected, some layers stayed frozen. Third: the model has randomly initialised layers, such as a classification head, and they were not listed in modules_to_save. On every load they will get new random weights.

Breaking the licence

“Open weights” does not mean “any use”. Some licences are permissive, such as Apache 2.0 and MIT, while others are developers’ own licences with restrictions: on the number of users, on particular uses, on the name of a derived model. The fine-tuning dataset may also have its own terms. Read the licence on the model card before you start, not just before release; for the kinds of licence, see the section “Model files, licences and safety”.

Choosing a model by a single benchmark

A benchmark tests a specific set of tasks. A high score on it does not guarantee good results in your language, format and data, and some of the tests may have leaked into the training data. Put together 20–50 of your own examples with expected answers and compare two or three candidates on them; for how to do this, see the section “How to choose a model”.

Loading a pickle from an unverified repository

Pickle is PyTorch’s default weights format, and loading such a file can execute arbitrary code. The Hugging Face documentation advises loading models from users and organisations you trust. Transformers itself takes weights from safetensors if the repository has them: this format is safer than pickle. Treat trust_remote_code=True with the same caution: it allows running the model’s code from its repository, not from Transformers. For more, see the section “Model files, licences and safety”.

  • Before running, calculate memory: all parameters × bytes, plus the KV cache and activations.
  • Compare models on your own examples, not by a single score.
  • For new facts use RAG; for style and format, fine-tuning.
  • Take the chat template and tokenizer from the same model.

Section sources

the section is written from these pages

Model families and versions

This reference covers PEFT 0.21 (latest release 0.21.3, 13 November 2026) together with TRL 1.18 and Diffusers 0.43. Below are the open-weight model families as of 17 November 2026, and library versions.

Open-weight model families

The table lists only models whose weights can be downloaded, and only what their huggingface.co pages state. Closed models behind an API, rankings and prices are out of scope. Sizes are given as on those pages: B is billions of parameters, T is trillions; “active” means the parameters that run on each token in a MoE model.

FamilySize and designContextModalitiesLicence
Qwen3.8 (Alibaba Qwen)27B dense; Flash-Next is MoE, 125B, 6B active; 2.4T-A95B is MoE, 2.4T, 95B active262,144 tokens, extendable to 1M27B and Flash-Next: text, images and video; 2.4T-A95B: text only27B: Apache 2.0; Flash-Next: qwen-community-1.0; 2.4T-A95B: qwen3.8-max
Gemma 4 (Google DeepMind)E2B, E4B, 12B and 31B dense; 26B A4B is MoE, 25.2B, 3.8B active128K for E2B and E4B, 256K for the resttext, images, video; audio for E2B, E4B and 12BApache 2.0
Llama 4 (Meta)Scout is MoE, 109B, 17B active (16 experts); Maverick is MoE, 400B, 17B active (128 experts)Scout: 10M, Maverick: 1Mtext and imagesLlama 4 Community License
Mistral Small 4 and Large 4 (Mistral AI)Small 4 is MoE, 119B, 6.5B active; Large 4 is MoE, about 1T, about 52B activeSmall 4: 256K, Large 4: 1Mtext and imagesSmall 4: Apache 2.0; Large 4: Mistral Ecosystem Open-Weight License
DeepSeek-V4 (DeepSeek)V4-Flash is MoE, 284B, 13B active; V4-Pro is MoE, 1.6T, 49B active; V4.1-Flash is MoE, 552B in the main part, 8B active when processing the prompt and 16B when generating1MV4-Flash and V4-Pro: text; V4.1-Flash: text and imagesMIT
gpt-oss (OpenAI)gpt-oss-120b is MoE, 117B, 5.1B active; gpt-oss-20b is MoE, 21B, 3.6B active131,072 tokens (per config.json)textApache 2.0
GLM-5.3 (Z.ai)GLM-5.3 is MoE, about 753B (from the weight files); GLM-5.3-Flash is MoE, 320B, 18B active1MGLM-5.3: text; Flash: text and imagesGLM-5.3: glm-5.3; Flash: MIT
Olmo (Ai2)Olmo 3 and 3.1 are dense, 7B and 32B; Olmo Hybrid is 7B, a hybrid of recurrent layers and attention65,536 tokenstextApache 2.0
Phi-4 (Microsoft)Phi-4 is dense, 14B; Phi-4-reasoning-vision-15B is 15B16KPhi-4: text; reasoning-vision: text and imagesMIT
FLUX 3 Image Klein (Black Forest Labs)5.6B in the image transformer, with a separate Qwen3-VL-4B text encoder; Klein is distilled, 16 steps; Klein Base is for fine-tuning, 50 steps—input: text and up to 10 images; output: an imageFLUX Kommunity License: non-commercial use; commercial use of outputs if annual revenue is under 5 million dollars
Stable Diffusion 3.5 (Stability AI)Large is about 8B, MMDiT; Medium is about 2.5B, MMDiT-X—text to imageStability Community License: free if annual revenue is under 1 million dollars
Whisper (OpenAI)large-v3 is 1.55B; large-v3-turbo is 809M, with 4 decoder layers instead of 3230-second windowspeech to textlarge-v3: Apache 2.0; large-v3-turbo: MIT

How to read the table and where to check

The model cardmodel cardA short document accompanying a machine learning model: what it is intended for, what data it was trained on, how it was evaluated, and what its limitations and licence are.Read more: model card on huggingface.co is the primary source: take sizes, context and licence from it, not from this table. The set of families changes every few weeks, so news about model releases links to this page, and the table is updated along with them.

Library versions

LibraryBranchLatest releaseDate
PEFT0.210.21.313 November 2026
TRL1.181.18.117 November 2026
Diffusers0.430.43.012 November 2026
Transformers5.235.23.013 November 2026

Transformers is covered in the “LLMs and RAG” reference, in the section “Versions and what’s new”; here it matters only as a dependency of PEFT and TRL.

What’s new in PEFT 0.21

  • New methods: the Riemannian-preconditioned LoRA optimiser, the LoRA variant KaSA, Super-Tuning and ShadowPEFT (0.21.0, 15 September).
  • Stricter adapter handling: add_adapter raises an error if the adapter targets layers that do not exist; a merged adapter cannot be removed. Catch errors as peft.PeftError.
  • Fixed a bug when combining LoRA adapters through add_weighted_adapter in the SVD variant: the scale was applied twice.
  • Added support for torchao 0.18 with the new tensor types Int8Tensor and Float8Tensor.
  • In 0.21.3, saving a model with tensor parallelismTPtensor parallelismA way of splitting one neural network layer across several GPUs: the layer’s matrices are cut into pieces, each GPU computes its share, and the results are combined through communication.Read more: TP gathers only the adapter weights, not the whole model sharded across GPUs.

What’s new in TRL and Diffusers

  • TRL 1.18: AsyncGRPOTrainer is now stable and imported from trl; the old path from trl.experimental.async_grpo still works but emits a warning and will be removed in 2.0.0.
  • TRL 1.17: when training GRPO with vLLM and importance-sampling correction (on by default), GRPOConfig raises an error if top_p < 1.0 or min_p > 0.0 is set and top_k is not above 0; set top_k (for example, 512).
  • TRL 1.17: an example of LoRA fine-tuning Mistral-Large-4-1T-A52B with SFTTrainer on a single node of 8 B300 GPUs; it needs transformers>=5.22.0, peft>=0.21.0 and accelerate>=1.15.0.
  • Diffusers 0.42.1 closed a trust_remote_code bypass when loading through from_pretrained; update if you are on 0.42.0.
  • Diffusers 0.43: in the LoRA training examples for text-to-image and SDXL LCM, --max_grad_norm now takes effect, so runs with large gradients may behave differently from before.

How to update

Update the libraries together: TRL and PEFT depend on the Transformers version.

bash
pip install -U peft trl diffusers

In a project, pin the branches so that a mid-project release does not break training.

textrequirements.txt
peft>=0.21,<0.22trl>=1.18,<1.19diffusers>=0.43,<0.44transformers>=5.23,<5.24

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 1 entry

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · no changes · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “AI models” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61