Document Image Denoising: Architecture Ablations, int8 Quantization, and CPU Deployment
Summary
I trained six convolutional models to restore degraded document images (JPEG compression artifacts, blur, sensor noise), all under one fixed protocol: same data, same degradation distribution, same seed, same evaluation set. The models differ in one design choice at a time. The main findings:
- Skip connections dominate. Removing them costs 2.05 dB. Cutting width to 25% of the parameters costs 0.22 dB.
- Residual learning speeds up early convergence but doesn't raise the final PSNR at a 10-epoch budget.
- Static int8 quantization is close to free: โ0.002 to โ0.14 dB (bootstrap 95% CIs), ~4ร smaller files, ~15โ20% lower CPU latency for most variants.
The deployable artifact is a 104MB Docker image with no PyTorch in it. It denoises a full 1100ร1575 page on CPU in about 2 seconds.
Code: github.com/jere1882/DocDenoising ยท Weights: Hugging Face ยท Data: 50k crops
Degraded input / model output / clean target for the held-out crop with the largest
measured gain (+18.2 dB). The page is real (from the held-out split); the degradation is
the synthetic pipeline described below.
1. Task
Input: a degraded image of a document page. Output: the clean page. This is pixel-to-pixel regression, trained with MSE loss and evaluated with PSNR. Degraded scans are a common pre-processing problem in document pipelines: compression artifacts and blur hurt both readability and downstream OCR.
2. Data and degradation model
Clean targets. 50,000 crops of 512ร512 px, rendered from a public PDF corpus with PyMuPDF at 4ร scale (~288 DPI). Mostly-blank crops are rejected at extraction time with thresholds on grayscale mean and standard deviation. Split 90/10 at the file level with a fixed seed: 45,000 train, 5,000 validation.
Degraded inputs are synthesized, not stored. Each clean crop goes through a three-step stochastic pipeline, applied in order:
| Step | Probability | Parameter range |
|---|---|---|
| Gaussian blur | 0.5 | radius โ [0.5, 2.5] px |
| JPEG round-trip | 1.0 | quality โ [5, 25] |
| Gaussian noise | 0.7 | ฯ โ [0.01, 0.06] (pixels in [0, 1]) |
- Training: fresh random degradation every time a crop is loaded, so the model never sees the same input twice. That's free augmentation with no disk cost.
- Validation: the degradation is seeded per file (an md5 hash of the filename, which
is stable across processes, unlike Python's
hash()). Every model, every epoch and every export sees identical validation inputs, which makes cross-model comparisons paired.
Is the task non-trivial? Before trusting learned numbers, I compared against classical filters on the same validation set:
| Method | PSNR |
|---|---|
| Identity (no processing) | 24.0 dB |
| Median filter | 23.8 dB |
| Bilateral filter | 25.2 dB |
| Adaptive threshold | 15.8 dB |
| Best learned model | 30.3 dB |
The best classical method improves on the identity baseline by 1.2 dB; the learned model improves on it by 6.3 dB. Adaptive thresholding is the worst of all, because it binarizes, while the clean targets are grayscale with anti-aliased text.
3. Models
All models are written from scratch in PyTorch, fully convolutional, and share one
building block: DoubleConv = (3ร3 conv โ BatchNorm โ ReLU) ร 2.
| Model | Design | Params (c=64) |
|---|---|---|
unet | 3-level encoder/decoder with skip connections (concatenation), sigmoid output | 7.70M |
plain_encoder_decoder | identical depth and widths, no skip connections | 6.93M |
residual_unet | unet body predicting the noise; output = clamp(x โ tanh(head(ยท)), 0, 1) | 7.70M |
Design notes:
- Width is a single parameter,
base_channels(c), and channels double per level (c โ 2c โ 4c โ 8c). Params scale โ cยฒ, so the width sweep c โ 8 covers 7.70M โ 0.12M parameters. - Residual head bounded with tanh. Input and target pixels are both in [0, 1], so the true residual lies in [โ1, 1], exactly tanh's range. DnCNN uses an unbounded residual output. The bound reduces how often x โ nฬ falls into the zero-gradient region of the final clamp.
- Receptive field: 92ร92 px, measured by back-propagating from a single output pixel. That's about 1โ2 lines of text at this resolution, which is enough to see JPEG block structure (8ร8) and the shapes of individual glyphs.
- Input size must be a multiple of 8 (three 2ร poolings). Arbitrary page sizes are handled by tiling (ยง6.3).
4. Training protocol
| Optimizer | Adam, lr 1e-3, no schedule |
| Loss | MSE |
| Batch | 8 per GPU ร 2 GPUs (NVIDIA T4) = 16 |
| Budget | 10 epochs (~28k steps), single run per configuration, seed 42 |
| Precision | 16-mixed (fp16 autocast + loss scaling): measured ~2.7ร throughput over fp32 |
| Multi-GPU | DDP with SyncBatchNorm: batch statistics are computed over the global batch of 16, not 8 per GPU |
| Stabilization | gradient clipping by value (ยฑ1.0), not by global norm (see ยง7) |
| Checkpoint selection | best validation PSNR |
Stack: PyTorch Lightning for the training loop, Hydra for configuration (every hyperparameter overridable from the CLI, with the resolved config saved per run), and Weights & Biases for tracking.
5. Evaluation protocol
Global PSNR. All reported numbers use one PSNR per model, computed from the summed squared error over all pixels of all 5,000 validation crops:
This is not the mean of per-image PSNRs, and the difference is large here. For unet
the mean of per-image PSNRs is 33.07 dB against a global PSNR of 30.33 dB. Averaging in
the log domain overweights easy, mostly-white crops, whose individual PSNRs are very
high. The validation PSNR logged during training (the mean of per-batch PSNRs) sits in
between, at 30.9 dB. These three are different quantities, and mixing them across tables is a
common source of inflated claims, so everything below comes from one evaluation script
using the global definition.
Uncertainty. For fp32-vs-int8 comparisons I report a paired bootstrap 95% CI (2,000 resamples of validation images) on the PSNR difference. This captures evaluation-set sampling noise for a fixed pair of models. It does not capture training-run variance; see ยง8.
6. Results
6.1 Architecture and width ablation
| Model | Params | PSNR | ฮ vs unet |
|---|---|---|---|
unet (c=64) | 7.70M | 30.33 dB | โ |
residual_unet (c=64) | 7.70M | 30.25 dB | โ0.08 |
residual_unet (c=32) | 1.93M (25%) | 30.03 dB | โ0.30 |
residual_unet (c=16) | 0.48M (6.3%) | 29.22 dB | โ1.11 |
residual_unet (c=8) | 0.12M (1.6%) | 27.36 dB | โ2.97 |
plain_encoder_decoder (c=64) | 6.93M | 28.28 dB | โ2.05 |
Skip connections matter more than capacity. With the same depth and nearly the same
parameter count, removing skip connections costs 2.05 dB. That's more than shrinking
residual_unet 16ร (c=16, โ1.03 dB relative to its own c=64). This is consistent with
the nature of the task: the output is nearly the input, and skip connections give the
decoder a direct path to the high-resolution detail that a bottleneck would otherwise
have to carry.
Residual learning: faster start, same ceiling. residual_unet leads unet by
~0.9 dB after epoch 0 (a bounded residual is an easier early target than the whole
image), but finishes 0.08 dB behind. With a single seed per configuration I don't treat
that 0.08 dB as a ranking. The supported conclusion is that residual learning bought no
final-quality advantage here, contrary to the usual expectation.
Width has a knee. Going from c=64 to c=32 is nearly free (โ0.22 dB for 4ร fewer parameters); c=16 costs ~1 dB; and at c=8 quality breaks (โ2.9 dB). For deployment, c=32 is the practical operating point.
Budget caveat. Every model except c=8 reached its best validation PSNR at the last epoch, so none had converged at 10 epochs. These are comparisons at a fixed compute budget, which is a fair protocol but not a statement about asymptotic quality.
6.2 Static int8 quantization
Pipeline: Lightning checkpoint โ backbone nn.Module โ ONNX (opset 17, dynamic batch
and spatial axes; the fp32 export matches PyTorch to a max abs diff of ~7e-7) โ ONNX
Runtime quantize_static in QDQ format, with per-channel int8 weights and uint8
activations. Calibration uses 500 training crops, disjoint from the evaluation set.
| Model | Size fp32 โ int8 | PSNR fp32 โ int8 | ฮ int8 (95% CI) | CPU latency fp32 โ int8 |
|---|---|---|---|---|
unet c64 | 30.8 โ 7.8 MB | 30.33 โ 30.24 | โ0.091 [โ0.098, โ0.083] | 288 โ 243 ms |
residual_unet c64 | 30.8 โ 7.8 MB | 30.25 โ 30.18 | โ0.070 [โ0.075, โ0.065] | 286 โ 239 ms |
residual_unet c32 | 7.7 โ 2.0 MB | 30.03 โ 30.00 | โ0.032 [โ0.035, โ0.029] | 90 โ 76 ms |
residual_unet c16 | 1.9 โ 0.5 MB | 29.22 โ 29.22 | โ0.002 [โ0.009, +0.006] | 44 โ 34 ms |
residual_unet c8 | 0.5 โ 0.16 MB | 27.36 โ 27.23 | โ0.137 [โ0.142, โ0.131] | 18 โ 18 ms |
plain_enc_dec c64 | 27.7 โ 7.0 MB | 28.28 โ 28.20 | โ0.080 [โ0.084, โ0.076] | 239 โ 194 ms |
The quantization loss is statistically detectable for every model except c=16, where the CI includes zero, but it is โค0.14 dB everywhere. The smallest model has the largest relative loss and no latency gain: at 18 ms per tile, fixed per-inference overhead dominates the arithmetic that int8 accelerates.
Latency methodology. One 512ร512 tile, batch 1, 4 intra-op threads, on an idle
Apple Silicon machine, reported as the median of 30 timed runs after a warm-up call. I
cross-checked three tools: torch.utils.benchmark and a perf_counter loop agreed
within 2%; ONNX Runtime's own onnxruntime_perf_test read ~15% higher than timing the
same session from Python, and I didn't fully resolve why. These are relative numbers
from one machine, not a hardware claim.
6.3 Full-page inference
Pages are reflect-padded, cut into overlapping 512ร512 tiles (32 px overlap), denoised, and blended back with a 2D Hann window, so tile seams don't show. Two details:
- Border correctness. A Hann window is exactly zero at its endpoints, and at the outer page border only one tile covers each pixel, so the blend weight there is zero and those pixels come out black. Flooring the window at 1e-3 fixes this. A regression test checks that an identity predictor reconstructs a random image pixel-exactly for single-tile, multi-tile, and smaller-than-one-tile pages.
- Batching tiles does not help on CPU. The GPU intuition (amortize launch overhead) doesn't carry over. Batch 8 was 38% slower than batch 1 for the PyTorch backend, and no faster for ONNX Runtime: a single 512ร512 tile already saturates the cores, and larger batches only add memory traffic. Inference defaults to batch 1.
Full-resolution region of a real held-out page (a municipal budget document), degraded
with the synthetic pipeline and restored with tiled inference.
6.4 Serving
The inference path depends on the model artifact, not on the training framework. Tiling is pure numpy, the core package dependencies are numpy, Pillow, ONNX Runtime and Hydra, and PyTorch is only imported if you ask for the checkpoint backend. The result is a multi-stage Docker image with the int8 model baked in at build time:
docker build -t docdenoising . # --build-arg MODEL=unet_bc64 for another variant
docker run --rm -v "$PWD:/data" docdenoising infer.input=/data/page.pngThe image is 104MB compressed, against ~1GB+ for any image that includes PyTorch. An 1100ร1575 page takes ~2 s end to end, including container start-up.
7. Case study: diagnosing training divergence
Moving from local fp32 runs with milder degradation to 2-GPU mixed-precision training on the harder pipeline, runs started diverging to NaN within the first epoch. I ruled out hypotheses with direct evidence rather than plausibility:
- Mixed precision: ruled out. Lightning's
16-mixedalready instantiates aGradScaler, and PyTorch's autocast runsmse_lossin fp32. (The classic trap isBCELoss, which doesn't apply here.) - Data: ruled out. All 50,000 crops went through the actual degradation pipeline: zero non-finite values, no degenerate images.
- Gradient clipping: a real failure mode, found. A failed checkpoint had 64 of 71 tensors NaN simultaneously, including plain conv weights. That pattern points to Lightning's default clipping by global norm: โgโ = โฮฃgยฒ, so one non-finite gradient anywhere makes the norm NaN, and the shared rescale factor writes NaN into every parameter in a single step. Clipping by value treats each parameter independently, which keeps a fault local and diagnosable.
Two architecture details were corrected during the same review: BatchNorm moved to the canonical per-conv Conv โ BN โ ReLU position (it had been a single BN after two Conv โ ReLU pairs), and the residual head was given the tanh bound. SyncBatchNorm was enabled for the 2-GPU setup.
Honest attribution: stable training came with the combination of these changes, and I didn't run the ablation that would isolate a single root cause. What the evidence does establish is the norm-clipping propagation mechanism, which is worth knowing on its own: under global-norm clipping, one bad gradient corrupts the entire model at once.
8. Limitations and threats to validity
- One seed per configuration. Differences below ~0.1 dB (
unetvsresidual_unet) are not resolved. The bootstrap CIs cover evaluation sampling, not training variance. - Synthetic degradation. The model is trained and evaluated on one parametric degradation family. Real scans add bleed-through, skew, uneven illumination and scanner-specific noise; performance under that distribution shift is untested.
- PSNR only. No SSIM/LPIPS, and, more relevant for documents, no downstream OCR accuracy. PSNR rewards the dominant white background; a metric weighted toward text pixels, or a character error rate, would track usefulness better.
- Fixed, short budget. Models were still improving at 10 epochs, and rankings could change with longer training or a learning-rate schedule.
- Selected examples. The figures show the crops with the largest measured gain, chosen to illustrate the method, not to represent typical performance. The typical case is in the tables.
- Latency on one machine, CPU only.
9. Reproducing
pip install -e ".[train]"
denoising-extract-crops --pdf-dir pdfs/ --output-dir data/crops --scale 4.0
denoising-train model=residual_unet model.backbone_cfg.base_channels=32 \
trainer.devices=2 +trainer.strategy=ddp +trainer.sync_batchnorm=true \
+trainer.precision=16-mixed trainer.max_epochs=10
denoising-export --checkpoint <run>/checkpoints/last.ckpt \
--clean-dir data/crops/clean --out-dir <run>/export # ONNX fp32 + int8 + report.jsonThe export step writes the global PSNR, bootstrap CIs and file sizes for each model to
report.json; the quality and size numbers in ยง6 come from those reports. The latency
column comes from the dedicated, cross-checked benchmark runs described in ยง6.2 (idle
machine), not from the export's built-in timing.