Donut consists of a vision encoder (Swin Transformer) and a text decoder (BART).
Given an image, the encoder first encodes the image into a tensor of embeddings (of shape batch_size, seq_len, hidden_size),
after which the decoder autoregressively generates text, conditioned on the encoding of the encoder.
Donut_architecture
How to use
py
1import torch
2from PIL import Image
3from transformers import DonutProcessor, VisionEncoderDecoderConfig, VisionEncoderDecoderModel
45model_id ="hf-tuner/donut-base-finetuned-docvqa"67config = VisionEncoderDecoderConfig.from_pretrained(model_id)8processor = DonutProcessor.from_pretrained(model_id)9device ="cuda"if torch.cuda.is_available()else"cpu"10config.dtype = torch.float16 if torch.cuda.is_available()else torch.float32
1112model = VisionEncoderDecoderModel.from_pretrained(ckpt, config=config)13model.to(device)1415PROMPT_TEMPLATE ="<doc_vqa><s><s_question>{}</s_question><s_answer>"1617defpredict(image, question):18 prompt = PROMPT_TEMPLATE.format(question)1920 pixel_values = processor(image,21 return_tensors="pt"22).pixel_values.to(device)23 decoder_input_ids = processor.tokenizer(prompt,24 add_special_tokens=False,25 return_tensors="pt"26).input_ids.to(device)2728 generated_ids = model.generate(pixel_values,29 decoder_input_ids=decoder_input_ids,30 max_length=64,31 bad_words_ids=[[processor.tokenizer.unk_token_id]]32)33 generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]34 output_json = processor.token2json(generated_text)35return output_json
3637output = predict(image=Image.open('doc-image.png'), question="Which is the date of the approval form?")38# {"question": "Which is the date of the approval form?", "answer": "april 5, 1995"}
Training hyperparameters
The following hyperparameters were used during training:
learning_rate: 2e-05
train_batch_size: 1
eval_batch_size: 8
seed: 42
optimizer: Use OptimizerNames.ADAMW_TORCH with betas=(0.9,0.999) and epsilon=1e-08 and optimizer_args=No additional optimizer arguments