Skip to Content
Recodocs

02 · Choose a base model that fits

Four questions, each able to rule a model out. Qwen2.5-1.5B-Instruct is chosen because it is Apache-2.0, trains with LoRA in 5.8 GB of a 15.6 GB T4, and scores 73.0% before any training at 177 ms per message.

14 min read
Part 1
Decide
Model
Qwen2.5 0.5B, 1.5B and 7B; seven tokenizers
Data
BANKING77, and six support messages in four languages
Hardware
One T4, in Google Colab
Open in ColabSaved with the outputs of a GPU run

Lesson 1 decided whether to fine-tune. This lesson decides what to fine-tune. The choice matters more than it looks. When Intercom trained models for the same job on the same data, the base model alone moved the result by 12 points:

Same task, same training data: the base model alone moved the result 12 points

Intercom issue extractor, offline downstream answer rate, %

1
0%20%40%60%GPT-4.1, prompted63.3Gemma 8B, fine-tuned51.0Qwen3 8B, fine-tuned55.0Qwen3 14B, fine-tuned63.4
Source: Intercom Fin research, David vs Goliath: are small LLMs any good?

Pinterest made the same choice by measurement: it trained students of 0.6, 1.7, 4 and 8 billion parameters and served the 4-billion one, for the best balance of quality and throughput. Shopify picked a 2.6-billion-parameter model over a 14-billion one that recalled 2.7 points more, because it answered four times faster. Across the business cases, 25 of the 35 programmes that name their model trained one of 8 billion parameters or fewer.

The result comes first and the exact setup, time and cost are in How it was built at the end.

So the choice is a measurement under constraints, not a leaderboard lookup. This lesson asks four questions in order. Each is cheaper to answer than the next, and each can rule a model out, so by the end only models that pass all four are left.

  1. May we use it? Licence and access.
  2. Will it train on our GPU? Memory, predicted and then measured.
  3. What does our language cost? Tokens per message, and what tokens do to memory and price.
  4. Is it good enough, and fast enough? Accuracy and latency before any training.

The notebook answers each question on a free Colab T4 with 16 GB of memory, the GPU this course trains on.

1. May we use it?

Licence comes first because it is free to check and it is final: no result later in the lesson can overturn it. The Hugging Face Hub publishes each model's licence tag, whether downloading it requires an approved request (gated), and its configuration. The notebook reads all three in one loop:

from huggingface_hub import model_info

for model_id in CANDIDATES:
    info = model_info(model_id)
    card = info.card_data.to_dict() if info.card_data else {}
    licence = card.get("license_name") or card.get("license")  # e.g. "apache-2.0", "llama3.2"
    print(model_id, licence, "gated" if info.gated else "open", info.safetensors.total)

Licences differ inside one family, and two leading families are gated

Candidate base models: size, licence, access, vocabulary, context window and attention heads

2
ModelParametersLicenceAccessVocabularyContextKV / query headsLicence condition
Qwen2.5-0.5B
0.49bn
Apache-2.0Open
152k
32k2 / 14Permissive
Qwen2.5-1.5B
1.54bn
Apache-2.0Open
152k
32k2 / 12Permissive
Qwen2.5-3B
3.09bn
Qwen ResearchOpen
152k
32k2 / 16Non-commercial use only
Qwen2.5-7B
7.62bn
Apache-2.0Open
152k
32k4 / 28Permissive
SmolLM2-1.7B
1.71bn
Apache-2.0Open
49k
8k32 / 32Permissive
Mistral-7B v0.3
7.25bn
Apache-2.0Open
33k
32k8 / 32Permissive
Phi-4-mini
3.84bn
MITOpen
200k
128k8 / 24Permissive
Llama 3.2 1B
1.24bn
Llama 3.2Gated
128k
128k8 / 32Over 700m monthly users needs Meta’s grant; derived names start with “Llama”
Gemma 3 1B
1.00bn
GemmaGated
262k
32k1 / 4Prohibited-use policy binds every derivative
Sources: Hugging Face model metadata and config.json for each model; Llama 3.2 licence (Meta); Gemma Terms of Use (Google); Qwen Research licence (Alibaba Cloud).

Read the licence column before the size column. Three different situations appear.

  • Permissive (Apache-2.0, MIT). Use, modify and ship a fine-tuned model commercially, keeping the licence notice.
  • Permitted with conditions (Llama, Gemma). The Llama 3.2 licence requires a separate grant from Meta for products with more than 700 million monthly active users, and a fine-tuned model you distribute must have "Llama" at the start of its name. The Gemma terms bind every derived model to Google's prohibited-use policy, which you must pass on to anyone you distribute to. Both are gated: each user accepts the licence and downloads with an account token.
  • Not for commercial use. Qwen2.5-3B sits between two Apache-2.0 siblings but carries the Qwen Research licence, which grants rights "for non-commercial purposes only". A team that picked "Qwen2.5" by family name and the 3B by size would have built on a model it could not ship.

The rule that follows is small and saves the most time in this lesson: check the licence of the exact model, not the family. For the rest of this lesson the notebook uses only open, ungated models, so it runs without an account. The 3B model is ruled out here.

2. Will it train on our GPU?

Treat the device budget as a hard constraint, not a model-size ranking. The weights, activations and optimiser state compete for memory during training. A smaller candidate that meets the task's quality requirement may be the better choice.

Training memory has four parts. The weights; a gradient for each weight that is being trained; the optimizer state, which for Adam is two running averages per trained weight; and the activations, the intermediate results each layer saves so the backward pass can use them.

The first three can be predicted from the number of parameters Ψ\Psi and the bytes each one costs. Activations depend on sequence length, batch size and model width, so they are measured.

Mtrain  ≈  bw Ψ⏟weights  +  (bg+bo) Ψtrained⏟gradients and optimizer  +  MactivationsM_{\text{train}} \;\approx\; \underbrace{b_w\,\Psi}_{\text{weights}} \;+\; \underbrace{(b_g + b_o)\,\Psi_{\text{trained}}}_{\text{gradients and optimizer}} \;+\; M_{\text{activations}}
MethodWeights bwb_wTrained parametersGradients and Adam bg+bob_g + b_oBytes per parameter, before activations
Full fine-tune, mixed precision4 (fp32)all4 + 816
LoRA2 (16-bit, frozen)adapters only4 + 8 on the adaptersabout 2
QLoRA0.5 (4-bit NF4) + constantsadapters only4 + 8 on the adaptersabout 0.52

The 16 bytes are the accounting in the ZeRO paper: for mixed-precision Adam, "2Ψ + 2Ψ + KΨ = 16Ψ bytes", where K = 12 covers an fp32 copy of the weights and Adam's two moments. QLoRA's 4-bit weights cost half a byte each, plus 0.127 bits per parameter for the quantisation constants after its double quantisation.

A worked example, Qwen2.5-7B (Ψ\Psi = 7.62 billion):

Full: 16×7.62=122 GBLoRA: 2×7.62=15.2 GBQLoRA: 0.516×7.62=3.9 GB\text{Full: } 16 \times 7.62 = 122\ \text{GB} \qquad \text{LoRA: } 2 \times 7.62 = 15.2\ \text{GB} \qquad \text{QLoRA: } 0.516 \times 7.62 = 3.9\ \text{GB}

On paper a full fine-tune needs eight T4s, LoRA sits exactly at the T4's limit with nothing left for activations, and QLoRA leaves 12 GB spare. The notebook then runs one real training step for each combination that the prediction does not rule out by a wide margin, and records the peak memory.

def measure(model_id, method):
    load = dict(device_map={"": 0})
    if method == "full":
        # fp32 weights, fp16 compute: what the Trainer does with fp16=True
        model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32, **load)
    elif method == "lora":
        # frozen weights in 16-bit
        model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, **load)
    else:
        # frozen weights in 4-bit NF4, as QLoRA does
        q = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                               bnb_4bit_use_double_quant=True,
                               bnb_4bit_compute_dtype=torch.float16)
        model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=q, **load)
        model = prepare_model_for_kbit_training(model)  # what TRL calls for 4-bit models
    model.gradient_checkpointing_enable()
    # ... attach LoRA adapters (r=16, all linear layers) for "lora" and "qlora", then one step:
    with torch.autocast("cuda", dtype=torch.float16):
        loss = model(input_ids=IDS, labels=IDS).loss
    loss.backward()
    opt.step()                                           # allocates Adam's two moments
    return torch.cuda.max_memory_allocated() / 1e9

The naive rule is a floor: measured memory runs higher, and the 7B fits only in 4-bit

GB for one training step on a 512-token sequence. Grey: full fine-tune; blue: LoRA; orange: QLoRA

3
naive predictionafter loadingpeak during the step0 GB5 GB10 GB15 GB20 GB25 GBT4 memory: 15.6 GB0.5B · full9.9 GB peak0.5B · LoRA2.8 GB peak0.5B · QLoRA3.1 GB peak1.5B · full25 GB predicted: not attempted1.5B · LoRA5.8 GB peak1.5B · QLoRA5.6 GB peak7B · full122 GB predicted: not attempted7B · LoRAout of memory on the first step7B · QLoRA15.2 GB peak
Source: lesson notebook on a Colab T4, gradient checkpointing on, batch of one. Bars past the scale are clipped and labelled.

Read the chart row by row, against the dashed outline of the prediction.

  • Full fine-tuning held to the rule, with activations on top. The 0.5B model needed 9.9 GB against a predicted 7.9: the 16 bytes per parameter, plus about 2 GB of activations. The 1.5B and 7B models were not attempted, at 25 and 122 GB predicted.
  • LoRA's 7B failed at the edge. The 7B model loaded into 15.4 GB of a 15.6 GB card and ran out of memory on the first step. The prediction said "exactly at the limit", and at the limit there is no room for activations.
  • QLoRA fitted the 7B, but at 15.2 GB, not 4.6. And for the 0.5B model, QLoRA used more memory than LoRA: 3.1 GB against 2.8.

The gap has a cause the naive rule leaves out. QLoRA quantises the large linear layers, but not the token embedding or the output head, and the standard recipe (prepare_model_for_kbit_training, which TRL calls for 4-bit models) casts those to fp32 for stable training. Their size is the vocabulary times the model width:

152,064×3,584=545 million parameters per matrix×2 matrices×4 bytes=4.36 GB152{,}064 \times 3{,}584 = 545\ \text{million parameters per matrix} \times 2 \text{ matrices} \times 4\ \text{bytes} = 4.36\ \text{GB}

That is more than the whole 4-bit body of the 7B model. Put both into the rule and it predicts the measured 7.9 GB after loading almost exactly:

0.516×(7.62−1.09)+4×1.09  ≈  3.4+4.4  =  7.8 GB0.516 \times (7.62 - 1.09) + 4 \times 1.09 \;\approx\; 3.4 + 4.4 \;=\; 7.8\ \text{GB}

The step then added 7.3 GB more: activations for 512 tokens, the gradient flowing back through the fp32 output head, and the adapters' optimizer state. The lesson for choosing: QLoRA saves memory on the body of a large model, and on a small model with a large vocabulary the fp32 embeddings cancel the saving. Lesson 5 shows how to keep those layers in 16-bit when sequences get longer.

One detail of the GPU matters here too. The T4 (compute capability 7.5) has no bfloat16 tensor cores, which arrived with Ampere (8.0), so training on it runs in float16; the notebook checks this before anything else.

3. What does our language cost?

A tokenizer splits text into the pieces a model reads, and every piece costs memory in training and money in serving. A larger vocabulary can cover a language in fewer, longer pieces, but each vocabulary entry is a row in the embedding matrix, which is the memory found in section 2. The notebook runs the same six banking messages, in four languages, through seven tokenizers:

for name, model_id in TOKENIZERS.items():
    tok = AutoTokenizer.from_pretrained(model_id)
    for lang, sentences in SENTENCES.items():
        ids = [tok(s, add_special_tokens=False)["input_ids"] for s in sentences]
        counts[name][lang] = sum(len(i) for i in ids)

The same Hindi messages cost 68 tokens in one tokenizer and 420 in another

Tokens for six identical customer messages, by tokenizer and language; right: Hindi tokens against vocabulary size (log)

4
EnglishHindiSpanishChineseGPT-256420 ×7.5120 ×2.1167 ×3.0SmolLM256296 ×5.3117 ×2.1142 ×2.5Mistral v0.356286 ×5.1104 ×1.985 ×1.5Qwen2.556252 ×4.585 ×1.551 ×0.9Llama 3.256143 ×2.685 ×1.565 ×1.2Phi-4-mini5687 ×1.671 ×1.362 ×1.1Gemma 35668 ×1.271 ×1.354 ×1.0Hindi tokens vs vocabulary015030045032k64k128k256kGPT-2SmolLM2Mistral v0.3Qwen2.5Llama 3.2Phi-4-miniGemma 3Vocabulary size (log) →
Source: lesson notebook, Hugging Face tokenizers as published. Messages translated by Recohut; English counts happen to match across these tokenizers.

English costs 56 tokens in every tokenizer. Hindi costs anywhere from 68 tokens (Gemma 3, 1.2 times its English) to 420 (GPT-2, 7.5 times). Qwen2.5, the family that passed sections 1 and 2, needs 252 tokens for the Hindi messages, 4.5 times its English. The scatter on the right shows why vocabulary size alone does not predict this: Qwen2.5's vocabulary is larger than Llama 3.2's, yet Llama needs fewer Hindi tokens. What matters is how much of the language the tokenizer was trained on.

Token count multiplies every cost in the earlier sections. Activation memory grows with sequence length. A context window of 32,768 tokens holds 4.5 times less Hindi than English for Qwen2.5. A hosted model charges per token. For an English or Chinese task Qwen2.5 is efficient; for a Hindi task, a team should measure Gemma or Phi before deciding.

The same arithmetic sets serving memory. At inference the model keeps the keys and values of every previous token for every layer, the KV cache:

KV bytes per token  =  2×layers×KV heads×head size×2\text{KV bytes per token} \;=\; 2 \times \text{layers} \times \text{KV heads} \times \text{head size} \times 2

Fewer key-value heads, smaller serving memory: a 1.7B model can need more than a 7B one

KV cache per generated or prompt token, KB in 16-bit; GB for one 8,192-token sequence at the end of each bar

5
0 KB50 KB100 KB150 KB200 KBQwen2.5-0.5B24 layers, 2 KV of 14 heads12 KB · 0.10 GBQwen2.5-1.5B28 layers, 2 KV of 12 heads28 KB · 0.23 GBQwen2.5-7B28 layers, 4 KV of 28 heads56 KB · 0.47 GBMistral-7B v0.332 layers, 8 KV of 32 heads128 KB · 1.07 GBSmolLM2-1.7B24 layers, 32 KV of 32 heads192 KB · 1.61 GB
Computed from each model's config.json: 2 × layers × KV heads × head size × 2 bytes.

Grouped-query attention, where several query heads share one key–value head, is why Qwen2.5-7B needs 56 KB per token while SmolLM2-1.7B, which keeps all 32 heads, needs 192 KB. For long prompts or many simultaneous users, the KV cache can outgrow the weights; lesson 12 returns to it.

4. Is it good enough, and fast enough?

The last question needs your task, and it is the one lesson 1 already set up: score each candidate on held-out examples before any training, with the strongest prompt you have, and time it. Here BANKING77 stands in for your task, with lesson 1's prompt of ten retrieved, labelled examples, on 385 test messages. The 7B model runs in 4-bit, the only way it fits the T4.

Bigger is more accurate before training, and slower: choose on both axes

BANKING77, 385 held-out messages, prompt with 10 retrieved examples: accuracy % (right axis) against ms per message (log); dot area = GPU memory

6
506070809010030 ms100 ms300 ms1000 msQwen2.5-0.5B65.7% · 58 ms · 1.9 GB · 3.4% not an intentQwen2.5-1.5B73.0% · 177 ms · 4.8 GB · 7.0% not an intentQwen2.5-7B, 4-bit90.1% · 706 ms · 7.6 GB · 1.8% not an intentMilliseconds per message (log) →Accuracy, %
Source: lesson notebook on a Colab T4, batched generation. The 7B model runs in 4-bit NF4.

Before any training, size bought accuracy: 65.7% for the 0.5B model, 73.0% for the 1.5B and 90.1% for the 7B in 4-bit. It also bought latency and memory: 58, 177 and 706 milliseconds per message, and 1.9, 4.8 and 7.6 GB. The 7B model is the most accurate and twelve times slower than the 0.5B.

Neither Pinterest nor Shopify served the most accurate model they measured; both chose on the two axes together. And these are numbers before training, which is the point of measuring them. The question lesson 4 answers is how much of the 17-point gap between the 1.5B and 7B models a LoRA fine-tune closes, at the 1.5B model's speed and memory. (On this particular label task, lesson 1's classifier at 92.2% remains the baseline to beat; BANKING77 stands in here for your own held-out set.)

5. The decision

Each question ruled something out. Put the answers side by side and the choice for this course is not a matter of taste.

Four questions, one table: the 1.5B model for training on a T4, the 7B for QLoRA

Each column is one question from this lesson, as measured in the notebook; Hindi cost is tokens relative to English

7
Model1Licence2LoRA peakQLoRA peak3Hindi cost4AccuracyLatencyVerdict
Qwen2.5-0.5BApache-2.02.8 GB3.1 GB×4.565.7%58 msFastest and smallest; weakest before training
Qwen2.5-1.5BApache-2.05.8 GB5.6 GB×4.573.0%177 msTrains with LoRA in a third of the T4: the model for lessons 3 and 4
Qwen2.5-3BNon-commercial——×4.5——Ruled out at question 1
Qwen2.5-7BApache-2.0Out of memory15.2 GB×4.590.1%706 msMost accurate; trains only with QLoRA, at the GPU’s limit: lesson 5
Source: lesson notebook on a Colab T4 (15.6 GB), Hugging Face metadata and licence texts.

For lessons 3 and 4 the course uses Qwen2.5-1.5B-Instruct: Apache-2.0, trainable with LoRA in 5.8 GB of a 15.6 GB card, which leaves room for longer sequences, and fast enough to iterate on. Lesson 5 takes the 7B model, which only QLoRA can train here, and the memory chart has already set its first problem: the fp32 embeddings that leave 0.4 GB spare at 512 tokens.

A different task changes the answer, and the table shows where. A Hindi assistant fails question 3 with every Qwen model, at 4.5 times the English token count; Gemma 3 (1.2 times) or Phi-4-mini (1.6 times) would need questions 2 and 4 asked again, and Gemma would also need question 1, for its gated licence. The method transfers even when the answer does not.

The template comes with the model

One more property is fixed the moment you choose: the model's chat template, the exact text that marks system, user and assistant turns. Training examples must be written in it, and a model fine-tuned in the wrong template learns the wrong boundaries. The notebook prints the same three-turn conversation in three templates:

system: You are a bank’s assistant. user: When will my card arrive? assistant: Within five working days.

Qwen2.5
<|im_start|>system ↵ You are a bank’s assistant.<|im_end|> ↵ <|im_start|>user ↵ When will my card arrive?<|im_end|> ↵ <|im_start|>assistant ↵ Within five working days.<|im_end|>
Mistral
<s>[INST] When will my card arrive?[/INST] Within five working days.</s>
Phi-4-mini
<|system|>You are a bank’s assistant.<|end|><|user|>When will my card arrive?<|end|><|assistant|>Within five working days.<|end|><|endoftext|>

The same conversation as the notebook prints it, with ↵ marking a line break. Mistral’s version has no system text at all.

The three formats differ in more than punctuation. Mistral's template has no system turn at all: the system message in the input was dropped, without an error. Data written for one model and trained on another teaches the wrong turn boundaries, and an instruction placed in a system message that the template drops is never seen.

Lesson 3 starts here: it turns raw examples into training data in the chosen model's template, decides which tokens the loss is computed on, and splits the data so the held-out set stays clean.

What to keep

The four answers are side by side in the decision table above. If you have a task like this one:

  • Check the licence of the exact model. Qwen2.5-3B carries a non-commercial licence between two Apache-2.0 siblings, and Llama 3.2 and Gemma are gated.
  • Predict memory, then run one training step. The 16-bytes-per-parameter rule was a floor: the 7B model with QLoRA measured 15.2 GB against 4.6 GB predicted, because the fp32 embedding and output head cost 4.36 GB.
  • Count tokens in your own language. Hindi cost 1.2 to 7.5 times English across the seven tokenizers, and 4.5 times for Qwen2.5.
  • Score every candidate before training, on two axes. Accuracy and milliseconds per message together; the 7B model was 12 times slower than the 0.5B (derived).
  • Write training data in the chosen model's chat template. Mistral's drops the system message without an error.
  • Next to try, not tested here: the 0.5B model and 1.5B overlap on accuracy before training, so whether training closes the gap to the 7B is lesson 4's question; and a Hindi or Spanish task needs Gemma 3 or Phi-4-mini measured through questions 2 and 4.

How it was built

ItemSetting
Base modelNine candidates for the licence read; Qwen2.5-0.5B, 1.5B and 7B Instruct for memory and accuracy, the 7B in 4-bit NF4 for accuracy; fp16 for the others
DataMemory step: one 512-token paragraph of banking text. Tokens: six messages per language in English, Hindi, Spanish and Chinese. Accuracy: BANKING77, train split as the example pool
Test385 BANKING77 test messages, five per intent (seed 0); accuracy is exact match of the parsed intent name, and messages that parse to no intent are counted separately
MethodOne training step per pair with gradient checkpointing and AdamW: full fine-tune (fp32 weights, fp16 compute), LoRA (16-bit frozen weights) and QLoRA (NF4, double quantisation, prepare_model_for_kbit_training); adapters r=16, lora_alpha=32, lora_dropout=0.0, target_modules="all-linear", trained in fp32
TrainingNo training run: 1 forward, backward and optimizer step on 512 tokens, learning rate 1e-5, no gradient scaler, set_seed(42)
DecodingAccuracy probe: greedy, at most 12 new tokens, batches of 16 (0.5B, 1.5B) or 8 (7B), prompt of the ten nearest training examples by TF-IDF
HardwareOne Tesla T4 (15.6 GB, compute capability 7.5, float16) on Google Colab; transformers 4.51.3, peft 0.15.2, accelerate 1.6.0, bitsandbytes 0.50.2

Time and cost. The whole notebook takes about 20 minutes, most of it model downloads. Each memory number is the peak of one step: 9.92 GB for the 0.5B full fine-tune, 2.79 GB and 3.13 GB for its LoRA and QLoRA, 5.82 GB and 5.58 GB for the 1.5B, and 15.20 GB for the 7B with QLoRA; the 7B with LoRA was out of memory after loading 15.42 GB. Scoring the 385 messages took 58.1, 176.5 and 706.4 ms per message at 1.88, 4.76 and 7.59 GB. The 95% intervals on the three accuracies are 60.8 to 70.3, 68.4 to 77.2 and 86.7 to 92.7 (derived, Wilson). Intercom's figure at the top of the page is company-reported; every other number comes from this notebook.

Run it yourself

The notebook runs top to bottom on a free Colab T4 in about 20 minutes, most of it model downloads. Its sections follow this page: 1 is the licence, 2 the memory step, 3 the tokenizers and KV cache, 4 the accuracy and latency probe, 5 the decision table and 6 the chat templates. Three changes to try, predicting each result first:

  1. Change the measured sequence length from 512 to 2,048 tokens. Which runs still fit, and which part of memory grew?
  2. Add your own language to SENTENCES. Which tokenizer handles it best?
  3. Add HuggingFaceTB/SmolLM2-1.7B-Instruct to the accuracy probe. Where does it land against Qwen2.5-1.5B?

How is this page?

Last updated on