Originally published in Towards AI.
The Donut model in Python is a model to extract text from a given image. This can be useful in several scenarios, for example, when it comes to scanning receipts. You can easily download the Donut model from GitHub, but as is common with AI models, you should fine-tune the model for your specific needs. This article was written as I did not find any tutorials showing me exactly how to fine-tune the Donut model with my dataset. I therefore had to learn this from other tutorials (which will be linked throughout the tutorial) and figure out issues myself. These issues were especially prevalent as I did not have a GPU on my local computer, and to simplify the process for others, I therefore made this tutorial.

Extract information from receipts. The picture was taken from this Google Colab file using a photo taken by me
Story overview
Finding a dataset to fine-tune with
Fine-tuning with Google Colab
Changing parameters
Fine-tuning locally
Finding a dataset to fine-tune with
Finding a dataset online
To fine-tune the model, we need a dataset to fine-tune with. If you want a simple solution, you can find a prepared dataset in this folder on Google Drive. You should then copy this dataset over to your own Google Drive. Note that this was taken from this tutorial under the “Downloading and parsing SROIE” headline. The tutorial is a great read, which inspired this article, as I wanted to create a more in-depth tutorial for fine-tuning the Donut model in Google Colab. So if you want a more in-depth look at generating the dataset, I recommend reading the tutorial above.
The dataset linked above, however, is not necessarily for your specific purpose. If you want to fine-tune a model to your specific needs, you either need to find a fitting dataset online or create a dataset yourself.
Annotating your own dataset
Annotating your own dataset is a surefire way to create a dataset that perfectly fits your needs. There are many annotating tools online, but a free one I recommend is the Sparrow UI data annotation tool. Here you can upload your image, put bounding boxes on the image, and label each bounding box. You can then extract the labeled data in JSON format and use it following the rest of the tutorial. Make sure your dataset is in the same format as the dataset I have provided earlier.
Annotating a receipt with the Sparrow UI data annotation tool
Fine-tuning with Google Colab
To make the fine-tuning process as simple as possible, I provided a Google Colab file you can use here. (Some code is taken from this GitHub page). Note that package versions need to be exactly as provided in the Drive, as wrong package versions were the root of a lot of the problems I faced fine-tuning the Donut model myself.
Before fine-tuning using the Google Colab file, there are 3 things you need to do.
Upload data to your Google Drive.
Upload the dataset I provided earlier to your Google Drive (in the root folder). Also, download this config file and add it to the root folder of your Google Drive.
2. Link your Google Drive, to your Google Colab.
Press the files icon (red in the image below), and the the Mount Drive Icon (blue in the image below). Then you will get a code snippet that you can run, and now your Google Drive is connected. Note that if you have not connected Google Colab to Google Drive before, you have to log into your Google Drive after pressing the Drive icon, and give permission for Colab to access Drive (prompts for this should appear automatically when you try to link the Drive)
3. Change one line of code inside a downloaded package.
After running all the cells with pip installations in the provided Google Colab file, you need to change a line in one of the packages, due to a bug (Note that this is probably something to do with a package version, though I could not find another solution than the one I am providing here). The bug gave the error: AttributeError: ‘SwinTransformer’ object has no attribute ‘pos_drop’. To solve this, do the following:
Press the files directory again (red circle in the image above), and go to the following file (note you have to start from the root directory in the files page on Google Colab):
usr/local/lib/python3.10/dist-packages/donut/model.py
Double-click the file to open it, go to line 100, and comment it out (see image below):

Finally: restart your runtime
After altering files on Google Colab, you always have to restart your runtime to see the latest updates.
Changing parameters
Great! Now you can run the cells in the notebook, and you should receive a fine-tuned model. Remember, you can also change the Config parameters to, for example, train for longer, use more workers, and so on.

Example of Config parameters you can change.
Note that I am working with the Donut model fine-tuned on the CORD dataset, as I want to be able to read receipts. You can also find other Donut models here, with the other options being Document parsing, Document classification, or document visual question answering (DocVQA).
Fine-tuning locally
Fine-tuning can also be run locally, mostly relevant for you if you have a GPU, as CPU training will take a long time. To run locally, you have to:
First, clone this GitHub repository
Add the prepared fine-tuning dataset to the root folder.
If you want to save the fine-tuned model, add the line below to train.py line 164, right below “trainer.fit(…)”
#...
trainer.save_checkpoint(f”{Path(config.result_path)}/{config.exp_name}/{config.exp_version}/model_checkpoint.ckpt”)
#...4. You then need to comment out GPU processes in the PyTorch Lightning Trainer, and add the line: accelerator=”cpu”
#train.py file
#...
trainer = pl.Trainer(
#Comment out the lines above
# num_nodes=config.get(”num_nodes”, 1),
# devices=torch.cuda.device_count(),
# strategy=”dp”,
# accelerator=”gpu”,
accelerator=”cpu”, #TODO add this line
plugins=custom_ckpt,
max_epochs=config.max_epochs,
max_steps=config.max_steps,
val_check_interval=config.val_check_interval,
check_val_every_n_epoch=config.check_val_every_n_epoch,
gradient_clip_val=config.gradient_clip_val,
precision=16,
num_sanity_val_steps=0,
logger=logger,
callbacks=[lr_callback, checkpoint_callback, bar],
)
#...5. Make sure the max_epochs parameter in your Config file is set to -1 (if not, you will get a division by zero error). You can decide the training time by setting the parameter max_steps
6. Fine-tuning can then be run with:
python train.py --config config/train_cord.yamlWhere “train_cord.yaml” is the Configuration file you want to use.
Source of problems
After a lot of testing, I realized most problems that appear when using Donut, both on Google Colab and in a local environment, are package versions. For many packages, you cannot use the latest versions, and you therefore have to install specific versions. I, therefore, list all my packages and their version below (note that this is mostly relevant for a local runtime, as I have specified the required packages in the linked Google Colab file):
absl-py==1.4.0
aiofiles==23.2.1
aiohttp==3.8.5
aiosignal==1.3.1
altair==5.1.0
annotated-types==0.5.0
ansicon==1.89.0
anyio==3.7.1
arrow==1.2.3
asttokens==2.2.1
async-timeout==4.0.3
attrs==23.1.0
backcall==0.2.0
backoff==2.2.1
beautifulsoup4==4.12.2
blessed==1.20.0
blinker==1.6.2
cachetools==5.3.1
certifi==2023.7.22
cffi==1.15.1
charset-normalizer==3.2.0
click==8.1.7
colorama==0.4.6
comm==0.1.4
contourpy==1.1.0
croniter==1.4.1
cycler==0.11.0
Cython==3.0.2
datasets==2.14.4
dateutils==0.6.12
debugpy==1.6.7.post1
decorator==5.1.1
deepdiff==6.3.1
dill==0.3.7
exceptiongroup==1.1.3
executing==1.2.0
fastapi==0.103.0
ffmpy==0.3.1
filelock==3.12.3
Flask==2.3.3
fonttools==4.42.1
frozenlist==1.4.0
fsspec==2023.6.0
google-auth==2.22.0
google-auth-oauthlib==1.0.0
gradio==3.41.2
gradio_client==0.5.0
grpcio==1.57.0
h11==0.14.0
httpcore==0.17.3
httpx==0.24.1
huggingface-hub==0.16.4
idna==3.4
importlib-resources==6.0.1
imutils==0.5.4
inquirer==3.1.3
ipykernel==6.25.1
ipython==8.14.0
itsdangerous==2.1.2
jedi==0.19.0
Jinja2==3.1.2
jinxed==1.2.0
joblib==1.3.2
jsonschema==4.19.0
jsonschema-specifications==2023.7.1
jupyter_client==8.3.0
jupyter_core==5.3.1
kiwisolver==1.4.5
lightning @ git+https://github.com/PyTorchLightning/pytorch-lightning@d5440a0b3fa0474674b329c1790755b9994f9632
lightning-cloud==0.5.37
lightning-utilities==0.9.0
Markdown==3.4.4
markdown-it-py==3.0.0
MarkupSafe==2.1.3
matplotlib==3.7.2
matplotlib-inline==0.1.6
mdurl==0.1.2
mpmath==1.3.0
multidict==6.0.4
multiprocess==0.70.15
munch==4.0.0
nest-asyncio==1.5.7
networkx==3.1
nltk==3.8.1
numpy==1.25.2
oauthlib==3.2.2
opencv-python==4.8.0.76
ordered-set==4.1.0
orjson==3.9.5
packaging==23.1
pandas==2.0.3
parso==0.8.3
pickleshare==0.7.5
Pillow==10.0.0
platformdirs==3.10.0
prompt-toolkit==3.0.39
protobuf==3.20.1
psutil==5.9.5
pure-eval==0.2.2
pyarrow==13.0.0
pyasn1==0.5.0
pyasn1-modules==0.3.0
pycparser==2.21
pydantic==2.1.1
pydantic_core==2.4.0
pyDeprecate==0.3.2
pydub==0.25.1
Pygments==2.16.1
PyJWT==2.8.0
Pympler==1.0.1
pyparsing==3.0.9
pytesseract==0.3.10
python-dateutil==2.8.2
python-editor==1.0.4
python-multipart==0.0.6
pytorch-lightning==2.0.7
pytz==2023.3
pywin32==306
PyYAML==6.0.1
pyzmq==25.1.1
readchar==4.0.5
referencing==0.30.2
regex==2023.8.8
requests==2.31.0
requests-oauthlib==1.3.1
rich==13.5.2
rpds-py==0.10.0
rsa==4.9
ruamel.yaml==0.17.32
ruamel.yaml.clib==0.2.7
safetensors==0.3.3
scipy==1.11.2
sconf==0.2.5
semantic-version==2.10.0
sentencepiece==0.1.99
six==1.16.0
smmap==5.0.0
sniffio==1.3.0
soundfile==0.12.1
soupsieve==2.4.1
stack-data==0.6.2
starlette==0.27.0
starsessions==1.3.0
sympy==1.12
tenacity==8.2.3
tensorboard==2.14.0
tensorboard-data-server==0.7.1
timm==0.5.4
tokenizers==0.13.3
toml==0.10.2
toolz==0.12.0
torch==2.0.1+cu117
torchaudio==2.0.2+cu117
torchmetrics==1.1.0
torchvision==0.15.2+cu117
tornado==6.3.3
tqdm==4.66.1
traitlets==5.9.0
transformers==4.25.1
typing_extensions==4.7.1
tzdata==2023.3
urllib3==1.26.16
uvicorn==0.23.2
validators==0.21.2
watchdog==3.0.0
wcwidth==0.2.6
websocket-client==1.6.2
websockets==11.0.3
Werkzeug==2.3.7
xxhash==3.3.0
yarl==1.9.2
zipp==3.16.2
zss==1.2.0You can then copy this to your working directory, activate your virtual environment, and install the packages with specific versions with the command:
pip install -r requirements.txtRunning on CPU
If you are running on CPU after all, you will encounter some problems unless you make some changes:
donut/train.py, change the “accelerator” parameter to “cpu” (from “gpu”), and remove the parameters: “num_nodes”, “devices”, and “strategy”.
Then, in your Config file (for example, “train_cord.yaml”), set max_epochs to -1, and then specify the parameter “max_steps”. This is because you will encounter a division by 0 error if you have max_epoch larger than 0
After these changes, running on a CPU should work as well.
Conclusion
In this article, I have shown you how to easily fine-tune the Donut model using your own data, something which will hopefully result in improved accuracy for your fine-tuned Donut model. The applicabilities of the Donut model are endless, and this is just one way to use it, which I hope is useful.
Related reading
Get practical AI-engineering workflows in your inbox.
If you also use coding agents to build your AI projects, explore my configuration library. The paid Vault includes global and project templates, commands, hook configuration, prompt patterns and the parallel-agent setup. Access and updates are included while subscribed.
Try the free Claude Code Setup Pack · My website · LinkedIn · X



