Home | Login | Register

Building a 1.16B Arabic OCR Vision-Language Model

Learn how I built a 1.16B Arabic-English OCR vision-language model using Qwen, LoRA and four-stage training on a single GPU, including benchmarks and failures.

...
Shweta Gargade

...
Category:

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:

  • On 500 PATS printed-Arabic samples, character error rate (CER) fell from 0.127 for the untuned Qwen2.5-VL-3B baseline to 0.028 for my final model under the same evaluation procedure.
  • In a separate 48-example synthetic Arabic test, CER was 0.024 versus 0.144 for that baseline.
  • On the same L4 benchmark setup, median measured inference time per line was 0.574 seconds versus 0.843 seconds, with peak measured GPU memory of 2.3 GB versus 7.5 GB.
  • On 48 generated evaluation forms, field-level accuracy reached 0.992—but this is not accuracy on real Emirates IDs or invoices, and the JSON evaluator has limitations discussed below.
  • Printed-English recognition didn't improve everywhere: on the separate 48-example English set, the untuned 3B model performed better (0.003 CER vs. 0.011).

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.

1. Why Arabic–English OCR is difficult

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.

2. The architecture: 1.157B parameters, three components

The design uses:

ComponentOriginParametersRole
Vision encoderQwen2.5-VL-3B-Instruct~632MConverts the document image into visual features
Custom projectorNewly constructed, partially warm-started~30.8MMaps vision features to the smaller decoder’s embedding dimension
Language decoderQwen2.5-0.5B-Instruct~494MGenerates 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.

Architecture: Qwen2.5-VL vision encoder, custom projector, and Qwen2.5-0.5B language decoder

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.

3. The failure: lower loss did not mean better OCR

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:

  1. Warm-start the projector from compatible pretrained Qwen weights rather than initializing the entire mapping randomly.
  2. Match visual-embedding scale to the decoder’s text-embedding scale.
  3. Increase alignment data from approximately 3,200 to 30,000 rendered examples and fix an Arabic-Indic numeral rendering issue.

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.

4. Data: rendered text, public handwriting, and synthetic forms

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.

Rendered Arabic and bilingual text samples from the Colab notebook

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.

Synthetic Arabic English form example generated in Colab

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.

5. The four training stages—and what v5 actually retrained

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.

StageGoalTrainable componentsData / scaleStatus in v5
1. Projector alignmentMake vision features understandable to the decoderProjector in full30,000 rendered lines; 3,750 optimizer stepsReused v3 checkpoint
2. Vision adaptationTeach the vision stack general text-reading featuresVision LoRA + projector; decoder frozen25,000 examples; 3,125 stepsReused v3 checkpoint
3. Arabic-focused OCRImprove Arabic, handwriting, mixed text, and English retentionVision LoRA on blocks 0–23, last 8 vision blocks in full, projector, decoder LoRA90,000 examples; 11,250 stepsTrained in v5
4. Forms to JSONLearn structured field extraction while retaining OCRSame component groups as stage 316,000 presentations; 2,000 stepsTrained in v5

Four stages of VLM training with checkpoint reuse and newly trained stages

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.

Training loss and CER plots captured from the Colab notebook

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.

6. How I evaluated the model

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.

Public and held-out-set results

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 setSamplesv5 after stage 4v5 after stage 3v4 after stage 4Untuned Qwen 3B
PATS (printed Arabic)5000.0280.0250.0560.127
SythenAR (diacritized)5000.0920.0950.1310.309
ISI-PPT (slides)5000.0810.0880.1080.294
KHATT (Arabic handwriting)2000.2970.2430.3380.750
OnlineKhatt2000.2300.1640.3300.582
EvArEST (scene text)5000.2000.2230.2770.596
HistoryAr2000.6770.9880.9811.288
ADAB (handwritten words)2000.2420.2330.3151.510
Muharaf (historical handwriting)2000.2040.2100.8380.832
KHATT test split5000.0630.0290.3430.683
Muharaf test split5000.1680.1780.7730.877
IAM English handwriting test5000.0510.0490.0520.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.

Selected CER comparisons between untuned Qwen baseline and custom v5

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.

Controlled synthetic-task and inference comparison

A separate 48-example evaluation gave the following results:

MeasurementUntuned Qwen2.5-VL-3BFinal v5 model
Arabic synthetic lines, CER0.1440.024
Diacritized synthetic lines, CER0.3410.046
Bilingual synthetic lines, CER0.4210.008
English synthetic lines, CER0.0030.011
IAM handwriting lines, CER0.0900.074
Field accuracy on generated forms0.4660.992
Median seconds per line0.8430.574
Median seconds per form4.0862.276
Measured peak inference GPU memory7.5 GB2.3 GB

Inference time and GPU memory comparisons on the same L4

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.

7. The most important finding: a handwriting benchmark can flatter you

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 subsetLinesv5 stage-4 CERv5 stage-3 CERv4 CER
Text overlap found880.040.040.25
No four-word overlap found1120.490.400.41

KHATT CER split by four word overlap with training

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.

8. Stage 4 improved forms but changed the OCR trade-off

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.

9. Decoding settings mattered more than expected

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.

10. What still does not work well enough

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.

11. What I would do next

My priorities are straightforward:

  1. Build a genuine external test set: obtain 100–300 carefully anonymized, permissioned bilingual document images with transcriptions and field labels, and keep them untouched until evaluation.
  2. Tighten form evaluation: require the entire output to parse as JSON, penalize missing or extra keys, calculate exact full-form match, and report errors by field type—not only pooled expected-field accuracy.
  3. Test generalization without repeated passages: use writer-, passage-, and document-disjoint splits where possible; keep the overlap check and report performance separately on flagged and non-flagged material.
  4. Re-score decoding strategies: test repetition controls on every public subset and assess whether they suppress legitimate repeated text.
  5. Evaluate a crop-first pipeline: detect lines or fields, then pass high-resolution crops to the OCR model instead of shrinking a complete page into one image budget.
  6. Run targeted ablations: vary the handwritten-data source, number of fully trained vision blocks, and task-tuning mix one at a time.
  7. Make deployment decisions only after evaluation: compare the stage-3 OCR checkpoint against the stage-4 form checkpoint on the actual application workload, then review licensing before any commercial use.

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.

12. What this project taught me

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.


Reproducibility and references

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


© VisionNLP LLP 2020 - 2026
Created By WEBNext Labs Theme By Amit Kumar Jha