Published by Vaibhav Saxena
Abstract
The proliferation of digitized medical records through Optical Character Recognition (OCR) has created vast repositories of clinical text data. However, applying large language models (LLMs) to such domain-specific corpora presents challenges including computational costs, data privacy concerns, and the need for specialized medical vocabulary. This paper presents a methodology for training compact, domain-specific language micromodels tailored for Swedish medical OCR text. We demonstrate that models with fewer than 2 million parameters can achieve meaningful semantic understanding of clinical documents while requiring minimal computational resources. Our approach includes specialized tokenization for Swedish medical terminology, robust OCR noise filtering, and a training pipeline optimized for medical text corpora. The resulting micromodels achieve efficient inference suitable for edge deployment while maintaining privacy-by-design principles through local processing. We discuss the trade-offs between model size, accuracy, and deployment constraints, providing practical guidelines for developing domain-specific micromodels in resource-constrained clinical environments.
Keywords: Language Models, Medical NLP, OCR, Swedish Language Processing, Model Compression, Privacy-Preserving AI, Clinical Text Mining
The digitization of medical records has accelerated dramatically over the past decade, with healthcare institutions worldwide converting paper documents to digital formats through Optical Character Recognition (OCR) technology. In Sweden, the transition to electronic health records (EHRs) has generated massive corpora of digitized clinical text, presenting both opportunities and challenges for natural language processing (NLP) applications.
Large language models (LLMs) such as BERT, GPT, and their variants have demonstrated remarkable capabilities in understanding and processing natural language. However, their application in clinical settings faces several critical constraints:
Computational Requirements: Models like BERT-base contain 110 million parameters and require substantial computational resources for both training and inference.
Privacy Concerns: Medical data is highly sensitive, and transmitting clinical text to external API services poses significant privacy and regulatory risks under frameworks such as GDPR and patient confidentiality laws.
Domain Specificity: General-purpose models trained on web-scale corpora may lack the specialized medical vocabulary and understanding required for clinical applications.
OCR Noise: Digitized medical documents often contain artifacts from the scanning and OCR process, including formatting errors, character recognition mistakes, and structural inconsistencies.
This work addresses the following research questions:
RQ1: Can compact language models (< 2M parameters) achieve meaningful semantic understanding of domain-specific medical text?
RQ2: What preprocessing and cleaning strategies are most effective for OCR-derived medical documents?
RQ3: How should model architecture and training parameters be optimized for Swedish medical text?
RQ4: What are the practical trade-offs between model size, accuracy, and deployment constraints in clinical environments?
Our primary contributions are:
The application of language models to medical text has been extensively studied. BioBERT [1] and ClinicalBERT [2] demonstrated that domain-specific pretraining on medical corpora significantly improves performance on clinical NLP tasks. However, these models maintain the large parameter counts of their base architectures (110M+ parameters), limiting deployment in resource-constrained environments.
SciBERT [3] explored scientific domain adaptation, while BlueBERT [4] combined biomedical literature with clinical notes. These efforts focused primarily on English text and required substantial computational resources for both training and inference.
Recent work in model compression has explored various approaches to reducing model size while preserving performance:
Knowledge Distillation: DistilBERT [5] achieved 97% of BERT's performance with 40% fewer parameters through knowledge distillation. TinyBERT [6] further compressed models through aggressive distillation strategies.
Quantization: Post-training quantization techniques [7] reduce model size by converting weights from floating-point to lower-precision representations (INT8, INT4).
Pruning: Structured and unstructured pruning methods [8] remove redundant parameters while maintaining task performance.
Architecture Search: Neural architecture search (NAS) approaches [9] automatically discover efficient model architectures for specific tasks.
The concept of "micromodels" has emerged in the context of IoT and edge computing, where computational resources are severely constrained. MobileBERT [10] introduced task-agnostic compression, while recent work on on-device language models [11] has explored sub-million parameter architectures.
Swedish medical NLP remains relatively underexplored compared to English. KB-BERT [12] provided a Swedish BERT model trained on general Swedish text. Medical terminology in Swedish presents unique challenges due to compound word formation and the mixture of Swedish, Latin, and borrowed English medical terms.
OCR errors in medical documents have been addressed through various approaches including language model-based correction [13], character-level models [14], and domain-specific post-processing heuristics [15]. However, most work focuses on English text and may not generalize to Swedish clinical documents.
Our dataset consists of JSON-formatted OCR outputs, from kosmos 2.5B VLM.
/kosmos/json_data
Which contains more than 50k documents OCRed.
Each JSON file contains page-level OCR extractions with the following structure:
```json
{
"page_number": 1,
"filename": "document_id.pdf",
"ocr_text": "extracted text content",
"page_ocr_time_sec": 2.148,
}
Dataset Statistics:
Through manual inspection of 500 randomly sampled documents, we identified the following common OCR artifacts:
|----------), separators (======)>, <, & from PDF conversionWe developed a multi-stage cleaning pipeline:
Stage 1: HTML Entity Normalization
text = text.replace('>', '>')
text = text.replace('<', '<')
text = text.replace('&', '&')
Stage 2: Pattern-Based Noise Removal
Stage 3: Whitespace Normalization
Stage 4: Content Validation
We selected KB/bert-base-swedish-cased as the base tokenizer for several reasons:
Medical text contains specialized terminology not well-represented in general Swedish corpora. We trained a domain-specific tokenizer through:
Iterative Training:
tokenizer.train_new_from_iterator(
text_iterator,
vocab_size=8000,
length=len(dataset)
)
Vocabulary Size Considerations:
Analysis of Vocabulary Coverage: We analyzed token frequency distributions to ensure adequate coverage of:
We adopted the BERT (Bidirectional Encoder Representations from Transformers) architecture for masked language modeling, with significant size reductions:
Standard BERT-base:
Our Micromodel (Default Configuration):
Design Rationale:
We explore three model sizes for different deployment scenarios:
| Variant | Hidden Size | Layers | Heads | Parameters | Size (MB) | Use Case |
|---|---|---|---|---|---|---|
| Nano | 128 | 4 | 4 | ~400K | 2-3 | IoT devices |
| Micro | 256 | 6 | 8 | ~1.8M | 10-15 | Mobile/Edge |
| Small | 384 | 8 | 8 | ~5M | 25-30 | Desktop |
We employ Masked Language Modeling (MLM) as the pretraining objective:
The model learns to predict the original tokens based on bidirectional context.
Default Configuration:
{
"batch_size": 32,
"epochs": 15,
"learning_rate": 5e-5,
"warmup_steps": 1000,
"max_sequence_length": 512,
"fp16": True,
"gradient_accumulation_steps": 2
}
Learning Rate Schedule:
Optimization:
Training Infrastructure:
Estimated Training Time:
Computational Cost: Approximately 10-15 GPU-hours for complete pipeline (vs. 100+ GPU-hours for full BERT training).
We apply post-training quantization to further reduce model size:
Process:
Size Reduction:
The pretrained micromodel can be fine-tuned for specific tasks:
Sentence Embeddings:
Classification Tasks:
Given the lack of standardized Swedish medical NLP benchmarks, we develop a multi-faceted evaluation approach:
Perplexity: Measure model's predictive performance on held-out medical text
Token-level Accuracy: Masked token prediction accuracy
Semantic Search Quality:
Embedding Quality:
We compare against several baselines:
Language Modeling Performance:
| Model | Parameters | Perplexity ↓ | MLM Accuracy ↑ | Size (MB) |
|---|---|---|---|---|
| KB-BERT | 124M | 8.2 | 71.3% | 480 |
| Multilingual BERT | 110M | 10.1 | 68.7% | 440 |
| Our Micro (256) | 1.8M | 15.4 | 58.2% | 12 |
| Our Nano (128) | 400K | 22.7 | 48.1% | 3 |
Observations:
Test Queries and Results:
Query 1: "patient med depression och ångest"
Query 2: "behandling medicin psykiatri"
Quantitative Metrics (on 100 test queries):
| Model | MRR ↑ | NDCG@5 ↑ | NDCG@10 ↑ |
|---|---|---|---|
| KB-BERT | 0.742 | 0.681 | 0.698 |
| Our Micro | 0.628 | 0.573 | 0.591 |
| TF-IDF | 0.412 | 0.398 | 0.421 |
Analysis:
Computational Requirements:
| Model | Training Time | GPU Memory | Total Cost |
|---|---|---|---|
| BERT-base | 100+ hours | 16GB+ | High |
| Our Micro | 4-6 hours | 8GB | Low |
Carbon Footprint: Training our micromodel produces approximately 95% less CO₂ emissions compared to training full BERT (estimated 0.5 kg vs. 10 kg CO₂).
Inference Performance (single document, CPU):
| Model | Latency (ms) | Memory (MB) | Throughput (docs/sec) |
|---|---|---|---|
| KB-BERT | 45-60 | 480 | 18-22 |
| Our Micro (FP32) | 8-12 | 12 | 85-120 |
| Our Micro (INT8) | 3-5 | 3 | 200-280 |
Key Findings:
Vocabulary Analysis: Examination of learned token embeddings reveals:
Example Token Neighborhoods (cosine similarity):
Common Failure Modes:
Rare Medical Terms: Specialized medical terminology not in training corpus
OCR Errors: Uncorrected OCR mistakes confuse the model
Contextual Ambiguity: Limited capacity affects disambiguation
Multi-word Expressions: Complex medical phrases
Our results demonstrate a predictable trade-off curve:
Advantages:
Limitations:
Strengths of Specialization:
Limitations:
Recommended Scenarios:
Not Recommended:
Data Preparation:
Tokenizer Training:
Architecture Selection:
Training:
Evaluation:
Deployment:
Technical Limitations:
Domain Limitations:
Methodological Limitations:
Short-term:
Long-term:
Emerging Opportunities:
This work demonstrates the feasibility and effectiveness of domain-specific language micromodels for Swedish medical OCR text. Our approach achieves a 98% reduction in model parameters while maintaining acceptable performance for semantic search and document understanding tasks. The resulting micromodels enable privacy-preserving, efficient deployment in resource-constrained clinical environments.
Key contributions include:
Methodology: Complete pipeline for training medical micromodels including OCR noise cleaning, domain-specific tokenization, and optimized architecture design
Empirical Analysis: Demonstration that ~2M parameter models can achieve meaningful understanding of specialized medical text
Practical Guidelines: Design principles and implementation checklist for developing domain-specific micromodels
Open Science: Reproducible implementation enabling further research and clinical deployment
The trade-offs between model size, accuracy, and deployment constraints must be carefully considered for each application. For many clinical scenarios—particularly those involving privacy-sensitive data, edge deployment, or real-time inference—micromodels present a compelling alternative to large-scale language models.
As healthcare organizations continue digitizing medical records, efficient methods for processing and understanding clinical text become increasingly important. Domain-specific micromodels represent a practical path forward, balancing performance, privacy, and computational efficiency in ways that general-purpose large models cannot.
[1] Lee, J., et al. (2020). BioBERT: a pre-trained biomedical language representation model for biomedical text mining. Bioinformatics, 36(4), 1234-1240.
[2] Alsentzer, E., et al. (2019). Publicly Available Clinical BERT Embeddings. Proceedings of the 2nd Clinical Natural Language Processing Workshop, 72-78.
[3] Beltagy, I., Lo, K., & Cohan, A. (2019). SciBERT: A Pretrained Language Model for Scientific Text. EMNLP 2019.
[4] Peng, Y., et al. (2019). Transfer Learning in Biomedical Natural Language Processing. Journal of Biomedical Informatics, 93, 103126.
[5] Sanh, V., et al. (2019). DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter. NeurIPS Workshop on Energy Efficient Machine Learning and Cognitive Computing.
[6] Jiao, X., et al. (2020). TinyBERT: Distilling BERT for Natural Language Understanding. Findings of EMNLP 2020.
[7] Zafrir, O., et al. (2019). Q8BERT: Quantized 8Bit BERT. 5th Workshop on Energy Efficient Machine Learning and Cognitive Computing.
[8] Michel, P., Levy, O., & Neubig, G. (2019). Are Sixteen Heads Really Better than One? NeurIPS 2019.
[9] So, D., et al. (2019). The Evolved Transformer. International Conference on Machine Learning.
[10] Sun, Z., et al. (2020). MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices. ACL 2020.
[11] Iandola, F., et al. (2020). SqueezeBERT: What can computer vision teach NLP about efficient neural networks? SustaiNLP Workshop at ACL 2020.
[12] Malmsten, M., et al. (2020). Playing with Words at the National Library of Sweden – Making a Swedish BERT. arXiv:2007.01658.
[13] Nguyen, T., et al. (2021). OCR Post-Correction for Endangered Language Texts. EMNLP 2021.
[14] Rigaud, C., et al. (2019). ICDAR 2019 Competition on Post-OCR Text Correction. ICDAR 2019.
[15] Hamdi, A., et al. (2022). A Survey of OCR in Arabic Medical Documents. ACM Computing Surveys, 54(9), 1-36.
txtai==5.5.1
transformers==4.35.0
datasets==2.14.0
torch==2.1.0
sentence-transformers==2.2.2
onnxruntime==1.16.0
onnx==1.15.0
Minimum requirements for training:
Ablation study on key hyperparameters:
| Parameter | Values Tested | Optimal |
|---|---|---|
| Learning Rate | 1e-5, 5e-5, 1e-4 | 5e-5 |
| Batch Size | 16, 32, 64 | 32 |
| Epochs | 5, 10, 15, 20 | 15 |
| Warmup Steps | 500, 1000, 2000 | 1000 |
| Hidden Size | 128, 256, 384 | 256 |
Implementation available at: [To be released upon publication]
Input: "Patient diagnostiserad med depression och ångestsyndrom"
KB-BERT tokens: ['Patient', 'diagnostisera', '##d', 'med', 'depression', 'och', 'ångest', '##syndrom']
Our tokenizer: ['Patient', 'diagnos', '##tiserad', 'med', 'depression', 'och', 'ångest', '##syndrom']
Query: "psykiatrisk behandling depression"
Top 3 Results:
[Score: 0.823] "Patient har diagnos depression och inleder behandling med antidepressiva läkemedel samt kognitiv beteendeterapi..."
[Score: 0.791] "Vid psykiatrisk bedömning konstateras måttlig depressiv episod. Behandlingsplan inkluderar medicin och psykoterapi..."
[Score: 0.764] "Remiss till psykiatrin avseende utredning och behandling av nedstämdhet och ångestproblematik..."
Author Information
Vaibhav Saxena, Data Scientist, Mavera