<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Julien Brouwers - AI & Automation]]></title><description><![CDATA[Hands-on experiments, practical guides, and honest insights and experiences on cloud AI, local AI, automation, and software development.]]></description><link>https://julienbrouwers.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 30 Nov 2026 00:30:22 GMT</lastBuildDate><atom:link href="https://julienbrouwers.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Local LLMs on 16GB RAM & 4GB VRAM: From Legacy PHP Audits to PDF Parsers and a 1,000-Book Benchmark]]></title><description><![CDATA[Reproducible Ollama benchmark on a 16GB RAM / 4GB VRAM laptop: Qwen 2.5, Llama 3.2 & Mistral 7B Modelfiles, dynamic JSON Schema, FR vs EN tokens.]]></description><link>https://julienbrouwers.hashnode.dev/local-llms-on-16gb-ram-4gb-vram-from-legacy-php-audits-to-pdf-parsers-and-a-1-000-book-benchmark</link><guid isPermaLink="true">https://julienbrouwers.hashnode.dev/local-llms-on-16gb-ram-4gb-vram-from-legacy-php-audits-to-pdf-parsers-and-a-1-000-book-benchmark</guid><category><![CDATA[ollama]]></category><category><![CDATA[llm]]></category><category><![CDATA[Prompt]]></category><category><![CDATA[Local LLM]]></category><category><![CDATA[#qwen]]></category><category><![CDATA[MistralAI]]></category><dc:creator><![CDATA[Julien Brouwers]]></dc:creator><pubDate>Wed, 25 Nov 2026 09:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6af58c60b9b6233d06241a01/87d7fa42-1e90-4c53-831b-9ea0e424c69b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Technical Deep-Dive Companion to Episode 2 on LinkedIn · Series: “Local LLMs: What I Can Actually Do on My Work Laptop” (Episode 2/5)</em></p>
<p>Alright, are we actually running this local AI, or just arguing about it on LinkedIn?</p>
<p>Before dropping thousands on a dedicated GPU rig just to summarize three emails, I wanted to see what my everyday work laptop can really take: an <code>Intel Core i7-10750H</code>, <strong>16 GB RAM</strong>, and a <strong>NVIDIA GTX 1650 Ti with 4 GB of VRAM</strong>.</p>
<p>Starting on 4 GB of VRAM is deliberate. <strong>4 GB of VRAM is an unforgiving teacher.</strong> It has zero patience for sloppy prompts, chat histories that grow like weeds, oversized KV caches, or a <code>repeat_penalty</code> copy-pasted from a random forum thread.</p>
<p>This is the hands-on technical companion to my LinkedIn Episode 2 post, written as a <strong>100% reproducible engineering lab notebook</strong>. Every claim, every broken first run, and every token count below comes from real executions on this laptop.</p>
<blockquote>
<p><strong>TL;DR: What Actually Happened on 4 GB VRAM</strong></p>
<ul>
<li><strong>Modelfiles matter (</strong><code>ollama show</code><strong>):</strong> <code>qwen2.5:3b</code> (<code>ChatML</code>, <code>dim=2048</code>), <code>llama3.2:3b</code> (<code>Meta headers</code>, <code>dim=3072</code>), and <code>mistral:7b</code> (<code>[INST]</code> with <strong>no separate</strong> <code>&lt;system&gt;</code> <strong>token</strong>, <code>dim=4096</code>) don’t share the same sampling sweet spot.</li>
<li><strong>Part 1 (Legacy PHP Audit):</strong> Ditching shared chat history (<code>-84%</code> tokens) + adding a dynamic JSON Schema (<code>minItems</code> from real PHP branches) hit <code>6/6 PASS</code>, and English prompts cut input tokens by <code>-11.6%</code> <strong>to</strong> <code>-13.2%</code> (<code>-26%</code> to <code>-42%</code> faster).</li>
<li><strong>Part 2A (PDF Invoices → Python Parser Codegen):</strong> 1-shot naive dump (<code>0/3</code>), pure TDD example (<code>0/3</code>), 3-turn self-correction (<code>0/2</code>), and plain-English layout rules (<code>0/2</code>) ALL failed on <code>3B</code>. Only an explicit 4-step algorithm spec reached <code>3/3 PASS</code> <strong>in English</strong> (vs. <code>1/3</code> in French).</li>
<li><strong>Part 2B &amp; 2C (Search, 100 Real Books &amp; Recommendations):</strong> JSON input costs <code>+24%</code> <strong>tokens</strong> over CSV; 64-row stateless chunks scale search to <code>1,000</code> <strong>books at 100% GPU</strong> (<code>74.23 s</code>, <code>3/3</code>, <code>0</code> FP); and grounded catalog recommendations catch my missing <em>Alien Tome 1</em> with zero hallucinated authors.</li>
</ul>
</blockquote>
<hr />
<h2>1. Hardware Baseline &amp; 60-Second Setup</h2>
<table>
<thead>
<tr>
<th>Component</th>
<th>Spec</th>
</tr>
</thead>
<tbody><tr>
<td><strong>CPU</strong></td>
<td>Intel Core <code>i7-10750H</code> (6 cores)</td>
</tr>
<tr>
<td><strong>RAM</strong></td>
<td><code>16 GB DDR4</code></td>
</tr>
<tr>
<td><strong>GPU</strong></td>
<td><code>NVIDIA GeForce GTX 1650 Ti Mobile</code> (<code>4 GB VRAM</code>)</td>
</tr>
<tr>
<td><strong>Runtime</strong></td>
<td>Windows + WSL2 · <strong>Ollama</strong> <code>0.40.18</code> · Python 3.12 &amp; VSCodeInsiders + Continue</td>
</tr>
<tr>
<td><strong>Models (</strong><code>Q4_K_M</code><strong>)</strong></td>
<td><code>qwen2.5:3b</code> · <code>llama3.2:3b</code> · <code>mistral:7b</code></td>
</tr>
</tbody></table>
<h3>Clone &amp; Install</h3>
<pre><code class="language-powershell"># 1. Pull the three local models and verify Ollama
ollama --version
ollama pull qwen2.5:3b
ollama pull llama3.2:3b
ollama pull mistral:7b
ollama list

# 2. Clone the exact Episode 2 branch and install dependencies
git clone -b episode-2-llmlocaux https://github.com/julienbrouwers/LocalLLMExamples.git
Set-Location .\LocalLLMExamples
python -m pip install -r requirements.txt
</code></pre>
<h3>Minimalist Repo Layout</h3>
<pre><code class="language-text">LocalLLMExamples/
├── donnees/
│   ├── entrees/
│   │   ├── calculs_legacy.php                  # 5 legacy PHP functions (131 lines)
│   │   └── factures/FA000101.pdf..FA000104.pdf # 4 anonymized PDF invoices (8 items)
│   └── inventaires/                            # Consolidated Excel + 100 categorized books
├── fonctions/                                  # 8 reproducible Python scripts
└── prompts/
    ├── php-{qwen,llama,mistral}-{fr,eng}.txt   # Part 1 generalist PHP audit prompts
    ├── pdf-codegen-{qwen,llama,mistral}-*.txt  # Part 2A PDF parser codegen prompts
    └── recherche-inventaire-{fr,eng}.txt       # Part 2B CSV vs JSON search prompts
</code></pre>
<hr />
<h2>2. Why Naive Prompting Breaks (V1 Mental Math &amp; Shared Context)</h2>
<p>My first test threw a 131-line legacy PHP file (<code>calculs_legacy.php</code>, 5 functions) at all three models and asked them to explain the business rules <strong>and</strong> walk through worked numerical examples.</p>
<p>Here is the very first 24-line function (<code>calculTva</code>) we used as our controlled audit target:</p>
<pre><code class="language-php">function calculTva($montant, $codeTaux = 1, $depuisTtc = false)
{
    if ($codeTaux == 1) $taux = 0.20;
    elseif ($codeTaux == 2) $taux = 0.10;
    elseif ($codeTaux == 3) $taux = 0.055;
    elseif ($codeTaux == 4) $taux = 0.021;
    else $taux = 0;

    if (!$depuisTtc) {
        $ttc = $montant * (1 + $taux);
        $tva = $ttc - $montant;
        $ht = $montant;
    } else {
        $ht = $montant / (1 + $taux);
        $tva = $montant - $ht;
        $ttc = $montant;
    }

    return [
        'ht' =&gt; round($ht, 2),
        'tva' =&gt; round($tva, 2),
        'ttc' =&gt; round($ttc, 2)
    ];
}
</code></pre>
<p>Two things broke immediately:</p>
<ol>
<li><strong>Shared chat history explodes token usage:</strong> passing all 5 functions in one thread (<code>-ModeConversation Partage</code>) burned <code>13,722</code> <strong>tokens</strong> on <code>llama3.2:3b</code>. Switching to stateless calls (<code>-ModeConversation Separe</code>) dropped that to <code>2,190</code> <strong>tokens</strong> (<code>-84%</code>) with cleaner answers.</li>
<li><strong>Mental math fails</strong> <code>5/5</code> <strong>times:</strong> asking a 3B/7B model to compute reverse VAT, 120-month compound interest loops, or shipping thresholds in prose produces confident nonsense.</li>
</ol>
<pre><code class="language-powershell"># Compare shared history (13,722 tok) vs isolated calls (2,190 tok)
.\rejouer-essais-ollama.ps1 -Essai PHP -FichierPHP .\donnees\entrees\calculs_legacy.php `
  -Langues FR -Modeles llama3.2:3b -ModeConversation Partage -Contexte 8192

.\rejouer-essais-ollama.ps1 -Essai PHP -FichierPHP .\donnees\entrees\calculs_legacy.php `
  -Langues FR -Modeles llama3.2:3b -ModeConversation Separe -Contexte 8192

# Replay the V1 mental-math prompt
python -X utf8 .\fonctions\tester_php_unitaire.py --modele llama3.2:3b --ancien-prompt --mesures
</code></pre>
<blockquote>
<p><strong>Design Rule #1:</strong> Never ask an LLM to compute numbers. Make the LLM <strong>describe the code structure and propose structured JSON test inputs</strong>, then let <strong>deterministic code execute the real math</strong>.</p>
</blockquote>
<hr />
<h2>3. Auditing Each Model’s Modelfile &amp; Official Docs (<code>ollama show</code>)</h2>
<p>Before tuning a single word of a prompt, I inspected each model’s actual Ollama Modelfile and crossed it with official vendor documentation (HuggingFace Qwen2.5, Meta Llama 3.2, Mistral AI, Ollama Structured Outputs):</p>
<pre><code class="language-powershell">foreach ($m in 'qwen2.5:3b', 'llama3.2:3b', 'mistral:7b') {
    ollama show $m --parameters --template
}
</code></pre>
<table>
<thead>
<tr>
<th>Technical Property</th>
<th><code>qwen2.5:3b</code> (<code>Q4_K_M</code>)</th>
<th><code>llama3.2:3b</code> (<code>Q4_K_M</code>)</th>
<th><code>mistral:7b</code> (<code>Q4_K_M</code>)</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Architecture &amp; Size</strong></td>
<td><code>qwen2</code> · <code>3.1B</code></td>
<td><code>llama</code> · <code>3.2B</code></td>
<td><code>llama</code> · <code>7.2B</code></td>
</tr>
<tr>
<td><strong>Embedding</strong> <code>dim</code> <strong>(KV Cache)</strong></td>
<td><code>2,048</code>: lightest KV cache (<code>2.2 GB</code> @ 4k, <code>2.6 GB</code> @ 15k)</td>
<td><code>3,072</code>: +40% heavier (<code>2.6 GB</code> @ 4k, <code>3.7 GB</code> @ 15k → 29% CPU)</td>
<td><code>4,096</code>: <code>5.1 GB</code> @ 4k → <code>49% CPU / 51% GPU</code> on 4 GB VRAM</td>
</tr>
<tr>
<td><strong>Native Ollama Template</strong></td>
<td><strong>ChatML</strong> (<code>&lt;|im_start|&gt;system</code>)</td>
<td><strong>Meta Headers</strong> (<code>&lt;|start_header_id|&gt;system&lt;|end_header_id|&gt;</code>)</td>
<td><strong>No separate</strong> <code>&lt;system&gt;</code> <strong>token!</strong> Concatenates inside <code>[INST] ... [/INST]</code></td>
</tr>
<tr>
<td><strong>Official Sampling &amp; Tuning</strong></td>
<td><code>temperature: 0</code>, <code>repeat_penalty: 1.05</code>, <code>top_p: 0.8</code>, <code>top_k: 20</code></td>
<td><code>temperature: 0</code>, <code>repeat_penalty: 1.15</code>, short bullet prompt + strict Schema</td>
<td><code>temperature: 0</code>, <strong>NO</strong> <code>repeat_penalty</code> (<code>1.0</code> default), compact prompt</td>
</tr>
</tbody></table>
<p>That single inspection explained three mysteries at once:</p>
<ul>
<li>Why <code>repeat_penalty: 1.15</code> fixed Llama loops but degraded JSON on Qwen and Mistral.</li>
<li>Why Mistral 7B requires a compact prompt (half of its prefill runs on CPU at 4 GB VRAM).</li>
<li>Why Llama 3.2 3B ignores long prose instructions unless constraints live <strong>directly inside the JSON Schema</strong>.</li>
</ul>
<hr />
<h2>4. The Architecture That Works: External Prompts + Dynamic JSON Schema + Local Verifier</h2>
<p>Strict rule: <strong>zero function-specific hints.</strong> Every prompt in <code>prompts/php-*.txt</code> is <strong>100% generalist</strong> and works on any PHP function.</p>
<p>How <code>fonctions/tester_php_unitaire.py</code> enforces reliability without hardcoding business logic:</p>
<ol>
<li><strong>External prompt files (</strong><code>--prompt</code> <strong>/</strong> <code>--langue fr|eng</code><strong>):</strong> edit any <code>.txt</code> prompt in <code>prompts/</code> without touching Python.</li>
<li><strong>Dynamic JSON Schema derived from the PHP source:</strong><ul>
<li>Parses <code>if</code>, <code>elseif</code>, <code>else</code>, and ternary <code>? A : B</code> counts dynamically and sets <code>"minItems": nb_branches</code> on <code>branches</code> (Ollama’s GBNF grammar physically prevents a 3B model from dropping the second <code>if/else</code> block).</li>
<li>Enforces <code>"minLength": 1</code> on <code>parametres</code> fields (<code>nom</code>, <code>defaut</code>, <code>role</code>).</li>
<li>Uses a structured <code>retour</code> object across all 3 models so <code>round(..., 2)</code> is never omitted:</li>
</ul>
</li>
</ol>
<pre><code class="language-json">{
  "retour": {
    "type": "array",
    "cles": ["ht", "tva", "ttc"],
    "arrondi": "2 decimals"
  }
}
</code></pre>
<ol start="3">
<li><strong>Deterministic execution + local verifier:</strong> runs all 4 LLM-proposed test inputs in Python and outputs an objective verdict:</li>
</ol>
<pre><code class="language-text">Cas de test proposés par le LLM -&gt; exécutés de façon déterministe :
  * Nominal case          | {'montant': 100, 'codeTaux': 2, 'depuisTtc': False} =&gt; {'ht': 100.0, 'tva': 10.0, 'ttc': 110.0}
  * Alternative codeTaux  | {'montant': 100, 'codeTaux': 4, 'depuisTtc': False} =&gt; {'ht': 100.0, 'tva': 2.1, 'ttc': 102.1}
  * Reverse VAT (TTC-&gt;HT) | {'montant': 100, 'codeTaux': 1, 'depuisTtc': True}  =&gt; {'ht': 83.33, 'tva': 16.67, 'ttc': 100.0}
  * Small edge value      | {'montant': 0.01, 'codeTaux': 2, 'depuisTtc': False} =&gt; {'ht': 0.01, 'tva': 0.0, 'ttc': 0.01}

Vérification locale : PASS
  [OK] json_et_stop : done_reason=stop
  [OK] parametres   : 3/3 présents
  [OK] branches     : 7 décrite(s) (attendu &gt;= 7 d'après le code PHP)
  [OK] retour       : 3 clé(s) présentes
  [OK] tests        : 4/4 exécuté(s), 4 jeu(x) distinct(s)
</code></pre>
<h3>Reproduce Part 1 Locally</h3>
<pre><code class="language-powershell"># Run one model with an explicit external prompt file
python -X utf8 .\fonctions\tester_php_unitaire.py `
  --fichier .\donnees\entrees\calculs_legacy.php `
  --fonction calculTva `
  --prompt .\prompts\php-qwen-eng.txt `
  --modele qwen2.5:3b --mesures

# Benchmark all 3 models in French and English
foreach ($m in 'qwen2.5:3b', 'llama3.2:3b', 'mistral:7b') {
    python -X utf8 .\fonctions\tester_php_unitaire.py --fonction calculTva --modele $m --langue fr --mesures
    python -X utf8 .\fonctions\tester_php_unitaire.py --fonction calculTva --modele $m --langue eng --mesures
}
</code></pre>
<hr />
<h2>5. Measured Results: French (<code>-fr.txt</code>) vs. English (<code>-eng.txt</code>) on <code>calculTva()</code></h2>
<p>Measured back-to-back (<code>num_ctx: 4096</code>, <code>temperature: 0</code>, <code>seed: 42</code>, <code>keep_alive: 0</code> between runs):</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>Prompt File</th>
<th align="right">Input Tok</th>
<th align="right">Output Tok</th>
<th align="right">Total Tok</th>
<th align="right">Input Delta (EN vs FR)</th>
<th align="right">Wall Time</th>
<th>Verifier</th>
</tr>
</thead>
<tbody><tr>
<td><code>qwen2.5:3b</code></td>
<td><code>prompts/php-qwen-fr.txt</code></td>
<td align="right"><code>768</code></td>
<td align="right"><code>789</code></td>
<td align="right"><code>1,557</code></td>
<td align="right">-</td>
<td align="right"><code>124.69 s</code></td>
<td>✅ <strong>PASS</strong></td>
</tr>
<tr>
<td><code>qwen2.5:3b</code></td>
<td><code>prompts/php-qwen-eng.txt</code></td>
<td align="right"><code>669</code></td>
<td align="right"><code>825</code></td>
<td align="right"><code>1,494</code></td>
<td align="right"><code>-12.9%</code></td>
<td align="right"><code>83.45 s</code> (<code>-33.1%</code>)</td>
<td>✅ <strong>PASS</strong></td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td><code>prompts/php-llama-fr.txt</code></td>
<td align="right"><code>703</code></td>
<td align="right"><code>872</code></td>
<td align="right"><code>1,575</code></td>
<td align="right">-</td>
<td align="right"><code>155.95 s</code></td>
<td>✅ <strong>PASS</strong></td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td><code>prompts/php-llama-eng.txt</code></td>
<td align="right"><code>610</code></td>
<td align="right"><code>778</code></td>
<td align="right"><code>1,388</code></td>
<td align="right"><code>-13.2%</code></td>
<td align="right"><code>90.57 s</code> (<code>-41.9%</code>)</td>
<td>✅ <strong>PASS</strong></td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td><code>prompts/php-mistral-fr.txt</code></td>
<td align="right"><code>725</code></td>
<td align="right"><code>900</code></td>
<td align="right"><code>1,625</code></td>
<td align="right">-</td>
<td align="right"><code>260.08 s</code></td>
<td>✅ <strong>PASS</strong></td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td><code>prompts/php-mistral-eng.txt</code></td>
<td align="right"><code>641</code></td>
<td align="right"><code>839</code></td>
<td align="right"><code>1,480</code></td>
<td align="right"><code>-11.6%</code></td>
<td align="right"><code>192.13 s</code> (<code>-26.1%</code>)</td>
<td>✅ <strong>PASS</strong></td>
</tr>
</tbody></table>
<p><strong>Key takeaways:</strong></p>
<ul>
<li><strong>English saves</strong> <code>-11.6%</code> <strong>to</strong> <code>-13.2%</code> <strong>of input tokens</strong> even when the PHP code itself is identical, translating into <code>-26%</code> <strong>to</strong> <code>-42%</code> <strong>faster wall-clock time</strong> on 4 GB VRAM.</li>
<li><strong>Dynamic JSON Schema bounds</strong> turned <code>PARTIAL</code> runs into <code>6/6 PASS</code>.</li>
<li><strong>Deterministic execution still catches prose hallucinations:</strong> even on a <code>PASS</code>, <code>llama3.2:3b</code> occasionally invents a division-by-zero note in prose, immediately disproved by running its own generated test inputs in Python.</li>
</ul>
<hr />
<h2>6. Part 2A: PDF Invoices to Excel (Making Local LLMs Generate the Parser)</h2>
<p>First reality check: <strong>a local text LLM cannot read a binary</strong> <code>.pdf</code> <strong>file.</strong> So the pipeline splits into two jobs:</p>
<ol>
<li><strong>Python (</strong><code>pymupdf</code><strong>)</strong> extracts the non-empty text lines from each PDF (<code>FA000101.pdf</code>..<code>FA000104.pdf</code>, 8 purchases total).</li>
<li><strong>Each local LLM</strong> generates <code>parse_articles(lines: list[str]) -&gt; list[tuple[str, int]]</code>, which Python <strong>compiles and executes live against all 4 real PDFs</strong> (<code>8/8</code> expected articles + <code>ValueError</code> guard).</li>
</ol>
<h3>Step 1: 1-Shot Naive Dump (~90 Full Invoice Lines): <code>0/3 PASS</code></h3>
<p>Feeding the entire 90-line invoice (<code>~1,100</code> tokens of addresses, tax blocks, PayPal footer, and a second <code>"Total"</code> line) caused <strong>all three models to produce compiling Python that face-planted at runtime</strong>:</p>
<table>
<thead>
<tr>
<th>Model (Step 1 · EN)</th>
<th align="right">Tokens (in / out)</th>
<th align="right">Time</th>
<th>Verifier</th>
<th>Exact Runtime Bug on the 4 Real PDFs</th>
</tr>
</thead>
<tbody><tr>
<td><code>qwen2.5:3b</code></td>
<td align="right"><code>1,110 / 185</code></td>
<td align="right"><code>42.70 s</code></td>
<td>❌ <strong>FAIL</strong></td>
<td>Ignored <code>"Produit"</code> / <code>"Détail des"</code>, called <code>float()</code> on <code>'Bloodshot Intégrale'</code>, raised <code>StopIteration</code>.</td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td align="right"><code>906 / 273</code></td>
<td align="right"><code>51.48 s</code></td>
<td>❌ <strong>FAIL</strong></td>
<td>Set <code>total_idx</code> on <code>"Produit"</code> instead of <code>"Total"</code>, inverted guard (<code>len(line.strip()) == 0</code>).</td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td align="right"><code>1,114 / 407</code></td>
<td align="right"><code>158.88 s</code></td>
<td>❌ <strong>FAIL</strong></td>
<td>Assumed tab-separated rows (<code>split('\t')</code>) instead of 5 separate list elements.</td>
</tr>
</tbody></table>
<h3>Step 1b: Pure TDD &amp; 3-Turn Self-Correction (Zero Pseudo-Code): Still <code>0/3</code>!</h3>
<p>Before giving away any algorithm steps, I tested three approaches with <strong>zero Python pseudo-code</strong>:</p>
<ol>
<li><strong>1-shot TDD (</strong><code>assert parse_articles(lines) == [...]</code><strong>):</strong> <code>0/3 FAIL</code> (all three hallucinated <code>'Détail des taxes'</code> on a single line when <code>pymupdf</code> splits it into <code>'Détail des'</code> and <code>'taxes'</code>).</li>
<li><strong>Autonomous 3-turn self-correction (</strong><code>--max-tours 3</code><strong>):</strong> still <code>0/2 FAIL</code> on <code>3B</code>! <code>qwen2.5:3b</code> (<code>80.18 s</code>, <code>2,620</code> tok in) repeated <code>lines.index('Détail des taxes')</code> across all 3 turns; <code>llama3.2:3b</code> (<code>70.51 s</code>, <code>2,235</code> tok in) repeated <code>lines[7] != 'Détail des taxes'</code> twice then hardcoded <code>lines[0] != 'Référence'</code>.</li>
<li><strong>Plain-English layout rules (zero Python syntax):</strong> still <code>0/2 FAIL</code> on <code>3B</code> (<code>qwen2.5:3b</code> hardcoded <code>range(9, ...)</code> and crashed on <code>'59000 Lille'</code>; <code>llama3.2:3b</code> truncated its JSON).</li>
</ol>
<blockquote>
<p><strong>Honest Senior-Dev Reality Check on 3B Code Generation</strong> On a <code>4 GB VRAM</code> laptop, a <code>3B</code> model is <strong>not</strong> an autonomous engineer that reverse-engineers a messy PDF layout from a test case. It only reaches <code>3/3 PASS</code> below once you hand it the explicit 4-step algorithm. At that level of hand-holding, a developer writes the 10-line Python function faster by hand, and admitting that upfront is the whole point of a real benchmark.</p>
</blockquote>
<h3>Step 2: Focused Slice + Explicit 4-Point Spec: <code>3/3 PASS</code> (EN) vs. <code>1/3 PASS</code> (FR)</h3>
<p>Passing only the Python list slice around <code>"Produit"</code> → <code>"Détail des"</code> (<code>-45%</code> to <code>-52%</code> input tokens) plus the explicit 4-point spec flipped the results <em>(note: the latest script in the repo also appends the TDD assertion, adding ~90 input tokens, e.g.</em> <code>628 -&gt; 175 tok</code> <em>on</em> <code>qwen2.5:3b</code><em>, still</em> <code>PASS</code> <code>8/8</code><em>)</em>:</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>Prompt File</th>
<th align="right">Tokens (in / out)</th>
<th align="right">Time</th>
<th>Verifier</th>
<th>Real Result on All 4 PDFs (<code>8</code> Articles)</th>
</tr>
</thead>
<tbody><tr>
<td><code>qwen2.5:3b</code></td>
<td><code>pdf-codegen-qwen-eng.txt</code></td>
<td align="right"><code>538 / 177</code></td>
<td align="right"><code>31.31 s</code></td>
<td>✅ <strong>PASS</strong></td>
<td><code>8/8</code> <strong>exact</strong> + <code>ValueError</code> OK (<code>-51.5%</code> input tok vs. Step 1).</td>
</tr>
<tr>
<td><code>qwen2.5:3b</code></td>
<td><code>pdf-codegen-qwen-fr.txt</code></td>
<td align="right"><code>567 / 181</code></td>
<td align="right"><code>29.40 s</code></td>
<td>❌ <strong>FAIL</strong></td>
<td>Index bug <code>enumerate(block[::5])</code>: <strong>passed on 1-article PDFs</strong>, crashed on multi-article PDFs!</td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td><code>pdf-codegen-llama-eng.txt</code></td>
<td align="right"><code>497 / 181</code></td>
<td align="right"><code>29.31 s</code></td>
<td>✅ <strong>PASS</strong></td>
<td><code>8/8</code> <strong>exact</strong> + <code>ValueError</code> OK (<code>-45.1%</code> input tok vs. Step 1).</td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td><code>pdf-codegen-llama-fr.txt</code></td>
<td align="right"><code>520 / 191</code></td>
<td align="right"><code>34.20 s</code></td>
<td>❌ <strong>FAIL</strong></td>
<td>Wrong length check <code>(len(lines) - end) % 5 != 0</code>.</td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td><code>pdf-codegen-mistral-eng.txt</code></td>
<td align="right"><code>591 / 275</code></td>
<td align="right"><code>86.43 s</code></td>
<td>✅ <strong>PASS</strong></td>
<td><code>8/8</code> <strong>exact</strong> + <code>ValueError</code> OK (<code>-46.9%</code> input tok, <code>-45.6%</code> faster).</td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td><code>pdf-codegen-mistral-fr.txt</code></td>
<td align="right"><code>609 / 369</code></td>
<td align="right"><code>114.02 s</code></td>
<td>✅ <strong>PASS</strong></td>
<td><code>8/8</code> <strong>exact</strong>, but <code>+34%</code> output tok and <code>+27.6 s</code> slower than EN.</td>
</tr>
</tbody></table>
<p>Here is the exact Python function generated by <code>qwen2.5:3b</code> (identical across all 3 repeatability runs below):</p>
<pre><code class="language-python">def parse_articles(lines: list[str]) -&gt; list[tuple[str, int]]:
    prod_idx = lines.index('Produit')
    total_idx = lines.index('Total', prod_idx + 1)
    start = total_idx + 1
    end = next(i for i, line in enumerate(lines[start:], start) if line.startswith('Détail des'))
    block = lines[start:end]
    if not block or len(block) % 5 != 0:
        raise ValueError('Invalid invoice structure')
    return [(line.strip(), int(block[i+3])) for i, line in enumerate(block) if i % 5 == 0]
</code></pre>
<blockquote>
<p><strong>Two Huge Lessons From Step 2</strong></p>
<ol>
<li><strong>English isn’t just cheaper on 3B codegen, it’s more accurate:</strong> <code>3/3 PASS</code> <strong>(EN)</strong> vs. <code>1/3 PASS</code> <strong>(FR)</strong> on the exact same spec.</li>
<li><strong>Never test a generated parser on a single-item sample:</strong> Qwen’s French bug passed on both 1-book invoices (<code>FA000101</code>, <code>FA000102</code>) and only blew up on 2-book and 4-book invoices.</li>
</ol>
</blockquote>
<h3>Step 3: Repeatability Check (3 Runs per Model Across Seeds &amp; <code>temperature: 0.2</code>)</h3>
<table>
<thead>
<tr>
<th>Model (EN Prompt)</th>
<th>Run 1 (<code>temp=0, seed=42</code>)</th>
<th>Run 2 (<code>temp=0.2, seed=101</code>)</th>
<th>Run 3 (<code>temp=0.2, seed=2026</code>)</th>
<th align="right">Stability</th>
</tr>
</thead>
<tbody><tr>
<td><code>qwen2.5:3b</code></td>
<td>✅ <code>PASS</code> (<code>32.22 s</code> · <code>8/8</code>)</td>
<td>✅ <code>PASS</code> (<code>28.84 s</code> · <code>8/8</code>)</td>
<td>✅ <code>PASS</code> (<code>35.44 s</code> · <code>8/8</code>)</td>
<td align="right"><strong>3/3 (100%)</strong></td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td>✅ <code>PASS</code> (<code>34.10 s</code> · <code>8/8</code>)</td>
<td>✅ <code>PASS</code> (<code>45.49 s</code> · <code>8/8</code>)</td>
<td>✅ <code>PASS</code> (<code>40.59 s</code> · <code>8/8</code>)</td>
<td align="right"><strong>3/3 (100%)</strong></td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td>✅ <code>PASS</code> (<code>116.59 s</code> · <code>8/8</code>)</td>
<td>✅ <code>PASS</code> (<code>97.27 s</code> · <code>8/8</code>)</td>
<td>❌ <code>FAIL</code> (<code>72.64 s</code> · <code>SyntaxError</code> in JSON)</td>
<td align="right"><strong>2/3 (67%)</strong></td>
</tr>
</tbody></table>
<blockquote>
<p><strong>Wait: How Can an “AI” Produce the Exact Same 177 Tokens 3 Times Across Different Seeds?</strong> An LLM samples from a <code>softmax</code> distribution. At <code>temperature: 0</code>, decoding is pure greedy <code>argmax</code> (100% deterministic on the same GPU). At <code>temperature: 0.2</code>, raw logits are divided by <code>0.2</code> (multiplying the gap between token #1 and #2 by <strong>5×</strong> before <code>softmax</code>): an <code>88% / 12%</code> split at <code>T = 1.0</code> collapses to <code>99.995% / 0.005%</code>. Combined with <code>top_p: 0.8</code>, <code>top_k: 20</code>, GBNF JSON grammar, and explicit variable names, token #1 holds &gt;99% probability at every step on Qwen, while Llama varied slightly in prose (<code>181</code> vs. <code>182</code> tok) and Mistral diverged across all 3 runs (<code>275</code> → <code>247</code> → <code>128</code> tok).</p>
</blockquote>
<h3>Reproduce Part 2A Locally</h3>
<pre><code class="language-powershell"># 1. Generate and test parse_articles(lines) live on all 4 PDFs
foreach ($m in 'qwen2.5:3b', 'llama3.2:3b', 'mistral:7b') {
    python -X utf8 .\fonctions\generer_parseur_pdf.py --modele $m --langue eng --mesures
}

# 2. Replay the 3-run repeatability check
foreach ($cfg in @( @{t=0.0;s=42}, @{t=0.2;s=101}, @{t=0.2;s=2026} )) {
    python -X utf8 .\fonctions\generer_parseur_pdf.py `
      --modele qwen2.5:3b --langue eng --temperature $cfg.t --seed $cfg.s --mesures
}

# 3. Export the consolidated Excel inventory directly from the generated parser
python -X utf8 .\fonctions\generer_parseur_pdf.py `
  --modele qwen2.5:3b --langue eng `
  --sortie-excel .\donnees\inventaires\inventaire-qwen-verification.xlsx
</code></pre>
<hr />
<h2>7. Part 2B: CSV Text vs. JSON Input Format &amp; Scaling to 1,000 Books</h2>
<p>Once the 4 PDFs are in Excel (<code>8</code> rows), what is the best input format to send tabular data to a local LLM? Look at the raw payload difference for just 2 rows:</p>
<pre><code class="language-csv">Libellé;Facture;Page;Article
Alien Tome 2 : Renouveau;FA000104.pdf;1;1
Aliens Volume 2 Omnibus;FA000104.pdf;1;3
</code></pre>
<pre><code class="language-json">[
  {"Libellé":"Alien Tome 2 : Renouveau","Facture":"FA000104.pdf","Page":"1","Article":"1"},
  {"Libellé":"Aliens Volume 2 Omnibus","Facture":"FA000104.pdf","Page":"1","Article":"3"}
]
</code></pre>
<p>Running the exact same external prompt (<code>prompts/recherche-inventaire-eng.txt</code>) on <code>"alien"</code> (<code>3</code> expected matches, <code>0</code> FP allowed) while toggling only <code>--format-entree csv</code> vs. <code>--format-entree json</code>:</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>Input Format</th>
<th align="right">Tokens (in / out)</th>
<th align="right">JSON Overhead</th>
<th align="right">Wall Time</th>
<th>Result (<code>3</code> Expected)</th>
<th>Verifier</th>
</tr>
</thead>
<tbody><tr>
<td><code>qwen2.5:3b</code></td>
<td><strong>CSV text</strong></td>
<td align="right"><code>339 / 36</code></td>
<td align="right">-</td>
<td align="right"><code>16.37 s</code></td>
<td><code>3/3</code><strong>,</strong> <code>0</code> <strong>FP</strong></td>
<td>✅ <strong>PASS</strong></td>
</tr>
<tr>
<td><code>qwen2.5:3b</code></td>
<td><strong>JSON</strong></td>
<td align="right"><code>419 / 36</code></td>
<td align="right"><code>+23.6%</code></td>
<td align="right"><code>15.02 s</code></td>
<td><code>3/3</code><strong>,</strong> <code>0</code> <strong>FP</strong></td>
<td>✅ <strong>PASS</strong></td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td><strong>CSV text</strong></td>
<td align="right"><code>318 / 44</code></td>
<td align="right">-</td>
<td align="right"><code>15.22 s</code></td>
<td><code>2/3</code>, <code>2</code> FP (missed <code>"Aliens"</code>)</td>
<td>❌ <strong>FAIL</strong></td>
</tr>
<tr>
<td><code>llama3.2:3b</code></td>
<td><strong>JSON</strong></td>
<td align="right"><code>398 / 25</code></td>
<td align="right"><code>+25.2%</code></td>
<td align="right"><code>16.06 s</code></td>
<td><code>2/3</code>, <code>0</code> <strong>FP</strong> (missed <code>"Aliens"</code>)</td>
<td>❌ <strong>FAIL</strong></td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td><strong>CSV text</strong></td>
<td align="right"><code>388 / 51</code></td>
<td align="right">-</td>
<td align="right"><code>37.16 s</code></td>
<td><code>3/3</code>, <code>1</code> FP (<code>Bloodshot</code>)</td>
<td>❌ <strong>FAIL</strong></td>
</tr>
<tr>
<td><code>mistral:7b</code></td>
<td><strong>JSON</strong></td>
<td align="right"><code>482 / 42</code></td>
<td align="right"><code>+24.2%</code></td>
<td align="right"><code>42.98 s</code></td>
<td><code>3/3</code><strong>,</strong> <code>0</code> <strong>FP</strong></td>
<td>✅ <strong>PASS</strong></td>
</tr>
</tbody></table>
<p><strong>What this proves:</strong></p>
<ul>
<li><strong>JSON costs ~</strong><code>+24%</code> <strong>more input tokens</strong> purely from repeated keys and braces.</li>
<li><code>qwen2.5:3b</code><strong>:</strong> already hits <code>3/3</code><strong>,</strong> <code>0</code> <strong>FP</strong> in compact <strong>CSV text</strong> (no reason to pay the JSON tax).</li>
<li><code>mistral:7b</code><strong>:</strong> needs <strong>JSON</strong> to eliminate its <code>Bloodshot</code> false positive (<code>3/3</code>, <code>0</code> FP).</li>
<li><code>llama3.2:3b</code><strong>:</strong> drops from <code>2</code> FP to <code>0</code> in JSON, but still needs its dedicated few-shot mode for the plural <code>"Aliens"</code>.</li>
<li><strong>Scaling to 1,000 books (</strong><code>--taille-bloc 64</code><strong>,</strong> <code>num_ctx: 4096</code><strong>):</strong> resetting chat history every <strong>64 rows</strong> keeps <code>3B</code> models at <strong>100% GPU</strong> (<code>0% CPU</code>). On <code>1,000</code> <strong>books</strong> (<code>16</code> stateless chunks), <code>llama3.2:3b</code> completed in <code>74.23 s</code> with <code>16/16 stop</code>, <code>3/3</code> <strong>recall</strong>, and <code>0</code> <strong>false positives</strong>.</li>
</ul>
<h3>Reproduce Part 2B Locally</h3>
<pre><code class="language-powershell"># 1. Benchmark CSV vs. JSON input format on all 3 models
foreach ($m in 'qwen2.5:3b', 'llama3.2:3b', 'mistral:7b') {
    foreach ($fmt in 'csv', 'json') {
        "alien" | python -X utf8 .\fonctions\interroger_comics.py `
          --modele $m --format-entree $fmt --langue eng --mesures
    }
}

# 2. Scale to 1,000 books in 16 stateless chunks of 64 rows (100% VRAM)
"alien" | python -X utf8 .\fonctions\interroger_comics.py `
  --modele llama3.2:3b --contexte 4096 `
  --lignes-fictives 1000 --max-lignes 1000 --taille-bloc 64 --json --mesures
</code></pre>
<blockquote>
<p><strong>The Senior Dev Reality Check</strong> Before someone jumps into the comments: yes, <code>"alien" in title.lower()</code> takes <code>&lt; 1 ms</code> <strong>and</strong> <code>0</code> <strong>tokens in Python</strong>. I know, that’s the point. Exact search was a controlled lab bench to expose JSON’s <code>+24%</code> token tax, plural edge cases, and KV-cache cliffs on 4 GB VRAM. In real apps, let deterministic Python handle exact filters, and save your local LLM for jobs Python <em>can’t</em> do alone.</p>
</blockquote>
<hr />
<h2>8. Part 2C: Where Local LLMs Actually Shine (100 Real Books &amp; Grounded Recommendations)</h2>
<h3>8.1 Semantic Genre Categorization (<code>categoriser_livres.py</code>)</h3>
<p>With <code>qwen2.5:3b</code> + <code>enum</code> JSON schema + <code>--regle-accessoire</code>:</p>
<ul>
<li><strong>8 PDF purchases (</strong><code>1</code> <strong>chunk):</strong> <code>289</code> tok in → <code>92</code> tok out in <code>23.69 s</code> (cleanly isolates <em>Marque-page Excalibur - The Witcher</em> into <code>Accessoire / Papeterie</code>).</li>
<li><strong>100 real books (</strong><code>8</code> <strong>PDF +</strong> <code>92</code> <strong>OpenLibrary books,</strong> <code>2</code> <strong>stateless chunks of</strong> <code>64 + 36</code> <strong>with progressive CSV flush):</strong> <code>88.81 s</code> total at 100% VRAM (<code>23</code> Superhero/Action, <code>21</code> Sci-Fi/Horror, <code>19</code> Fantasy, <code>17</code> Adventure/Exploration, and <code>20</code> in <code>Accessoire / Papeterie</code>: it caught the promotional bookmark cleanly, but also swept in 19 multi-book classic compilations, another honest reminder that <code>3B</code> outputs still deserve a quick human spot-check).</li>
</ul>
<h3>8.2 Grounded Recommendations vs. Pure Memory (<code>recommander_livres.py</code>)</h3>
<p>Ask a <code>3B</code> model to recommend books from memory and it turns into that friend at a bar who swears Stephen Baxter wrote David Wellington’s novel:</p>
<table>
<thead>
<tr>
<th>Mode (<code>qwen2.5:3b</code>, Genre 1: Sci-Fi / Horror)</th>
<th align="right">Tokens (in / out)</th>
<th align="right">Wall Time</th>
<th>Result</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Pure memory (</strong><code>--sans-catalogue</code><strong>, 8 PDF)</strong></td>
<td align="right"><code>224 / 291</code></td>
<td align="right"><code>44.54 s</code></td>
<td><strong>Hallucinated authors</strong> (<em>Le Dernier Astronaute</em> attributed to Stephen Baxter instead of David Wellington; only 2 items returned).</td>
</tr>
<tr>
<td><strong>Python 1 ms pre-filter (</strong><code>21/100</code><strong>) + grounded catalog</strong></td>
<td align="right"><code>840 / 234</code></td>
<td align="right"><code>54.29 s</code></td>
<td><strong>3 real, verified titles,</strong> <code>0</code> <strong>duplicates,</strong> <code>0</code> <strong>invented authors.</strong></td>
</tr>
</tbody></table>
<p>Actual console output from the grounded run:</p>
<pre><code class="language-text">Recommandations « Science-fiction / Horreur » (basées sur tes 21 livres de ce genre) :

1. Alien Tome 1 : Lignes de sang (Phillip Kennedy Johnson)
   Lien avec ta collection : La série Alien que vous avez commencée avec le Tome 2
2. Le cycle des robots (Tome 1) - Les robots (Isaac Asimov)
3. Sensor (Junji Ito &amp; Anais Koechlin)
</code></pre>
<h3>Reproduce Part 2C Locally</h3>
<pre><code class="language-powershell"># 1. Categorize 8 PDF purchases, then 100 real books in 2 chunks (64 + 36)
python -X utf8 .\fonctions\categoriser_livres.py --modele qwen2.5:3b --regle-accessoire --mesures

python -X utf8 .\fonctions\categoriser_livres.py `
  --modele qwen2.5:3b --livres-api 92 --max-lignes 100 --taille-bloc 64 `
  --regle-accessoire --sortie-csv .\donnees\inventaires\inventaire-100-vrais-livres-categorise.csv --mesures

# 2. Grounded recommendations (100 real books) vs. pure memory (--sans-catalogue)
"1" | python -X utf8 .\fonctions\recommander_livres.py --modele qwen2.5:3b --mesures
"1" | python -X utf8 .\fonctions\recommander_livres.py --modele qwen2.5:3b --seulement-pdf --sans-catalogue --mesures
</code></pre>
<hr />
<h2>9. Final Engineering Takeaways (What 4 GB of VRAM Taught Me)</h2>
<ol>
<li><strong>Inspect the Modelfile before touching the prompt (</strong><code>ollama show</code><strong>).</strong> <code>qwen2.5:3b</code> (<code>ChatML</code>, <code>dim=2048</code>, <code>repeat_penalty: 1.05</code>, <code>top_p: 0.8</code>, <code>top_k: 20</code>), <code>llama3.2:3b</code> (<code>Meta headers</code>, <code>dim=3072</code>, <code>repeat_penalty: 1.15</code>), and <code>mistral:7b</code> (<code>[INST]</code> with <strong>no separate</strong> <code>&lt;system&gt;</code> <strong>token</strong>, <code>dim=4096</code>, <strong>no</strong> <code>repeat_penalty</code>) are not interchangeable black boxes.</li>
<li><strong>Constrained JSON Schemas (</strong><code>format</code><strong>) are a force multiplier for 3B models, not magic.</strong> Dynamic <code>minItems</code>, <code>minLength</code>, <code>enum</code>, and structured sub-objects turned broken PHP audits into <code>6/6 PASS</code>. On Python parser codegen, however, <code>3B</code> models failed raw dumps (<code>0/3</code>), pure TDD (<code>0/3</code>), 3-turn self-correction (<code>0/2</code>), and plain-English layout rules (<code>0/2</code>): they only hit <code>3/3 PASS</code> with an explicit 4-step algorithm spec, proving that a senior dev still writes tricky 10-line parsers faster by hand.</li>
<li><strong>English prompts aren’t just cheaper, they’re more reliable on 3B codegen.</strong> English cut input tokens by <code>-11.6%</code> <strong>to</strong> <code>-13.2%</code>, sped up inference by <code>-26%</code> <strong>to</strong> <code>-42%</code>, and raised 3B Python parser generation from <code>1/3 PASS</code> <strong>(FR)</strong> to <code>3/3 PASS</code> <strong>(EN)</strong>.</li>
<li><strong>Stay stateless and chunk tight (</strong><code>1</code> <strong>function or</strong> <code>64</code> <strong>rows,</strong> <code>num_ctx: 4096</code><strong>).</strong> Dropping shared chat history cut PHP token usage by <code>-84%</code> (<code>13,722</code> → <code>2,190</code> tokens), and 64-row stateless chunking scaled search to <code>1,000</code> <strong>books at 100% GPU</strong> (<code>74.23 s</code>, <code>16/16 stop</code>, <code>3/3</code>, <code>0</code> FP).</li>
<li><strong>Pair the LLM with deterministic Python, always.</strong> Let Python extract PDFs, run exact filters (<code>&lt; 1 ms</code>), compile &amp; execute generated code against multi-case tests, and ground recommendations against real catalogs. Keep the local LLM on the parts Python can’t do alone.</li>
</ol>
<p>Every script, every external prompt (<code>prompts/</code>), and every anonymized dataset (<code>donnees/entrees/</code>) is in the repo so you can clone it and replay <strong>100% of this article</strong> on your own machine. Zero cloud bills, zero magic, just engineering.</p>
]]></content:encoded></item></channel></rss>