Scaling Clinical Handwriting OCR with TorchTPU

machine-learning
computer-vision
deep-learning
implementation
pytorch
torchtpu
research-notes
Porting PP-OCRv6 to native PyTorch with token-for-token numerical parity, fine-tuning on RxHandBD with mixed-precision bfloat16 across Apple Silicon MPS and Google Cloud TPUs via TorchTPU, and reaching zero-shot Gemini-3.8-Flash accuracy at local edge latency.
Author

Muhammad Ghifary

Published

November 29, 2026

In the previous article, I shared how to port Baidu’s PP-OCRv6_medium_rec (~34.5M parameters) from PaddlePaddle to JAX/Flax NNX and fine-tune it on handwritten clinical prescriptions using TPUs. Three constraints drove that architecture choice: Protected Health Information (PHI) rules that keep patient records off external cloud APIs, tight edge-compute budgets, and the risk of Vision-Language Models (VLMs) hallucinating medication names.

Here, I follow the same OCR fine-tuning strategy while shifting the stack from JAX on TPU to TorchTPU—running native PyTorch on Google Cloud TPUs alongside local CPU and Apple Silicon MPS prototyping. The practical question is straightforward: can one static-shape PyTorch codebase match reference PP-OCRv6_medium_rec outputs token-for-token, train locally on CPU or Apple Silicon MPS, and scale to Cloud TPUs via torch_tpu without rewriting the training loop?

On RxHandBD (3,794 train / 669 validation crops), one PyTorch codebase handles all three. With a 40-epoch, batch-size-64 mixed-precision bfloat16 recipe, the same loop finishes locally on an Apple M4 Pro (MPS) in 44.01 minutes and scales to a Cloud TPU v6e-1 in 4.16 minutes, cutting validation Character Error Rate (CER) from 32.61% to 11–12% and beating zero-shot gemini-3.8-flash on held-out accuracy at ~256× higher throughput.

The full porting and fine-tuning code is available at github.com/ghif/ocrtorch.

PyTorch and TorchTPU: One Codebase from Laptop to Cloud

PyTorch’s main draw for applied ML work is its unified execution model: you write standard Pythonic tensor code, debug interactively in eager mode, and target CPUs, NVIDIA GPUs, or Apple Silicon GPUs (MPS) by changing a device string.

Until recently, Google Cloud TPUs were the exception. Targeting TPUs from PyTorch meant adopting torch_xla: a lazy-tensor wrapper that required xm.xla_device(), explicit xm.mark_step() graph barriers, and careful refactoring to avoid silent CPU fallbacks. Maintaining both standard PyTorch for a MacBook and torch_xla for Cloud TPUs added real engineering friction.

Announced in late 2026 by Google and Meta, TorchTPU (torch_tpu) [4] replaces that wrapper model with a native PyTorch backend. Rather than intercepting tensors through a separate lazy-execution layer, torch_tpu plugs directly into the PyTorch dispatcher, giving TPUs first-class device status (torch.device("tpu")) alongside "cpu", "cuda", and "mps":

import torch
import torch_tpu  # Registers the "tpu" backend with the PyTorch dispatcher

device = torch.device("tpu")

Figure 1 contrasts the legacy torch_xla wrapper path with TorchTPU’s native dispatcher integration.

%%{init: {
  'theme': 'base',
  'themeVariables': {
    'darkMode': true,
    'background': '#0a0c10',
    'primaryTextColor': '#f3f4f6',
    'lineColor': '#8b949e',
    'edgeLabelBackground': '#161b22',
    'clusterBkg': '#0f1218',
    'clusterBorder': '#30363d',
    'fontSize': '14px'
  }
}}%%
flowchart TB
    classDef app fill:#161b22,stroke:#475569,stroke-width:1.5px,color:#f3f4f6;
    classDef legacy fill:#241418,stroke:#b91c1c,stroke-width:1.5px,color:#fecaca;
    classDef native fill:#0f2419,stroke:#238636,stroke-width:1.5px,color:#bbf7d0;
    classDef hw fill:#101d2e,stroke:#58a6ff,stroke-width:1.5px,color:#dbeafe;

    TR["PyTorch Training Loop<br/>(Standard forward / backward / AdamW)"]:::app

    subgraph LEGACY["Legacy Path: torch_xla"]
        direction TB
        L1["xm.xla_device() + Lazy Tensors"]:::legacy --> L2["Explicit xm.mark_step() Barriers"]:::legacy
    end

    subgraph NATIVE["Unified PyTorch Dispatcher"]
        direction TB
        D["torch.device(device_type)"]:::native
        D -->|"cpu"| C1["CPU Kernels"]:::hw
        D -->|"mps"| M1["Apple Metal GPU<br/>+ CPU CTC Bridge"]:::hw
        D -->|"tpu (torch_tpu)"| T1["TorchTPU Backend<br/>ATen Kernels + StableHLO / XLA"]:::native
        T1 --> T2["Google Cloud TPU (v5e1 / v6e-1)"]:::hw
    end

    TR -. "Requires code changes" .-> LEGACY
    TR -->|"Same training code"| NATIVE

    style LEGACY fill:#161114,stroke:#7f1d1d,stroke-width:1.25px,color:#fca5a5
    style NATIVE fill:#0f1218,stroke:#30363d,stroke-width:1.5px,color:#f3f4f6

Figure 1: Legacy torch_xla lazy-tensor workflow versus TorchTPU’s native PyTorch dispatcher integration alongside CPU and Apple Silicon MPS.

Inside PP-OCRv6 and Porting Without Drift

PP-OCRv6_medium_rec [2] (~34.5M parameters) maps a fixed-size cropped line image \(X \in \mathbb{R}^{B \times 3 \times 48 \times 320}\) to frame-level character logits \(Z \in \mathbb{R}^{B \times 40 \times 18710}\) across \(T=40\) time steps and \(V=18{,}710\) classes (18,709 characters plus CTC blank ID 0). As shown in Figure 2, it has three stages:

%%{init: {
  'theme': 'base',
  'themeVariables': {
    'darkMode': true,
    'background': '#0a0c10',
    'primaryTextColor': '#f3f4f6',
    'lineColor': '#8b949e',
    'edgeLabelBackground': '#161b22',
    'fontSize': '14px'
  }
}}%%
flowchart LR
    classDef input fill:#161b22,stroke:#475569,stroke-width:1.5px,color:#f3f4f6;
    classDef backbone fill:#101d2e,stroke:#58a6ff,stroke-width:1.5px,color:#dbeafe;
    classDef neck fill:#1a162b,stroke:#8b5cf6,stroke-width:1.5px,color:#ede9fe;
    classDef head fill:#231a10,stroke:#d97706,stroke-width:1.5px,color:#fde68a;
    classDef loss fill:#0f2419,stroke:#238636,stroke-width:2px,color:#bbf7d0;

    IN["Input Tensor<br/>[B, 3, 48, 320]"]:::input --> BB["PPLCNetV4 Backbone<br/>RepDW + SE + Pool<br/>→ [B, 768, 1, 40]"]:::backbone
    BB --> NK["LightSVTR Neck<br/>1×7 Local Conv + 2× Attention<br/>+ LayerNorm → [B, 192, 1, 40]"]:::neck
    NK --> HD["Linear CTC Head<br/>192 → 18,710 classes<br/>Logits: [B, 40, 18710]"]:::head
    HD --> LS["CTC Loss<br/>Static T=40 Alignment"]:::loss

Figure 2: End-to-end architecture and tensor shape progression of PP-OCRv6_medium_rec.

  • Visual Backbone (PPLCNetV4): Early stem layers downsample both axes (\(48 \times 320 \to 12 \times 80\)), whereas deeper stages stride only vertically ((2, 1)), preserving horizontal resolution (\(80 \to 40\) steps after pooling) so adjacent handwritten letters do not smear together. Residual blocks combine reparameterizable depthwise convolutions (RepDW), SqueezeExcite channel attention, and \(1 \times 1\) GELU projections.
  • Sequence Neck (LightSVTR): Projects channels from \(768 \to 192\), applies a \(1 \times 7\) depthwise SiLU convolution for local stroke continuity, and runs two multi-head self-attention blocks (8 heads, head dimension 24, MLP ratio 4.0) over \(T=40\) steps with a residual projection.
  • CTC Head (nn.Linear): A single \(192 \to 18{,}710\) linear projection (~3.59M parameters), whose wide vocabulary matrix drives a large share of memory traffic during backpropagation.

1. Direct PaddleOCR-to-PyTorch Conversion

ocrtorch converts weights directly from the official PaddleOCR 3.x PIR inference artifacts (inference.json and inference.pdiparams) in pure Python and NumPy, without requiring a paddlepaddle runtime installation. load_paddle_pir_params reads the parameter names and shapes from inference.json and unpacks the 161 float32 tensors sequentially from inference.pdiparams.

Mapping those 161 Paddle tensors into PyTorch’s 407-tensor state_dict relies on three rules:

  • Native OIHW convolutions, IO → OI linears: PaddlePaddle already stores 4D convolution kernels in PyTorch’s OIHW layout, so convolutions copy directly without axis permutation. Only 2D linear weights (qkv, proj, fc1, fc2, and ctc) transpose from IO to OI (w.T).
  • Unfusing backbone ConvBN and RepDW blocks: Paddle’s inference graph folds each backbone ConvBN and RepDW block into a single biased convolution (conv2d_73..130). To preserve the explicit BatchNorm2d and residual skip structure needed for fine-tuning, those BatchNorm2d nodes are initialized to the identity transform (\(\gamma = 1, \beta = 0, \mu = 0, \sigma^2 = 1 - 10^{-5}\)) and subtract 1.0 from the center weight of each fused \(3 \times 3\) RepDW kernel to account for RepDWConv’s explicit identity_bn skip connection.
  • Unfused neck and attention layers: The LightSVTR neck convolutions (conv2d_70..72) keep their separate batch_norm2d_58..60 statistics (w_0, b_0, w_1, w_2), alongside layer_norm_0..4 and linear_0..8.
# Paddle PIR -> PyTorch weight mapping
kernel = arrays[f"conv2d_{layer}.w_0"].copy()  # Already OIHW: [C, 1, 3, 3]
kernel[:, 0, 1, 1] -= 1.0                     # Preserve explicit RepDW identity skip
mapped[f"{prefix}.branch3.conv.weight"] = torch.from_numpy(kernel)
mapped[f"neck.blocks.{block}.{name}.weight"] = torch.from_numpy(arrays[f"linear_{l}.w_0"].T)

2. Asymmetric Even-Kernel Padding & Valid Pooling

Weight parity alone is not enough—several operator and preprocessing differences between PaddleOCR and PyTorch defaults will silently drift activations across 50+ layers if left unhandled:

  • Asymmetric \(2 \times 2\) "same" padding: In StemBlock (stem2a, stem2b, and max-pooling), Paddle applies right/bottom (0, 1, 0, 1) padding for even \(2 \times 2\) kernels. In PyTorch, ConvBN and StemBlock apply F.pad explicitly (with -inf before max_pool2d):
# Asymmetric padding in StemBlock & ConvBN
if self.use_custom_even_padding:
    x = F.pad(x, (0, 1, 0, 1))
x = self.conv(x)

# In StemBlock.forward():
x2 = self.stem2b(self.stem2a(x))
x1 = F.max_pool2d(F.pad(x, (0, 1, 0, 1), value=-float("inf")), kernel_size=2, stride=1)
  • Valid-window \(3 \times 2\) average pooling: During evaluation, PPLCNetV4Rec slices the feature map to exact valid (kh=3, kw=2) windows rather than using AvgPool2d boundary padding; during training, it uses F.adaptive_avg_pool2d(x, (1, 40)) to guarantee a static \(T = 40\) sequence length:
def avg_pool_valid(x: torch.Tensor, kh: int = 3, kw: int = 2) -> torch.Tensor:
    b, c, h, w = x.shape
    oh, ow = (h - kh) // kh + 1, (w - kw) // kw + 1
    x = x[:, :, :oh * kh, :ow * kw].reshape(b, c, oh, kh, ow, kw)
    return x.mean(dim=(3, 5))

3. RepDWConv, Hard-Sigmoid SE, and LightSVTR Dtype Safety

Residual backbone blocks (LCNetV4Block) use RepDWConv (summing a \(3 \times 3\) depthwise ConvBN, a \(1 \times 1\) depthwise conv, and an identity skip into identity_bn) and SqueezeExcite with Paddle’s hard-sigmoid (torch.clamp((scale + 3.0) / 6.0, 0.0, 1.0)). In LightSVTR, BatchNorm2d and AttentionBlock LayerNorm layers use eps=1e-5, while the final LightSVTR.norm uses eps=1e-6. To prevent mixed-dtype StableHLO lowering errors under torch_tpu bfloat16 autocast, AttentionBlock and LightSVTR also cast LayerNorm inputs to weight.dtype (float32) and attention probabilities to v.dtype (bfloat16):

# RepDWConv & AttentionBlock dtype handling
class RepDWConv(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.identity_bn(self.branch3(x) + self.branch1(x) + x)

# Inside AttentionBlock.forward():
norm1_x = self.norm1(x.to(self.norm1.weight.dtype))
...
attn = F.softmax(attn.float(), dim=-1).to(v.dtype)

4. BGR Input Preprocessing Contract

Finally, the input preprocessing pipeline matches PaddleOCR’s DecodeImage + RecResizeImg contract: converting RGB PIL images to BGR (rgb[:, :, ::-1]), bilinearly resizing to height 48 px while preserving aspect ratio (clamped at 320 px), right zero-padding onto a [48, 320, 3] canvas, and normalizing to [-1, 1] before transposing to CHW:

# BGR preprocessing & aspect-ratio resize
image = np.asarray(image.convert("RGB"))[:, :, ::-1]  # PaddleOCR uses BGR
resized_w = min(image_width, max(1, int(np.ceil(image_height * w / h))))
resized = Image.fromarray(image.astype(np.uint8)).resize((resized_w, image_height), Image.Resampling.BILINEAR)
canvas = np.zeros((image_height, image_width, 3), dtype=np.float32)
canvas[:, :resized_w] = np.asarray(resized, dtype=np.float32)
canvas = (canvas / 255.0 - 0.5) / 0.5
chw = np.transpose(canvas, (2, 0, 1))

Evaluating all 16 intermediate stages in float32 confirms numerical parity within \(\max |\Delta| < 10^{-4}\) and 40 / 40 (100.00%) greedy argmax token agreement (Table 1).

Stage Output Shape Max Absolute Diff Mean Absolute Diff
backbone_stem [1, 128, 12, 80] \(4.00 \times 10^{-5}\) \(8.89 \times 10^{-7}\)
backbone_blocks5 [1, 768, 3, 80] \(5.26 \times 10^{-5}\) \(2.14 \times 10^{-6}\)
backbone_pool [1, 768, 1, 40] \(2.71 \times 10^{-5}\) \(1.69 \times 10^{-6}\)
neck_block_1 [1, 40, 192] \(1.95 \times 10^{-5}\) \(3.42 \times 10^{-6}\)
ctc_logits [1, 40, 18710] \(8.42 \times 10^{-5}\) \(6.49 \times 10^{-6}\)
probabilities [1, 40, 18710] \(2.90 \times 10^{-5}\) \(1.08 \times 10^{-9}\)
Argmax Token Agreement 40 / 40 steps — 100.00%

Table 1: Numerical parity verification across key stages of the PyTorch PP-OCRv6_medium_rec port.

5. Apple Silicon MPS Exception: Offloading aten::_ctc_loss to CPU

While CPU and TorchTPU execute the full forward-and-loss graph on a single device, Apple Silicon MPS mode is an exception: PyTorch 2.10.0 does not yet implement aten::_ctc_loss on MPS. Rather than falling back to CPU for the entire network, the CTCLossStep wrapper moves only log_probs, targets, input_lengths, and target_lengths to CPU for nn.CTCLoss and returns the scalar loss to MPS, keeping all convolutional and attention backpropagation on the Metal GPU.

Zero-Shot Baseline: Why Pretrained OCR and Frontier VLMs Need Fine-Tuning

First, how well do out-of-the-box models read RxHandBD [5], a dataset of pre-cropped handwritten prescription word images (128 × 128 px RGB crops). Its labeled training pool (Train_Label.csv, 4,463 crops) is partitioned 85%/15% into 3,794 training and 669 validation crops, while 1,115 disjoint crops (Test_Labels.csv) are held out strictly for final evaluation. As Figure 3 illustrates, RxHandBD combines cramped cursive drug names, hyphens, and numeric dosages with high inter-writer stroke variability.

Figure 3: Representative RxHandBD held-out test crops (128 × 128 px) paired with their ground-truth handwriting labels.

Two zero-shot baselines were evaluated on the 1,115-crop Held-Out Test Set: PP-OCRv6_medium_rec locally on Apple M4 Pro MPS (batch_size=64), and gemini-3.8-flash (temperature=0.0, thinking_level="LOW", max_output_tokens=4096, 12 concurrent cloud workers via Google AI Studio). For comparison with fine-tuned validation checkpoints, the same gemini-3.8-flash setup was also run on the 669-crop Validation Split.

Across all evaluations, four corpus-level OCR metrics are reported. Let \(r_i\) and \(y_i\) denote the raw reference and predicted transcripts for crop \(i\), and let \(\tilde{r}_i, \tilde{y}_i\) denote their case-folded, whitespace-collapsed forms (normalize_text):

  • Raw Exact Match (Raw EM): Fraction of crops with exact character-for-character equality (\(r_i = y_i\)).
  • Normalized Exact Match (Norm EM): Fraction of crops matching after case-folding and whitespace normalization (\(\tilde{r}_i = \tilde{y}_i\)).
  • Character Error Rate (CER ↓): Corpus character Levenshtein edit distance \(d_{\text{edit}}\) divided by total normalized reference characters.
  • Word Accuracy (1 - WER ↑): Corpus word-level accuracy computed from whitespace-delimited token edit distance on normalized transcripts:

\[\text{CER} = \frac{\sum_{i=1}^{N} d_{\text{edit}}(\tilde{r}_i, \tilde{y}_i)}{\sum_{i=1}^{N} |\tilde{r}_i|}, \qquad \text{NormEM} = \frac{1}{N} \sum_{i=1}^{N} \mathbb{I}(\tilde{r}_i = \tilde{y}_i), \qquad \text{WordAcc} = 1 - \frac{\sum_{i=1}^{N} d_{\text{edit}}(\text{words}(\tilde{r}_i), \text{words}(\tilde{y}_i))}{\sum_{i=1}^{N} |\text{words}(\tilde{r}_i)|}\]

Model Deployment / Footprint Raw EM Norm EM CER ↓ Word Acc (1 - WER) ↑ Latency / Crop Throughput (N=1,115)
PP-OCRv6 Zero-Shot Local M4 Pro MPS (34.5M) 28.16% 32.65% 34.48% 28.94% 6.67 ms 150.0 img/s (7.43 s)
Gemini-3.8-Flash Zero-Shot Cloud API (12 workers) 37.85% 44.04% 30.23% 36.38% 21,020.8 ms (p50 15.52 s, p99 53.85 s) 0.565 img/s (1,974.59 s)

Table 2: Zero-shot Held-Out Test Set (N = 1,115) baseline comparing pretrained PP-OCRv6_medium_rec against gemini-3.8-flash (thinking_level=“LOW”).

On the 669-crop Validation Split, gemini-3.8-flash reaches 27.20% Raw EM, 46.94% Norm EM, 20.45% CER, and 46.08% Word Accuracy (17,928.1 ms mean latency, p50 = 11.16 s, p99 = 51.42 s, 0.676 img/s, 852.64 s total).

Frontier models like gemini-3.8-flash provide substantially better zero-shot accuracy in general (+11.39 pp Norm EM and -4.25 pp CER over zero-shot PP-OCRv6 on Test), but at a steep cost in latency (~3,152× higher per crop) and throughput (~265× lower: 0.565 img/s vs. 150.0 img/s), alongside cloud PHI exposure and occasional English-word substitutions on ambiguous strokes ("Bishop" for Biscor, "for a few" for Farofew). Conversely, pretrained PP-OCRv6 meets local latency (6.67 ms/crop) and privacy constraints but lacks clinical handwriting accuracy. The goal is an efficient local recognizer that retains PP-OCRv6’s speed while bringing its accuracy on par with frontier models—which directly motivates domain-specific post-training.

Fine-Tuning with CTC and Mixed-Precision bfloat16

CTC Alignment and Objective

Like most real-world OCR datasets, RxHandBD provides cropped word images \(X\) paired with unsegmented character transcripts \(y = (y_1, \dots, y_L)\) (\(L \le T\)), without bounding boxes mapping horizontal slices to individual letters. Connectionist Temporal Classification (CTC) [3] solves this unsegmented alignment by augmenting the vocabulary with a blank symbol \(\epsilon\) (ID 0) and defining a many-to-one collapsing operator \(\mathcal{B}\) that merges consecutive repeated tokens and strips all \(\epsilon\) tokens (so "aa_bb" and "a_b_b" both collapse to "ab").

First, applying log-softmax across the vocabulary axis of the frame logits \(Z \in \mathbb{R}^{T \times V}\) yields frame-wise log-probabilities:

\[\log p_t(k \mid X) = Z_{t,k} - \log \sum_{j=1}^{V} \exp(Z_{t,j})\]

To compute the likelihood of target \(y\), CTC constructs the blank-interleaved sequence \(y' = (\epsilon, y_1, \epsilon, y_2, \dots, y_L, \epsilon)\) of length \(2L + 1\) and uses the forward-backward dynamic programming algorithm to marginalize over every valid monotonic alignment path \(\pi \in \mathcal{B}^{-1}(y)\) of length \(T = 40\):

\[P(y \mid X) = \sum_{\pi \in \mathcal{B}^{-1}(y)} \prod_{t=1}^{T} p_t(\pi_t \mid X), \qquad \mathcal{L}_{\text{CTC}}(X, y) = -\log P(y \mid X)\]

PyTorch’s nn.CTCLoss(blank=0, zero_infinity=True, reduction="mean") computes this exact loss over [T, B, V] log-probabilities (zero_infinity=True prevents divergence on invalid paths).

# Greedy CTC collapsing (operator B): merge repeats and strip blank_id = 0
def ctc_greedy_decode(logits: torch.Tensor, characters: list[str], blank_id: int = 0) -> list[str]:
    token_ids = torch.argmax(logits, dim=-1).detach().cpu().tolist()  # [B, T]
    outputs = []
    for row in token_ids:
        previous, chars = None, []
        for token in row:
            if token != previous and token != blank_id:
                chars.append(characters[token - 1])
            previous = token
        outputs.append("".join(chars))
    return outputs
# Static-shape CTC loss over [T, B, V] log-probabilities (with MPS CPU bridge)
class CTCLossStep(nn.Module):
    def __init__(self, blank_id: int = 0, zero_infinity: bool = True):
        super().__init__()
        self.criterion = nn.CTCLoss(blank=blank_id, zero_infinity=zero_infinity, reduction="mean")

    def forward(
        self,
        logits: torch.Tensor,         # [B, T, V]
        targets: torch.Tensor,        # [B, max_target_len]
        input_lengths: torch.Tensor,  # [B], all T=40
        target_lengths: torch.Tensor, # [B]
    ) -> torch.Tensor:
        log_probs = logits.float().log_softmax(dim=-1).permute(1, 0, 2)  # [T, B, V]
        if logits.device.type == "mps":
            loss = self.criterion(
                log_probs.cpu(), targets.cpu(), input_lengths.cpu(), target_lengths.cpu()
            )
            return loss.to(logits.device)
        return self.criterion(log_probs, targets, input_lengths, target_lengths)

Why Selective Full-Model Fine-Tuning (vs. LoRA / PEFT)

When adapting pretrained models, a natural alternative is Parameter-Efficient Fine-Tuning (PEFT)—such as LoRA (injecting low-rank updates \(\Delta W = BA\) into frozen attention projections) or linear-head probing (updating only the final nn.Linear(192, 18710) classifier). I instead use selective full-model fine-tuning with frozen BatchNorm2d, for three architectural reasons:

  1. Compact parameter footprint: Unlike 7B+ parameter LLMs or VLMs where LoRA is needed to fit optimizer states in memory, PP-OCRv6_medium_rec has only ~34.5M parameters. Updating all non-BatchNorm weights fits comfortably inside 24 GB unified memory on MPS and a single Cloud TPU chip (v5e1 / v6e-1).
  2. Convolutional feature shift: Adapting from clean printed text to cramped physician handwriting requires reshaping early visual stroke filters (PPLCNetV4 depthwise convolutions) alongside sequence context (LightSVTR) and character priors (nn.Linear). Linear probing leaves visual features fixed, and standard LoRA targets attention/MLP layers while leaving convolutional backbones frozen.
  3. BatchNorm as the structural stabilizer: Freezing all nn.BatchNorm2d layers (both affine weight/bias and running_mean/running_var) in .eval() mode prevents noisy handwriting batches from perturbing pretrained normalization scales, providing the stability of frozen-backbone PEFT without restricting convolutional adaptability.

Mixed-Precision bfloat16 and Static-Shape Optimization

At batch_size=64 (59 steps/epoch), casting weights directly to bfloat16 (7-bit mantissa) causes small ~4e-5 updates to underflow below 1 ULP, stalling convergence. Instead, mixed-precision bfloat16 is used: torch.autocast(device_type, dtype=torch.bfloat16) accelerates convolutions, linear layers, and attention on hardware MXUs, while master weights and AdamW moments (m, v) remain in float32. Under torch_tpu 0.3.0, LightSVTR also casts LayerNorm inputs to weight.dtype (float32) and attention probabilities to v.dtype (bfloat16) to avoid a mixed-dtype StableHLO lowering error.

To prevent XLA graph recompilation, every batch uses static [64, 3, 48, 320] inputs, max_target_len=40 target padding, input_lengths=40, and drop_last=True, with mild brightness/contrast jitter ([0.9, 1.1]), sharpness jitter, and ±2° rotation:

model.train()
freeze_batchnorm(model)  # Keep BatchNorm2d weights and running stats in eval mode

optimizer.zero_grad()
with torch.autocast(device_type=device.type, dtype=torch.bfloat16):
    logits = model(images)                                # [64, 40, 18710]
loss = ctc_loss_step(logits, targets, input_lengths, target_lengths)

loss.backward()
torch.nn.utils.clip_grad_norm_(trainable_params, max_norm=5.0)
optimizer.step()

Optimization uses AdamW (\(\eta_{\max} = 4 \times 10^{-5}\) with a 3-epoch linear warmup, cosine decay to \(\eta_{\min} = 10^{-6}\), weight decay \(10^{-4}\), and gradient norm clipping \(\tau = 5.0\)), accumulating loss on-device and syncing once per epoch. After each epoch, greedy CTC decoding (logits.argmax(dim=-1)) is evaluated on the validation split via CER and NormEM (patience=8, min_delta=1e-4).

Benchmarks and RxHandBD Fine-Tuning Results

Training and validation run on the RxHandBD [5] training split (seed=20261017, 85%/15% partition, without touching held-out test labels; TPU VM v6e-1 used a seed=42 partition of the same split), yielding 3,794 training crops and 669 validation crops. Before fine-tuning, the zero-shot pretrained PP-OCRv6_medium_rec baseline scores 2.0488 validation loss, 32.61% CER, and 26.76% Normalized Exact Match.

Local runs executed on an Apple M4 Pro (12 CPU cores, Metal GPU, 24 GB Unified Memory, macOS, Python 3.11.11, PyTorch 2.10.0). Cloud runs executed on Colab TPU v5e1 and a provisioned Google Cloud TPU VM (ct6e-standard-1t, v6e-1) using Python 3.13.14, PyTorch 2.15.0+cpu, torch-tpu 0.3.0, and libtpu 0.0.53.1 (PJRT API 0.117).

Local Inference Microbenchmark (CPU vs. MPS)

As a local serving baseline, Table 3 reports float32 inference latency on Apple M4 Pro. MPS cuts single-crop latency from 2,526.37 ms to 8.91 ms (283.5× speedup) and peaks at 167.50 img/s at batch size 8.

Workload Batch Size CPU (12 Cores) Apple Silicon MPS Speedup (MPS / CPU)
Inference 1 2,526.37 ms (0.40 img/s) 8.91 ms (112.21 img/s) 283.5×
Inference 8 3,778.85 ms (2.12 img/s) 47.76 ms (167.50 img/s) 79.1×
Inference 16 3,641.86 ms (4.39 img/s) 98.17 ms (162.98 img/s) 37.1×

Table 3: Float32 inference latency and throughput on Apple M4 Pro.

Fine-Tuning Comparison

All four accelerators ran the exact same training configuration (batch_size=64, epochs=40, lr=4e-5, warmup_epochs=3, min_lr=1e-6, patience=8, num_workers=4, max_target_len=40, drop_last=True). Table 4 and Figure 4 compare wall-clock training time across all four backends, while Figure 5 tracks the 40-epoch validation accuracy trajectories across MPS, Colab v5e1, and TPU VM v6e-1.

Accelerator Precision Epoch 1 Steady-State Epoch Speedup (vs. CPU / vs. MPS) Total Time (40 Epochs)
Apple M4 Pro CPU (12 Cores) fp32 (no autocast) ~4,724.7 s (~78.7 min, proj.) ~4,724.7 s (scaled from 28.92 s/step) 1.0× / 0.01× ~52.5 hrs (projected)
Apple M4 Pro MPS autocast(bf16) + fp32 master 65.32 s 64.36 s (57.66–72.24 s) 73.4× / 1.0× 2,640.53 s (44.01 min)
Colab TPU v5e1 autocast(bf16) + fp32 master 20.79 s (incl. XLA compile) 9.09 s (8.22–9.38 s) 519.8× / 7.08× 404.83 s (6.75 min)
TPU VM v6e-1 autocast(bf16) + fp32 master 18.75 s (incl. XLA compile) 4.99 s (4.67–5.27 s) 946.8× / 12.90× 249.34 s (4.16 min)

Table 4: Controlled 4-way time-complexity comparison (batch_size=64, epochs=40) using each accelerator’s fastest precision (fp32 on CPU; mixed-precision bfloat16 on MPS and Cloud TPUs).

Figure 4: (a) Steady-state epoch latency (log scale) and speedup relative to CPU; (b) total 40-epoch wall-clock runtime across completed runs.

Figure 5: 40-epoch validation convergence on RxHandBD (batch_size=64, mixed-precision bfloat16) for Apple M4 Pro MPS, Colab TPU v5e1, and TPU VM v6e-1.

Three operational patterns stand out from these runs:

  • Why fp32 (no autocast) is CPU’s fastest configuration: Unlike TPU MXUs or Apple Metal GPUs, PyTorch’s ARM CPU kernels lack native hardware bfloat16 matrix acceleration for these ops, so autocast(bf16) adds software dtype-conversion overhead (37.10 s/step, 6,061.10 s measured for Epoch 1) compared to native fp32 (28.92 s/step, ~4,724.7 s scaled per epoch). Table 4 therefore reports fp32 as the fair CPU baseline.
  • XLA compilation cache stability: On TPU VM v6e-1, Epoch 1 absorbed initial StableHLO/XLA compilation (18.75 s), after which Epochs 2–40 held steady at 4.67–5.27 s (yielding the 4.99 s steady-state epoch latency and 4.16 min total runtime plotted in Figure 4). The compilation cache logged 2,521,981 requests with 2,521,423 hits (99.9%), 558 compilations, and 0 unbounded dynamic hits—confirming that static [64, 3, 48, 320] shapes and max_target_len=40 padding prevented recompilation thrashing.
  • Convergence across backends: As Figure 5 shows, mixed-precision bfloat16 enabled MPS, v5e1, and v6e-1 to follow closely aligned validation trajectories, improving by more than 20 percentage points in CER over the 32.61% zero-shot baseline, with Colab v5e1 reaching the lowest validation CER (11.15%, 62.63% Normalized Exact Match) and v6e-1 finishing 40 epochs in 4.16 minutes.

End-to-End Evaluation on Train, Validation, and Held-Out Test Splits

To assess generalization uniformly across all completed checkpoints, each model was evaluated (batch_size=64, Apple Silicon MPS) over all three RxHandBD splits: Train (3,794 crops, seed=20261017), Validation (669 crops, seed=20261017), and the completely disjoint Held-Out Test Set (1,115 crops, Test_Labels.csv).

Figure 6: Character Error Rate (CER ↓) and Normalized Exact Match (↑) across Train (n=3,794), Validation (n=669), and Held-Out Test (n=1,115) splits. Note: TPU VM v6e-1 was trained on a seed=42 85%/15% partition (12.32% CER / 61.29% Norm EM on its own validation split), so ~85% of the seed=20261017 validation split overlaps with its training set; on the disjoint Held-Out Test (1,115) split, v6e-1 (46.82% Norm EM, 25.50% CER) closely matches v5e1 (46.91% Norm EM, 25.47% CER).

Compared to the zero-shot baseline (32.65% Norm EM, 34.48% CER, 28.94% Word Accuracy), mixed-precision bfloat16 post-training improves held-out Test performance by +14.26 pp Normalized Exact Match (46.91% on v5e1), -9.01 pp CER (25.47%), and +13.42 pp Word Accuracy (42.36%). All three mixed-precision bf16 runs—Apple M4 Pro MPS (46.01%), Colab TPU v5e1 (46.91%), and TPU VM v6e-1 (46.82%)—converge to virtually identical held-out Test accuracy (25.47%–26.25% CER), confirming that autocast(bf16) with float32 master weights introduces no hardware-dependent degradation.

Figure 6 also exposes a clear split gap. Whereas the zero-shot model scores uniformly across splits (30.85%–34.48% CER), 40 epochs at batch_size=64 drive Train CER down to 0.09%–0.18% (98.8%–99.5% Norm EM) and Validation CER to 11.43%–11.81% (61.43%–61.88% Norm EM), while Held-Out Test CER plateaus at 25.47%–26.25% (46.01%–46.91% Norm EM).

That ~15 pp Validation-to-Test gap comes from how Train_Label.csv was partitioned: splitting randomly at the sample level (seed=20261017) without a writer or prescription grouping key leaves similar handwriting styles and drug vocabularies in both Train and Validation. Test_Set introduces unseen writers and drug-name variations, which explains why scaling from fp32 bs=8 (12 epochs, 81.29% Train EM) to mixed-precision bf16 bs=64 (40 epochs, 99.53% Train EM) gained +5.23 pp on Validation (56.65% → 61.88%) but only +1.98 pp on Held-Out Test (44.93% → 46.91%). Dataset diversity and writer-disjoint regularization—not compute precision or optimizer steps—are now the main bottleneck.

Post-Training Payoff vs. Zero-Shot Baselines (N = 1,115 Held-Out Test)

Table 5 puts the fine-tuned PP-OCRv6 (v5e1 mixed-precision bfloat16, trained in 6.75 min) side by side with both zero-shot baselines on the Held-Out Test Set.

Model Deployment / Footprint Raw EM Norm EM CER ↓ Word Acc (1 - WER) ↑ Latency / Crop Throughput (N=1,115)
PP-OCRv6 Zero-Shot Local M4 Pro MPS (34.5M) 28.16% 32.65% 34.48% 28.94% 6.67 ms 150.0 img/s (7.43 s)
Gemini-3.8-Flash Zero-Shot Cloud API (12 workers) 37.85% 44.04% 30.23% 36.38% 21,020.8 ms (p50 15.52 s, p99 53.85 s) 0.565 img/s (1,974.59 s)
PP-OCRv6 Fine-Tuned (v5e1 Mixed-Precision) Local M4 Pro MPS (34.5M) 37.58% 46.91% 25.47% 42.36% 6.91 ms 144.8 img/s (7.70 s)

Table 5: Post-training payoff on the Held-Out Test Set (N = 1,115) compared against the zero-shot baselines from Table 2.

Domain-specific fine-tuning achieves the goal set out in Table 2: preserving PP-OCRv6’s local speed while surpassing gemini-3.8-flash on clinical handwriting accuracy.

Even with 12 concurrent cloud workers, gemini-3.8-flash averaged 21.02 s per crop (p50 = 15.52 s, p95 = 50.22 s, p99 = 53.85 s) and took 1,974.59 s (~32.9 min) for 1,115 crops (0.565 img/s). Fine-tuned PP-OCRv6 processed the same 1,115 crops locally on Apple M4 Pro MPS in 7.70 s (6.91 ms/crop, 144.8 img/s)—~256× faster wall-clock throughput and ~3,042× lower per-crop latency, with zero patient data leaving the device.

On accuracy, 4.16–6.75 minutes of mixed-precision bfloat16 post-training on Cloud TPU moves the 34.5M-parameter PP-OCRv6 past gemini-3.8-flash on both splits. On Held-Out Test (N = 1,115), fine-tuned PP-OCRv6 reaches 46.91% vs. 44.04% Norm EM (+2.87 pp), 25.47% vs. 30.23% CER (-4.76 pp), and 42.36% vs. 36.38% Word Accuracy (+5.98 pp); on Validation (N = 669), the lead widens to 62.63% vs. 46.94% Norm EM (+15.69 pp) and 11.15% vs. 20.45% CER (-9.30 pp).

Comparing the error profiles also shows where each model still excels. gemini-3.8-flash matches fine-tuned PP-OCRv6 on Raw EM (37.85% vs. 37.58%) thanks to strong casing and formatting priors, and drops only -2.90 pp Norm EM from Validation to Test (46.94% → 44.04%), reflecting broader out-of-distribution writer robustness. Fine-tuned PP-OCRv6 drops -15.72 pp (62.63% → 46.91%) due to limited writer diversity in the training split, yet avoids substituting plausible English words ("Bishop" for Biscor, "for a few" for Farofew). That complementary split suggests using frontier VLMs offline—for pseudo-labeling, hard-example mining, and synthetic prescription generation to close the ~15 pp Validation→Test gap—while keeping fine-tuned PP-OCRv6 at the clinical edge.

Conclusion

One static-shape PyTorch codebase is enough to take PP-OCRv6_medium_rec from PaddleOCR inference weights through local Apple Silicon MPS prototyping (44.01 min) to Google Cloud TPU v6e-1 training (4.16 min) without rewriting the training loop. With mixed-precision bfloat16 and frozen BatchNorm2d layers, a 34.5M-parameter recognizer can be adapted in minutes to reach—and on Norm EM and CER exceed—zero-shot gemini-3.8-flash on clinical handwriting while keeping inference on-device at 6.91 ms/crop.

Two practical boundaries define what remains before clinical deployment. On data, closing the ~15 pp gap between validation (~61–62% Norm EM) and held-out test (~46–47%) will require writer-disjoint splits and broader handwriting diversity, where frontier VLMs are better suited offline for mining hard prescriptions or synthesizing training crops. On the runtime side, Apple Silicon still awaits a native Metal aten::_ctc_loss kernel to remove the CTCLossStep CPU bridge, and torch-tpu 0.3.0 still hits an MLIR inlining error under torch.compile(..., backend="tpu") on LightSVTR LayerNorm as well as a SIGABRT when libtcmalloc_minimal.so.4 is preloaded alongside forked DataLoader workers (num_workers=4).

References

  1. Ghifary, M. (2026). Building Efficient OCR for Clinical Handwriting with JAX. ghif.github.io/posts/2026-11-12-building-efficient-ocr-clinical-handwriting-jax/
  2. PaddleOCR Team. (2026). PP-OCRv6: Practical Ultra-Lightweight OCR System. arXiv:2606.13108
  3. Graves, A., Fernández, S., Gomez, F., & Schmidhuber, J. (2006). Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks. ICML.
  4. PyTorch & Google Cloud. (2026). Introducing TorchTPU: Native PyTorch Backend for Google Cloud TPUs. pytorch.org/blog/introducing-torchtpu/
  5. Islam, M. M. (2024). RxHandBD: A Handwritten Prescription Word Image Dataset. Mendeley Data, DOI: 10.17632/dsb5r6vskg.3