At one point during this project, my model generated fluent Arabic text, and its training loss was decreasing. It seemed to be learning.
One problem remained: it was barely reading the image.
When I replaced the input with a blank white image, the loss was almost the same as when I supplied the actual text image. The language model was producing plausible text from its learned patterns, not reliably extracting the text it could see.
That failure shaped the rest of the project.
I wanted to investigate whether a compact vision–language model (VLM) could read Arabic, English, and mixed-script text without needing a multi-GPU training setup. My long-term application was document processing in the UAE, where a single form may contain Arabic labels, English values, Western and Arabic-Indic numerals, and handwritten entries.
I assembled a 1.157-billion-parameter model from a Qwen vision encoder, a custom projector, and a smaller Qwen language decoder. Using earlier alignment checkpoints, I trained its Arabic-focused and form-extraction stages on a single Google Colab L4 GPU across resumable sessions.
The results were encouraging, but mixed. The numbers below come from different, explicitly labeled evaluation setups, and I am separating those rather than combining them into one headline score:
Most importantly, a handwriting overlap check showed that some attractive benchmark scores were inflated by training text similar to evaluation text. I want to explain that openly, because it changed how I interpret the results.
This is a research log, not a claim of production-ready OCR. Here is what I built, what failed, what I measured, and what I would do next.
English and Arabic do not simply differ in their alphabets. Arabic letters connect and change shape depending on position; text flows right to left, while embedded English words and many numbers flow left to right. Arabic diacritics can make exact transcription harder, and handwriting introduces a much wider range of shapes than printed fonts.
In the UAE-document setting, that means an OCR system may need to interpret ?????? (????): 13,984.00, a phone number displayed with Arabic-Indic digits, a stamped label, or a handwritten name—sometimes on the same page.
The aim was not to replace a production document-understanding pipeline immediately. It was to investigate a smaller, trainable VLM capable of extracting text and, eventually, structured fields.
Grab’s engineering article, How We Built a Custom Vision LLM to Improve Document Processing at Grab, influenced me. Their work showed a compelling path: combine a capable vision encoder with a smaller decoder, then train progressively. I adapted that idea to Arabic and English, public/synthetic data, and a single-GPU constraint. This architecture is assembled from pretrained components, not trained from random initialization end to end.
The design uses:
| Component | Origin | Parameters | Role |
|---|---|---|---|
| Vision encoder | Qwen2.5-VL-3B-Instruct | ~632M | Converts the document image into visual features |
| Custom projector | Newly constructed, partially warm-started | ~30.8M | Maps vision features to the smaller decoder’s embedding dimension |
| Language decoder | Qwen2.5-0.5B-Instruct | ~494M | Generates the transcription or extracted fields |
| Total | ~1.157B |
The untuned Qwen2.5-VL-3B baseline has approximately 3.755B parameters, based on the notebook’s measurement. The custom model has roughly 31% of that parameter count.
Figure 1 — The assembled model, using parameter counts measured in the notebook. This is an explanatory diagram, not a screenshot of the training run.
The difficult part is the projector. The vision encoder produces features in a space meant for Qwen’s larger language model. My compact decoder expects embeddings of width 896, not the larger decoder’s width. I therefore needed a projector that retained useful visual information while producing embeddings the smaller decoder could handle.
I reused the shape-compatible first projection layer and normalization from the pretrained Qwen vision–language model, initialized the remaining projection to match the decoder’s input scale, and checked that the transplanted language decoder preserved its original text-only behavior.
This seemingly small alignment problem turned out to explain my first major failure.
Early versions (v1 and v2) generated coherent-looking Arabic but performed poorly on transcription. Character error rate was around 3 on the tests described in my earlier research logs—an error rate above 1 is possible when predictions contain enough insertions or substitutions relative to the reference.
At first, the training curve looked reassuring. Yet the answers were too long, and swapping the real image for a blank image barely changed the loss.
The assembled model’s visual token scale was also badly mismatched with the decoder’s text embeddings: an early assembly check reported average magnitudes around 5.71 versus 0.45. The decoder was receiving visual embeddings that didn't match the inputs it had learned to interpret.
Three changes helped v3 begin to use the image:
From then on, I tracked two diagnostics together: answer loss with the real image and answer loss when the image was replaced with a same-sized blank image.
For example, at the end of v5 stage 3, the recorded losses were approximately 0.105 (real image) versus 5.718 (blank image). This substantial gap supports the conclusion that image information materially affected prediction. It does not, by itself, prove perfect grounding or rule out language-model guessing—but it catches one failure mode that ordinary training loss misses.
Lesson: for a VLM doing OCR, track whether removing visual evidence makes the task harder. A declining loss curve alone is insufficient.
Real, labeled Arabic–English business documents were not available for this experiment. I therefore built an on-the-fly data generator and combined it with public handwriting datasets.
The data-preparation process gathered Arabic and English text from Wikipedia, diacritized Arabic from the riotu-lab dataset, fonts from Google Fonts, and handwriting lines from KHATT, Muharaf, and IAM. It also included a small SynthDoG English-page component.
For each generated example, the pipeline selected text, chose a suitable font and layout, rendered it into an image, optionally applied blur, rotation, compression, noise, or perspective distortion, and paired the image with an instruction and target answer.
Figure 2 — Actual synthetic text samples displayed by the v5 notebook, illustrating variation in fonts, layouts, mixed scripts, and diacritics.
The resulting training images included short Arabic lines, diacritized text, multi-line blocks, English lines, bilingual Arabic-label/English-value lines, and generated forms. Forms varied across 12 possible field types, with four layouts, randomized field selection, stamps, and other visual decoration. Target form outputs were normalized JSON objects rather than raw transcriptions.
Figure 3 — A synthetic bilingual form rendered by the training generator. The content is artificial; this is not a real Emirates ID, invoice, or production document.
A particularly awkward case was bidirectional numeral layout. A bidirectional text engine may display an Arabic-Indic phone number with groups separated by spaces in an unexpected visual order. The generator deliberately exposed the model to both display conventions while keeping the desired answer in logical order.
During stage 3, the notebook generated 90,000 examples with a mixture of printed Arabic, diacritized text, classical-style lines, handwriting, English text, scene words, and bilingual lines. Stage 4 added 16,000 example presentations, 40% of which were generated forms.
I also tried to reduce benchmark overlap: the data-preparation code filtered text shared with KITAB-Bench and checked for near-duplicate handwriting images. That helped, but the later evaluation revealed a serious limitation: some handwriting training and evaluation items still shared text sequences. I return to this in the results section.
The synthetic generator was valuable for controlling typography and layout. It was not a substitute for evaluating real documents.
An important distinction: the final v5 model uses four stages in its training lineage, but I did not rerun all four stages from scratch. The notebook reused the stage-1 and stage-2 checkpoints from v3, then retrained stages 3 and 4 with the v5 data and configuration.
| Stage | Goal | Trainable components | Data / scale | Status in v5 |
|---|---|---|---|---|
| 1. Projector alignment | Make vision features understandable to the decoder | Projector in full | 30,000 rendered lines; 3,750 optimizer steps | Reused v3 checkpoint |
| 2. Vision adaptation | Teach the vision stack general text-reading features | Vision LoRA + projector; decoder frozen | 25,000 examples; 3,125 steps | Reused v3 checkpoint |
| 3. Arabic-focused OCR | Improve Arabic, handwriting, mixed text, and English retention | Vision LoRA on blocks 0–23, last 8 vision blocks in full, projector, decoder LoRA | 90,000 examples; 11,250 steps | Trained in v5 |
| 4. Forms to JSON | Learn structured field extraction while retaining OCR | Same component groups as stage 3 | 16,000 presentations; 2,000 steps | Trained in v5 |
Figure 4 — Training lineage. The distinction between checkpoint reuse and new v5 training is essential when interpreting the compute budget.
For stages 3 and 4, the LoRA configuration used rank 32, alpha 64, dropout 0.05. The last eight vision blocks were updated in full using a lower learning rate (2×10????), while LoRA and the projector followed the stage learning rate (2×10???? in stage 3; 1×10???? in stage 4).
The model was trained with bf16 mixed precision, gradient checkpointing, AdamW, warm-up, cosine learning-rate decay, and loss only on assistant-answer tokens.
On the L4, stage 3 ran 11,250 steps in 722 minutes (about 12 hours), with a recorded peak training allocation around 13.8 GB. Stage 4 ran 2,000 steps in 238 minutes (about 4 hours), with peak memory around 11.6 GB. Those are the recorded execution times for these stages; they do not include every prior experiment, dataset-preparation step, or benchmark pass.
Colab interrupted stage 4 during the experiment. Saving trainable weights, optimizer state, and progress to Google Drive allowed the run to resume from a saved checkpoint rather than restarting. The optional decoder continued-pretraining switch was disabled in this v5 run.
Figure 5 — Original stage-3 and stage-4 training plots saved in the notebook outputs. Their short held-out progress checks are diagnostics, not substitutes for the larger public evaluation.
One deliberate change between v4 and v5 was to train the final eight vision blocks in full rather than relying solely on LoRA. But because the data, handwriting mix, and visual limits also changed, the current run does not isolate the improvement attributable to that specific change.
I used character error rate (CER) and word error rate (WER). Both compare predicted text against a reference; lower is better, and 0 means exact agreement under the selected normalization.
The headline results use Unicode NFC and whitespace normalization, with a consistent mapping of Persian-style yeh/kaf to Arabic forms across models. I also calculated alternate scores with diacritics removed and with additional Arabic-letter normalization, because changes in marks and letter variants can otherwise obscure what the model is getting wrong.
For controlled comparisons, the models received the same images, OCR instruction, decoding approach, and evaluation normalization. The public-set evaluation covered nine KITAB-Bench OCR subsets, plus the KHATT, Muharaf, and IAM test splits. It scored 200 or 500 samples per set, depending on the subset and notebook configuration. I calculated the reported confidence intervals by bootstrapping examples.
I also ran a separate 48-example-per-category evaluation against the untuned Qwen2.5-VL-3B baseline, including synthetic Arabic, English, bilingual lines and forms, plus handwriting test lines.
I did not directly evaluate GPT-4o or Gemini in the same run. KITAB-Bench publishes results for those models, but its full-subset settings, prompting, and normalization are different. I therefore do not treat published GPT/Gemini scores as a controlled head-to-head comparison with my model.
The table below gives raw CER, using the same evaluation code for these four checkpoints. The final column is untuned Qwen2.5-VL-3B-Instruct, not Qwen after QLoRA. All numbers are from the notebook’s logged results.
| Evaluation set | Samples | v5 after stage 4 | v5 after stage 3 | v4 after stage 4 | Untuned Qwen 3B |
|---|---|---|---|---|---|
| PATS (printed Arabic) | 500 | 0.028 | 0.025 | 0.056 | 0.127 |
| SythenAR (diacritized) | 500 | 0.092 | 0.095 | 0.131 | 0.309 |
| ISI-PPT (slides) | 500 | 0.081 | 0.088 | 0.108 | 0.294 |
| KHATT (Arabic handwriting) | 200 | 0.297 | 0.243 | 0.338 | 0.750 |
| OnlineKhatt | 200 | 0.230 | 0.164 | 0.330 | 0.582 |
| EvArEST (scene text) | 500 | 0.200 | 0.223 | 0.277 | 0.596 |
| HistoryAr | 200 | 0.677 | 0.988 | 0.981 | 1.288 |
| ADAB (handwritten words) | 200 | 0.242 | 0.233 | 0.315 | 1.510 |
| Muharaf (historical handwriting) | 200 | 0.204 | 0.210 | 0.838 | 0.832 |
| KHATT test split | 500 | 0.063 | 0.029 | 0.343 | 0.683 |
| Muharaf test split | 500 | 0.168 | 0.178 | 0.773 | 0.877 |
| IAM English handwriting test | 500 | 0.051 | 0.049 | 0.052 | 0.068 |
How to read this table: v5 stage 4 has numerically lower CER than the untuned Qwen baseline on these 12 evaluated sets, but that does not mean 12 independent demonstrations of superior real-world OCR. Several handwriting sets are related to the training distribution; KHATT in particular has serious repeated-text overlap, and some apparent differences are small or statistically uncertain. IAM is effectively unchanged relative to v4. For actual OCR-only workloads, stage 3 can be preferable on some handwriting subsets, while stage 4 performs better on others.
Figure 6 — Selected measured CERs. PATS and Muharaf are public subsets; the drawn English comparison uses a separate 48-example evaluation. Different chart panels have independent scales, so compare the labeled numbers rather than bar lengths across panels.
On PATS, v5 stage 4 scored 0.028 CER with a 95% bootstrap interval of approximately 0.024–0.031, versus 0.127 (0.102–0.161) for the baseline. On the Muharaf subset, the v5 model scored 0.204 versus 0.832 for Qwen. The strongest claims are still limited to the measured subsets and evaluation procedure.
A separate 48-example evaluation gave the following results:
| Measurement | Untuned Qwen2.5-VL-3B | Final v5 model |
|---|---|---|
| Arabic synthetic lines, CER | 0.144 | 0.024 |
| Diacritized synthetic lines, CER | 0.341 | 0.046 |
| Bilingual synthetic lines, CER | 0.421 | 0.008 |
| English synthetic lines, CER | 0.003 | 0.011 |
| IAM handwriting lines, CER | 0.090 | 0.074 |
| Field accuracy on generated forms | 0.466 | 0.992 |
| Median seconds per line | 0.843 | 0.574 |
| Median seconds per form | 4.086 | 2.276 |
| Measured peak inference GPU memory | 7.5 GB | 2.3 GB |
Figure 7 — Results of the notebook’s baseline comparison: median time per line and peak allocated inference GPU memory. These are single-run measurements, not throughput or production-concurrency results.
These timings and memory figures are one notebook’s L4 inference measurements, not a deployment benchmark with production concurrency, different quantization methods, or other hardware. The 48-example task results are small and should be treated as indicative, not definitive.
There is also an important nuance in the form result. The current evaluation reports field-level accuracy over expected keys. Its valid_json metric uses a regular expression to extract a JSON object from the model’s response before parsing it. Consequently, a reported 1.000 means that a parseable JSON object was found; it does not prove that the entire response was strictly JSON with no surrounding text. The field-accuracy score does not penalize extra unexpected keys. I have therefore not labeled this result “99.2% document accuracy” or “100% strict JSON compliance.”
Real UAE forms were not scored in this notebook: the real-document evaluation cell reported that no labeled real documents were prepared.
The original KHATT results initially looked impressive. But KHATT includes copied passages, and v5's relaxed training-data filter retained many lines that shared word sequences with benchmark text.
The notebook flags a test item as overlapping if it shares four consecutive words with a line in the corresponding training handwriting source. This is a practical contamination check—not a proof that every item in the non-overlap bucket is entirely novel.
The results are revealing:
| KHATT subset | Lines | v5 stage-4 CER | v5 stage-3 CER | v4 CER |
|---|---|---|---|---|
| Text overlap found | 88 | 0.04 | 0.04 | 0.25 |
| No four-word overlap found | 112 | 0.49 | 0.40 | 0.41 |
Figure 8 — Overlap-flagged and non-flagged KHATT subsets. “Clean” here means no detected four-word overlap, not a guarantee of completely independent documents or writers.
On the 112 non-overlapping KHATT lines, stage 4 was worse than v4 (0.49 versus 0.41); stage 3 was approximately level with v4 (0.40 versus 0.41). The low CER on overlapping lines was pulling down the overall KHATT score.
The KHATT test split was even more problematic for making generalization claims: 487 out of 500 evaluated lines were flagged as sharing four-word sequences with training. Its low aggregate CER should not be presented as proof that the model can recognize entirely new handwriting passages.
The picture was more encouraging for Muharaf: 186 of 200 evaluated KITAB images had no flagged four-word overlap, and stage-4 CER in that bucket was about 0.19, versus about 0.83 for the untuned baseline. Even here, the train and test data come from a related source distribution, so an independent out-of-domain handwriting test would be stronger evidence.
Lesson: a benchmark can be public and still be contaminated relative to your training corpus. Before celebrating gains, check shared documents, repeated text, writer overlap, image near-duplicates, and source distributions.
Stage 4 was designed to teach the model to extract fields as JSON. On the generated held-out forms, field-level accuracy reached 0.992, compared with 0 before Stage 4 under the stage-specific evaluation.
The trade-off varied across OCR tasks. In the public evaluation, the stage-3 checkpoint outperformed the final stage-4 checkpoint on OnlineKhatt (0.164 versus 0.230 CER) and KHATT (0.243 versus 0.297). But stage 4 improved HistoryAr (0.677 versus 0.988) and EvArEST (0.200 versus 0.223).
This is not a simple story of “stage 4 damages all reading.” It changes the performance profile. The checkpoint worth deploying would depend on the actual document mix and whether the user wants plain transcription or structured field extraction. Without a labeled production-like evaluation set, I cannot choose a universal winner.
I also tested a small inference-time ablation on the first 100 examples of selected public subsets. On KHATT, greedy decoding produced a CER of 0.308. Setting no_repeat_ngram_size=4 reduced it to 0.167, and repetition_penalty=1.1 produced 0.163. On OnlineKhatt, the corresponding values were 0.296, 0.205, and 0.183.
Some remaining errors stemmed from the model generating repetitive text, not simply misidentifying letters. A decoding constraint could suppress part of that failure without another training run.
However, this was a limited 100-image ablation, not a full re-scoring across all twelve sets or real documents. I would repeat the experiment across the entire benchmark, look for cases where legitimate repeated text is incorrectly suppressed, and measure the latency effects before setting a new production default.
Increasing the visual-token limit from 640 to 1,024 or 1,280 did not change CER in the tested PATS, ISI-PPT, or KHATT line images. Those short lines were not resolution-limited in that experiment. This does not establish that 640 tokens are sufficient for full-page scans with small text.
Real-world forms. The model learned fields from a synthetic generator with limited layouts, names, and label types. It has not been evaluated on labeled Emirates IDs, trade licenses, labor contracts, or invoices. The synthetic form score cannot establish deployment readiness.
Printed English. On the separate 48-example synthetic English set, the larger untuned Qwen model remained better (CER 0.003 versus 0.011). My training mix favored Arabic adaptation and includes much less full-page English text. The small set isn't enough to diagnose every cause, but it shows that smaller doesn't automatically mean better across languages.
Unseen handwriting. A large part of the apparent KHATT gain was affected by text overlap. HistoryAr also remained difficult (stage-4 CER 0.677 and WER above 1), showing that historical writing remains a challenge.
Structured-output correctness. The current evaluation checks expected field values and extractable JSON objects, not strict whole-response JSON, extra-key behavior, or full-form exact match. Evaluate these before claiming reliable structured extraction.
Full-page reading. Most training and evaluation examples are lines or modest text blocks. A resolution-limited VLM processing an entire scanned page can lose small characters during image resizing. The next evaluation should explicitly separate full-page OCR from cropped-line OCR.
Causal attribution. v5 changed the data mixture, handwriting volume, fully trained vision blocks, image limits, and training schedule together. The current logs show improvement in the resulting system; they do not prove the independent benefit of each change. Proper ablations would hold other variables constant.
Licensing. The reused Qwen2.5-VL-3B vision weights are subject to the Qwen Research License. Several training datasets also impose research/non-commercial or other redistribution conditions. Treat this model as a research artifact, not commercially deployable, until all component, data, and redistribution terms have been reviewed. The smaller Qwen2.5-0.5B decoder is distributed under Apache 2.0, but that does not override restrictions on the other components.
My priorities are straightforward:
I would also evaluate English handwriting with punctuation-normalized references alongside raw CER/WER. Some IAM transcription conventions differ from ordinary English punctuation, which can confound comparisons if models format otherwise-identical words differently.
Building a compact OCR VLM was less about finding one perfect learning rate and more about systematically investigating failures.
Visual alignment matters. A decoder can produce fluent language while ignoring the picture. Comparing real-image loss with blank-image loss gave me a useful guardrail.
The training distribution matters. Broadening beyond a handful of Arabic fonts and adding different writing styles coincided with large improvements. But when several factors change at once, the results don't show which factor deserves the credit.
Evaluation can be misleading even when the code is reproducible. The KHATT overlap check turned an attractive aggregate score into a much more complicated result. That is exactly the kind of finding worth documenting.
Task adaptation introduces trade-offs. The form-extraction stage helped the intended task while affecting OCR subsets differently. There is no single best checkpoint without a defined target distribution.
Small models can be useful, but narrow successes are not production-ready. This 1.157B model beat the untuned 3B baseline on several controlled Arabic OCR tests and used substantially less GPU memory in my benchmark. It also lagged on English printed text in one comparison and has not been tested on labeled real UAE documents.
For me, the strongest result is therefore not “I beat a larger model.” It is that the sequence of experiments produced a clearer understanding of what the model learned, what the benchmark measured, and what remains unproven.
The experiment is organized across four Colab notebooks: (1) model assembly, (2) v5 data preparation, (3) four-stage training/evaluation, and (4) the earlier QLoRA baseline experiment. The supplied v5 training notebook includes logged stage-3 and stage-4 runs, checkpoint comparisons, public-subset results, inference measurements, and decoding ablations. The QLoRA/v1–v4 details described historically in this article come from earlier experiments and require their corresponding notebooks and logs for independent verification.
The v5 notebook writes detailed predictions and scores in results_v5.json; that output and the earlier notebooks should accompany any public reproducibility release. Check dataset access and redistribution permissions before uploading example images or weights.
Figure provenance: Figures 2, 3 and 5 are actual notebook-output images; figures 1, 4, 6, 7 and 8 were created for this article from notebook architecture/settings and recorded metric values; the cover is a conceptual illustration. None of these images are presented as photographs of real documents.
Primary sources:
Tags: Vision-Language Models, Arabic OCR, Custom VLM Training, Multimodal AI, Qwen2.5-VL, Deep Learning, QLoRA Fine-Tuning, Document AI