Multi-Task Sentence Transformer for Receipt Processing
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
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
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.
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.
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.
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.
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 asNasiand the price asTambah 7.000, assigning part of the product name to the price. - For
1 Ikan Bawal Besa 28.500, the correct name is extracted, butBawalis 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
14is 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.





