Election 2026 A Forecast of Every Senate, House & Governor Race See the Forecast

Multi-Task Sentence Transformer for Receipt Processing

Natural Language Processing
Deep Learning
A frozen BGE-M3 encoder with two lightweight heads that assign each receipt line a sentence class and token-level name and price tags, trained and evaluated on the public CORD-v2 corpus.
Published

January 24, 2026

The Decision

Freeze the BGE-M3 backbone and train only the two task heads.

Takeaways

  • 97.8% sentence classification accuracy on 414 held-out receipt lines.
  • 0.898 macro-F1 on entity tagging, with labels from the public CORD-v2 receipt corpus.
  • With a single stopping point for both tasks, one of the two has to be compromised.

A receipt can be treated as a sequence of short lines, each of which raises two questions: what type of line it is, and which of its words make up the product name and the price. This project addresses both with a single transformer encoder and two small task heads. The encoder is run once per line, and both heads read from its output.

Source code: github.com/olivia-jackson-lambert/sentence-project

System Overview

Six boxes stacked top to bottom and joined by arrows: Receipt Image, OCR with Tesseract, Segmentation into lines, the BGE-M3 encoder (24 layers, frozen, 1024-dimensional states), the two task heads, and Structured Data holding a line class plus name and price spans. Brackets at the side group the boxes into OCR, Preprocessing and Multi-Task Model.

The receipt processing pipeline, from photograph to structured line data.

The OCR stage converts the photograph to greyscale, applies denoising, binarises the result with Otsu thresholding and passes it to Tesseract. The extracted text is then split into lines on newlines and full stops.

import pytesseract
import cv2

def preprocess_receipt_image(image_path):
    """Preprocess receipt image for better OCR accuracy"""
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    denoised = cv2.fastNlMeansDenoising(gray, h=10)
    _, thresh = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    return thresh

def extract_text_from_receipt(image_path):
    """Extract text from receipt image using OCR"""
    return pytesseract.image_to_string(preprocess_receipt_image(image_path), config='--psm 6')

The results reported below do not use this stage. They are computed on CORD’s own transcribed lines, so OCR error is not measured; this is discussed further under Limitations.

The Model

Backbone

The encoder is BGE-M3 from the Beijing Academy of Artificial Intelligence, an XLM-RoBERTa-large model with 24 layers, 1024 hidden dimensions, a 250,000-token vocabulary and a 2.3 GB checkpoint. This is larger than a receipt parser strictly requires, but it provides strong general sentence representations, and its multilingual coverage matters because the CORD receipts are in Indonesian.

The “M3” in the name refers to multi-linguality, multi-granularity and multi-functionality, the last of which denotes support for dense, sparse and ColBERT-style retrieval. The model has no built-in classification or named entity recognition capability, so the multi-task structure was added on top of it.

Task Heads

Flow diagram. Input tokens go into the frozen BGE-M3 backbone (XLM-RoBERTa, 24 layers, 16 heads, hidden size 1024). The CLS token state of size 1024 feeds a classification head (Linear 1024 to 128, ReLU with dropout 0.1, Linear 128 to 4) that outputs four sentence classes. All token states feed an NER head (Linear 1024 to 5) that outputs one of five BIO tags per token. Only the heads are marked trainable.

The multi-task architecture. Both heads read the same frozen encoder output.

The classification head takes the CLS token state and passes it through a 128-unit hidden layer to four output classes. The entity head is a single linear layer applied to every token state.

self.cls_head = nn.Sequential(
    nn.Linear(1024, 128), nn.ReLU(), nn.Dropout(0.1), nn.Linear(128, 4)
)
self.ner_head = nn.Linear(1024, 5)
Labels
Sentence class (4) ITEM, ITEM_OPTION, SUBTOTAL, TOTAL
Entity tags (5) O, B-NAME, I-NAME, B-PRICE, I-PRICE

The entity tags follow the BIO scheme, in which B marks the first word of a name or price, I marks the words that continue it, and O marks all other words. This allows multi-word names such as Sambal Gabus Asin Cb to be identified.

The Data

Training data are drawn from CORD-v2, the Consolidated Receipt Dataset, which contains 1,000 photographed Indonesian receipts with line-level annotations. CORD groups the lines of a receipt into rows by group_id, and each row is used as one training sentence:

menu.cnt    "1"
menu.nm     "REAL GANACHE"    ->   "1 REAL GANACHE 16,500"
menu.price  "16,500"

This grouping is what gives the problem its multi-task structure: the sentence class describes the type of row, while the entity tags identify which words within it form the name and which form the price. An example training sentence is shown below.

[ITEM]  1/O  x/O  Nasi/B-NAME  Campur/I-NAME  Bali/I-NAME  75,000/B-PRICE

CORD tags the entire value field of a subtotal or total row as price, so a label word such as Subtotal also carries a price tag.

Split Sentences ITEM ITEM_OPTION SUBTOTAL TOTAL
Train 3,430 1,921 183 531 795
Validation 386 202 19 65 100
Test 414 229 22 63 100

Word-level tags are aligned to BGE-M3 subword tokens using the tokeniser’s word_ids() mapping. Only the first subword of each word carries the tag; continuation subwords and padding are set to -100 and therefore do not contribute to the loss.

Training

Because the backbone is frozen, its token states are computed once, cached and reused in every epoch, and only the heads are trained: 137K trainable parameters against 568M frozen, or 0.024 percent of the model, which makes training feasible on a laptop. The loss is the sum of the two cross-entropy losses. Training used AdamW with a learning rate of 0.001 and a batch size of 64 for 30 epochs.

The MultiTaskModel in the original notebook did not freeze any parameters: it never set requires_grad = False and passed model.parameters() to the optimiser. The training script used for these results, train_heads.py, adds the freeze.

Two line charts of cross-entropy loss by epoch, stacked on a shared epoch axis. Top, sentence classification: validation loss reaches its minimum of about 0.068 at epoch 4 and then climbs to about 0.11 by epoch 30, while training loss falls to near zero. Bottom, entity tagging: training and validation loss both fall steadily from about 0.7 to about 0.25 and are still falling at epoch 30.

Training and validation loss for each head over 30 epochs.

The two tasks benefit from different amounts of training. Classification validation loss reaches its minimum at epoch 4 and then rises while training loss approaches zero, which indicates that the classification head begins to overfit early. Entity tagging validation loss, by contrast, is still decreasing at epoch 30.

A single stopping point therefore requires a compromise between the tasks: stopping early favours classification and leaves entity tagging undertrained, while training for 30 epochs has the opposite effect. Separate learning rates for the two heads, or a loss weight that decays the classification term, would likely suit both tasks better, although neither was tested here.

Two line charts of score by epoch, stacked on a shared epoch axis. Top, sentence classification: validation accuracy and weighted F1 reach about 0.98 by epoch 2 and stay flat, while training accuracy rises to 1.0. Bottom, entity tagging: validation token accuracy and macro-F1 climb from about 0.79 to about 0.93 and are still rising at epoch 30.

Accuracy and F1 for each head over 30 epochs.

Results

Scores on the 414 held-out test lines:

Task Metric Score
Classification Accuracy 0.978
Classification F1 (weighted) 0.979
Entity tagging Token accuracy 0.902
Entity tagging F1 (macro) 0.898

Macro-F1 is reported as the headline entity metric because it weights all five tags equally, so that rarer tags count as much as common ones. In the test labels, B-PRICE is the most frequent tag at about 30 percent of words, and O accounts for about 16 percent.

Example Predictions

The predictions below are produced by the trained heads on held-out test lines.

Eight words of a receipt line, wrapped onto two rows of four, each in a coloured box with its predicted tag below: 1 is O; 35.000, Rp and 35.000 are each B-PRICE; NASI is B-NAME; GOR, SFD and TLR are I-NAME. The second 35.000 has a dashed outline because the reference tags it I-PRICE. The line reads: Sentence class ITEM (correct), tags matching the reference 7 of 8. A bar chart below puts nearly all class probability on ITEM.

One item line from the test set, with the entity tag and class probabilities the model predicted.

The name span and sentence class are both correct, and the only error concerns the price: the reference treats Rp 35.000 as one span, whereas the model begins a new span at 35.000.

Top, a photograph of an Indonesian restaurant receipt from the CORD-v2 test set. Below it, a table of 13 lines with the predicted class, the line text, the name span and the price span. Eleven ITEM rows, one SUBTOTAL and one TOTAL, all classified correctly. Four rows are shaded and outlined with dashes where the tags differ from the reference: Nasi Tambah, Ikan Bawal Besa, the subtotal row and the total row.

A full test receipt run through the model one line at a time.

All 13 lines are assigned the correct sentence class, and the tags match the reference exactly on 9 of them. The four remaining lines illustrate different kinds of error:

  • For 1 Nasi Tambah 7.000, the model gives the name as Nasi and the price as Tambah 7.000, assigning part of the product name to the price.
  • For 1 Ikan Bawal Besa 28.500, the correct name is extracted, but Bawal is tagged as the start of a second name.
  • In the subtotal row, part of the food and drink breakdown is tagged as price, whereas CORD leaves those words outside any span.
  • In the total row, the item count 14 is included in the price span.

Limitations

The data differ from the intended use case. CORD receipts are Indonesian, and the labels are derived by mapping CORD’s hierarchy onto four classes and five tags. English grocery receipts would require their own labelled sample.

The encoder is not adapted. Because the backbone is frozen, errors such as Nasi Tambah can be corrected only through the heads, not the encoder. Unfreezing the top layers would require substantial GPU time rather than a single cached forward pass.

Entity scoring is per token. A name with one incorrect I-NAME tag still receives most of its credit. Strict span matching would count the whole entity as missed and would probably yield a lower score.

A single stopping point serves the two tasks unevenly. Classification overfits from epoch 4, while entity tagging is still improving at epoch 30; this run uses 30 epochs.

OCR is outside the evaluated pipeline. Real Tesseract output would introduce errors into both tasks, and their extent has not been measured. In addition, the segmentation step splits on full stops, while CORD prices use a full stop as the thousands separator (7.000). As written, the step would split such prices in two, so it must be corrected before the OCR path is used.

Next Steps

Unfreeze the top encoder layers. This is the change most likely to improve entity tagging, and it would directly test the decision to freeze the backbone.

Weight the two losses. Decay the classification term once it saturates so that further training benefits entity tagging.

Score entities at span level. Report strict and relaxed span matches alongside token-level macro-F1.

Close the OCR loop. Correct the full-stop split, run Tesseract over the CORD photographs and re-evaluate both tasks on its output.

Also covered
Machine LearningMulti-Task LearningPyTorchTransformersSentence EmbeddingsNamed Entity RecognitionTransfer LearningOCRPython