Objectif du jour : ne plus jamais choisir un modèle « au feeling ». À la fin de cette séance, vous savez calculer sur un coin de table si un modèle donné tient dans une mémoire donnée, à quelle précision, avec quelle fenêtre de contexte utile — et vous savez pourquoi Q4_K_M est presque toujours le bon point de départ. Le gain du jour est un calculateur de budget mémoire et une table de décision que vous utiliserez à chaque projet.
Today's goal: never pick a model "by feel" again. By the end of this session you can work out on the back of an envelope whether a given model fits in a given memory, at what precision, with what usable context window — and you know why Q4_K_M is almost always the right starting point. Today's win is a memory-budget calculator and a decision table you will use on every project.
Un paramètre est un nombre (un « poids ») dans le réseau. Un modèle « 8 B » en contient 8 milliards. Chaque poids occupe une certaine précision, exprimée en bits : c'est le seul levier vraiment libre de l'ingénieur, et il détermine à la fois la mémoire et la vitesse. A parameter is a number (a "weight") in the network. An "8 B" model holds 8 billion of them. Each weight occupies a given precision, expressed in bits: that is the engineer's one genuinely free lever, and it determines both memory and speed.
| PrécisionPrecision | bits / poidsbits / weight | Poids d'un 8 BSize of an 8 B | UsageUse |
|---|---|---|---|
| FP32 | 32 | ~32 Go | Entraînement uniquement. Jamais en inférence.Training only. Never for inference. |
| FP16 / BF16 | 16 | ~16 Go | Référence « pleine précision » pour l'inférence et le fine-tuning.The "full precision" reference for inference and fine-tuning. |
| INT8 / Q8_0 | 8 | ~8 Go | Quasi sans perte. Quand la qualité prime sur le débit.Near-lossless. When quality beats throughput. |
| INT4 / Q4_K_M | ~4,8 | ~4,9 Go | Le défaut raisonnable. Meilleur compromis qualité/taille/débit.The sensible default. Best quality/size/throughput trade-off. |
| Q3 / Q2 (INT3/INT2) | 3 – 2 | ~3–2 Go | Dernier recours. Dégradation visible sur le code, le multilingue et le raisonnement.Last resort. Visible degradation on code, multilingual and reasoning. |
taille_poids (Go) ≈ paramètres × bits_par_poids / 8 / 1e9 bits_par_poids réel = taille_octets × 8 / paramètres # inversion, pour auditer
Cette formule n'est pas théorique : on la vérifie sur les modèles réellement installés sur le lab (relevé du 2026-09-18). This formula is not theoretical: we verify it against the models actually installed on the lab (reading of 2026-09-18).
| ModèleModel | ParamètresParameters | Quantif. annoncéeDeclared quant | Taille sur disqueOn-disk size | bits/poids calculébits/weight computed |
|---|---|---|---|---|
granite-embedding | 30,15 M | F16 | 0,06 Go | 15,9 ✅ (≈16 = F16)(≈16 = F16) |
mistral:7b | 7,2 B | Q4_K_M | 4,37 Go | 4,83 |
llama3.1:8b | 8,0 B | Q4_K_M | 4,92 Go | 4,90 |
qwen3.8:27b | 27,3 B | Q4_K_M | 17,74 Go | 5,20 |
_K_M gardent certains tenseurs (attention, embeddings) à plus haute précision, et que la proportion de ces tenseurs varie d'une architecture à l'autre. Ne calculez jamais avec « 4 bits » ; auditez la taille réelle du fichier. C'est exactement ce que fait le script du lab.
What that last column teaches you: "Q4" is not a single value. It is 4.83 bits/weight on Mistral-7B and 5.20 on the 27 B — because _K_M variants keep some tensors (attention, embeddings) at higher precision, and the proportion of those tensors varies by architecture. Never compute with "4 bits"; audit the real file size. That is exactly what the lab script does.
GGUF est le format de fichier standard de l'écosystème llama.cpp : un conteneur qui porte à la fois les métadonnées du modèle (architecture, nombre de couches, longueur de contexte, tokenizer) et les tenseurs quantifiés. C'est le format que vous trouverez partout — et celui que vous produirez vous-même en séance 8. GGUF is the standard file format of the llama.cpp ecosystem: a container carrying both the model's metadata (architecture, layer count, context length, tokenizer) and the quantized tensors. It is the format you will find everywhere — and the one you will produce yourself in session 8.
Q4_K_MDecoding Q4_K_M| FragmentFragment | SignificationMeaning |
|---|---|
Q4 | Environ 4 bits par poids. Q8 ≈ 8 bits, Q6 ≈ 6 bits.About 4 bits per weight. Q8 ≈ 8 bits, Q6 ≈ 6 bits. |
_K | Schéma de quantification par blocs avec des échelles apprises (« k-quant »), plus efficace que l'ancien schéma plat.Block-wise quantization scheme with learned scales ("k-quant"), more efficient than the older flat scheme. |
_M | Mélange « medium » : certains tenseurs sensibles restent à une précision plus élevée. Il existe _S (small), _M, _L (large)."Medium" mix: some sensitive tensors stay at higher precision. There is also _S (small), _M, _L (large). |
IQ* | « i-quants » : quantification avec codebook, meilleure qualité à très basse précision, mais plus lente à produire et parfois plus lente à exécuter."i-quants": codebook-based quantization, better quality at very low precision, but slower to produce and sometimes slower to run. |
Rappelez-vous : le décodage est memory-bound. Pour produire un token, le moteur doit lire tous les poids du modèle. Diviser par deux la taille des poids divise par deux le temps de lecture — donc, à bande passante égale, double le débit. La quantification n'est pas seulement une astuce de mémoire : c'est l'optimisation de performance la plus rentable du domaine. Remember: decoding is memory-bound. To produce one token, the engine must read all the model's weights. Halving the weight size halves the read time — so at equal bandwidth it doubles throughput. Quantization is not just a memory trick: it is the highest-leverage performance optimisation in the field.
Erreur classique : ne compter que la taille du fichier. La mémoire réellement consommée, c'est trois termes : les poids, le cache KV (la mémoire de l'attention), et le surcoût du runtime. Le cache KV est le terme que tout le monde oublie — et c'est celui qui explose avec la fenêtre de contexte. Classic mistake: counting only the file size. Actual memory use is three terms: the weights, the KV cache (the attention memory), and the runtime overhead. The KV cache is the term everyone forgets — and the one that explodes with the context window.
mémoire_totale ≈ poids + cache_KV + surcoût_runtime(≈5–10 %)
cache_KV (octets) = 2 × n_couches × n_têtes_KV × dim_tête × contexte × octets_par_élément
↑ ↑
(clé ET valeur) (2 en FP16, 1 en q8_0, 0.5 en q4_0)
dim_tête = dim_embedding / n_têtes # souvent 128 ; 256 sur certains modèles récents
-- Avec GQA (grouped-query attention), n_têtes_KV < n_têtes.
C'est ce qui rend le contexte long abordable. Toujours prendre n_têtes_KV,
PAS n_têtes, sinon vous surestimez le cache d'un facteur 4 à 8.
Valeurs d'architecture relevées via api/show le 2026-09-18 :
Architecture values read via api/show on 2026-09-18:
| ModèleModel | CouchesLayers | Têtes / Têtes KVHeads / KV heads | dim têtehead dim | cache KV / tokenKV cache / token | 8 k | 32 k | 128 k |
|---|---|---|---|---|---|---|---|
llama3.1:8b | 32 | 32 / 8 | 128 | 128 Kio | 1,07 Go | 4,29 Go | 17,18 Go |
qwen3.8:27b | 65 | 24 / 4 | 256 | 260 Kio | 2,18 Go | 8,72 Go | 34,90 Go |
poids : 4,92 Go cache KV : 1,07 Go surcoût : 0,39 Go ----------------------------- TOTAL : 6,39 Go
poids : 17,74 Go cache KV : 2,18 Go surcoût : 1,42 Go ----------------------------- TOTAL : 21,34 Go
qwen3.8:27b annonce 262 144 tokens de contexte. Pour l'utiliser réellement : 17,74 Go de poids + 34,90 Go de cache KV à 128 k = 54,06 Go. Le lab n'a que 24 Go de VRAM. La fenêtre annoncée est donc inutilisable telle quelle. Trois issues, dans l'ordre : (1) réduire la fenêtre au besoin réel, (2) quantifier le cache KV en q8_0 ou q4_0 (divise par 2 ou 4 le cache — à 128 k en q8_0, le cache retombe à 17,45 Go, ce qui reste insuffisant, mais à 32 k il passe de 8,72 à 4,36 Go et le total rentre enfin sur 2×3060), (3) changer de modèle. Notez que llama3.1:8b, qui annonce 131 k, a le même problème : 4,92 + 17,18 = 22,49 Go, soit tout juste la capacité des deux cartes — sans marge pour le traitement du prompt.
qwen3.8:27b advertises 262,144 tokens of context. To actually use it: 17.74 GB of weights + 34.90 GB of KV cache at 128 k = 54.06 GB. The lab has only 24 GB of VRAM. The advertised window is therefore unusable as-is. Three ways out, in order: (1) reduce the window to what you actually need, (2) quantize the KV cache to q8_0 or q4_0 (halves or quarters the cache — at 128 k in q8_0 the cache drops to 17.45 GB, still not enough, but at 32 k it goes from 8.72 to 4.36 GB and the total finally fits on 2×3060), (3) change model. Note that llama3.1:8b, advertising 131 k, has the same problem: 4.92 + 17.18 = 22.49 GB, i.e. exactly the two cards' capacity — with no headroom for prompt processing.
api/show) ; paramètres de cache KV et de contexte documentés dans le README de llama-server et la spécification GGUF.
Sources: architecture metadata read via the Ollama API (api/show); KV-cache and context parameters documented in the llama-server README and the GGUF specification.
| FamilleFamily | Sur le labOn the lab | Points fortsStrengths |
|---|---|---|
| Llama | llama3.1:8b | Écosystème énorme, outils d'inférence et de fine-tuning les mieux supportés, contexte long (131 k).Huge ecosystem, best-supported inference and fine-tuning tooling, long context (131 k). |
| Qwen | qwen3.6:27b, qwen3.8:27b | Excellent multilingue, support vision et thinking, très bon rapport taille/qualité. Attention : vocabulaire plus large.Excellent multilingual, vision and thinking support, very good size/quality ratio. Note: larger vocabulary. |
| Mistral | mistral:7b | Léger, rapide, licences permissives. Bon point de départ CPU.Light, fast, permissive licences. A good CPU starting point. |
| Gemma | gemma4:26b | Compact et solide, mais conditions d'utilisation spécifiques à lire avant usage commercial.Compact and solid, but read the specific terms of use before commercial deployment. |
| GLM / Nemotron | glm-4.7-flash, nemotron-3.5-lightning | Générations récentes, orientées efficacité et agents. À évaluer sur vos cas.Recent generations, efficiency- and agent-oriented. Evaluate on your cases. |
| EmbeddingsEmbeddings | granite-embedding | Rôle différent : ne génère pas de texte, produit des vecteurs. 384 dimensions, contexte 512, F16.Different role: does not generate text, produces vectors. 384 dimensions, 512 context, F16. |
nemotron-3.5-lightning (32,9 B, 25,4 Go) est de cette famille : gros sur disque, économe en calcul par token.
A dense model activates all its weights per token. A MoE (mixture of experts) activates only a fraction: high storage memory, but fast decoding. nemotron-3.5-lightning (32.9 B, 25.4 GB) is of that family: big on disk, cheap in compute per token.
llama3.1:8b → completion, tools · qwen3.8:27b → completion, vision, tools, thinking · granite-embedding → embedding. Si tools est absent, votre agent ne fonctionnera pas, quelle que soit la qualité du modèle.
Query them, do not assume. The lab answers: llama3.1:8b → completion, tools · qwen3.8:27b → completion, vision, tools, thinking · granite-embedding → embedding. If tools is missing, your agent will not work, however good the model is.
# Interroge le modèle via l'API, récupère son architecture réelle,
# puis calcule poids + cache KV + surcoût pour plusieurs contextes.
python3 labs/lab2_memory_budget.py --endpoint http://172.16.8.81:11434 \
--model qwen3.8:27b --contexts 4096 8192 32768 131072
# Auditer la quantification réelle d'un modèle :
python3 labs/lab2_memory_budget.py --endpoint http://172.16.8.81:11434 \
--model llama3.1:8b --audit
# Le script compare automatiquement aux profils du lab :
# 1x RTX 3060 (12 Go) · 2x RTX 3060 (24 Go) · poste CPU 64 Go RAM
python3 labs/lab2_memory_budget.py --endpoint http://172.16.8.81:11434 \
--model qwen3.8:27b --contexts 8192 32768 --hardware
Sur le lab, mistral:7b et llama3.1:8b sont tous deux en Q4_K_M. Pour comparer des quantifications, téléchargez deux variantes du même modèle :
On the lab, mistral:7b and llama3.1:8b are both Q4_K_M. To compare quantizations, pull two variants of the same model:
ollama pull llama3.1:8b-instruct-q8_0 # ~8,5 Go, quasi sans perte
ollama pull llama3.1:8b-instruct-q3_K_S # ~3,5 Go, dégradé
# puis, pour chaque variante :
python3 labs/lab2_memory_budget.py --endpoint http://172.16.8.81:11434 \
--model llama3.1:8b-instruct-q8_0 --audit
_K_M gardent certains tenseurs sensibles en précision plus élevée, ce qui pousse le total au-dessus de 4. Sur qwen3.8:27b on mesure même 5,20. Toujours auditer la taille réelle du fichier.4.92 GB × 8 / 8.0 B = 4.90 bits/weight. The _K_M variants keep some sensitive tensors at higher precision, pushing the total above 4. On qwen3.8:27b we measure 5.20. Always audit the real file size.llama3.1:8b a 32 têtes mais seulement 8 têtes KV ; qwen3.8:27b en a 24 pour 4 têtes KV. Utiliser le mauvais nombre surestime le cache d'un facteur 4 à 8 — et vous fait renoncer à un modèle qui rentrait.With GQA (grouped-query attention), several attention heads share one KV head. llama3.1:8b has 32 heads but only 8 KV heads; qwen3.8:27b has 24 for 4 KV heads. Using the wrong number overestimates the cache by 4–8× — and makes you give up on a model that would have fitted.qwen3.8:27b demande 32,5 Go de cache KV en plus des 17,74 Go de poids : 50 Go, contre 24 Go disponibles. Solutions : réduire la fenêtre, quantifier le cache KV (q8_0/q4_0), ou changer de modèle.At 128 k, qwen3.8:27b needs 32.5 GB of KV cache on top of 17.74 GB of weights: 50 GB against 24 GB available. Fixes: shrink the window, quantize the KV cache (q8_0/q4_0), or change model.tools, l'appel d'outil ne sera pas fiable, quelle que soit sa qualité rédactionnelle. Interrogez les capacités : qwen3.8:27b déclare vision, tools et thinking ; granite-embedding ne déclare que embedding. On ne devine pas, on lit.If the model does not expose tools, tool calling will not be reliable, however good its prose. Query the capabilities: qwen3.8:27b declares vision, tools and thinking; granite-embedding declares only embedding. You do not guess, you read.tools, vision, thinking) : elles sont éliminatoires, pas indicatives.Read the declared capabilities (tools, vision, thinking): they are disqualifying, not indicative.RESOURCES.md §8).
Session sources: ggml, GGUF specification · llama.cpp, quantize.cpp and llama-server README · Which Quantization Should I Use? A Unified Evaluation of llama.cpp, arXiv:2601.14277 · HF blog, Llama 3.1. Architecture readings and sizes: lab Ollama API, 2026-09-18 (RESOURCES.md §8).