Table of Contents

Class Donut<T>

Namespace
AiDotNet.Document.PixelToSequence
Assembly
AiDotNet.dll

Donut (Document Understanding Transformer) - OCR-free end-to-end document understanding model.

public class Donut<T> : DocumentNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, IOCRModel<T>, IDocumentQA<T>, IDocumentModel<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>

Type Parameters

T

The numeric type used for calculations.

Inheritance
Donut<T>
Implements
IFullModel<T, Tensor<T>, Tensor<T>>
IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>
IParameterizable<T, Tensor<T>, Tensor<T>>
ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>
IGradientComputable<T, Tensor<T>, Tensor<T>>
Inherited Members
Extension Methods

Remarks

Donut is an OCR-free model that directly converts document images to structured text outputs without requiring a separate OCR stage. It uses a vision encoder (Swin Transformer) and text decoder (BART) architecture.

For Beginners: Unlike traditional document AI which first extracts text using OCR and then processes it, Donut looks directly at the document image pixels and generates text output. This makes it:

  • Simpler: No need for a separate OCR system
  • More robust: Less affected by OCR errors
  • End-to-end trainable: Can optimize for the final task directly

Donut is excellent for:

  • Document parsing (invoices, receipts, forms)
  • Information extraction
  • Document question answering
  • Document classification

Example usage:

var donut = new Donut<float>(architecture);
var result = donut.ParseDocument(documentImage, "invoice");
Console.WriteLine(result.ParsedContent);

Reference: "OCR-free Document Understanding Transformer" (ECCV 2022) https://arxiv.org/abs/2111.15664

Constructors

Donut(NeuralNetworkArchitecture<T>, ITokenizer?, int, int, int, int, int[]?, int[]?, int, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Creates a Donut model using native layers for training and inference.

public Donut(NeuralNetworkArchitecture<T> architecture, ITokenizer? tokenizer = null, int imageHeight = 1920, int imageWidth = 2560, int maxGenerationLength = 768, int embedDim = 128, int[]? depths = null, int[]? numHeads = null, int windowSize = 10, int patchSize = 4, int mlpRatio = 4, int decoderHiddenDim = 1024, int numDecoderLayers = 4, int decoderHeads = 16, int vocabSize = 57522, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture.

tokenizer ITokenizer

Tokenizer for text generation (optional).

imageHeight int

Input image height (default: 1920 for donut-base).

imageWidth int

Input image width (default: 2560 for donut-base).

maxGenerationLength int

Maximum output sequence length (default: 768).

embedDim int

Initial embedding dimension (default: 128 for Swin-B).

depths int[]

Depths of each Swin stage (default: {2,2,14,2} for donut-base).

numHeads int[]

Attention heads per stage (default: {4,8,16,32}).

windowSize int

Window size for attention (default: 10 for donut-base).

patchSize int

Initial patch size (default: 4).

mlpRatio int

MLP expansion ratio (default: 4).

decoderHiddenDim int

Decoder hidden dimension (default: 1024).

numDecoderLayers int

Number of decoder layers (default: 4).

decoderHeads int

Number of decoder attention heads (default: 16).

vocabSize int

Vocabulary size (default: 57522).

optimizer IOptimizer<T, Tensor<T>, Tensor<T>>

Optimizer for training (optional).

lossFunction ILossFunction<T>

Loss function (optional).

Remarks

Default Configuration (donut-base from ECCV 2022 paper): - Input: 2560×1920 RGB images - Encoder: Swin-B with depths {2,2,14,2}, 128 initial dim, window size 10 - Decoder: 4-layer BART-style with 1024 hidden dim

Donut(NeuralNetworkArchitecture<T>, string, string, ITokenizer, int, int, int, int, int[]?, int[]?, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Creates a Donut model using pre-trained ONNX models for inference.

public Donut(NeuralNetworkArchitecture<T> architecture, string encoderPath, string decoderPath, ITokenizer tokenizer, int imageHeight = 1920, int imageWidth = 2560, int maxGenerationLength = 768, int embedDim = 128, int[]? depths = null, int[]? numHeads = null, int windowSize = 10, int patchSize = 4, int decoderHiddenDim = 1024, int numDecoderLayers = 4, int decoderHeads = 16, int vocabSize = 57522, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture.

encoderPath string

Path to the ONNX encoder model.

decoderPath string

Path to the ONNX decoder model.

tokenizer ITokenizer

Tokenizer for text generation.

imageHeight int

Input image height (default: 1920 for donut-base).

imageWidth int

Input image width (default: 2560 for donut-base).

maxGenerationLength int

Maximum output sequence length (default: 768).

embedDim int

Initial embedding dimension (default: 128 for Swin-B).

depths int[]

Depths of each Swin stage (default: {2,2,14,2} for donut-base).

numHeads int[]

Attention heads per stage (default: {4,8,16,32}).

windowSize int

Window size for attention (default: 10 for donut-base).

patchSize int

Initial patch size (default: 4).

decoderHiddenDim int

Decoder hidden dimension (default: 1024).

numDecoderLayers int

Number of decoder layers (default: 4).

decoderHeads int

Number of decoder attention heads (default: 16).

vocabSize int

Vocabulary size (default: 57522).

optimizer IOptimizer<T, Tensor<T>, Tensor<T>>

Optimizer for training (optional, Adam used if null).

lossFunction ILossFunction<T>

Loss function (optional, CrossEntropy used if null).

Exceptions

ArgumentNullException

Thrown if paths or tokenizer is null.

FileNotFoundException

Thrown if ONNX model files don't exist.

Properties

ExpectedImageSize

Gets the expected input image size (assumes square images).

public int ExpectedImageSize { get; }

Property Value

int

Remarks

Common values: 224 (ViT base), 384, 448, 512, 768, 1024. Input images will be resized to [ImageSize x ImageSize] before processing.

IsOCRFree

Gets whether this is an OCR-free model (end-to-end pixel-to-text).

public bool IsOCRFree { get; }

Property Value

bool

Remarks

OCR-free models like Donut directly convert pixels to text without explicit text detection or recognition stages. Traditional OCR has separate stages.

MaxGenerationLength

Gets the maximum generation length for output sequences.

public int MaxGenerationLength { get; }

Property Value

int

RequiresOCR

Gets whether this model requires OCR preprocessing.

public override bool RequiresOCR { get; }

Property Value

bool

Remarks

Layout-aware models (LayoutLM, etc.) require OCR to provide text and bounding boxes. OCR-free models (Donut, Pix2Struct) process raw pixels directly.

SupportedDocumentTypes

Gets the supported document types for this model.

public override DocumentType SupportedDocumentTypes { get; }

Property Value

DocumentType

SupportedLanguages

Gets the languages supported by this OCR model.

public IReadOnlyList<string> SupportedLanguages { get; }

Property Value

IReadOnlyList<string>

Remarks

Languages are specified using ISO 639-1 codes (e.g., "en", "zh", "ja"). Some models support multiple languages simultaneously.

Methods

AnswerQuestion(Tensor<T>, string)

Answers a question about a document.

public DocumentQAResult<T> AnswerQuestion(Tensor<T> documentImage, string question)

Parameters

documentImage Tensor<T>

The document image tensor.

question string

The question to answer in natural language.

Returns

DocumentQAResult<T>

The answer with confidence and evidence information.

AnswerQuestion(Tensor<T>, string, int, double)

Answers a question with generation parameters.

public DocumentQAResult<T> AnswerQuestion(Tensor<T> documentImage, string question, int maxAnswerLength, double temperature = 0)

Parameters

documentImage Tensor<T>

The document image tensor.

question string

The question to answer.

maxAnswerLength int

Maximum length of the generated answer.

temperature double

Sampling temperature for generation (0 = deterministic).

Returns

DocumentQAResult<T>

The answer result.

AnswerQuestions(Tensor<T>, IEnumerable<string>)

Answers multiple questions about a document in a batch.

public IEnumerable<DocumentQAResult<T>> AnswerQuestions(Tensor<T> documentImage, IEnumerable<string> questions)

Parameters

documentImage Tensor<T>

The document image tensor.

questions IEnumerable<string>

The questions to answer.

Returns

IEnumerable<DocumentQAResult<T>>

Answers for each question in order.

Remarks

Batching multiple questions is more efficient than calling AnswerQuestion repeatedly because the document encoding can be reused.

ApplyDefaultPostprocessing(Tensor<T>)

Applies Donut's industry-standard postprocessing: pass-through (autoregressive outputs are already final).

protected override Tensor<T> ApplyDefaultPostprocessing(Tensor<T> modelOutput)

Parameters

modelOutput Tensor<T>

Returns

Tensor<T>

ApplyDefaultPreprocessing(Tensor<T>)

Applies Donut's industry-standard preprocessing: normalize to [-1, 1].

protected override Tensor<T> ApplyDefaultPreprocessing(Tensor<T> rawImage)

Parameters

rawImage Tensor<T>

Returns

Tensor<T>

Remarks

Donut (Document Understanding Transformer) uses mean=0.5, std=0.5 normalization (NAVER paper). Expects large input images (2560x1920 typical).

CreateNewInstance()

Creates a new instance of the same type as this neural network.

protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()

Returns

IFullModel<T, Tensor<T>, Tensor<T>>

A new instance of the same neural network type.

Remarks

For Beginners: This creates a blank version of the same type of neural network.

It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.

DeserializeNetworkSpecificData(BinaryReader)

Deserializes network-specific data that was not covered by the general deserialization process.

protected override void DeserializeNetworkSpecificData(BinaryReader reader)

Parameters

reader BinaryReader

The BinaryReader to read the data from.

Remarks

This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.

For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.

Dispose(bool)

Disposes of resources used by this model.

protected override void Dispose(bool disposing)

Parameters

disposing bool

True if disposing managed resources.

EncodeDocument(Tensor<T>)

Processes a document image and returns encoded features.

public Tensor<T> EncodeDocument(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor [batch, channels, height, width] or [channels, height, width].

Returns

Tensor<T>

Encoded document features suitable for downstream tasks.

Remarks

For Beginners: This method converts a document image into a numerical representation (feature vector) that captures the document's content and structure. These features can then be used for tasks like classification, QA, or information extraction.

ExtractFields(Tensor<T>, IEnumerable<string>)

Extracts specific fields from a document using natural language prompts.

public Dictionary<string, DocumentQAResult<T>> ExtractFields(Tensor<T> documentImage, IEnumerable<string> fieldPrompts)

Parameters

documentImage Tensor<T>

The document image tensor.

fieldPrompts IEnumerable<string>

Field names or extraction prompts (e.g., "invoice_number", "total_amount").

Returns

Dictionary<string, DocumentQAResult<T>>

Dictionary mapping field names to their extracted values and confidence.

Remarks

For Beginners: This is a convenient way to extract multiple pieces of information at once. Instead of asking separate questions, you provide a list of field names and the model extracts all of them from the document.

GetModelMetadata()

Gets the metadata for this neural network model.

public override ModelMetadata<T> GetModelMetadata()

Returns

ModelMetadata<T>

A ModelMetaData object containing information about the model.

GetModelSummary()

Gets a summary of the model architecture.

public string GetModelSummary()

Returns

string

A string describing the model's architecture, parameters, and capabilities.

InitializeLayers()

Initializes the layers of the neural network based on the architecture.

protected override void InitializeLayers()

Remarks

For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.

ParseDocument(Tensor<T>, string)

Parses a document and returns structured output based on the document type.

public string ParseDocument(Tensor<T> documentImage, string documentType)

Parameters

documentImage Tensor<T>

The document image tensor.

documentType string

The type of document (e.g., "invoice", "receipt", "form").

Returns

string

Parsed document content as structured text.

Predict(Tensor<T>)

Makes a prediction using the neural network.

public override Tensor<T> Predict(Tensor<T> input)

Parameters

input Tensor<T>

The input data to process.

Returns

Tensor<T>

The network's prediction.

Remarks

For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).

RecognizeText(Tensor<T>)

Performs full OCR on a document image.

public OCRResult<T> RecognizeText(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor.

Returns

OCRResult<T>

OCR result with text, positions, and confidence scores.

RecognizeTextInRegion(Tensor<T>, Vector<T>)

Performs OCR on a specific region of the document.

public OCRResult<T> RecognizeTextInRegion(Tensor<T> documentImage, Vector<T> region)

Parameters

documentImage Tensor<T>

The document image tensor.

region Vector<T>

The region to process as normalized coordinates [x1, y1, x2, y2] where values are 0-1.

Returns

OCRResult<T>

OCR result for the specified region.

SerializeNetworkSpecificData(BinaryWriter)

Serializes network-specific data that is not covered by the general serialization process.

protected override void SerializeNetworkSpecificData(BinaryWriter writer)

Parameters

writer BinaryWriter

The BinaryWriter to write the data to.

Remarks

This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.

For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.

Train(Tensor<T>, Tensor<T>)

Trains the neural network on a single input-output pair.

public override void Train(Tensor<T> input, Tensor<T> expectedOutput)

Parameters

input Tensor<T>

The input data.

expectedOutput Tensor<T>

The expected output for the given input.

Remarks

This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.

For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)

The network then:

  1. Makes a prediction based on the input
  2. Compares its prediction to the expected output
  3. Calculates how wrong it was (the loss)
  4. Adjusts its internal values to do better next time

After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.

UpdateParameters(Vector<T>)

Updates the network's parameters with new values.

public override void UpdateParameters(Vector<T> gradients)

Parameters

gradients Vector<T>

Remarks

For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.

This is typically used by optimization algorithms that calculate better parameter values based on training data.

ValidateInputShape(Tensor<T>)

Validates that an input tensor has the correct shape for this model.

public void ValidateInputShape(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The tensor to validate.

Exceptions

ArgumentException

Thrown if the tensor shape is invalid.