Image to LaTeX Converter: Project Report

A deep learning-based system for converting images of mathematical expressions into LaTeX code, addressing challenges in digital document processing and enhancing accessibility of mathematical content.

Exact Match
21.9%
BLEU Score (generated)
0.790
Edit Distance
0.178
Best Epoch
14

Introduction

The Image to LaTeX (img2latex) project implements a deep learning-based system for converting images of mathematical expressions into LaTeX code. This technology addresses a significant challenge in digital document processing: transforming visual representations of mathematical formulas into their corresponding markup representation, which is essential for editing, searching, and accessibility.

Mathematical expressions are ubiquitous in scientific, engineering, and academic literature, but transferring them between different formats can be cumbersome. Traditional Optical Character Recognition (OCR) systems often struggle with the complex two-dimensional structure of mathematical formulas. The img2latex project provides an end-to-end solution to automatically recognize and transcribe mathematical expressions from images, significantly reducing the manual effort required for digitizing printed mathematical content.

The system uses a spatial CNN encoder that keeps the formula as a 2D feature grid, then a Transformer decoder that attends over that grid with a padding mask. Validation BLEU, exact match, and edit distance are computed from autoregressive generation, not teacher-forced token accuracy.

Data Analysis

Dataset Overview

The img2latex system uses the IM2LaTeX-100k dataset, which contains over 100,000 images of mathematical expressions paired with their corresponding LaTeX code. Our analysis of the dataset revealed:

Total Images 103,536
Mean Width 319.2 px
Mean Height 61.2 px
Mean Aspect Ratio 5.79
Most Common Size 320×64 px
Color Mode RGB (100%)
Image Size Distribution

Image Properties

  • Width range: 128 - 800 pixels
  • Height range: 32 - 800 pixels
  • Aspect ratio range: 1.00 - 15.00
  • File format: All images are RGB
  • Pixel value range: 0.0 - 255.0 (uint8)
  • Mean pixel value: 242.22
  • Std dev of pixel values: 45.70
Pixel Value Distribution

Preprocessing Strategy

Based on this analysis, our preprocessing pipeline includes:

  • Scale-to-fit: Each image is scaled to fit a 64×512 canvas without cropping, then padded with white on the right and bottom
  • Padding mask: Valid width and height are stored so the decoder cannot attend to empty canvas
  • Channel Conversion:
    • CNN encoder: grayscale (1 channel)
    • ResNet encoder: RGB (3 channels)
  • Cache: A one-time uint8 memmap of unique processed images avoids repeating decode and resize during training
  • Normalization: Pixel values are scaled to [0, 1]

The tokenizer is fit on the train split only with min_freq=5, then sequences are truncated at 141 tokens. Batches are length-bucketed so padding waste stays low.

Model Architecture

Architecture Overview

The img2latex system offers two encoder variants that share the same Transformer decoder:

1. CNN-Transformer Architecture

The default model (~4.45M parameters) consists of:

  • Encoder: Three Conv-BN-ReLU-MaxPool blocks (filters 32, 64, 128) downsample the 64×512 image by 8×. A 1×1 convolution projects to d_model=256, then 2D sinusoidal positional encoding is added. The result is a spatial grid of 8×64 = 512 memory tokens plus a padding mask for empty canvas.
  • Decoder: A 4-layer pre-norm Transformer decoder (8 heads, feedforward 1024, tied embeddings) with a boolean causal mask. Cross-attention reads the encoder grid, not a single collapsed vector.

2. ResNet-Transformer Architecture

The optional ResNet encoder replaces the CNN while keeping the same decoder:

  • Encoder: ResNet-18 with the classification head and avg-pool removed (children()[:-2]). layer4 stride is set to 1 so the feature map stays a spatial grid (~/16) instead of collapsing to one vector.
  • Decoder: The same Transformer decoder as the CNN model.

The previous CNN-LSTM / ResNet-LSTM stack collapsed each image to a single vector, so attention was a no-op. That, plus teacher-forced BLEU, is why the old report sat at 0.15 BLEU.

Training Process

Training Methodology

The training process implements several key strategies:

Optimization Setup

  • Optimizer: AdamW, learning rate 3e-4, weight decay 1e-4
  • Learning Rate Scheduling: Linear warmup for 5% of steps, then cosine decay
  • Loss Function: Cross-entropy with label smoothing (0.1), pad ignored

Training Techniques

  • Teacher Forcing: Used only for the training loss. Validation BLEU is computed from autoregressive generation on a fixed 256-sample subset
  • Gradient Clipping: Norm-based clipping at 1.0
  • Early Stopping: Stops after 8 epochs without a validation BLEU improvement
  • Checkpointing: Best checkpoint is selected on validation BLEU, not validation loss

Hardware Acceleration

  • Device Support: MPS on Apple Silicon (this run), CUDA, or CPU fallback
  • Precision: fp32 on MPS (no GradScaler). Mixed precision is available on CUDA only
  • DataLoader: num_workers=0 on macOS to avoid OpenMP / libomp collisions with PyTorch MPS

Inference Methods

Decoding Strategies

During inference, the model offers greedy decoding and batched beam search:

  1. Greedy Search: Selects the most probable token at each step. Used for validation BLEU so scores stay comparable across epochs
  2. Beam Search: Batched beam search with GNMT length penalty (beam size 5, length penalty 0.7). This is the default for the predictor CLI

Beam search is enabled in the predictor (it was previously short-circuited). Reported validation BLEU in this report uses greedy decode on 256 validation samples so the metric matches the checkpoint-selection criterion.

Results

Experimental Setup

Experiments used the CNN-Transformer on Apple Silicon MPS. Checkpoints are selected on validation BLEU from autoregressive generation, not teacher-forced token accuracy. Key configuration:

Model Type
CNN-Transformer
Image Dimensions
64 × 512 pixels
Batch Size
64
Learning Rate
3e-4 (AdamW)
Weight Decay
0.0001
Max Sequence Length
141
Embedding Dimension
256
Decoder
4 layers, 8 heads

Evaluation Metrics

Reported scores come from generated token sequences (greedy decode, 256 validation samples):

  1. BLEU-4: Smoothed corpus BLEU (nltk method3)
  2. Exact match: Generated tokens equal the reference after stripping START/END/PAD
  3. Normalized edit distance: Mean Levenshtein / max(len); lower is better
  4. Token accuracy: Teacher-forced diagnostic only; not used for checkpoint selection

Performance Results

Best checkpoint is epoch 14 of a 30-epoch schedule (img2latex_transformer_v1). BLEU is autoregressive. The legacy CNN-LSTM report of 0.1539 BLEU was teacher-forced and is not comparable.

Accuracy Curves
Epoch Val Loss TF Acc BLEU Exact Match Edit Dist
1 2.9760 0.4773 0.1165 0.0% 0.7295
5 1.5380 0.8461 0.6376 5.5% 0.2848
10 1.3741 0.8924 0.7508 15.2% 0.2093
14 1.2730 0.9152 0.7896 21.9% 0.1778
18 1.3295 0.9065 0.7880 21.1% 0.1770

Comparison to the Legacy LSTM

The previous CNN-LSTM / ResNet-LSTM numbers were teacher-forced and used encoders that collapsed the image to a single vector:

  • CNN-Transformer (this run): generated BLEU 0.790, exact match 21.9%, edit distance 0.178 (epoch 14)
  • Legacy CNN-LSTM (img2latex_v2): teacher-forced accuracy 62.56% and BLEU 0.1539; no checkpoint remained in the repo to re-score honestly
  • Spatial features plus a Transformer decoder moved generated BLEU from ~0.15 to ~0.79 in 14 epochs on MPS
BLEU Score Trends

Error Analysis

Common error patterns included:

  • Missing or incorrect brackets in nested expressions
  • Confusion between similar-looking symbols (e.g., 1/l, 0/O)
  • Incomplete transcription of complex subscripts and superscripts

Sample generations on a long nested integral show the remaining failure mode: the model recovers the overall structure (integrals, deltas, fractions) but still drops primes, confuses \mathrm{e} with \operatorname{e}, and loses subscripts inside nested fractions.

Key Insights

Analysis of our experiments revealed several important findings that inform future development directions.

Performance Progression: Generated BLEU rose from 0.117 at epoch 1 to 0.790 at epoch 14. Exact match went from 0% to 21.9% over the same span. After epoch 14 the run plateaued around 0.78–0.79 BLEU.
Architecture Comparison: Keeping a spatial feature grid and using a Transformer decoder is what moved generated BLEU from the legacy 0.15 (teacher-forced, collapsed encoder) to 0.79. The optional ResNet-Transformer config is available but was not the primary run.
Error Patterns: Analysis revealed specific challenges with complex nested expressions, similar-looking mathematical symbols, and multi-level subscripts/superscripts that suggest targeted improvements to the model architecture.
Decoding Strategy Impact: Validation BLEU uses greedy decode so checkpoint selection stays stable. Batched beam search with GNMT length penalty (beam size 5) is the predictor default for inference.
Complexity Correlation: Long nested formulas remain the main gap. Exact match is 21.9% while BLEU is 0.79, which means many predictions are close token sequences rather than letter-perfect LaTeX.

Conclusion

The img2latex project converts printed math images to LaTeX with a spatial CNN encoder and a Transformer decoder. On IM2LaTeX-100k, the best checkpoint (epoch 14, Apple Silicon MPS) reaches generated BLEU 0.790, exact match 21.9%, and normalized edit distance 0.178.

Key achievements of the revision include:

  1. Honest evaluation: corpus BLEU, exact match, and edit distance from autoregressive generation
  2. A spatial encoder grid with a real padding mask instead of a collapsed image vector
  3. Batched beam search with length normalization, enabled in the predictor
  4. A 64×512 scale-to-fit pipeline, train-only tokenizer, image cache, and length-bucketed batches
  5. AdamW with warmup plus cosine decay, trained in fp32 on MPS

Remaining gaps are mostly long nested formulas and rare symbols. The model still confuses similar glyphs and occasionally drops subscripts. Beam search at inference and a larger decoder would be the next levers; the Transformer rewrite already replaced the LSTM path that was planned as future work.

Future work could focus on:

  1. Scoring the full validation set with beam search, not just a 256-sample greedy subset
  2. A larger Transformer (more layers / heads) or the ResNet-Transformer variant
  3. Covering rare tokens that fall below min_freq=5
  4. Post-processing for common LaTeX bracket and delimiter errors

The img2latex system is a working image-to-LaTeX converter with metrics that match what the decoder actually emits at inference time.

Overall Assessment

The CNN-Transformer reaches generated BLEU 0.790 and exact match 21.9% at epoch 14, versus the legacy teacher-forced BLEU of 0.1539. Spatial features and honest autoregressive metrics were the difference. Remaining errors concentrate on nested structure and rare symbols rather than a collapsed encoder.

Example Visualizations

Formula Image Grid

Sample images from the IM2LaTeX-100k dataset showing various mathematical expressions.

Performance Metrics

Composite Metrics

Visualization of multiple performance metrics across training epochs, showing consistent improvement.

View on GitHub