<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dharma AI on Medium]]></title>
        <description><![CDATA[Stories by Dharma AI on Medium]]></description>
        <link>https://medium.com/@dharma-ai?source=rss-917a9f144050------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NGOETlAU_bxcSmjSubzbYA.png</url>
            <title>Stories by Dharma AI on Medium</title>
            <link>https://medium.com/@dharma-ai?source=rss-917a9f144050------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:09:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dharma-ai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why your fine-tuning job takes longer than the FLOPs say]]></title>
            <link>https://medium.com/@dharma-ai/why-your-fine-tuning-job-takes-longer-than-the-flops-say-fa019c8c4877?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa019c8c4877</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 18:56:26 GMT</pubDate>
            <atom:updated>2026-11-18T18:56:26.873Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Predicting end-to-end fine-tuning time on shared GPU clusters, from 272 production runs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUyknj8zOpINZ9qEqtxwNg.png" /></figure><p><strong>A preview of our upcoming paper, <em>Predicting End-to-End Fine-Tuning Time for Generative Language Models</em>. The full version will be on arXiv soon.</strong></p><p>GPUs are among the most expensive and scarcest resources in AI today. Anyone running a shared cluster has to decide, every day, which jobs go on which GPUs and in what order. That plan is only as good as the estimate of how long each job will take. When a job finishes hours early, GPUs sit idle until the next one is dispatched. When it runs hours late, everything queued behind it slips, experiments wait and delivery dates move.</p><p>Better duration estimates turn this into planning instead of guesswork: what runs, when, and on how many GPUs, with less idle capacity in between. Yet the estimate most teams use is a back-of-the-envelope FLOP calculation. It says nine hours, and the job finishes the next afternoon.</p><p>We wanted to know how far off that math really is, and whether we could do better before a job is even dispatched. So we took 272 real supervised fine-tuning (SFT) jobs from our production pool of NVIDIA H200 GPUs, about 7,382 GPU-hours in total, and compared analytical estimates against learned predictors.</p><p>The short version: the usual FLOP-based estimate explains little of what we observed (R² = 0.31, MAE 12.41 h). A CatBoost regressor that only sees information available before dispatch reaches <strong>R² = 0.98, with a mean absolute error of 1.71 h and a median error of 0.51 h</strong> in 5-fold cross-validation. The gap comes from two things a closed-form estimate cannot do. The regressor sees more training-specific signals, such as evaluation cadence, checkpoint policy, per-GPU load and fine-tuning regime, and it learns the nonlinear interactions between them from past runs.</p><h3>The estimate everyone uses is compute-only</h3><p>For a dense Transformer, training costs roughly 6·P·D floating-point operations, where P is the parameter count and D the number of training tokens. Divide that by what your GPUs can deliver and you get a training-loop time:</p><pre>T_theoretical = (6 · P · D) / (N_GPU · FLOPS_peak · MFU)</pre><p>Here N_GPU is the number of GPUs, FLOPS_peak is the peak throughput of one GPU from its spec sheet, and MFU (Model FLOPs Utilization) is the fraction of that peak the training actually achieves. Real jobs never run at peak because of memory traffic, communication and kernel inefficiencies, so MFU typically sits somewhere between 30% and 60%, and the right value for a given job is not known in advance.</p><p>This is a good description of the optimization loop. A job is more than its loop, though. Before the first step there is environment setup, model download and loading, and tokenization. During training there are periodic evaluations and checkpoint uploads. At the end, the final model goes to object storage. On a multi-tenant cluster, all of it competes with other jobs for network and storage I/O.</p><p>These overheads depend on configuration, and they do not scale neatly with workload or GPU count. Two jobs with the same nominal compute can finish hours apart.</p><p>To keep the comparison fair, the FLOP baseline we test counts the scheduled evaluation tokens as well as the training tokens, and we sweep MFU over a wide range.</p><h3>What we built</h3><p>We treat end-to-end duration as a supervised regression problem. Given a feature vector built from the job configuration and model metadata, predict the wall-clock time between the moment the job gets its GPUs and the moment it is done. Queue time is excluded.</p><p>Two design choices shaped the work:</p><ul><li><strong>Everything is known before dispatch.</strong> Every input comes from the submitted configuration: hyperparameters, dataset sizes, model identifiers, GPU allocation. No runtime logs, no partial progress. That is what makes the prediction usable for scheduling.</li><li><strong>Features that expose the overheads.</strong> On top of the raw configuration we derive quantities such as num_eval_data (samples processed across all evaluation cycles), num_saves and num_params_saved (checkpoint I/O), and per-GPU token volumes. The FLOP estimate itself, with MFU fixed at 0.45, goes in as one more feature (baseline_time), so the model starts from the compute-only number and learns the corrections.</li></ul><p>We compared Linear Regression, Ridge, XGBoost and CatBoost. Feature selection combined correlation filtering, mutual information and permutation importance across 18 candidate feature sets, followed by a grid search with MAE as the criterion. The final CatBoost model uses 24 features.</p><h3>The data</h3><ul><li><strong>272 SFT runs</strong> from the operational logs of a corporate production environment, covering several model families up to 15 billion parameters, both LoRA and full fine-tuning, and a wide range of dataset sizes and hyperparameters.</li><li><strong>Shared infrastructure.</strong> Jobs ran on 1, 2 or 4 GPUs drawn from a pool of 8 to 32 H200s across 1 to 4 nodes, alongside other training and inference workloads. The measured times include real contention.</li><li><strong>Durations from 1.6 to 172.4 hours</strong>, with a mean of 23.43 h and a median of 15.29 h.</li><li><strong>Stack:</strong> Hugging Face Transformers and Unsloth. We model the stack as a categorical feature and make no assumption about a fixed speedup between the two.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJ9O388XfEfvKn21arrUJw.png" /></figure><h3>Results</h3><p>All numbers come from stratified 5-fold cross-validation. The FLOP baselines and Calculon are analytical and involve no fitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Yl-H6MUhxRsAZqquj7DDg.png" /></figure><p>A few things stand out.</p><p><strong>No single MFU value fixes the FLOP baseline.</strong> We swept MFU from 0.25 to 0.65. The best setting, 30%, still leaves a mean error above 12 hours on jobs that last 23 hours on average.</p><p><strong>A more detailed analytical model does not close the gap.</strong> As a second baseline we took Calculon (Isaev et al., SC ‘23), an analytical performance model for LLM training from prior work. It builds an explicit layer graph and accounts for compute, memory traffic and inter-device communication. We extended the public implementation to cover LoRA, grouped-query attention, fused attention, bfloat16 and SwiGLU. Its estimates still correspond to a median of only 11% of the observed wall-clock time. That says nothing against Calculon as a step-level tool, which is what it was designed for. It shows how much of a production job happens outside the optimization step.</p><p><strong>Linear models help, and then stall.</strong> Ridge brings MAE down to 7.23 h. The relationship between configuration and duration is not well captured by a purely linear model.</p><p><strong>Gradient boosting does the heavy lifting.</strong> CatBoost and XGBoost land within one standard deviation of each other on every metric. We carry CatBoost forward because it has the lowest mean error across the board.</p><h3>What the predictor relies on</h3><p>CatBoost’s feature importance concentrates in a handful of features. Model and workload variables are there, as expected, but so are evaluation and checkpoint variables. num_eval_data, the total number of samples processed in evaluation over the life of the job, ranks first, followed by num_trainable_params, batch_eval_size_percent, num_all_params and num_gpus*batch_train_percent, with num_params_saved close behind. SHAP values tell the same story: high evaluation volume consistently pushes the predicted time up, while trainable parameter count has a nonlinear effect that only becomes large for the biggest models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*svZ5cy2YSiSo1sknbSZSBg.png" /></figure><p>Feature importance is not a causal claim. Still, the pattern lines up with how a job is actually spent. How often you evaluate, how large the evaluation set is and how many checkpoints you persist all shape the wall-clock time, alongside model and dataset scale. These are choices people often make by habit when writing a training config.</p><p>One caveat on reading the plots: larger GPU allocations show positive contributions to predicted time. In our data, bigger allocations go with bigger jobs, so num_gpus acts partly as a proxy for job scale. It does not mean adding GPUs makes a job slower.</p><h3>How wrong is it, and where</h3><p>Looking at all 272 out-of-fold predictions, the median absolute error is 0.51 h. 80% of predictions are within 2.20 h and 90% are within 4.31 h. Broken down by job duration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBou5p2pCdedEarNtb4Rcw.png" /></figure><p>Up to 60 hours, the median error stays at about one hour or less. The long tail is where the model struggles, and with only 13 runs above 60 hours we read that as a data limitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*XsMDm_70VgM8mNb1xnSwnQ.png" /></figure><p>More data should still help. On a fixed 20% holdout, MAE drops from 1.63 h to 1.50 h when going from 85% to 100% of the training partition, with no clear plateau.</p><h3>What it is good for</h3><p>In practice, the predictor gives a scheduler a duration it can plan around before a job starts: which jobs to run together, when GPUs will free up, and whether a run will finish in time for its deadline.</p><h3>Limitations</h3><ul><li><strong>SFT only.</strong> We did not include other training and alignment strategies such as RLHF, DPO or RLVR.</li><li><strong>One GPU type.</strong> Every run used H200s. The fitted model is calibrated to that infrastructure and should not be expected to transfer numerically to other GPU generations without retraining. A predictor for mixed pools would also need hardware descriptors such as compute throughput, memory capacity and bandwidth, and interconnect topology.</li><li><strong>Few very long runs.</strong> Errors widen above 60 hours.</li></ul><p>What does transfer is the method: overhead-aware features, multicollinearity-aware selection and the comparison protocol. The full paper will report the feature formulas, the selection procedure, the search spaces and the final hyperparameters in full, so the pipeline can be rebuilt on any execution-log dataset with a similar structure.</p><p>Next on our list: hardware-specific descriptors and validation on other GPU types, transfer learning for configurations with few observations, other training objectives, and more data on long runs.</p><h3>What’s next</h3><p>The full paper is coming to arXiv soon. Follow the Dharma-AI organization on Hugging Face to be notified when it is out, and leave your questions in the comments below. We would like to hear how you estimate job duration on your own clusters.</p><h3>Further reading</h3><ul><li><a href="https://huggingface.co/blog/Dharma-AI/gpu-management">GPU Management: Why Idle GPUs Are the New Grounded Aircraft</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/gpu-management-pt2">Same Cluster, 33 Points More Utilization: What Changed Was the Order</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/vocabx-vocabulary-specialization">How Specializing the Vocabulary of SLMs Can Cut Inference Cost by 77% in Real Applications</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/specialization-beats-scale">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/why-specialization-is-inevitable">Why Specialization Is Inevitable</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/newer-models-same-advantages">Newer Models, Same Advantage</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/direct-preference-optimization-beyond-chatbots">Direct Preference Optimization Beyond Chatbots</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/text-degeneration-a-production-failure-mode">Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track</a></li></ul><p><em>Originally published on the </em><a href="https://huggingface.co/blog/Dharma-AI/predicting-fine-tuning-time"><em>Dharma-AI blog on Hugging Face</em></a><em>.</em></p><p><em>Dharma-AI R&amp;D · We Make AI Your Model</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa019c8c4877" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dharma Field Extractor: Any Document In, Structured Fields in JSON Out]]></title>
            <link>https://medium.com/@dharma-ai/dharma-field-extractor-any-document-in-structured-fields-in-json-out-63adaa9e1f34?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/63adaa9e1f34</guid>
            <category><![CDATA[document-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 17:51:39 GMT</pubDate>
            <atom:updated>2026-11-04T17:51:39.518Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 2-billion-parameter model that extracts exactly the fields you ask for, from any document type, outperforming every frontier LLM we tested, at a fraction of the cost.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaseHS1mQFB3iaidAOwGHg.png" /></figure><p>In April, we released <a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE">DharmaOCR-LITE</a>, a model specialized for OCR across a wide range of documents, from contracts and court filings to invoices, IDs and forms. The <a href="https://arxiv.org/abs/2604.14314">paper</a> behind it made a narrow, well-measured case for domain specialization: a smaller model trained closer to its task beating general-purpose frontier APIs on that task.</p><p>OCR gives you the text on a page, faithful to the original formatting. That’s exactly what you want when the job is the whole document, like a contract you’ll read end to end or a manuscript you’re digitizing.</p><p>However, there’s a different use case: you don’t want the page, you want specific fields out of it, in a shape a system downstream can consume. Every line item on an invoice, as a list. The patient name, exam type and date from a medical requisition, ready to schedule. The fields off an ID, mapped to the columns of an employee record.</p><p>Run that document through OCR and you get back everything printed on it, line by line, with no indication of which string is the exam type, which is the date or which number is the total. Someone still has to write the code that maps each value to the right field before it reaches the database.</p><p>A general-purpose LLM can do this work today, with careful prompting. At frontier API pricing and latency, on a task many businesses need to run at high volume, that quickly becomes the expensive way to solve a well-defined problem.</p><p>So we built a model for it instead. The Field Extractor takes a document image and either a request for everything it can find, or an exact schema to fill, and returns structured JSON: typed, field by field, nested where the document nests. An invoice comes back with every line item as an ordered list, each with its own quantity and value, alongside the totals. An ID comes back as the fields you’ll store, under the names your system already uses for them. The same checkpoint handles all of it, with no per-type fine-tuning.</p><p>You can try it yourself <a href="https://ocr-portal.prd-us-east-2.dharma-ai.com/login">here</a>.</p><h3>What the Model Does</h3><p>Say a batch of supplier invoices lands every morning, and you need four things off each one to push into your system: the supplier, the invoice number, the due date, the total. Same story for medical requisitions going into a scheduler, or contracts feeding a compliance system, where what matters is the parties, the term, the penalties and the fine amounts. You don’t need the page, you need certain fields. With the Field Extractor there are two ways to ask for them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozSKesuDw_B2T1DTewMXeQ.gif" /></figure><ul><li><strong>Open</strong>: no schema supplied. The model reads the page and works out which parts of it are structured fields (a label followed by a value, a table with a header row over its columns) from context and layout, not from a fixed list of field names, and returns everything it finds as key-value pairs.</li><li><strong>Schema-directed</strong>: you specify the exact shape wanted, field by field, with a type for each one (string, number, or boolean), under the key names your system already uses. Ask for “service_provider” and “client_company”, and those are the exact keys that come back. Ask for a table and it fills it row by row, column by column, matching each cell to the key it belongs under. Ask for a field that isn’t on the document, and it returns null instead of inventing a value.</li></ul><p>The choice comes down to what you already know. Send an open request when you don’t know what the document holds. Send a schema when the output has to match a shape that already exists somewhere else.</p><p>Either way, what comes back is JSON: the fields as keys, the values typed as requested, and null where the document didn&#39;t have what you asked for. When you send a schema, the output follows it exactly, with the same keys and no extra fields, so it can go straight into the next system.</p><h3>How It Was Trained</h3><p>The base model is DharmaOCR-LITE v1.1, a new 2-billion-parameter version optimized from the one in the paper and already specialized for OCR through supervised fine-tuning and DPO. On top of that checkpoint we trained a LoRA adapter on 43,384 training examples covering both request modes.</p><p>The data is organized into three streams:</p><ul><li><strong>English multi-domain data</strong>: diverse documents collected from the public web, spanning many document types.</li><li><strong>Brazilian domain data</strong>: real Brazilian documents sourced internally, in Portuguese.</li><li><strong>Multilingual data</strong>: a smaller share covering other European and Asian languages, for broader generalization beyond English and Portuguese.</li></ul><p>All three streams are annotated at the field level. The mix is deliberately multi-domain: receipts, commercial invoices, forms, bank statements, ID documents and synthetic documents, rather than one filing type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmO4Z2cXy9qD3_XqT92oSw.png" /></figure><h3>Where the Benchmark Draws the Line</h3><p>The full benchmark covers 546 documents across three request scenarios, for 1,638 total cases: extracting every field with no schema, a partial schema naming only real fields, and a schema that also includes deliberately nonexistent fields. The score is field-level F1 (matched by path, including position inside a table), multiplied by the Levenshtein similarity on the values that matched and by the share of outputs that come back as valid JSON.</p><p>We ran the same benchmark against four general-purpose frontier configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dY5Z9HfWuHevEYAGJffI9Q.png" /></figure><p>Against general-purpose LLMs, the quality gap runs from 1.8 points (Claude Opus 5, the closest) to 9.3 points (GPT-5.6 Luna, the widest).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TI_os5_epklLMNWSUD_9DQ.png" /></figure><p>Cost runs from roughly 6 times lower (GPT-5.6 Luna) to roughly 147 times lower (GPT-5.6 Sol). The two sides are priced differently. The frontier figures come from measured average input and output tokens per page, reasoning tokens included, against each provider’s published list pricing. Every frontier model ran with reasoning set to low; Claude Opus 5 used adaptive effort, which can skip reasoning on simpler pages while staying at the low level. Ours isn’t billed per token: the model runs self-hosted, so the figure is GPU time on a single L40S at $2.24 per hour.</p><p>This is not a sales price. Self-hosted cost depends on the hardware, the volume and the latency each deployment needs. The comparison is here to show that a sovereign SSLM, deployed on your own infrastructure, is a real alternative to frontier APIs.</p><h3>A Test of Generalization</h3><p>SROIE and FUNSD are two public datasets in our benchmark, not used in training. Below is one example from each.</p><p>On a SROIE receipt, we asked for all 18 fields printed on it, with no phantom fields this time, and every one comes back correct: the multi-line, unlabeled billing address captured as a single field, the two blank fields (salesperson and ref) correctly returned as null, and every number on the receipt matching to the cent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npqUjX46bdzQeeWSJuctbA.png" /></figure><p>On a FUNSD photocopying variance form, a checklist of twelve boolean fields with one nested group of five sub-options, the model marks exactly the one box that’s checked (poor quality original, with a handwritten “faded” note beside it) as true, and the other eleven as false, matching the form exactly. It also reads the handwritten Bates ID off the page correctly, and returns null for the two fields left blank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-wPoVOJu9XKnss7-HxPVg.png" /></figure><h3>Quality and Cost, at the Same Time</h3><p>A 2-billion-parameter model scored 0.834, above every frontier configuration we tested, from Claude Opus 5 at 0.816 to GPT-5.6 Luna at 0.741, while running on a single L40S at a lower cost per extraction than every API in the comparison. Higher quality and lower cost, measured on the same benchmark, in the same run.</p><p>This isn’t the first time we’ve measured it. Our OCR paper put the first DharmaOCR-LITE, a 3-billion-parameter model, above every commercial frontier API tested on Brazilian Portuguese; three months later, newer and better-resourced models arrived, and the gap held. Now a 2-billion-parameter model does it on field extraction. Each result adds evidence for the thesis we started Dharma-AI with: on a bounded task, a small model trained close to that task beats a frontier model asked to do the same thing in general. In this benchmark, it also cost 6 to 147 times less to run.</p><p>Parameter count sets the ceiling; training decides how much of it a model reaches on your task. Your business doesn’t need the biggest model available. It needs one trained for your problem.</p><p>Try it on your own documents <a href="https://ocr-portal.prd-us-east-2.dharma-ai.com/login">here</a>. To learn more about Dharma-AI and the specialized models we build, visit <a href="https://dharma-ai.com/">dharma-ai.com</a>.</p><h3>Sources</h3><ul><li>BID. Brazilian Identity Document Dataset. Soares, Neves Jr., Bezerra (2020), “BID Dataset: a challenge dataset for document processing tasks,” Anais Estendidos XXXIII SIBGRAPI. <a href="https://github.com/ricardobnjunior/Brazilian-Identity-Document-Dataset">github.com/ricardobnjunior/Brazilian-Identity-Document-Dataset</a></li><li>CORD. Park et al., NAVER CLOVA (2019). <a href="https://huggingface.co/datasets/naver-clova-ix/cord-v2">huggingface.co/datasets/naver-clova-ix/cord-v2</a></li><li>DocVQA. Mathew et al., WACV 2021 (ICDAR 2019). <a href="https://huggingface.co/datasets/lmms-lab/DocVQA">huggingface.co/datasets/lmms-lab/DocVQA</a></li><li>WildReceipt. Sun et al., IJCAI 2021. <a href="https://huggingface.co/datasets/Theivaprakasham/wildreceipt">huggingface.co/datasets/Theivaprakasham/wildreceipt</a></li><li>SROIE (ICDAR 2019). Held out from training, evaluation only. <a href="https://huggingface.co/datasets/darentang/sroie">huggingface.co/datasets/darentang/sroie</a> (mirror); upstream <a href="https://rrc.cvc.uab.es/?ch=13">rrc.cvc.uab.es/?ch=13</a></li><li>FUNSD. Jaume et al. Held out from training, evaluation only. <a href="https://huggingface.co/datasets/nielsr/funsd">huggingface.co/datasets/nielsr/funsd</a> (mirror); <a href="https://guillaumejaume.github.io/FUNSD/">guillaumejaume.github.io/FUNSD</a></li><li>Zenodo Invoices (PT). Cruz &amp; Castelli, NOVA IMS (2022). <a href="https://zenodo.org/records/6371710">zenodo.org/records/6371710</a></li><li>line_items. Sagarjha456, Hugging Face. <a href="https://huggingface.co/datasets/Sagarjha456/line_items">huggingface.co/datasets/Sagarjha456/line_items</a></li><li>Katanaml Invoices (Donut). Kozłowski &amp; Weichbroth (2021), Mendeley Data <a href="https://doi.org/10.17632/tnj49gpmtz.2">doi:10.17632/tnj49gpmtz.2</a>. <a href="https://huggingface.co/datasets/katanaml-org/invoices-donut-data-v1">huggingface.co/datasets/katanaml-org/invoices-donut-data-v1</a></li><li>HumynLabs Brazilian Bills and Invoices. <a href="https://huggingface.co/datasets/HumynLabs/Brazilian_Bills_and_Invoices_Dataset">huggingface.co/datasets/HumynLabs/Brazilian_Bills_and_Invoices_Dataset</a></li><li>Tech4Humans BR-Doc Extraction. <a href="https://huggingface.co/datasets/tech4humans/br-doc-extraction">huggingface.co/datasets/tech4humans/br-doc-extraction</a></li><li>Cardoso, Gabriel Pimenta de Freitas, et al. “DharmaOCR: Specialized Small Language Models for Structured OCR that outperform Open-Source and Commercial Baselines.” arXiv preprint <a href="https://arxiv.org/abs/2604.14314">arXiv:2604.14314</a> (2026).</li></ul><h3>Further Reading</h3><ul><li><a href="https://huggingface.co/blog/Dharma-AI/vocabx-vocabulary-specialization">How Specializing the Vocabulary of SLMs Can Cut Inference Cost by 77% in Real Applications</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/gpu-management-pt2">Same Cluster, 33 Points More Utilization: What Changed Was the Order</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/gpu-management">GPU Management: Why Idle GPUs Are the New Grounded Aircraft</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/newer-models-same-advantages">Newer Models, Same Advantage</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/why-specialization-is-inevitable">Why Specialization Is Inevitable</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/specialization-beats-scale">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/text-degeneration-a-production-failure-mode">Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/direct-preference-optimization-beyond-chatbots">Direct Preference Optimization Beyond Chatbots</a></li></ul><p><em>Explore </em><a href="https://huggingface.co/Dharma-AI"><em>Dharma AI on Hugging Face</em></a><em> to </em><a href="https://huggingface.co/spaces/Dharma-AI/DharmaOCR-demo"><em>try our interactive demos</em></a><em>, </em><a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE"><em>download our open-source models</em></a><em>, and discover how specialized AI systems outperform general-purpose models in real enterprise applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63adaa9e1f34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Specializing the Vocabulary of SLMs Can Cut Inference Cost by 77% in Real Applications]]></title>
            <link>https://medium.com/@dharma-ai/how-specializing-the-vocabulary-of-slms-can-cut-inference-cost-by-77-in-real-applications-d2e1e3fef13c?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2e1e3fef13c</guid>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 17:50:50 GMT</pubDate>
            <atom:updated>2026-10-21T17:50:50.669Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Models specialized for a domain or a task by fine-tuning general open-source models, such as Qwen and Gemma, inherit a vocabulary built for many domains and general applications.</em></p><p><em>In an essay grader we run in production, that vocabulary split the text the model writes most into many tokens. This article previews some results from the VocabX paper, which we will publish soon: how we specialized the vocabulary around the cost of each token rather than its frequency, and cut measured inference cost by 77% without changing the base model.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*96Eu8Yr5yEa6_-q7.png" /></figure><p>The tokenizer is usually treated as a fixed property of the base model, inherited and left alone. For a model specialized in a single domain, it can be one of the largest cost levers, and it is set before any training step.</p><p>One of the systems we run in production is an automated grader for Portuguese essays, built on Qwen3–4B. It receives the essay, the prompt and the supporting texts, and returns a JSON assessment with a grade and a comment for each competency.</p><p>The model was already small, at 4 billion parameters, and had already been trained for the task. Its tokenizer, however, was still the original Qwen3–4B one, built for many languages and many kinds of text. In the grader, it was used for a single language, Portuguese, and a single response format. That had two costs: the text the grader writes on every request took more tokens than it needed, and at every generated token the model scored a vocabulary of 151,669 entries, including many this task almost never uses.</p><p>We rebuilt that vocabulary with a method we call VocabX, keeping the same base model, the same data and the same training recipe. The numbers in this article come from the current version of the paper, still under review, and may change before publication.</p><h3>A Vocabulary Built for Everyone</h3><p>The leading language models read and write in tokens, and the tokenizer decides how text becomes tokens. The tokenizers of the leading general-purpose models are trained on large collections of text from many domains and languages, from source code to contracts to Chinese. For a general-purpose model, that choice makes sense.</p><p>For a model used in a single domain, it creates two kinds of waste at once.</p><p>The first is fragmentation. The tokenizer splits into many pieces exactly what the domain repeats most. In the grader, every response starts with the same JSON envelope, the same competency names, the same evaluation phrases. In contracts, it is the boilerplate clauses. In code, the identifiers. Each of these sequences costs several tokens where one would do, and the model pays for every one of them on every request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atEBlZCvgSYwnlWIsGgixA.png" /></figure><p>The second is excess. The vocabulary carries tens of thousands of entries the domain never uses, and the model computes a score for all of them at every token it generates. A model tuned to grade American school biology exams will almost never write in Chinese, yet it computes the probability of every Chinese-language token at every step. The vocabulary splits into many pieces what the domain repeats most, and carries entries the domain never uses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4iYvM81uKBVs_Zx072b5A.png" /></figure><h3>Reading Is Cheap, Writing Is Expensive</h3><p>The natural reaction is to count tokens and try to reduce the count. But the count is not the bill.</p><p>To see why a generated token costs more, it helps to look at how inference works. It has two phases. In <em>prefill</em>, the model processes the whole input in a single pass through the network: each weight read from GPU memory is reused for every input token, and the limit is compute. In <em>decode</em>, the model generates the response one token at a time, and each token needs a full pass. Each weight read is used only a few times, and the GPU spends most of its time waiting for data to arrive from memory: the limit becomes memory bandwidth.</p><p>This effect is strongest exactly where we operate: small models served with moderate batches. Batching requests splits the weight reads across them and eases the problem, but does not solve it. At every decode step, the model also reads the KV cache, the attention memory that holds the context already processed and grows with it. In the case we measured, the grader, a generated token costs 7.4 times a token read, but the ratio varies with the hardware, the problem, the batch size, the context length and other factors, and it can be larger than that. In general, the direction holds: generating costs more than reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZYxMtN8SAbmCl-Kre9DNg.png" /></figure><p>Think of a shipping company that charges per box, but charges seven times more for outgoing boxes than for incoming ones. Reducing the total number of boxes helps. Reducing the outgoing boxes helps seven times more. A method that compresses input and output equally misses most of the possible savings.</p><p>The third component of the bill is the vocabulary itself. The model’s last layer, the LM head, turns the internal state into a score for every possible token. To do that, it holds one row of parameters per vocabulary entry. In a model the size of Qwen3–4B, that matrix accounts for almost 10% of the parameters. It is a share that large models absorb without noticing, but it weighs on a small model.</p><p>And the cost is not paid only once. The input layer looks up only the row of the token being read, but the LM head reads and multiplies the entire matrix for every generated token. Since decode is already memory-bound, every extra row is more data to move at every step. An entry the domain never uses costs exactly the same as a frequent one. That is why adding tokens can lower the count and raise the bill at the same time. VocabX does not include this term in its selection criterion, but it controls vocabulary size in two steps: the sub-word merge replaces the base vocabulary with a smaller, domain-specific one, and macros enter under a fixed budget. In the grader, the output layer went from about 152,000 to about 65,000 rows.</p><h3>Why Existing Solutions Fell Short</h3><p>Adapting a model’s vocabulary is not a new idea. Reference methods in the literature, such as fast vocabulary transfer (FVT), multi-word tokenization (MWT) and Liquid AI’s <a href="https://www.liquid.ai/blog/tokenizer-expansion">in-place tokenizer expansion</a> (in-place BPE), which continues BPE training from the original vocabulary, already reduce fragmentation. When we tested them on our problem, we found two limitations.</p><p>They choose tokens by frequency, not by cost. An expression that appears often in the input is worth more to them than one that appears less often in the response, even if the second is the more expensive one to serve.</p><p>They work on a single layer. They either adjust how words are cut into pieces, or merge whole phrases into one token. None of these three does both under the same criterion. And the grader’s biggest waste was precisely in long, repeated spans such as the JSON envelope, which a sub-word method only reaches after merging each part, one by one.</p><h3>How We Solved It</h3><p>VocabX addresses both limitations, plus a third problem that appears on the obvious path to solving the first.</p><p>First, we changed the question. Instead of asking how many tokens a candidate saves, we ask how much cost and time it saves. Each eliminated token is multiplied by the price of the field it appears in: system prompt, user message or model response. In the case we measured, the grader, a token saved in the response is worth 7.4 times one saved in the input, and the vocabulary is built accordingly.</p><p>Second, we work on both layers at once. Back to the shipping company: you can cut boxes by packing each item better, or by recognizing that the same twelve-item kit ships every week and sending the kit in a single box. VocabX does both. At the sub-word layer, it rebuilds how domain words are cut into pieces. At the multi-word layer, it looks for whole spans that repeat, from short expressions to full lines and JSON envelopes, and turns each into a single token, which we call a macro token. Both layers are chosen under the same cost criterion, each with its own budget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*KhnGKiAMCC3JpZWxaR8KyA.gif" /></figure><p>To find these spans, we use five miners, automatic searches for spans that repeat across the corpus, each specialized in one kind of repetition: long words, whole lines, expressions, complete sentences, and structures with punctuation such as JSON and tags. Averaged over eight corpora, the last one contributed the most, and on code it alone accounted for 17.5 points. Without all five, token reduction on the grader would drop by 55.6 points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*182sFta4IJIyIp4RLx1ufQ.png" /></figure><p><strong>Third, we estimate what the sample cannot see.</strong> Choosing tokens by cost requires knowing how much each candidate still saves after the ones already chosen. Measuring that exactly would require reprocessing the entire corpus after every choice, tens of thousands of times. A common way to do this at scale is to measure on a sample of documents, and then a candidate absent from the sample gets zero gain.</p><p>An expression that appears 37 times in 50,000 documents shows up in a 400-document sample only about 26% of the time. In a contracts corpus, only 16.6% of the candidates appear in a 400-document sample; the rest are never evaluated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9dD-OPXsauZbAU1Hjr6Pg.png" /></figure><p>A candidate’s gain has two parts. One is how much it saves over the entire corpus, and that can be counted exactly, without a sample. The other is how much of that saving is not yet covered by the tokens already chosen, and only that part needs to be estimated. For candidates the sample cannot see, we use a statistical estimate based on the behavior of the ones it can see, instead of zero. A candidate that is rare in the sample but frequent in the corpus is back in the running.</p><p>That change alone, with the same sample and the same budget, raised token reduction on a contracts corpus from 44.7% to 52.8%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmuZIguMco1qd1-ix6bqEQ.png" /></figure><h3>What Changed in the Grader</h3><p>To measure the real effect, we trained seven versions of the grader with the same base model, the same data, the same recipe and the same seed. The only difference between them is the tokenizer. All of them ran the same 500 requests on the same test machine, with an RTX 5090 GPU and the vLLM inference server, and cost was calculated from measured runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1jxNRW2e3R9hCVyBjmFNA.png" /></figure><p>The model’s response dropped from 350 to 101 tokens on average. Cost dropped 77.0%. Quality, measured by the bench score, which combines grading accuracy and the accuracy of screening off-topic or rule-breaking essays, rose from 0.703 to 0.810.</p><p>Getting there required a course correction. The first version of the vocabulary fused each competency’s grade with the surrounding JSON into a single macro token. It was the most compact option, but quality dropped: its bench score was 0.689, below the production grader’s 0.703. With the grade inside the macro, each combination of grade and structure became a different variant of the same token, and the model chose both in a single step. Giving the grade its own token cost 2 extra tokens per response, raised the bench score to 0.810 and, in the measurement, was even cheaper: a 77.0% reduction, against 73.3% for the fused version.</p><p>The lesson applies beyond the grader. Compression has a cost when the compressed span carries the very decision the model exists to make. The goal is not the cheapest possible vocabulary, but the cheapest one that preserves the tokens that matter.</p><h3>Beyond the Grader</h3><p>To find out whether the gain was specific to our case, we compared VocabX with the three reference methods on five public domains (contracts, medical papers, scientific papers, news and Python code) and three model families (Qwen3, Llama-3.1 and Gemma-3). All methods used the same mining and test documents, and the same vocabulary ceiling.</p><p>VocabX compressed more than the strongest reference method in all fifteen combinations, by 1.2 to 9.3 points. In estimated inference cost, the pruned version of VocabX also led in all fifteen, with average margins of 10.2 points on Qwen3, 7.5 on Llama-3.1 and 13.6 on Gemma-3. On contracts, the pruned version reached 62.6% token reduction with 113,426 vocabulary entries, against 61.8% for the best in-place BPE configuration, which uses 207,803.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwWSPZagJRUMy1xqL4nCOg.png" /></figure><h3>Paying Only for the Tokens That Matter</h3><p>VocabX does not make the model smarter. It makes the model stop paying for text it does not need to write piece by piece, and stop scoring a vocabulary it will never use. In our grader, that cut measured inference cost by 77%, with the same base model and the same training recipe.</p><p>Specialization usually starts with data and weights. It can also start one layer earlier, in the vocabulary.</p><p>The full method, the tables for every experiment and the discarded interventions will be in the VocabX paper, which we will publish soon.</p><h3>Sources</h3><ul><li>Dharma-AI. “VocabX: Cost-Weighted Vocabulary Adaptation for Domain-Specific Language Models.” In preparation (2026).</li><li>Gee, Leonidas, et al. “<a href="https://aclanthology.org/2022.emnlp-industry.41/">Fast vocabulary transfer for language model compression</a>.” EMNLP Industry Track (2022).</li><li>Gee, Leonidas, et al. “Multi-word tokenization for sequence compression.” EMNLP Industry Track (2023).</li><li>Smith, Jimmy T.H., et al. “<a href="https://arxiv.org/abs/2607.15232">In-Place Tokenizer Expansion for Pre-trained LLMs</a>.” arXiv:2607.15232 (2026).</li></ul><h3>Further Reading</h3><ul><li><a href="https://huggingface.co/blog/Dharma-AI/gpu-management-pt2">Same Cluster, 33 Points More Utilization: What Changed Was the Order</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/gpu-management">GPU Management: Why Idle GPUs Are the New Grounded Aircraft</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/why-specialization-is-inevitable">Why Specialization Is Inevitable</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/specialization-beats-scale">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a></li><li><a href="https://huggingface.co/blog/Dharma-AI/text-degeneration-a-production-failure-mode">Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track</a></li></ul><p><em>Explore </em><a href="https://huggingface.co/Dharma-AI"><em>Dharma AI on Hugging Face</em></a><em> to try our demos, download our open models, and see how specialized AI systems outperform general-purpose models in real enterprise applications.</em></p><p><em>Originally published at </em><a href="https://huggingface.co/blog/Dharma-AI/vocabx-vocabulary-specialization"><em>https://huggingface.co</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2e1e3fef13c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Same Cluster, 33 Points More Utilization: What Changed Was the Order]]></title>
            <link>https://medium.com/@dharma-ai/same-cluster-33-points-more-utilization-what-changed-was-the-order-27e1405c7f97?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/27e1405c7f97</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 21:01:38 GMT</pubDate>
            <atom:updated>2026-08-17T21:11:36.621Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://medium.com/@dharma-ai/gpu-management-why-idle-gpus-are-the-new-grounded-aircraft-fb9479fa3175">previous post</a> argued that utilization, not intelligence, is where the next real constraint in enterprise AI is forming, and it closed by noting that no playbook has emerged yet for what a mature GPU Management practice looks like. This is ours.</p><p>We built a constraint-aware GPU allocator and benchmarked it against a FIFO scheduler across seven benchmark scenarios. On identical hardware, running identical workloads, GPU utilization rose by as much as 33 percentage points, and priority-weighted output rose in every one of them, by as much as 105%. Nothing about the hardware changed. What changed was the order in which allocation decisions get made.</p><p>One note on measurement before the numbers start. Every gain below is expressed as improvement over the FIFO result on the same scenario. Utilization is reported in percentage points; value is reported as a percentage increase in priority-weighted output.</p><h3>The decision, stated precisely</h3><p>“Keep the GPUs busy” is not a decision a system can execute. The decision is narrower and much harder: which GPU runs which job, in which timestep, at what priority. Formally it is one binary choice per combination of GPU, job and timestep, and the output is a grid — every GPU, across the whole scheduling horizon, with a job name in each cell or nothing at all.</p><p>Four workload types compete for that grid: training, real-time inference, batch inference, and quantization. They split into two allocation shapes, and the split is where the difficulty lives. Training, batch inference and quantization are batch-like: once started, each needs a contiguous block of GPUs held without interruption until the job finishes. Real-time inference is the opposite: elastic, driven by a demand curve that changes every timestep, growing and shrinking as traffic does.</p><p>Two incompatible shapes competing for the same hardware in the same timestep is the core problem. A second heterogeneity sits inside a single type: for the same base model, training jobs range from a few hours to several days, and from one GPU to dozens.</p><h3>What FIFO costs under contention</h3><p>The comparison point throughout is a FIFO-based scheduler: real-time inference served from a fixed reservation, and every other job placed in arrival order, without regard for priority.</p><p>Under the right conditions, that is a reasonable policy. When the cluster has slack, allocation order costs nothing in utilization, everything fits regardless of sequence, so FIFO and anything more sophisticated fill the same fraction of the pool. Contention is where that ordering cost stops being invisible and starts costing capacity too. It then becomes expensive in two separate ways, and they are worth taking one at a time.</p><p><strong>The reservation.</strong> Real-time inference cannot wait for capacity; the GPUs have to be there the moment traffic needs them. A scheduler that places jobs in arrival order has no mechanism for releasing GPUs during a trough and reclaiming them before the next peak, so the only way to guarantee availability is to take each real-time application’s maximum demand for the day and reserve that many GPUs for the whole day. The cost lands in every hour that is not the peak. An application needing six GPUs at midday and two at 4am holds all six for twenty-four hours, and the four idle GPUs are unavailable to any batch job for the entire day. They are not being used, and they are not free either. It is why the baseline sits near half the cluster in the two scenarios where reservation dominates: 51.6% in the mixed control and 53.6% in the training-heavy case. Roughly half a pool, with much of the idle half reserved rather than free. This cost is paid whether the cluster is contended or not — contention only makes it visible.</p><p><strong>The ordering.</strong> Under real contention, which jobs fit at all depends on the order you place them, not just on how much capacity exists. Order is not a tiebreaker applied after the capacity question is settled. Order <em>is</em> a capacity decision. FIFO places each job as it arrives, without weighing what that job is worth and without checking what else still has to fit inside the horizon, so high-priority work waits behind whatever asked first and capacity gets committed in placements that later jobs cannot use.</p><p>The two compound. The block held for the day’s maximum real-time demand is off the table for every batch job in the queue, in every hour, and whatever remains is handed out in the order the requests happened to arrive.</p><p>It is the GPU equivalent of an airline assigning aircraft to whichever charter called first, then finding nothing left to fly the route that actually pays. And GPUs reserved all day for a peak lasting a couple of hours are the grounded aircraft from the previous piece in the most literal sense: on standby, earning nothing, unavailable to anyone else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rsyk1doJVMOj75_y4kLwog.png" /></figure><p>Across five benchmark scenarios built for genuine contention, the allocator improved both axes at once. Utilization moved from a 52–85% band to a 72–88% band. Priority-weighted value rose between 24.6% and 105.1%, averaging 52%. Every scenario, both metrics, no tradeoff to explain away.</p><p>The strongest single case was a training-heavy workload on 8 GPUs: utilization went from 53.6% to 87.0%, and value more than doubled, up 105%. Thirty-three points of a fixed, already-depreciating asset, recovered by reclaiming reserved standby capacity and placing the rest in priority order. (This figure reflect a single baseline ordering.)</p><p>The allocator removes both behaviors. Real-time demand is treated as a curve rather than a ceiling, allocated against demand at each timestep, with batch-like work occupying the troughs, bounded by the cap on how many GPUs a real-time job may swap between consecutive timesteps. And batch-like jobs are placed by priority across the whole horizon instead of in the order they arrived. The rest of this piece is how.</p><h3>Utilization is necessary. Priority is what turns it into value.</h3><p>Utilization measures occupancy: what fraction of available GPU-time is allocated to something. It carries no information about what that something is worth. One scenario pulls the two apart completely, and the gap runs in a direction that is easy to miss.</p><p>In the scale test, 30 jobs across 64 GPUs, FIFO and the allocator produced <strong>identical utilization</strong>, 44.9% each, and <strong>identical throughput</strong>, 27 of 30 jobs completed. The allocator delivered 15.9% more priority-weighted value. Every dashboard reads the same. The cluster produced materially different output.</p><p>An objective that does not price priority can fill the cluster to exactly the same level, finish exactly as many jobs, and still deliver less. The previous piece argued that occupancy is a poor read on whether a cluster is earning; this is the measured version of that claim.</p><h3>Writing the problem down</h3><p>The alternative is not a longer list of heuristic rules. Some constraints only mean anything globally, and no local rule can express them: contiguous blocks, a budget for how much GPU churn is acceptable across the entire horizon, a guarantee that running work is never preempted. To honor those, the problem has to be written down as one thing.</p><p>Five constraints define a legal allocation:</p><ul><li>A GPU serves at most one job per timestep.</li><li>Every job respects its demand range, and whatever is already running is inherited and held.</li><li>Batch-like jobs occupy contiguous blocks of GPUs, sized to a power of two.</li><li>Real-time jobs have a hard cap on how many GPUs they may swap between consecutive timesteps.</li><li>A job that has started cannot be interrupted.</li></ul><p>The objective function has two terms. Allocating a GPU to a batch-like job earns a reward equal to its priority multiplied by a time-decay weight. Failing to meet real-time demand incurs a penalty proportional to the size of the shortfall.</p><p>The relative size of those weights is the entire service-level policy, expressed as one number. The real-time penalty weight is 5 to 10 times greater than the allocation weight. One unit of unmet real-time demand therefore costs what 5 to 10 GPU-timesteps of equal-priority batch work costs. The asymmetry is deliberate, and it means latency obligations are enforced <em>inside</em> the same optimization that places batch work, rather than by a separate autoscaler competing with the scheduler for the same GPUs.</p><p>It is also what makes the elastic treatment of real-time demand safe. The allocator can hand a GPU to batch work during a trough because underserving real-time demand later is priced so far above whatever that batch work earns — the penalty, not a static reservation, is what protects availability.</p><p>The time weight decays across the horizon for a reason that only makes sense in an online system: by the next scheduling run, new jobs will have arrived. Capacity used now is worth more than capacity promised later.</p><h3>The allocator that already knows the constraints</h3><p>The formal model defines what a legal, well-scored allocation looks like. Answering an incoming request is a separate job, and it belongs to a separate component. This is NP-hard combinatorial allocation, and the scheduler is re-invoked every time a job arrives, so the decision has to come back in the gap between two API requests. That latency budget is the fixed constraint the architecture is designed around, which is why a heuristic sits on the hot path and the formal model sits behind it as the specification the heuristic is built to satisfy.</p><p>That heuristic is not a generic greedy allocator. Its rules <em>are</em> the formal model’s structural constraints, which means every grid it produces is a legal allocation by construction. Not usually valid. Valid by design.</p><p>That design, applied across the whole horizon rather than one arrival at a time, is what produces the utilization gain. The allocator sees every queued job before it places any of them, it can hold the free pool in shapes the remaining work can actually occupy, a batch job needing a contiguous block of a given size still has room when its turn comes. Priority decides who gets first claim on that room. FIFO has neither view: it commits capacity to whichever job asked first, and a job that arrives later and needs a specific shape may find nothing left that fits, so it goes unscheduled and the GPU-hours it would have consumed go unclaimed.</p><p>It runs in 1 to 2 milliseconds on the five contended scenarios, and 15 milliseconds at 64 GPUs and 30 jobs — fast enough to run on every incoming request.</p><p>The system exposes two modes. Fast mode runs the allocator alone and returns its grid; this is the hot path. Full mode uses that grid as a starting point for the formal model, which attempts to improve on it — suited to periodic review rather than per-request decisions.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*z3GonTy8vKmLyyyk_Z9bbw.png" /></figure><p>Utilization improved in every scenario but one, where it tied exactly. Value improved in all seven.</p><p>The scale test matters because it holds at size: 64 GPUs, 30 jobs, 15 milliseconds, 15.9% more value.</p><p>The uniform-priority test matters because it addresses the obvious skeptical reading. Override every job to identical priority, so that no priority signal distinguishes any of them, and the allocator still moves utilization from 76.8% to 87.5% and value up 23.1%. The gain is not purely an artifact of ordering by priority. Planning placements across the horizon contributes on its own.</p><h3>None of it works if the demand numbers are wrong</h3><p>Everything above assumes the scheduler knows how many GPU-hours each job needs and how much real-time traffic is coming. Both are predictions, not inputs, and a scheduler is only as good as they are.</p><p>A single generic estimator does not work, because the four workload types have qualitatively different cost drivers. This is where the specialization argument from the previous piece reconnects: the same logic that makes a task-specific model outperform a generalist applies to the estimators feeding the scheduler.</p><p><strong>Training is not one workload.</strong> It varies along two independent, freely combinable axes. Strategy determines how much of the model is updated (full fine-tuning against parameter-efficient methods like LoRA). Technique determines the optimization objective and the training loop (SFT, DPO, RLHF, RLVR, CPT). The differences are not marginal: LoRA cuts trainable parameters by up to 10,000× and GPU memory roughly 3× against full fine-tuning, on the same base model. DPO removes both the reward model and the sampling loop of RLHF. Estimating from model size alone averages across runs that differ by orders of magnitude, in exactly the two quantities the scheduler decides on, duration and GPU count. Our training forecaster conditions on 22 features, including a categorical variable distinguishing 10 concrete training variants.</p><p><strong>Quantization is a schedulable job, not a background chore.</strong> Quantizing a single large model can consume hours of GPU time on hardware that other work is waiting for. It gets its own forecast, built from calibration tiers by parameter count, with distinct handling per algorithm (bitsandbytes, AWQ, GPTQ) and a safety margin before rounding up to whole GPU-hours. Prior work in this area places quantization outside scheduling scope entirely.</p><p><strong>Real-time inference is not estimated per job at all.</strong> It is forecast as a continuously recalibrated weekly demand profile, rebuilt from hourly traffic history and mapped to GPU counts under the same swap cost the formal model enforces. Forecast and optimizer therefore agree on what churn costs, rather than disagreeing and fighting each other. This forecast is what replaces peak reservation. A per-timestep demand curve is the only thing that lets the scheduler release GPUs during a trough with any confidence that they can be reclaimed before the next peak.</p><p>This closes back to the ordering argument. Better demand estimates are what make priority-aware placement possible in the first place, you cannot sequence jobs well without knowing what they will consume.</p><h3>Optimize the day, commit the hour</h3><p>The obvious objection to all of this is that forecasts are wrong. What happens then?</p><p>The failure mode to avoid has a name worth borrowing: the end-of-world effect. An optimizer that cannot see past the end of its horizon makes present decisions that wreck the timesteps immediately outside it, because as far as the model is concerned, nothing exists after the horizon ends.</p><p>The architecture answers both problems at once. The scheduler optimizes a 24-hour horizon, but commits only the current timestep, and re-runs every 30 to 60 minutes. Run at 9am, and the 9am allocation is real; the plan for 10am through 5pm exists only so that the 9am decision is made by a model that knows a future exists. The real 10am allocation comes from the 10am run, against fresh data.</p><p>The consequence is that forecast error is absorbed by re-optimization instead of compounding. Each run inherits what is actually running and pins it in place, so successive plans update rather than thrash.</p><p>There is a secondary payoff. The horizon plan is itself a forecasting product: it surfaces real-time coverage risk and predictable idle windows before they arrive, which is useful whether or not those specific allocations are ever committed.</p><p>This is also why the time-decay weight exists. By the next run, the workload mix will have changed.</p><h3>What this generalizes to</h3><p>Airlines did not solve utilization by computing an optimal schedule. They solved it by encoding operational discipline into the order things happen (turnaround sequence, maintenance windows, crew rostering) and letting that discipline compound.</p><p>The same thing happened here. Thirty-three points of utilization in the hardest-packed scenario, and 52% more priority-weighted output on average, on the same hardware, with the same workloads, in a couple of milliseconds, came from encoding what the cluster physically permits into the order decisions get made. Structure beat sophistication.</p><p>The previous piece argued that specialization and orchestration are two halves of one problem: specialization shrinks what each workload needs, and orchestration decides where the difference goes. Neither lever pays off alone. This is what the second half looks like when it is built.</p><p>The GPUs were already installed, already committed, already depreciating. The gain was in how we chose to spend them.</p><h3>Further Reading</h3><ul><li><a href="https://medium.com/@dharma-ai/gpu-management-why-idle-gpus-are-the-new-grounded-aircraft-fb9479fa3175">GPU Management: Why Idle GPUs Are the New Grounded Aircraft</a></li><li><a href="https://medium.com/@dharma-ai/newer-models-same-advantage-29455bd3b73b">Newer Models, Same Advantage</a></li><li><a href="https://medium.com/@dharma-ai/why-specialization-is-inevitable-8a7aee8324b0">Why Specialization Is Inevitable</a></li><li><a href="https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a></li><li><a href="https://medium.com/@dharma-ai/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c">Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track</a></li><li><a href="https://medium.com/@dharma-ai/direct-preference-optimization-beyond-chatbots-dc14de1010fa">Direct Preference Optimization Beyond Chatbots</a></li></ul><p><em>Follow </em><a href="https://medium.com/@dharma-ai"><em>Dharma AI on Medium</em></a><em> for analysis on AI strategy, specialization, and the architecture decisions that determine enterprise AI outcomes.</em></p><p><em>Explore</em> <a href="https://huggingface.co/Dharma-AI"><em>Dharma AI on Hugging Face</em></a> <em>to</em> <a href="https://huggingface.co/spaces/Dharma-AI/DharmaOCR-demo"><em>try our interactive demos</em></a><em>,</em> <a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE"><em>download our open-source models</em></a><em>, and discover how specialized AI systems outperform general-purpose models in real enterprise applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27e1405c7f97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPU Management: Why Idle GPUs Are the New Grounded Aircraft]]></title>
            <link>https://medium.com/@dharma-ai/gpu-management-why-idle-gpus-are-the-new-grounded-aircraft-fb9479fa3175?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb9479fa3175</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 15:09:24 GMT</pubDate>
            <atom:updated>2026-07-30T20:17:10.454Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Utilization, not intelligence, is the next real constraint in AI.</em></p><p>Aviation learned this the hard way. For most of the industry’s history, the number that best predicted whether an airline would survive was how much of the day each aircraft spent on the ground.</p><p>The reason is structural. An aircraft’s costs accrue by the calendar hour: financing, depreciation, hull insurance, scheduled maintenance, crew contracts. Its revenue accrues only by the flight hour. Every hour spent on the ground shrinks the output side of that equation while the cost side keeps running exactly as before. Utilization also sits downstream of almost everything else an airline does. Turnaround discipline, network design, maintenance planning, crew rostering, and spare parts availability all eventually show up in that one number, because a broken operation underneath it keeps planes on the ground no matter what else goes right.</p><p>A bigger fleet still helps. More aircraft means more available capacity, plainly and simply. But two airlines flying comparable fleets on comparable routes can end up with very different economics, and most of that gap traces back to one measurement rather than fleet size.</p><p>Enterprise AI is running into the same structure, on a different piece of hardware. A GPU accrues cost by the calendar hour too, through financing, depreciation, power, and cooling, whether or not it’s doing anything useful in a given moment. Its output only accrues by the compute hour. More GPUs helps in roughly the way a bigger fleet helps an airline: real capacity, a genuine advantage, and still no guarantee of the result that actually decides who wins. Two companies with comparable GPU budgets increasingly diverge based on how much of that hardware is doing something useful at any given moment, not on how much of it either one owns. That same number, like an airline’s utilization rate, sits downstream of nearly every other infrastructure decision a company makes. Intelligence has carried the industry this far. Utilization is where the next real constraint is forming.</p><h3>The Bottleneck Moved From Models to Compute</h3><p>The scarcity didn’t disappear as AI scaled. It moved up the chain, landing on a different resource entirely.</p><p>The first wave of enterprise AI was won on model quality. Bigger models, trained on more compute, evaluated against tougher benchmarks: parameter count and leaderboard position dominated the conversation, and the race produced models genuinely good enough to run real enterprise workloads. That capability arrives bundled with a dependency, though. Production AI runs on specialized hardware, and today that hardware is almost entirely GPUs.</p><p>GPUs are expensive, supply constrained, and in demand far beyond what’s available, and this holds even at the very top of the market. In 2020, Microsoft built OpenAI a dedicated supercomputer: over 10,000 GPUs and 285,000 CPU cores, reported at the time as one of the five largest systems in the world, assembled to train what became GPT-3. At the time, it looked like an almost unimaginable concentration of hardware, the kind of number that made compute look like a solved problem for whoever could get access to it. Six years later, that number reads more like a starting point than a ceiling. By 2026, even the best capitalized labs on the planet were treating compute access as a live strategic constraint rather than a settled one. Anthropic alone was running simultaneous multi-gigawatt commitments across four separate hardware platforms, Amazon, Google, Microsoft, and AMD, layered within months of one another, while Meta signed a comparable multi-gigawatt deal of its own. Spreading commitments across four vendors at once is what compute scarcity looks like when a buyer has effectively unlimited capital and still can’t get enough from any single source.</p><p>Six years apart, both events marked the frontier of what a lab needed just to stay competitive. What changed in between has less to do with AI getting more capable, and everything to do with capability no longer being the binding constraint.</p><p>The same pattern shows up downstream of the labs, in a different form. Enterprises consuming these models through an API run into a pricing problem more than a hardware one. Cost scales linearly with tokens used, and that single fact separates the economics of a proof of concept from the economics of production almost completely. A PoC processing a few thousand requests a month looks affordable. The same workload at production volume can turn into a cost line that never quite clears. The alternative gaining ground is straightforward enough: enterprises acquiring their own GPUs and running models locally, trading a variable, linearly scaling cost for a fixed capital one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaEMZn9H01R9jEO-5O59oQ.png" /><figcaption><em>API cost rises with usage, while owned infrastructure stays close to fixed. Past the breakeven point, the trade reverses.</em></figcaption></figure><p>That shift turns the GPU into infrastructure rather than a line item, sized for growth, sized for demand peaks, and therefore sized above what any given week actually needs. Which means the purchase doesn’t close the problem. It opens a new one. The day the cluster comes online, the question stops being <em>can we get accelerators</em> and becomes <em>can we keep them busy</em>, and only the first question had a procurement team assigned to it. Signing for the hardware is the part with a deadline and an owner. Keeping it off the ground is the part that quietly decides whether the deal was worth signing.</p><p>These deals describe capacity commitments, not efficiency. How well that capacity gets used is a separate question, owned by different people, measured far less rigorously, and considerably further from being solved.</p><h3>Why Busy Clusters Still Waste Capacity</h3><p>A cluster full of busy GPUs can still be wasting most of its potential, and the reason is almost always the same one. GPUs run continuously, day and night, while the demand placed on them does not. Infrastructure has to be sized for the peak, the moment training runs, batch jobs, and real time traffic all land at once, which leaves a meaningful share of capacity provisioned and unused outside that peak. Better forecasting could solve that on its own if every GPU could absorb every kind of work equally well. Few can, and that turns out to be the harder half of the problem.</p><p>The mismatch begins one layer deeper.</p><p>In the first generation of enterprise AI, a GPU’s job was largely singular: run inference. Today the same hardware supports training, fine-tuning, quantization, real-time inference, batch inference, embedding generation, and model evaluation, often for the same organization, sometimes for the same model, on the same cluster. Each of these workloads wants something different from the hardware, and the differences run deep. Real-time inference needs low latency above nearly everything else, because a slow response counts as a failed one. Batch work cares about throughput and tolerates delay, sometimes for hours. Training can occupy a GPU continuously for a stretch measured in hours or days. Quantization needs a large amount of capacity, but only briefly. A scheduler tuned for one of these will misallocate the other three almost by default. The failure doesn’t always show up on a utilization dashboard either. A cluster can report high average occupancy while several queued jobs wait for a GPU shape that happens to be busy running something else entirely.</p><p>The exact workload mix varies by organization. The shape of the problem does not. This is also where the aircraft analogy runs into its limit, and the limit teaches something rather than just qualifying the comparison. An idle aircraft can usually be redeployed to any route in the fleet: a 737 sitting in Chicago can fly to Denver instead of Dallas without much penalty. An idle GPU can only absorb a workload whose memory, latency, and duration profile it can actually serve. That difference makes orchestration harder than fleet scheduling, and it’s why the question stops being whether GPUs are occupied and turns into which workload should run on which GPU, at what time, with what priority. Buying another rack of GPUs adds capacity and cost, not a fix for the mismatch, and that new capacity can sit in the wrong shape at the wrong moment just as easily as the capacity already installed.</p><h3>Intelligence Moves Into the Infrastructure</h3><p>Maximizing GPU ROI takes more than a one-time provisioning decision. It calls for continuous, active management of the infrastructure itself, running every hour rather than only at procurement time. What’s emerging in response is a distinct discipline, GPU Management, an orchestration layer sitting between workloads, models, and hardware. Its job is to decide, continuously, which workload runs, when it runs, how it runs, and on which specific GPU in the cluster. None of this is exotic in concept. It’s closer to what a good operations team already does by instinct, just formalized and running continuously instead of depending on someone noticing a problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLpREOF-84gRIDQfGkrN-w.png" /><figcaption><em>Intelligence doesn’t stop at the model boundary. The orchestration layer is making real-time allocation decisions the model itself has no visibility into.</em></figcaption></figure><p>Intelligence used to sit almost entirely in the model: bigger, better trained, more capable, and that was most of the game. Now it also has to sit in the infrastructure, in the layer deciding, moment to moment, which of several competing workloads gets the GPU that just freed up, and at what priority relative to everything else waiting in the queue. Keeping GPUs busy stops being the goal on its own, since busy is easy to fake by running low priority work that could have waited. Maximizing the return generated by each installed GPU becomes the actual target, and that turns out to be a far more continuous problem than the provisioning question that came before it.</p><p>Provisioning well doesn’t make this go away so much as change its shape. A provisioning decision gets made once, at purchase time. An allocation decision gets made constantly: every time a job finishes, every new request that arrives, every shift in priority between a customer facing service and an internal training run. That frequency explains why the decision has moved from something a person handles case by case into something that has to run automatically. No engineer is watching a dashboard at three in the morning to decide whether a finished training run should hand its GPU to a queued batch job or hold it for an incoming burst of customer traffic. Something else has to make that call, continuously, and make it correctly often enough that nobody needs to check.</p><p>The discipline is new enough that its tooling and conventions are still forming, and no single playbook has emerged yet for what a mature GPU Management practice looks like. What has settled, at least, is where the constraint moved.</p><h3>Specialization Frees Capacity; Orchestration Spends It</h3><p>Specialization and orchestration solve different halves of the same problem.</p><p>Specialized, smaller models can perform specific tasks at a fraction of the resource cost a large generalist model would need for the same job, without giving up the quality the task requires. That has a direct effect on utilization. Workloads that once required a single, large model, occupying a large share of a cluster’s capacity for the full duration of the job, can instead run on smaller, task-specific models occupying a fraction of that footprint. Capacity that used to be entirely spoken for is suddenly free.</p><p>How much capacity specialization frees varies by workload and model, but the freed capacity still has to go somewhere or it just sits there. A smaller specialized model only converts into GPU ROI if something is actively deciding what happens next with the space it frees up, reallocating it to another workload, another model, another queue waiting behind it. Left unmanaged, freed capacity becomes a different flavor of idle rather than a win, invisible in a different way than an obviously unused GPU, but no more productive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eY91Zi-Mxqtf9W9dC3Rb3A.png" /><figcaption><em>Specialization without orchestration frees capacity nobody reclaims. Orchestration without specialization has less capacity worth reclaiming. Neither lever does the whole job alone.</em></figcaption></figure><p>Specialization without orchestration frees capacity that nobody reclaims. Orchestration without specialization has less capacity worth reclaiming in the first place, because the models are still large and the footprint they leave behind is small. Neither lever does the whole job alone; each one raises the ceiling on what the other lever can achieve. Neither is optional if the goal is to actually close the gap between installed capacity and useful output, rather than shifting where the waste happens to sit.</p><p>This is why model architecture and GPU management are two ways to address the same problem, approached from two different directions that end up leaning on each other. One shrinks what each workload needs. The other decides, continuously, where the difference goes.</p><p>A bigger fleet has always been a real advantage, and nothing here argues otherwise. Among airlines with comparable fleets, sometimes even a smaller one facing a larger rival, the winner was usually whichever one flew what it had more completely, carrying the weight of everything the airline did well underneath it. Enterprise AI is arriving at the same discipline from a different direction. GPUs are already installed, already depreciating, already committed. Specialized models and GPU Management are parallel solutions, or bivalent strategies. Specialization shrinks what each workload needs. Management maximizes the return on infrastructure. Enterprises that master both will set the pace of AI competition for the next decade.</p><h3>Further Reading</h3><ul><li><a href="https://medium.com/@dharma-ai/newer-models-same-advantage-29455bd3b73b">Newer Models, Same Advantage </a>— Despite newer architectures, DharmaOCR outperformed Mistral OCR4 and Unlimited-OCR on Brazilian Portuguese through domain specialization and targeted training. This article presents the evidence and the mechanism behind that advantage.</li><li><a href="https://medium.com/@dharma-ai/why-specialization-is-inevitable-8a7aee8324b0">Why Specialization Is Inevitable</a> — The structural and theoretical foundation for the specialization argument. Optimization theory, evolutionary biology, competitive markets, and machine learning all converge on the same prediction: under finite resources and selection pressure, fit beats breadth.</li><li><a href="https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a> — The empirical and strategic complement to this article. Where the No Free Lunch theorem establishes why specialization is structurally predicted, this piece examines the evidence that it outperforms in practice — and why it remains underweighted in most AI procurement decisions.</li><li><a href="https://medium.com/@dharma-ai/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c">Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track</a> — A documented failure mode that emerges when language models operate outside the boundaries of their effective domain.</li><li><a href="https://medium.com/@dharma-ai/direct-preference-optimization-beyond-chatbots-dc14de1010fa">Direct Preference Optimization Beyond Chatbots</a> — How preference optimization techniques extend into specialized domains beyond conversational AI — a concrete instantiation of the domain focus strategy this article argues is structurally predicted.</li></ul><p><em>Follow </em><a href="https://medium.com/@dharma-ai"><em>Dharma AI on Medium</em></a><em> for analysis on AI strategy, specialization, and the architecture decisions that determine enterprise AI outcomes.</em></p><p><em>Explore</em> <a href="https://huggingface.co/Dharma-AI"><em>Dharma AI on Hugging Face</em></a> <em>to</em> <a href="https://huggingface.co/spaces/Dharma-AI/DharmaOCR-demo"><em>try our interactive demos</em></a><em>,</em> <a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE"><em>download our open-source models</em></a><em>, and discover how specialized AI systems outperform general-purpose models in real enterprise applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb9479fa3175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Newer Models, Same Advantage]]></title>
            <link>https://medium.com/@dharma-ai/newer-models-same-advantage-29455bd3b73b?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/29455bd3b73b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 11:53:27 GMT</pubDate>
            <atom:updated>2026-07-16T11:53:27.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Despite newer architectures, DharmaOCR outperformed Mistral OCR4 and Unlimited-OCR on Brazilian Portuguese through domain specialization and targeted training. This article presents the evidence and the mechanism behind that advantage.</h3><p>Three months ago, we published a <a href="https://arxiv.org/abs/2604.14314">paper on DharmaOCR</a> and <a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE">open-sourced one of the models</a>. The objective was specific: optical character recognition engineered for Brazilian Portuguese.</p><p>The training pipeline was built in two stages. The first was a supervised fine-tuning step, drawing on a broad collection of Portuguese-language files from different sources, formats, and levels of complexity. This stage aligned the model’s weights to the specific vocabulary, syntax, and document structures of Brazilian Portuguese — concentrating representational capacity on the target language rather than distributing it across a broader multilingual space. The second stage applied Direct Preference Optimization: rather than training only on correct transcriptions, the model learned from comparative preference data between competing outputs, teaching it to consistently select the better extraction at inference time. This stage addressed a different problem: not accuracy, but stability. By suppressing the failure modes that cause generative models to produce repetitive or incoherent output, DPO reduced inference time and cost, and materially improved the reliability of what the model delivered in production.</p><p>The combined result was a model that achieved the highest extraction quality score with the lowest degeneration rate on a Portuguese-focused benchmark. Both stages were necessary. The fine-tuning stage built domain competency; the DPO stage ensured that competency held under the conditions where models tend to fail.</p><p>OCR models have been moving quickly. But the gaps that originally motivated DharmaOCR’s design (in extraction quality on complex documents and in model stability under production conditions) have not closed. They have, if anything, become more instructive as the field has changed.</p><p>The proliferation of multimodal generative models made language model-based OCR widely accessible, and the wave of fine-tuned OCR variants that followed reflects how fast that adoption has moved. That proliferation has not, however, changed the fundamental character of the technology. Every OCR system built on a generative model is probabilistic. Transcription errors are an inherent variable of this probabilistic technology. What differentiates models is how many errors they make and of what kind. That is determined by two things: the structure of the model (its architecture and parameter count) and how those parameters were trained for the task.</p><p>Architecture and parameter count establish the ceiling on what a model can learn. Training determines how that capacity is allocated.</p><p>This distinction is where specialization becomes a structural question rather than a design preference. When a model is trained on a restricted domain — a single language, a bounded document type, a specific task — All of its parameters are dedicated to that specific task. When a model is trained to cover a broader range of domains — a multilingual model handling N languages, for instance — those same parameters must be distributed across all of them. The distribution is not linear: the neuron superposition principle means individual parameters can encode multiple features simultaneously. But the division is real, and its consequences are real. A model covering more ground commits less to any given part of it.</p><p>DharmaOCR was trained to accept that constraint in reverse. The model is not designed to be the best option for other languages, and was never intended to be. In exchange, every parameter available to the network could be oriented toward the specific vocabulary, morphology, and orthographic patterns of Brazilian Portuguese — the most directed possible use of the model’s resources for that domain.</p><p>That concentration is the structural basis of an inherent advantage over multilingual and broader-domain models. The advantage does not depend on having a larger architecture or a more sophisticated training procedure than competitors use — new architectures and new training techniques improve what any model can do. It depends on where those resources are directed: at one domain rather than spread across many.</p><p>Three months later, newer models have arrived. Whether the case for specialization holds when those models are newer and more capable is a different question.</p><p>Three months after the DharmaOCR paper appeared, two new OCR models attracted significant attention from the research community: Mistral OCR4 and Unlimited-OCR. Both represent genuine technical advances — new training techniques, new datasets, and strong results across multiple languages on a range of benchmark evaluations. They are the kind of models that raise the competitive standard for what OCR systems are expected to deliver.</p><p>When we ran both against the DharmaOCR benchmark — an evaluation designed exclusively around Portuguese — the results were conclusive.</p><p>DharmaOCR scored 0.925. Mistral OCR4 scored 0.798. Unlimited-OCR scored 0.7587.</p><p>The difference is significant. Mistral OCR4 falls approximately 13 points below DharmaOCR; Unlimited-OCR falls more than 16 points below. Both were released after our model, both backed by substantial research resources. On a task where DharmaOCR’s fundamental design decision was to concentrate entirely on Portuguese, the specialization advantage is measurable and significant.</p><p>The benchmark is the central finding. What follows illustrates why the gap takes the specific shape it does.</p><p>Processing non-trivial Portuguese documents reveals precisely where multilingual models tend to break. ENEM essays (Brazil’s national high school examination) combine handwritten text with vocabulary, proper nouns, and cultural references that are specific to Brazilian Portuguese. They are exactly the kind of documents where language-specific training produces a return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/0*okzbMfBGCefseTZR.png" /></figure><p>Figure 1: ENEM essay manuscript used in benchmark evaluation with outputs of the each model. Misreads marked in red.</p><p>Mistral OCR4, evaluated on documents of this kind, transcribed the name Chico Buarque (one of Brazil’s most widely recognized musicians and poets) as “Chico Barque.” Unlimited-OCR rendered the same name as “chico bique.” Confronted with the phrase “O Brasil não exclui, assimila” (“Brazil does not exclude, it assimilates”, a Chico Buarque quotation embedded in the same document) Unlimited-OCR returned: “a dose de chico bique, ‘o Brasil no exclu, eliminila.’</p><p>These are not random errors. A model with insufficient exposure to Brazilian Portuguese does not fail arbitrarily — it fails at precisely the vocabulary and proper nouns that distinguish Brazilian Portuguese from the broader multilingual corpus. Chico Buarque is not an obscure reference; the name is nationally recognized. Its systematic corruption across outputs is not an edge case. It is a diagnostic: evidence of where the model’s training did not go.</p><p>DharmaOCR, evaluated on the same documents, handles these cases correctly. The reason is direct: the model’s training was concentrated on this linguistic space, orienting its resources toward the vocabulary and proper noun distributions that characterize Brazilian Portuguese rather than spreading them across many languages at once.</p><p>The examples illustrate the benchmark rather than replace it. The benchmark establishes the magnitude of the gap; the examples show why it is concentrated in language-specific recognition rather than in general capability.</p><p>Extraction accuracy, however, is only one dimension of production performance. Stability under visual difficulty is another — and operationally, it is the more consequential one to fail on.</p><p>When a generative model encounters a document it cannot clearly resolve — small fonts, degraded scan quality, dense handwriting — it faces uncertainty in its input signal. Models trained primarily on next-token prediction objectives face a specific vulnerability here: when the visual signal becomes ambiguous, the model can continue generating from prior learned patterns rather than from the source document. The result is text degeneration — output that is repetitive, incoherent, and semantically disconnected from the page.</p><p>Presented with a document with small fonts, Mistral OCR4 produces output with no connection to what is written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ie4_KHyqW-w0gH7D.png" /></figure><p>Figure 2: small-font document</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MM2EKe0i0uzhdPNt.png" /></figure><p>Figure 3: DharmaOCR output and Mistral OCR4 degenerated output</p><p>This is not a low-quality transcription of the source. It is a failure of an entirely different category.</p><p>The operational consequence is distinct from that of a transcription error. An incorrect transcription is wrong in a recoverable way — it stands in a relationship to the source document, and the error can in principle be identified and corrected. Degenerated output has no such relationship. It cannot be corrected because there is nothing to correct toward. For downstream processes that depend on structured OCR output — document classification, information extraction, compliance workflows — degenerated output is not inaccurate data. It is structurally unusable data. The efficiency that automation was meant to deliver is negated at precisely the point where output stops being information.</p><p>Mistral OCR4 and Unlimited-OCR are good models with significant technical advances behind them. The degeneration behavior described here does not define them; it identifies a specific failure condition that their current training has not addressed for this domain. The question is what a training pipeline designed to address it looks like.</p><p>In DharmaOCR, the answer is the DPO stage.</p><p>Supervised fine-tuning concentrates the model’s resources on the target domain — the stage that builds the linguistic alignment described above. But SFT trains on individual token predictions: the model learns to produce the correct next token given the context preceding it. Under visual complexity, this creates the condition that produces degeneration. If an early token in the output diverges from the source document, each subsequent prediction is conditioned on that divergent state, and the output continues to drift. Repetition loops and incoherent sequences are an inherent characteristic in this context — they are the predictable result of an objective optimized step by step without accounting for the coherence of the full extraction.</p><p>DPO trains against a different signal. Where SFT trains token by token, DPO trains the model against the quality of complete outputs — teaching it to discriminate between competing responses based on the coherence of the full extraction rather than the accuracy of individual predictions. The effect is stabilizing: on documents where visual complexity would otherwise trigger drift, the model is less likely to commit to a divergent path, because its training penalized outputs that lost coherence at the extraction level.</p><p>The result is what the original benchmark demonstrated: lower degeneration rates alongside higher extraction accuracy, on the same documents where models without this training stage lose coherence.</p><p>The benchmark establishes what is true today. It is less precise about what will be true in two years.</p><p>It is possible — and likely — that newer models will eventually outperform the current DharmaOCR even in Brazilian Portuguese. Architectures will improve. Training techniques will advance. Datasets will expand. The field moves toward higher capability at every level, and there is no reason to expect that trajectory to stop. This is expected, and it is welcome.</p><p>What changes with each architectural generation is the ceiling on absolute performance. What does not change is the structural logic that determines which systems come closest to their ceiling in a given domain.</p><p>Available resources — compute, parameters, training data — are finite. They must be directed somewhere. A system that directs them at a single domain will extract more from them in that domain than a system distributing the same resources across many. This relationship holds regardless of how capable the generalist model has become. The gap between specialist and generalist may evolve as architectures improve. The structural dynamic does not reverse. We explored this principle in more depth in an earlier piece on why specialization continues to produce an advantage as AI systems advance (<a href="https://medium.com/@dharma-ai/why-specialization-is-inevitable-8a7aee8324b0">Why Specialization Is Inevitable</a>).</p><p>This is what shapes how Dharma approaches what comes next. The objective is not to defend the current model’s benchmark position. It is to remain at the frontier of emerging techniques — new architectures, new training methods, new approaches to alignment and evaluation — and adapt them toward the same end: a specialized system for Brazilian Portuguese OCR that makes the best possible use of available resources, at the lowest possible cost and the shortest possible inference time.</p><p>Better tools do not work against specialization. They expand what it can achieve.</p><p>Three months ago, we showed that concentrating a model’s training on a specific domain produces a measurable advantage over generalist systems, including ones that are newer and better-resourced. That advantage held. The same principle will determine how DharmaOCR continues to evolve — not by staying fixed, but by applying whatever progress the field makes to a domain that remains fixed.</p><h4>Source</h4><ul><li>Cardoso, Gabriel Pimenta de Freitas, et al. “DharmaOCR: Specialized Small Language Models for Structured OCR that outperform Open-Source and Commercial Baselines.” <a href="https://arxiv.org/abs/2604.14314">arXiv preprint arXiv:2604.14314</a> (2026).</li></ul><h4><strong>Further Reading</strong></h4><ul><li><a href="https://medium.com/@dharma-ai/why-specialization-is-inevitable-8a7aee8324b0">Why Specialization Is Inevitable</a> — The structural and theoretical foundation for the specialization argument. Optimization theory, evolutionary biology, competitive markets, and machine learning all converge on the same prediction: under finite resources and selection pressure, fit beats breadth.</li><li><a href="https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a> — The empirical and strategic complement to this article. Where the No Free Lunch theorem establishes why specialization is structurally predicted, this piece examines the evidence that it outperforms in practice — and why it remains underweighted in most AI procurement decisions.</li><li><a href="https://medium.com/@dharma-ai/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c">Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track</a> — A documented failure mode that emerges when language models operate outside the boundaries of their effective domain.</li><li><a href="https://medium.com/@dharma-ai/direct-preference-optimization-beyond-chatbots-dc14de1010fa">Direct Preference Optimization Beyond Chatbots</a> — How preference optimization techniques extend into specialized domains beyond conversational AI — a concrete instantiation of the domain focus strategy this article argues is structurally predicted.</li></ul><p><em>Follow </em><a href="https://medium.com/@dharma-ai"><em>Dharma AI on Medium</em></a><em> for analysis on AI strategy, specialization, and the architecture decisions that determine enterprise AI outcomes.</em></p><p><em>Explore</em> <a href="https://huggingface.co/Dharma-AI"><em>Dharma AI on Hugging Face</em></a> <em>to</em> <a href="https://huggingface.co/spaces/Dharma-AI/DharmaOCR-demo"><em>try our interactive demos</em></a><em>,</em> <a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE"><em>download our open-source models</em></a><em>, and discover how specialized AI systems outperform general-purpose models in real enterprise applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29455bd3b73b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Specialization Is Inevitable]]></title>
            <link>https://medium.com/@dharma-ai/why-specialization-is-inevitable-8a7aee8324b0?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7aee8324b0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 14:38:47 GMT</pubDate>
            <atom:updated>2026-06-30T14:38:47.932Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>What optimization theory, evolutionary biology, competitive markets, and machine learning all predict — and why the answer is the same</em></h4><p>Those who follow Dharma AI already know that we view specialization as one of the defining principles of effective AI systems, shaping everything from cost and performance to reliability and sovereignty. Few papers have articulated that case as rigorously as the 2026 work by Goldfeder, Wyder, LeCun, and Shwartz-Ziv.</p><p>In this article, we explore and interpret ideas from <em>AI Must Embrace Specialization via Superhuman Adaptable Intelligence</em> (Goldfeder, Wyder, LeCun, &amp; Shwartz-Ziv, 2026). The paper’s convergence case — spanning optimization theory, biology, organizational economics, and machine learning — provides both the evidential structure and the intellectual foundation for the discussion that follows. The framing, organization, and editorial synthesis presented here are Dharma’s.</p><p>The conventional expectation is reasonable: as AI systems grow more capable, they should also grow more general. Greater capability and broader applicability seem like natural companions — more resources, better methods, and expanded training should produce systems that approach more tasks with increasing confidence.</p><p>The pattern that actually appears is different. The systems that achieve the most significant results in any given domain tend to be the ones most narrowly focused on it. The breakthrough in protein structure prediction came from a system engineered for a single scientific task. The historical milestones of AI, examined closely, reflect intense domain targeting rather than expanding generality.</p><p>This pattern recurs. It recurs across domains, across decades, across architectural choices that have almost nothing in common. A pattern this consistent suggests a common cause — one that does not originate inside AI research at all.</p><h3>An Algorithm Wins by Fitting Its Target</h3><p>In 1997, Wolpert and Macready proved something that rarely surfaces in discussions of AI architecture: no single, general-purpose optimization algorithm outperforms all others across all possible problems (Wolpert &amp; Macready, 1997). The proof is mathematical, not philosophical. Averaged across every conceivable problem a learner might face, every algorithm performs equally well — and equally poorly. An algorithm that gains on one distribution of problems necessarily concedes on others. The performance is redistributed, not multiplied.</p><p>The practical implication is direct: “an algorithm wins by being a good fit for the target problem” (Goldfeder et al., 2026). The theorem does not say generality is impossible — it says generality is not a performance advantage. The consistent structural path to outperformance is concentration: trading breadth for fit.</p><p>This becomes sharper when finite resources enter the picture. Any real system operates under constraints — finite compute, finite data, finite development time. Given finite energy, an approach that directs available resources toward learning a finite set of tasks will outperform one that distributes those same resources across an unlimited range. The arithmetic is unforgiving: as the task set expands without bound, the resources available per task shrink toward zero. Universal coverage and meaningful performance are, under finite resources, in direct tension.</p><p>The conclusion the theorem points toward is not that generality is bad. It is narrower and more operational than that: as the paper states, “universal generality is a theoretical concept, but in practical terms it is a myth” (Goldfeder et al., 2026). What survives contact with real constraints is not the system that tries to do everything — it is the system that fits its target.</p><p>The mathematics establishes this as a prediction, not a preference. Whether that prediction holds in the world beyond optimization theory is a different question.</p><h3>What Biology and Markets Already Know</h3><p>Two other domains arrived at the same prediction before optimization theory gave it a name.</p><p>As the paper describes the biological case: every performance gain in one niche comes at a cost elsewhere. A generalist carries traits suited to many environments but optimal for none — competence spread too thin to dominate any particular condition. There are no performance gains without trade-offs; the resources invested in one capability are unavailable for another. Selection favors designs matched to local conditions over those optimized for uniform coverage across all possible environments. The organisms that survive to reproduce are not the most generally capable — they are the most specifically matched. The result, accumulated over evolutionary timescales, is not generalists dominating — it is specialists filling niches. As the paper states: “Specialization is not an accident of biology; it is a predictable consequence of limited resources, competing objectives, and environments that reward performance on a small subset of evolutionarily relevant challenges” (Goldfeder et al., 2026).</p><p>Competitive markets follow the same dynamic through different means. Organizations and strategies that fail to meet performance thresholds are eliminated — not through extinction, but through exit, defunding, and replacement by better-matched alternatives. Competition acts as a selection mechanism: it amplifies effective strategies and eliminates ineffective ones. The mechanism has nothing in common with biological selection — no inheritance, no mutation, no evolutionary timescale. The unit of selection is not the organism but the organization, the product, the strategy. Yet the structural pressure is the same: finite resources, performance requirements, and the systematic removal of entities too broadly distributed to excel where it counts. Concentrated capacity outcompetes distributed capacity when performance standards are clear and consistent.</p><p>Evolution and markets operate through entirely different mechanisms — different timescales, different units of selection, different inheritance mechanisms. Yet both produce the same outcome under resource pressure: fit over breadth. The theorem predicts this. Biology and markets arrive at it independently. When a third domain arrives at the same finding through different means entirely, the pattern ceases to look like a theorem and begins to look like something more general about how constrained systems behave.</p><h3>Machine Learning Keeps Rediscovering Specialization</h3><p>The same pattern has emerged inside machine learning — not derived from optimization theory, but arrived at through the accumulated experience of building systems and watching what improves them.</p><p>The clearest form is negative transfer: a measurable degradation that occurs when a system trained on multiple tasks suffers because those tasks compete rather than cooperate (Ruder, 2017). When tasks share structure, training together helps. But when tasks compete for representational capacity, or impose conflicting gradients during training, performance on individual tasks falls below what a dedicated system would achieve. The gain from breadth becomes a cost to depth. It is a documented consequence of dividing finite capacity across tasks that pull against each other. The specialist, facing no such competition, does not pay this cost.</p><p>The architecture of frontier models offers a different form of evidence. Mixture-of-experts systems achieve their breadth not through uniform generality across all parameters, but by routing each input to a specialized subset of the network — activating different experts for different tasks. The paper’s authors read this as a structural concession: a system designed to be general achieving its results by recovering specialization internally. This is an argued interpretation, not a demonstrated theorem — these architectures were designed for computational efficiency, and what they imply about generality’s limits is a reasonable inference rather than a stated intent. But it is a notable one: the most capable general-purpose systems reach their performance by doing internally what specialist systems do by design.</p><p>The clearest historical example follows the same logic. AlphaFold achieved a step change in protein structure prediction by targeting that specific task with task-specific architecture and training choices (Jumper et al., 2021). Its gains came from narrower focus, not broader coverage. The paper uses AlphaFold as an archetypal case — not as evidence that all specialized systems achieve equivalent gains, but as an unusually clear illustration of the mechanism. That mechanism has appeared repeatedly: the history of AI milestones, the paper notes, frequently reflects intense domain targeting rather than broad competence, even when the results look like demonstrations of general intelligence.</p><p>Three distinct places. Three different mechanisms. The same finding.</p><h3>What Scaling Doesn’t Change</h3><p>The picture would be incomplete without addressing one of AI research’s most cited observations. Sutton’s Bitter Lesson holds that methods relying on domain knowledge are consistently outperformed by methods that scale computation (Sutton, 2019). On its face, this appears to complicate the case for specialization: if scale and generality win, perhaps specialization is only a useful heuristic under resource constraints that will ease as compute becomes cheaper.</p><p>The objection rests on a conflation between two distinct concepts. Domain knowledge refers to hand-coded features, engineered priors, and rules designed to give a system insight into a particular area. The Bitter Lesson targets this — and it is correct to do so. Systems that encode explicit domain knowledge have been consistently outperformed as scale increases.</p><p>Domain specialization is different: the decision to <a href="https://medium.com/@dharma-ai/direct-preference-optimization-beyond-chatbots-dc14de1010fa">direct a system’s resources, architecture, and training toward a bounded set of tasks</a> rather than distributing them broadly. This is not the encoding of knowledge about a domain. It is a decision about scope.</p><p>The paper draws the distinction precisely:</p><p>“The diminishing usefulness of domain knowledge is distinct from the usefulness of domain specialization. As scaling progresses, we will need to know less about proteins to build a system that does protein folding; however, such a system still benefits from focusing specifically on proteins.” (Goldfeder et al., 2026)</p><p>Scaling changes what systems can learn from data. It does not change whether concentrating resources on a finite task set outperforms distributing them across an unlimited range. The Bitter Lesson and the specialization argument operate on different dimensions — one describes how knowledge should be acquired, the other describes what a system should be pointed at. Both can be true simultaneously. Scaling changes the mechanisms by which systems learn; it does not dissolve the constraint that makes <a href="https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65">fit more valuable than breadth</a>.</p><p>Across four analytical traditions, the same pattern emerged through different paths. This is not a coincidence that demands explanation. It is the evidence.</p><p>When finite resources meet selection pressure — in an optimization problem, an ecosystem, a market, or a training run — fit consistently beats breadth. The specific mechanisms differ. The timescales differ. The units of selection differ. But the structural dynamic is the same, and it produces the same result.</p><p>The theorem does not cause this pattern in biology. Biology does not cause it in markets. Neither causes it in machine learning. They all face the same underlying constraint: performance under scarcity requires concentration. What the theorem establishes mathematically, evolutionary history confirms empirically, competitive markets demonstrate institutionally, and machine learning rediscovers architecturally.</p><p>Specialization is not a preference. It is what emerges when finite resources meet the requirement to perform.</p><p>If you’re evaluating how domain focus affects AI performance in your organization — or building the case internally for a specialization strategy — we’d like to hear about your context. <a href="https://dharma-ai.com/">Get in touch with Dharma AI.</a></p><p><strong>Primary Source</strong></p><ul><li>Goldfeder, S., Wyder, M., LeCun, Y., &amp; Shwartz-Ziv, R. (2026). AI must embrace specialization via superhuman adaptable intelligence. arXiv:2602.23643.</li></ul><p><strong>Sources</strong></p><ul><li>Wolpert, D.H. &amp; Macready, W.G. (1997). No free lunch theorems for optimization. <em>IEEE Transactions on Evolutionary Computation</em>, 1(1), 67–82.</li><li>Forister, M.L., Novotny, V., Panorska, A.K., Baje, L., Basset, Y., Butterill, P.T., &amp; Dyer, L.A. (2012). Global distribution of diet breadth in insect herbivores. <em>Proceedings of the National Academy of Sciences</em>, 109(2), 418–423.</li><li>Futuyma, D.J. &amp; Moreno, G. (1988). The evolution of ecological specialization. <em>Annual Review of Ecology and Systematics</em>, 19, 207–233.</li><li>Hannan, M.T. &amp; Freeman, J. (1977). The population ecology of organizations. <em>American Journal of Sociology</em>, 82(5), 929–964.</li><li>Loasby, B.J. (1983). Knowledge, learning and the firm. As cited in Goldfeder et al. (2026).</li><li>Ruder, S. (2017). An overview of multi-task learning in deep neural networks. arXiv:1706.05098.</li><li>Fedus, W., Zoph, B., &amp; Shazeer, N. (2022). Switch transformers: Scaling to trillion parameter models with simple and efficient sparsity. <em>Journal of Machine Learning Research</em>, 23(120), 1–39.</li><li>Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., &amp; Hassabis, D. (2021). Highly accurate protein structure prediction with AlphaFold. <em>Nature</em>, 596, 583–589.</li><li>Silver, D., Hubert, T., Schrittwieser, J., Antonoglou, I., Lai, M., Guez, A., &amp; Hassabis, D. (2018). A general reinforcement learning algorithm that masters chess, shogi, and Go through self-play. <em>Science</em>, 362(6419), 1140–1144.</li><li>Sutton, R.S. (2019). The bitter lesson. Retrieved from <a href="http://www.incompleteideas.net/IncIdeas/BitterLesson.html">http://www.incompleteideas.net/IncIdeas/BitterLesson.html</a></li></ul><p><strong>Further Reading</strong></p><p><a href="https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a> — The empirical and strategic complement to this article. Where the No Free Lunch theorem establishes why specialization is structurally predicted, this piece examines the evidence that it outperforms in practice — and why it remains underweighted in most AI procurement decisions.</p><p><a href="https://medium.com/@dharma-ai/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c">Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track</a> — A documented failure mode that emerges when language models operate outside the boundaries of their effective domain.</p><p><a href="https://medium.com/@dharma-ai/direct-preference-optimization-beyond-chatbots-dc14de1010fa">Direct Preference Optimization Beyond Chatbots</a> — How preference optimization techniques extend into specialized domains beyond conversational AI — a concrete instantiation of the domain focus strategy this article argues is structurally predicted.</p><p><em>Follow </em><a href="https://medium.com/@dharma-ai"><em>Dharma AI on Medium</em></a><em> for analysis on AI strategy, specialization, and the architecture decisions that determine enterprise AI outcomes.</em></p><p><em>Explore</em> <a href="https://huggingface.co/Dharma-AI"><em>Dharma AI on Hugging Face</em></a> <em>to try our interactive demos, download our open-source models, and discover how specialized AI systems outperform general-purpose models in real enterprise applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7aee8324b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Direct Preference Optimization Beyond Chatbots]]></title>
            <link>https://medium.com/@dharma-ai/direct-preference-optimization-beyond-chatbots-dc14de1010fa?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc14de1010fa</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 12:59:32 GMT</pubDate>
            <atom:updated>2026-06-03T12:59:32.973Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Rejection Pairs From Your Model’s Own Failures</h4><p>In April, we released DharmaOCR, our specialized structured OCR model (<a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE">available on Hugging Face</a>) along with a <a href="https://arxiv.org/abs/2604.14314">paper </a>detailing the methodology behind it and a benchmark demonstrating its superior quality and cost efficiency.</p><p>The paper benchmarked leading vision-language model families — both open-source and commercial — on a structured document extraction task: OCR on Brazilian Portuguese text. Among the reported metrics was text degeneration rate: the frequency with which a model produces a repetition loop instead of a transcription.</p><p>Across the tested open-source families, vanilla degeneration rates ranged from below 1% to above 33%. Supervised fine-tuning reduced those rates for most models — but rarely to production-acceptable levels. The pattern points to a structural limitation: SFT optimizes for correct outputs, but does not explicitly penalize degeneration. There appears to be a ceiling on how much task-focused fine-tuning alone can reduce this failure mode (<a href="https://medium.com/@dharma-ai/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c">Text Degeneration Article</a>).</p><p>A second training stage — applied after supervised fine-tuning (SFT), on the same documents, using the same model — reduced text degeneration in every family tested. No exceptions. Average reduction: 59.4%. Best case: 87.6%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*9B8UHTnPA2K8ICB9h6APqg.jpeg" /><figcaption>Figure 1: DPO reduced degeneration relative to SFT in every family tested — average reduction of 59.4%, peak of 87.6% (Nanonets-OCR2–3B: 1.61% to 0.20%). The direction is invariant; only the magnitude varies.</figcaption></figure><p>That second stage was Direct Preference Optimization (DPO). Almost all published DPO applications target chat alignment — models trained on human judgments about helpfulness or harmlessness (example: Rafailov et al., 2023). OCR carries none of that subjectivity: the task is objective, and there is no conversational context. There is, however, a clear preference signal. A correct transcription is chosen; a degeneration loop is rejected. DharmaOCR used that binary to construct a DPO training set, testing the technique not for alignment, but as a direct mitigation tool for a specific failure mode.</p><p>The training signal came from the model itself — specifically from the outputs it produced when it failed. How a failure mode becomes a training signal is a structural question about the failure, not the model.</p><h3>The Loop Survives Fine-Tuning</h3><p>Why SFT has a ceiling on degeneration is still an open question — but the leading conjecture points to loss granularity. SFT trains token by token: each prediction is evaluated in isolation, and a repetition loop is never penalized as a completion-level failure. DPO inverts that logic. The training signal is the full output — chosen or rejected — which means a degenerated completion can be explicitly labeled as the wrong outcome, not just a sequence of locally probable tokens.</p><p>When a training objective maximizes the likelihood of observed sequences, it concentrates probability mass in the regions of distribution space those sequences occupy. A model that enters one of those high-probability attractor regions during inference assigns elevated probability to the same token at the next step — which increases the probability further, which sustains the loop until the sequence hits the maximum token limit. Text degeneration is the output of this geometry: a self-reinforcing repetition loop that an autoregressive model cannot exit without external intervention (Holtzman et al., 2020). It is not purely a decoding artifact. The attractor involves the training objective, the learned distribution, and how probability mass concentrates during inference — a systems-level failure rather than a failure localized to any single component.</p><p>The geometry of this failure is visible at the token level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*Z4fzpkERawYOVXbzDLM6ug.jpeg" /><figcaption>Figure 2: When a token dominates its own conditional distribution, every sampling step deepens the attractor. The decoder samples from this geometry; it does not determine it.</figcaption></figure><p>Inference-layer interventions — repetition penalties, temperature adjustments, early-abort logic — operate on the sampling step. They contain the symptom without touching the distribution that produces it. The attractor persists.</p><p>Supervised fine-tuning moves the distribution closer to the task domain. For a structured generation pipeline, this means training on domain-specific documents, in the target language, with the required output format. The model gains fluency with longer sequences, constrained syntax, domain vocabulary. What SFT does not do is attack degeneration directly. Its objective — maximizing the likelihood of observed sequences — has no term that penalizes repetition loops. The failure mode is simply outside the scope of what the training signal optimizes for.</p><p>One model family in the DharmaOCR benchmark showed an unexpected pattern: vanilla degeneration rate of 0.60%, rising to 3.23% after SFT, before a subsequent DPO stage brought it to 1.41%. It is a single data point — an exception, not a rule — and it would be overstating the evidence to treat it as proof of a mechanism. What it does illustrate is that SFT does not reliably reduce degeneration. Capability and degeneration resistance can move independently.</p><p>The distinction matters structurally. SFT and DPO are not interchangeable training stages performing the same operation at different intensities. SFT closes the distance between the model’s prior distribution and the task domain. What it does not do is target degeneration as an objective — its effect on the failure mode is incidental, and the benchmark results show it is not consistent. The attractor that produces degeneration is not a problem with the model’s proximity to the task — it is a problem with the shape of the distribution space the model now occupies.</p><p>Addressing that geometry requires a training signal built specifically to point the model away from its own failure modes. For a structured, non-conversational task with no human preference labels and no conventional “helpful versus harmful” distinction, constructing that signal is a design decision.</p><h3>The Design Decision: Degenerate Outputs as Rejection Pairs</h3><p>The DharmaOCR pipeline’s contribution to DPO methodology is specific: it used the SFT model’s own degenerate outputs as the rejected examples — not as noise to remove, but as the negative training signal the optimization needed.</p><p>DPO requires preference pairs: a chosen output and a rejected output for the same input, with a quality difference clear enough for the optimization to learn from. In chat alignment, human annotators produce those judgments — rating responses as more or less helpful, accurate, or safe. Structured generation tasks have no equivalent annotation source. An OCR pipeline either produces a correct transcription or it does not. Quality differences exist, but they are not produced by human preference rankings — they are produced by the task’s own criteria for correctness.</p><p>The DharmaOCR pipeline identified a preference signal that structured generation tasks already produce: the range of outputs the SFT model generates in inference. A model capable of performing a structured task is also capable of failing at it in characteristic ways. Those failures — outputs that enter the degeneration attractor — are not noise to filter. They are the most informative negative signal available.</p><p>The paper implemented this on 23,726 training documents, generating multiple candidate responses per document with the SFT model and scoring each with an automated LLM judge. The pipeline is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMG3cPw9pd5ZysekdDXcTQ.png" /><figcaption>Figure 3: The critical design decision is not in the pipeline’s structure — it is in what the pipeline preserved: outputs displaying text degeneration were deliberately labeled as rejected examples, not filtered out as low-quality noise.</figcaption></figure><p>The conventional response when degenerate outputs appear in training data is to remove them. They are low-quality signal; filtering produces a cleaner dataset. The DharmaOCR approach inverted this logic. Degenerate outputs were deliberately retained as the rejected examples in each (chosen, rejected) pair, because they represent exactly the failure mode the DPO stage was designed to suppress. Removing them would have discarded the clearest target available.</p><blockquote>The pipeline did not discard its failures. It trained on them.</blockquote><p>The paper describes this as “preference-guided implicit unlikelihood” — the model is trained not only toward better outputs but away from a specific class of failure. Where SFT maximizes the likelihood of high-quality outputs, the DPO stage simultaneously penalizes outputs displaying the degeneration attractor geometry. The direction of the optimization is explicit in a way SFT alone cannot achieve.</p><p>Degenerate outputs are particularly well-suited as rejection examples because they represent a consistent failure mode rather than varied low-quality outputs. A transcription that misses words is low quality, but its failure is case-specific. Repetition loops, by contrast, appeared persistently across documents and model families even after SFT — a pattern consistent with a failure mode that likelihood-based optimization does not reliably correct. DPO applies its loss differently: at the completion level, with explicit rejection signals. The post-hoc analysis cannot establish causality, but the evidence suggests that what SFT’s objective leaves unresolved, DPO’s may address.</p><p>This approach requires no specialized annotation infrastructure — only a model capable of producing both acceptable and identifiable-failure outputs, and a scoring model to label preference pairs. A rule-based mechanism could detect repetition loops mechanically — but it could not identify which outputs represented high-quality transcriptions worth preserving as chosen examples. The scoring model does both: it flags degeneration as the rejected output and validates clean extractions as the chosen one, keeping the model’s extraction capability intact while the DPO signal penalizes the failure mode. Whether the resulting training signal successfully moves the distribution in the intended direction — and whether it does so consistently across architectures — is the evidence question.</p><h3>Consistent Across Five Model Families</h3><p>The DPO stage reduced text degeneration in every model family tested — with reductions ranging from 37% to 88% and an average of 59.4% relative to SFT alone. The result held across architectures, parameter scales, and starting degeneration profiles that differed by more than one order of magnitude. One case in the dataset saw degeneration increase after the SFT stage before DPO corrected it. That case does not complicate the consistency. It confirms the mechanism more directly than any of the others.</p><p>Figure 1 shows the three-stage degeneration rate for each of the five model families tested: Vanilla, SFT, and SFT+DPO. In four of the five families, degeneration falls at each stage. The fifth family’s bars move differently — and that difference is the most analytically important data point in the study.</p><p>The Qwen2.5-VL-3B result, read carefully, is not a complication. It is a confirmation. The model’s vanilla degeneration rate was 0.60% — not because it was stable, but because it was too generic to produce long structured outputs at all. The model was not entering the degeneration attractor because it was not attempting the task seriously enough to find it.</p><p>SFT changed that. After domain adaptation, Qwen2.5-VL-3B became capable of the task — producing longer, more structured outputs with the domain vocabulary and format the pipeline required. That capability brought it into proximity with the degeneration attractor for the first time. Its degeneration rate rose to 3.23%.</p><blockquote>Treated as the same operation, the Qwen2.5-VL-3B result looks like an error. Treated as distinct operations — which is what the SFT + DPO pipeline formally does — the result is consistent with the hypothesis that SFT and DPO address different failure dimensions.</blockquote><p>This is the mechanism made empirically visible: SFT moved the model toward the task and toward the task’s failure geometry simultaneously. These are not necessarily the same operation. A training stage that increases task capability can increase failure-mode exposure as a side effect — particularly when the failure mode lives at the edge of the capability frontier. Treated as the same operation, the Qwen2.5-VL-3B result looks like an error. Treated as distinct operations — which is what the SFT + DPO pipeline formally does — the result is consistent with the hypothesis that SFT and DPO address different failure dimensions.</p><p>The DPO stage then brought the degeneration rate to 1.41%. It did not restore the vanilla baseline because it was not designed to: the model after SFT was more capable than it had been, and a return to 0.60% would have required undoing that capability. What the DPO stage did was address the failure geometry the SFT stage had introduced.</p><p>The remaining four model families add quantitative weight to the same conclusion. Figure 1 shows the SFT-to-SFT+DPO comparison for all five.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*9B8UHTnPA2K8ICB9h6APqg.jpeg" /><figcaption>Figure 1: DPO reduced degeneration relative to SFT in every family tested — average reduction of 59.4%, peak of 87.6% (Nanonets-OCR2–3B: 1.61% to 0.20%). The direction is invariant; only the magnitude varies.</figcaption></figure><p>No model family showed degeneration increasing after DPO. No family was immune to its effect. The consistency extends to gemma-3–4b-it, which entered the benchmark with the highest vanilla degeneration rate by an order of magnitude — 33.96%, compared to the next highest at 2.62% — and still reached a 75% reduction after the DPO stage. The reduction range — 37.3% to 87.6% — reflects differences in starting configuration and architecture, not inconsistency in the intervention’s direction.</p><p>This is not a proof of universal applicability. DPO may not transfer to every domain, failure mode, or model family. What the DharmaOCR benchmark provides is evidence across five OCR architectures that the core hypothesis holds: optimizing over complete preference pairs — rather than maximizing token-level likelihood — addresses a failure mode that SFT structurally cannot target. The result was consistent in direction across every model family tested. That consistency, within the scope of this benchmark, is what the evidence supports.</p><h3>The Pattern Beyond OCR</h3><p>The DharmaOCR approach was possible because this pipeline satisfied a set of structural conditions that allowed a DPO training stage to function as designed — conditions whose presence or absence determines whether the same methodology applies elsewhere (<a href="https://arxiv.org/abs/2604.14314">Dharma OCR Paper on ArXiv</a>). It was not possible because OCR is a unique domain.</p><p>The first condition is that the failure mode be identifiable as a distinct class of output, not just a point on a quality continuum. Text degeneration qualifies because a repetition loop is categorically different from a transcription that misses words or misreads a character. The output is not merely suboptimal — it is broken in a specific, behaviorally recognizable way. That categorical distinctness is what allowed the pipeline to construct preference pairs where the rejected examples represented a coherent failure geometry, not noise. A task whose failure modes blend into its range of acceptable variation lacks this property.</p><p>The second condition is that a scoring mechanism can reliably distinguish acceptable outputs from failure-mode outputs without requiring human annotation. In the DharmaOCR pipeline, an automated LLM judge scored candidate responses against four task-specific criteria. The scoring did not need to be perfect — it needed to be consistent enough to produce preference pairs with a meaningful quality gap between chosen and rejected. Pairs with ambiguous quality differences contribute noise to DPO training, not signal. The judge’s consistency was a design requirement, not an incidental feature.</p><p>The third condition is sufficient volume — enough inference outputs to generate a preference dataset with meaningful variance in quality. This is not an extraordinary requirement by fine-tuning standards, but it is a real one.</p><p>When all three conditions are present, the methodological move is structurally available. The design decision at the center of the DharmaOCR pipeline — treating the model’s own failure outputs as the rejected examples rather than filtering them — applies wherever a model’s failures are categorically identifiable, scoreable, and sufficiently numerous.</p><blockquote>What makes a failure mode usable as training signal is not the domain — it is whether the failures are consistent enough, identifiable enough, and numerous enough to constitute a legible signal.</blockquote><p>The practical implication for ML engineers building structured generation pipelines is direct. SFT is necessary — it closes the distance between a generalist model and a task-capable one. It is not sufficient for structured output reliability, because task capability and degeneration resistance are different properties of the distribution. A DPO stage after SFT is a one-time training investment. In the DharmaOCR results, the degeneration reduction did not come at the cost of extraction quality — the paper’s benchmark results show both moving together (<a href="https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65">Specialization Beats Scale article</a>).</p><p>What makes a failure mode usable as training signal is not the domain — it is whether the failures are consistent enough, identifiable enough, and numerous enough to constitute a legible signal. In the DharmaOCR pipeline, they were. Whether the same holds in another context is a structural question about the task’s failure mode, not a question about the model family or the domain.</p><p>The DharmaOCR result does not depend on the domain being special. It depends on the failures being useful.</p><p>Text degeneration qualifies as useful because it is categorically distinct from acceptable outputs, consistently produced across inference runs, and reliably scoreable without human annotation. Those three properties — not the OCR context, not the model family, not the language — determined whether the preference dataset was tractable. A failure mode that satisfies them is not noise to remove. It is the most direct evidence available of where the distribution should not go.</p><p>The DPO stage used that evidence. Degeneration fell in every model family tested — in models that entered the benchmark with vanilla rates below 1% and in models that entered with rates above 33%. The direction held.</p><p>The pipeline did not discard its failures. It trained on them.</p><h3>Sources</h3><ol><li>Cardoso, Gabriel Pimenta de Freitas, et al. “DharmaOCR: Specialized Small Language Models for Structured OCR that outperform Open-Source and Commercial Baselines.” <a href="https://arxiv.org/abs/2604.14314">arXiv preprint arXiv:2604.14314</a> (2026).</li><li>Dharma AI. “<a href="https://medium.com/@dharma-ai/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c">Text Degeneration: The Production Failure Mode That LLM Benchmarks Ignore</a>.” Medium (2026).</li><li>Dharma AI. “<a href="https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65">Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook</a>.” Medium (2026).</li><li>Holtzman, Ari, et al. “The Curious Case of Neural Text Degeneration.” <a href="https://arxiv.org/abs/1904.09751">arXiv preprint arXiv:1904.09751</a> (2020).</li><li>Rafailov, Rafael, et al. “Direct Preference Optimization: Your Language Model is Secretly a Reward Model.” <a href="https://arxiv.org/abs/2305.18290">arXiv preprint arXiv:2305.18290</a> (2023).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc14de1010fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Specialization Beats Scale: A Strategic Variable Most AI Procurement Decisions Overlook]]></title>
            <link>https://medium.com/@dharma-ai/specialization-beats-scale-a-strategic-variable-most-ai-procurement-decisions-overlook-37ead4692a65?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ead4692a65</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Thu, 21 May 2026 13:45:51 GMT</pubDate>
            <atom:updated>2026-05-21T13:45:51.415Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When a model’s training history is moved close enough to its deployment task, parameter count stops being the decisive variable. A 3-billion-parameter specialized model outperformed every commercial frontier API tested in a well-measured enterprise domain — at roughly fifty times lower cost.</em></p><p>In April, we released DharmaOCR — a pair of specialized small language models for structured OCR, alongside a benchmark and the accompanying<a href="https://arxiv.org/abs/2604.14314"> paper</a>. The models and the benchmark are available on<a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE"> Hugging Face</a>. Together they form part of a broader effort at Dharma to study how specialization, alignment, and inference economics interact in production AI systems.</p><p>This article isolates one strategic implication from those findings: the relationship between specialization, distributional alignment, and parameter scale. What follows develops it within the boundaries the paper supports.</p><p>For the past three years, enterprise AI strategy has largely operated on a stable assumption: the safest choice was usually the largest frontier model available. Smaller models were considered primarily where the workload could tolerate some reduction in quality in exchange for lower cost. The logic behind that assumption was straightforward. Capability appeared to scale with parameter count, frontier providers consistently led the major benchmarks, and the cost of choosing the wrong model was often perceived as greater than the cost of paying for the leading one.</p><p>The reasoning is defensible. But the empirical record now includes a result that the comparison set behind it cannot easily explain.</p><p>Earlier this year, Dharma published a benchmark in which a 3-billion-parameter model — specialized through a fine-tuning pipeline any well-resourced enterprise could replicate — outperformed every commercial frontier API tested. Not by a small margin, and not on a metric a buyer would dismiss. The cost gap ran in the opposite direction from the quality gap: the highest-scoring model was also the cheapest to operate, by a margin large enough to alter procurement arithmetic at any meaningful volume.</p><p>The result is not isolated. It is the most rigorously measured instance, to date, of a pattern Dharma has observed across other domains — and one a growing body of specialization research has begun to document (Subramanian et al., 2025; Pecher et al., 2026). But it does raise a question worth asking explicitly: when the largest model is not the best-performing model, what variable is doing the work?</p><h3>The Strategic Default</h3><p>The procurement default did not arrive by accident. It arrived because, for most of the past three years, it was correct.</p><p>When GPT-4 was released, it outperformed every smaller model on the benchmarks that mattered. The pattern repeated, with refinements, through Claude 3, Gemini 1.5, and each generation of frontier release in 2025. Capability scaled with parameter count and with training compute (Kaplan et al., 2020) — the empirical relationship OpenAI’s scaling laws had formalized years earlier. The lesson followed: a buyer who picked the largest model available was, on average, picking the best-performing tool. In the absence of a more discriminating signal, defaulting to scale was the rational move.</p><p>The assumption was defensible because, for most of the comparisons that produced it, it was correct. What changed was not that the assumption had always been wrong. What changed was that the comparison set on which it rested may not have been complete.</p><p>What was missing was a different kind of model. Not a smaller frontier model. A specialized model — one whose training history had been deliberately moved closer to the task it would be asked to do, through a sequence of fine-tuning steps that adapted a smaller base to the domain it would be deployed in. The paper described in the opening is among the first to run that comparison with cost, quality, and production stability measured side by side.</p><h3>What the Empirical Record Actually Shows</h3><p>The benchmark used in the paper was a domain-specific evaluation: Brazilian Portuguese OCR across printed documents, handwritten text, and legal and administrative records. The benchmark itself is not the point of this article. What matters is what it measured, and the comparisons it ran.</p><p>On extraction quality, the highest-scoring model in the comparison was the specialized 3-billion-parameter model. It scored 0.911 on the benchmark’s composite score, which combines edit-distance similarity with n-gram overlap. The closest frontier alternative — Claude Opus 4.6 — scored 0.833. Below it: Gemini 3.1 Pro at 0.820, GPT-5.4 at 0.750, Google Vision at 0.686, Google Document AI at 0.640, GPT-4o at 0.635, Amazon Textract at 0.618, and Mistral OCR 3 at 0.574. The specialized model finished first, and the gap to Claude Opus 4.6 — close to eight percentage points — was wider than any other gap between adjacent finishers in the comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*n3CyZa__07yUG1vDbG-35Q.jpeg" /><figcaption>Results of the models evaluated on DharmaOCR-Benchmark. Parentheses in the first column indicate the specialization techniques used. When a model is not indicated as LoRA, it means that full fine-tuning has been performed. Entries marked with “Quant” indicate AWQ-quantized variant with best performance among the quantized configurations.</figcaption></figure><p>On cost, the gap was far wider. The specialized 3B model ran at approximately fifty-two times lower cost per million pages than Claude Opus 4.6 — a margin computed from inference-infrastructure cost against published API pricing. The quality–cost picture, plotted as a Pareto frontier, shows the specialized model in the upper-left of the chart, with the commercial APIs below and to the right. (The financial-modeling depth is developed in <a href="https://medium.com/@commercial_98991/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c">The Real Economics of Text Degeneration</a>.)</p><p>On production stability, the same model produced the lowest text-degeneration rate evaluated — a measure of how often a generation enters a self-reinforcing loop and fails to produce a usable output. <em>(The production-stability case is developed in the cluster’s </em><a href="https://medium.com/@commercial_98991/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c"><em>Text Degeneration article</em></a><em>.)</em> The 3B model recorded 0.20% on this benchmark; the next closest specialized model, 0.40%; the larger general-purpose open-source baselines ran higher; the commercial APIs were not benchmarked on this metric directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*XMbnrjUgwP4VrXJnITH5Zw.jpeg" /><figcaption>Text degeneration rate (%) across alignment stages. SFT reduces degeneration relative to vanilla models in most cases, whereas DPO further reduces it, even compared to the SFT-tuned model.</figcaption></figure><p>These three findings — quality, cost, and stability, all led by the same 3B specialized model — are the article’s empirical anchor. Together, they make the empirical case stronger than any single finding would alone. The paper does not claim, and this article does not claim, that the result generalizes to every enterprise AI workload. What it claims is that on this benchmark, the smallest specialized model in the experiment was first on every dimension that mattered.</p><p>Which makes the obvious question the right question. The smallest model in the comparison won on quality, on cost, and on stability. Parameter count, by itself, does not explain that result. The natural follow-up — identifying the variable that does — is where the conversation moves next.</p><h3>The Variable That Mattered</h3><p>Part of this is intuitive. A 3-billion-parameter model focused on the deployment task will often outperform a much larger model whose parameters are spread across material the task will never touch — other languages, other corpora, other domains. What the paper adds goes further: one of the important variables is not only how parameters are allocated, but how the model’s training history has been moved toward the task. In the experiments reported, this variable predicted relative performance more reliably than any other tested — including parameter count.</p><p>The paper names this directly. In its discussion, the authors describe the result as supporting the claim that “contextual specialization can be more decisive than number of model parameters alone.” What determined whether a model performed best was not parameter count, but how close its training trajectory had been moved to its deployment task. A larger model trained on a wider distribution finished below a smaller model trained on a narrower one. The narrower training was the variable that produced the win.</p><p>This is a different way of thinking about model performance than the procurement default invites. Under the default, parameter count is the dominant variable and training history is a secondary modifier. Under the framing the paper proposes, the priority reverses. Distributional alignment to the task becomes the dominant variable. Parameter count becomes one factor among several that shape how much benefit a given alignment step produces.</p><p>Specialization is not a way to compensate for being small. It is a way to be aligned.</p><p>The numbers bear the framing out. The 3B Nanonets-OCR2 — already specialized for general OCR before the paper began — was fine-tuned on the target domain through supervised fine-tuning and Direct Preference Optimization, and reached 0.921 with a 0.20% degeneration rate. A 3B general-purpose model of identical architecture, Qwen2.5-VL-3B, was run through the same procedure and reached 0.793 with 1.41% degeneration. Same architecture, same training, different result. The variable was the distance the model had already traveled toward the task before the procedure began.</p><p>Distributional alignment, on the framing the paper proposes, is not specific to OCR. It is a property of the relationship between a model and the task it is asked to perform. The question of which model is best for a given enterprise workload is, on this framing, mostly a question of how aligned its training history is — not how large the model is.</p><p>If distributional alignment is one of the variables that mattered most, the next question is how it accumulates. The paper’s evidence suggests it does not arrive in a single step. The result above turns out to be one instance of a broader pattern: specialization, in the paper’s data, behaves less like a binary state than like a hierarchy through which a model can be moved one step at a time.</p><h3>Specialization Compounds</h3><p>Alignment is not a single thing a model either has or lacks. It is a position on a hierarchy that can be moved up one step at a time. A general-purpose model sits at the bottom; a general-domain specialist (trained for the broader category of work) sits above it; a domain specialist (trained for the specific work it will be deployed on) sits above that. The same downstream training produces different results depending on which step the model starts from.</p><p>The paper’s evidence for this is structural. Two pairs of comparisons illustrate it directly.</p><p>At the 7-billion-parameter scale: the best fine-tuned model derived from Qwen2.5-VL-7B-Instruct — a general-purpose start — reached 0.906 with a 1.01% degeneration rate. The same training applied to olmOCR-2–7B — already specialized for general OCR — reached 0.927 with 0.40% degeneration. The quality gain was approximately 2.3 percent; the degeneration rate fell by nearly half. Same architecture, same data, same training pipeline. The variable was the starting position.</p><p>At the 3-billion-parameter scale (the comparison introduced earlier): Qwen2.5-VL-3B finished at 0.793 with 1.41% degeneration; Nanonets-OCR2–3B finished at 0.921 with 0.20% degeneration. Same procedure, same architecture class, different starting position. The quality gain was approximately 16 percent; the degeneration rate fell by a factor of roughly seven.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*VlcijlqX7ggJb3blNWn7Rw.jpeg" /><figcaption>Progressive specialization strategy and comparison of two training paths. Three specialization levels are shown — vanilla generalist (Level 1), general-domain OCR specialist (Level 2), and domain-specific OCR specialist (Level 3) — plus a projected Level N for future sub-domain specialization.</figcaption></figure><p>Two pairs, two parameter scales, two consistent results. Specialization accumulates. A model already moved closer to the broader category of its eventual task benefits more from the same domain-specific training than a model starting from a wider distribution. The procedure does not produce alignment from nothing. It builds on whatever alignment is already present.</p><p>There are levels of specialization, and each level builds on the distribution encoded by the one before it. Multiple stages of training can progressively move a model closer to the target task distribution, producing materially different downstream outcomes even under similar architectural and computational constraints.</p><p>That pattern — alignment as an accumulating quantity — is the article’s strongest claim from the paper’s evidence. Its boundaries deserve to be marked explicitly. The hierarchy was demonstrated in one domain, on one benchmark, with two pairs of model comparisons. The mechanism has no domain-specific reason to be confined to OCR — but the evidence has not yet been gathered elsewhere, and an argument that respects its boundaries should mark that distinction. Expanding that empirical investigation across additional enterprise domains is part of the broader research direction this work opens, and that Dharma intends to investigate further across additional enterprise domains.</p><p>With that boundary marked, the strategic conversation moves forward. A variable shown to dominate parameter count in one well-measured enterprise domain is one strategy teams now have reason to weigh — not in every setting, but in any where the alignment test can be run.</p><h3>The Strategic Questions That Change</h3><p>A useful way to read the paper is not as an instruction for what enterprises should do next, but as a prompt for what they should ask. Three questions come into sharper focus.</p><p>The first: whether distributional alignment should be elevated alongside parameter count as a first-class variable in serious AI evaluation. The paper’s evidence does not argue for elevating it above parameter count. It argues, more modestly, that alignment is large enough as a variable to be tested explicitly rather than assumed to be small.</p><p>The second follows: is benchmark leadership, on its own, sufficient evidence for an enterprise procurement decision? In one well-measured domain, the model that led the public benchmarks was not the model that delivered the best result. If that divergence appears in other domains — and the paper does not establish that it does, only that it can — enterprise evaluation may need an additional layer of evidence, run on workloads representative of the deployment.</p><p>The third is about architecture, not method. If alignment is a position on a hierarchy that compounds, the choice of starting model — not only the fine-tuning procedure — becomes a strategic decision in its own right. A starting model already closer to the deployment task may produce materially better outcomes than a larger, more general model under the same training budget. But the deeper implication may be organizational rather than procedural. If specialization compounds, enterprises may eventually benefit less from searching for a single universally capable model than from building an ecosystem of models progressively aligned to their own domains, workflows, and operational constraints. Whether that architecture proves advantageous in practice is a question each organization has to evaluate within its own environment.</p><h3>A Bounded Reframe</h3><p>The article’s contribution is narrow, by design. It has not argued that frontier models are inferior, or disposable, or that the procurement default should be inverted. It has argued, on the strength of one paper’s evidence, that frontier models are not necessarily the best-performing choice for every enterprise AI workload. In the experiments reported, smaller specialized models with training histories more closely aligned to the deployment task achieved superior quality, lower cost, and greater production stability than the larger commercial APIs evaluated. The implication is not that frontier models are inferior. It is that specialization history may be a more strategically important variable for enterprise AI systems than many evaluation frameworks currently assume.</p><p>We wrote this article not to argue that scale no longer matters, but to isolate a variable the current enterprise AI conversation may still underweight. Training history can be observed, evaluated, and moved closer to a deployment task through successive stages of specialization. In the comparisons reported in the paper, that relationship materially changed the ranking of every model evaluated. Whether it changes rankings elsewhere is a question for the next set of experiments.</p><h3>Sources:</h3><ol><li>Cardoso, Gabriel Pimenta de Freitas, et al. “DharmaOCR: Specialized Small Language Models for Structured OCR that outperform Open-Source and Commercial Baselines.” <a href="https://arxiv.org/abs/2604.14314">arXiv preprint arXiv:2604.14314</a> (2026).</li><li>Subramanian, Karthik, et al. “Small Language Models for Domain-Specific Enterprise AI Workloads.” <a href="https://arxiv.org/abs/2503.11872">arXiv preprint arXiv:2503.11872</a> (2025).</li><li>Pecher, Branislav, et al. “<a href="https://www.semanticscholar.org/paper/Comparing-Specialised-Small-and-General-Large-on-to-Pecher-Srba/7f42b3a79ad1e176f5c881f1764b0ae87f65c252">Comparing specialised small and general large language models on text classification: 100 labelled samples to achieve break-even performance</a>”, (2026).</li><li>Kaplan, Jared, et al. “Scaling Laws for Neural Language Models.” <a href="https://arxiv.org/abs/2001.08361">arXiv preprint arXiv:2001.08361</a> (2020).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ead4692a65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Degeneration: A Production Failure Mode That Most Benchmarks Do Not Track]]></title>
            <link>https://medium.com/@dharma-ai/text-degeneration-a-production-failure-mode-that-most-benchmarks-do-not-track-c63b34a3a47c?source=rss-917a9f144050------2</link>
            <guid isPermaLink="false">https://medium.com/p/c63b34a3a47c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Dharma AI]]></dc:creator>
            <pubDate>Fri, 08 May 2026 14:36:42 GMT</pubDate>
            <atom:updated>2026-05-08T14:36:42.264Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A self-reinforcing failure mode of autoregressive language models, with measurable consequences for inference cost and throughput, and a structural fix grounded in the training distribution.</em></p><p>In our recent work specializing a small language model for domain-specific OCR — detailed in the <a href="https://arxiv.org/abs/2604.14314">DharmaOCR paper</a> and <a href="https://huggingface.co/Dharma-AI/Dharma-OCR-LITE">available on HuggingFace</a> (<a href="https://huggingface.co/spaces/Dharma-AI/DharmaOCR-demo">with demo space</a>) — we show that in real-world PDF document OCR scenarios, fewer than three percent of pages can consume nearly half of the total wall-clock time.</p><p>The requests responsible were the ones that had hit the configured maximum-token limit and exhibited an n-gram repetition pattern at their tail. They had not produced a complete output. They had stopped emitting an end-of-sequence token, repeated a fragment, and continued repeating until the system’s hard limit cut them off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5CHNb3iFiHk1ovlZ2dsFw.png" /><figcaption>Start and end time of each request (in submission order). Each request is represented by a bar whose left edge marks start time and whose right edge marks end time. Degenerate requests are highlighted in red.</figcaption></figure><p>We re-ran the experiment on a second dataset, and a third. The same shape appeared, with varying intensity. A small minority of requests was responsible for a measurable share of the total wall-clock time of the batches they were in. <strong>This phenomenon is called Text Degeneration.</strong></p><h3>The Anomaly in the Inference Log</h3><p>What we were measuring was not noise, text degeneration is a known phenomenon , described in the language-modeling literature since Holtzman and colleagues’ 2020 paper, and characterized in subsequent works as a self-reinforcing failure of autoregressive generation.</p><p>The shape was always the same. A small number of requests would enter a generation loop. The model would repeat a token, then a fragment, then the same token again, until the system’s max-tokens guard cut it off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*7qYijoKg6hIFHkasMwuUlA.png" /><figcaption>Pictorial example of token and sequence-level text degeneration, in which a single token (or token sequence) dominates the conditional distribution, producing repetitions indefinitely.</figcaption></figure><p>The reason is structural. A healthy request ends when the model emits an EOS token — the model’s signal that the output is complete. A degenerate request never reaches that signal. It loops, filling its allocated context with repeated tokens or sentences until the hard max-tokens limit forcibly terminates it.</p><p>The difference in output length between the two is not marginal. And because inference time scales directly with the number of tokens generated, a degenerate request occupies the GPU for a multiple of the time a well-formed request of comparable input would.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*MXw5-Xs_Cn8uQWPomW3ayg.png" /><figcaption>Source: Dong et al, 2026.</figcaption></figure><p>The instinct, watching one of these requests in real time, is to treat it as a tuning problem. Raise the repetition penalty. Lower the temperature. Switch the decoder. Add a streaming check that aborts a request once it begins to repeat. <strong>These instincts are reasonable, and they all help. They do not address the cause.</strong></p><p>The cause is older than any of these decoders, and it is built into the optimization objective that produced the model in the first place.</p><h3>Why Degeneration Is Structural, Not Configurable</h3><p>A language model trained with maximum-likelihood — which is to say, almost every model in production today — is trained on a single, narrow imperative: given everything that has come before, assign high probability to whatever came next. Minimize the negative log-likelihood of the reference sequence, token by token, across the entire corpus.</p><p>Because the model is autoregressive, it never sees the full sequence it will eventually produce: it only ever predicts one token at a time, conditioned on what precedes it. The objective does not care what the model generates as a whole. It cares only that, at each step, the model assigns high probability to the next token in the reference corpus.</p><p>This produces models that are extraordinarily good at continuation. It also produces a side effect that has been documented in the literature for years and that, despite a steady record of inference-time mitigations, remains structurally unresolved.</p><p>The effect was first formalized by Holtzman and colleagues in 2020 and can be stated, in the form most useful here, as a self-reinforcement of the conditional distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*hJKmj-m_5Rvj2nhuJajrZQ.png" /></figure><p>The more often a token or a fragment has appeared in recent context, the more probable it becomes on the next step. Once the model enters such a region, the gradient of probability points back into it, not out of it. The end-of-sequence token, which would normally close the generation, sits at a vanishingly low probability relative to the repeated fragment. The loop sustains itself until something external — a max-tokens cap, a streaming abort, an exhausted KV cache — finally interrupts it.</p><p>This is what makes degeneration structural. The loop is not a defect of the decoding strategy. It is a high-probability region of the distribution itself, produced by the training objective, reinforced by repetitive patterns in the empirical training data, and embedded in the geometry of the model’s internal activations — a description supported in successive analyses since 2020 (Source: Holtzman et al, 2020).</p><p>Decoding strategies — temperature, top-p, repetition penalties, beam search variants — operate on top of that distribution. They can make the loop less likely to be entered. They cannot remove it. The same is true of specialized models and general-purpose models alike: each inherits this geometry from the optimization that produced it.</p><p>This is the part of the problem that has been discussed in research papers. What is much less discussed — and what we addressed directly in our recent work — is what happens to the rest of the system while one of these loops is running.</p><p>Because the cost of a degenerate request is not contained inside the request. That the output is broken is obvious — no one wants a model that has locked itself into printing the same fragment until the hard limit cuts it off. The problem that has received far less attention is what that loop costs the system around it.</p><h3>The Cost Multiplier Hiding in Plain Sight</h3><p>We replaced the degenerate requests with synthetic requests of average duration in our experiment — a simple way to estimate the cost the loops had imposed. Total inference time fell from 7.3 minutes to 4.2 minutes. The wall-clock cost of the entire batch had been inflated by 42.47% by a small minority of degenerated requests.</p><p>This is not a story about the failed request. The failed request’s runtime was, in some sense, secondary. What mattered was that during the time the loop was alive, every other request running on the same GPU paid for it.</p><p>We measured this directly. Across three datasets, the duration distribution of healthy requests shifted whenever a degenerate request was active in parallel. The mean duration of a healthy request rose by at least 15%, and in one dataset by more than 71%, when at least one degenerate sequence was occupying the same machine. The healthy requests had not become more difficult. The system serving them had become measurably slower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*I9FhxSzHgQaXueW06DEKXQ.png" /><figcaption>Distribution of healthy-request durations for the three datasets, contrasting periods with at least one degenerate request running in parallel versus periods with no degenerate request running. The mean of each distribution is marked in black with an “x” inside each box, with its value next to it.</figcaption></figure><p>The mechanism is mundane and material. Modern inference servers — vLLM in our experiments — extract throughput by holding many requests in a dynamic batch and serving them in parallel through paged memory. The amount of memory occupied by a sequence grows roughly linearly with the number of tokens it has produced. When a sequence enters a degeneration loop and approaches the configured token cap, it occupies a disproportionate share of the available memory, for a disproportionately long time. The scheduler has less room to admit new sequences to the batch. Parallelism falls. Throughput across the batch falls with it. (Source: Kwon et al, 2026).</p><p>Which means the cost of a single degenerate request is not paid by the request. It is paid by the queue.</p><p>That cost is measurable. The degeneration-rate of the model used in this experiment — Qwen2.5-VL-7B-Instruct vanilla — was 2.42% on this benchmark. A failure rate that small, on a workload of any meaningful volume, was sufficient to inflate wall-clock time by 42.47% on the most affected dataset.</p><p>This raises a question about evaluation. If degeneration is a structural property of the training objective, and if its production cost is large, sustained, and contagious — why does it not appear on the standard benchmarks used to compare these models?</p><p>It does not appear on any benchmark we are aware of — OCR-specific or otherwise. The metric is absent from every standard evaluation suite used to compare these models. The omission is worth taking seriously.</p><h3>The Benchmark Blind Spot</h3><p>The explanation is likely straightforward: benchmark designers focus on measuring output quality, and standard evaluations tend to capture average response quality rather than pathological edge cases. Failure modes fall outside that frame. But in the case of text degeneration, that omission has real consequences — even occurring in fewer than 3% of requests, its impact on system throughput is disproportionate enough to matter.</p><p>A consequence visible in our results is that two models can produce nearly identical quality scores while differing substantially in degeneration rate, and therefore in production cost. In our Table 1, several pairs of fine-tuned models illustrate this. A model with a marginally higher quality score is not necessarily the better model to deploy. The benchmark cannot tell which is which. It was not designed to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*Uc6T_51ZH3lIKfcym4Ss3g.png" /><figcaption>Results of the models evaluated on DharmaOCR Paper.</figcaption></figure><p>The argument we make explicitly in the <a href="https://arxiv.org/abs/2604.14314">DharmaOCR paper</a> (Source: Cardoso et al, 2026) is that this is a methodological gap. Studies that propose models and benchmarks for autoregressive generation should track degeneration rate as a first-class metric, alongside accuracy and cost. The omission is structural. The consequences are operational and economic.</p><p>Another reasonable response to all of this is that benchmark omission may be that the failure mode itself is solvable at the inference layer. Detect repetition early. Abort the request. Retry. Route to a fallback. The system, the argument goes, can be made resilient even if the benchmark cannot be made complete.</p><p>It is a reasonable response. It is also, by the paper’s evidence, partial.</p><h3>Why Mitigation Is Itself a Tax</h3><p>The mitigations described in the literature operate at the inference layer. Real-time repetition detection screens for loops as they form. Retry mechanisms reissue affected requests, sometimes against a different model or decoding configuration. Both are real interventions, and both reduce the visible footprint of degeneration in production.</p><p>Both also have a cost. Real-time detection runs on every output, not only the ones that fail — it is an online monitoring mechanism running alongside inference, which carries its own latency and compute overhead. Retries multiply the inference cost of the requests they handle. And degeneration does not always manifest as simple, easily recognizable repetition patterns: heuristics broad enough to catch pathological loops will also penalize legitimate outputs that contain natural repetition. The mitigations contain the worst-case behaviour of any single request. They do not reduce the compute already spent on requests that have entered the loop, and they do not address the source of the loop.</p><p>The inference-layer fix is partial. Total throughput, measured under realistic load, remains depressed by the contagion effect even when individual requests are aborted on detection. A more complete fix has to be addressed earlier — in the model itself.</p><h3>The Specialization–Stability Link</h3><p>If the failure is structural, the fix has to be structural too — which means it cannot live in the decoder. It has to live in the distribution itself.</p><p>The intervention we evaluated was a two-stage training pipeline. The first stage was supervised fine-tuning on domain-aligned examples — the canonical move when adapting a general-purpose model to a narrower task. SFT pulls the model toward the target distribution. It is necessary, and on its own, it is not sufficient. Even after SFT, the high-probability loop regions inherited from the pretraining objective remained present in the models we tested. The models were better at the task. They still occasionally fell into the same wells.</p><p>The second stage was Direct Preference Optimization, applied to a curated set of preference pairs. DPO is usually framed as an alignment technique for chat — training a model to prefer better responses over worse ones in a curated set of pairs (Source: Rafailov et al, 2023). We used it differently. We constructed pairs in which the rejected example was a degenerate generation drawn from the same model, and the chosen example was a healthy one. The training signal pushed the model away from the geometry of its own failure mode.</p><p>The effect was substantial. Across five model families, ranging from 3B to 7B parameters, DPO reduced the degeneration rate by 37% to 87% relative to SFT alone. The strongest result was on a 3B model — Nanonets-OCR2 — which fell from 1.61% to 0.20%, an 87.6% reduction. The same intervention applied to general-purpose models in the 7B range produced reductions in the 37–56% range. The average reduction across families was 59.4%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*N4RAsceNRaFWFkDsYtlbhw.png" /><figcaption>Text degeneration rate (%) across alignment stages. SFT reduces degeneration relative to vanilla models in most cases, whereas DPO further reduces it, even compared to the SFT-tuned model.</figcaption></figure><p>There are two ways to read these numbers. The first is that DPO works as a degeneration-mitigation technique, which it does. The second, which we think is the more important reading, is that the smallest specialized model in our experiments achieved the lowest degeneration rate of any model we tested — including substantially larger general-purpose ones. The variable that mattered most for stability was not the size of the model. It was the distance between its training history and the task.</p><p>This is what specialization changes. Not only the average quality of the output, but the geometry of the failure itself. A model that has been moved closer to the target distribution by SFT, and then explicitly pushed away from the failure regions by DPO with degenerate-rejected pairs, is operating in a different probabilistic landscape than the model it started as. The loop is not simply less likely to be sampled. It is, by the empirical evidence, less present.</p><p>In the comparisons we conducted, training history mattered more than parameter count.</p><p>Which raises a final question, suggested directly by the paper’s argument.</p><p>If degeneration can be measured, if it can be reduced structurally, and if the difference between models on this dimension is large enough to matter — what should change about how these models are evaluated and observed?</p><h3>Reframing Evaluation and Observability</h3><p>The first change is observability. Degeneration rate is computable from data the inference server already produces: a request that hits the configured token cap with n-gram repetition at its tail is a degenerate request, and the rate is the fraction of those over a window. The paper argues, and the empirical results support, that this metric should be tracked alongside latency, throughput, and quality. Adding it costs little. Not adding it leaves the largest cost-shape in the system invisible.</p><p>The second change is evaluation. A model’s score on a benchmark that does not measure stability is incomplete. Two models can score nearly identically on a quality benchmark and differ by an order of magnitude in degeneration rate, and therefore in inference stability. The benchmark score cannot reveal that. Comparisons are most useful when made against an evaluation that includes stability and cost on workloads representative of the deployment, not only quality on synthetic ones.</p><p>What this amounts to, taken together, is the methodological argument the paper makes directly: text degeneration belongs in the evaluation frame, not outside it.</p><h3>What Changes When You Start Measuring This</h3><p>The argument of this article — and of the paper it draws on — has been narrow.</p><p>A failure mode characterized in the language-modeling literature for years. Treated, in most prior work, as a generation-quality issue. Routed around, in production, at the inference layer. Measured directly under realistic inference load, it produces costs and throughput effects that the conventional metrics do not surface.</p><p>It is structurally produced by the same training objective that makes language models useful. It is contagious across the requests sharing a GPU with it. It is not currently tracked in the major OCR benchmarks used to compare models. And, in the experiments we report, it is reducible — by close to an order of magnitude in the strongest case — by training models in a way that explicitly pushes the failure regions out of their distribution rather than waiting to detect them at runtime.</p><p>Each of those claims is empirically grounded. Taken together, they argue for a different way of evaluating autoregressive generation systems and a different way of observing them in production. Once degeneration is measured, much of what depends on it changes with it.</p><h3><strong>Sources:</strong></h3><ol><li>Cardoso, Gabriel Pimenta de Freitas, et al. “DharmaOCR: Specialized Small Language Models for Structured OCR that outperform Open-Source and Commercial Baselines.” <a href="https://arxiv.org/abs/2604.14314">arXiv preprint arXiv:2604.14314</a> (2026).</li><li>Holtzman, Ari, et al. “The curious case of neural text degeneration.” <a href="https://arxiv.org/abs/1904.09751">arXiv preprint arXiv:1904.09751</a> (2020).</li><li>Dong, Sixun, et al. “Rethinking Model Efficiency: Multi-Agent Inference with Large Models.” <a href="https://arxiv.org/abs/2604.04929">arXiv preprint arXiv:2604.04929</a> (2026).</li><li>Kwon, Yongchan, et al. “What LLMs think when you don’t tell them what to think about?” <a href="https://arxiv.org/abs/2602.01689">arXiv preprint arXiv:2602.01689</a> (2026).</li><li>Rafailov, Rafael, et al. “Direct preference optimization: Your language model is secretly a reward model. In Advances in Neural Information Processing Systems (NeurIPS).” <a href="https://arxiv.org/abs/2305.18290">arXiv preprint arXiv:2305.18290</a> (2023).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63b34a3a47c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>