Table of Contents

Class DocFormer<T>

Namespace
AiDotNet.Document.LayoutAware
Assembly
AiDotNet.dll

DocFormer neural network for end-to-end document understanding.

public class DocFormer<T> : DocumentNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, ILayoutDetector<T>, IDocumentClassifier<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
DocFormer<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

DocFormer is a multi-modal transformer that jointly learns text, visual, and spatial features for document understanding tasks. It uses shared spatial encodings across all modalities.

For Beginners: DocFormer combines three types of information: 1. Text content (what the words say) 2. Visual features (what the document looks like) 3. Spatial layout (where elements are positioned)

Unlike LayoutLM which adds position embeddings to text, DocFormer uses shared spatial encodings that align all three modalities in the same coordinate space.

Example usage:

var model = new DocFormer<float>(architecture);
var result = model.DetectLayout(documentImage);

Reference: "DocFormer: End-to-End Transformer for Document Understanding" (ICCV 2021) https://arxiv.org/abs/2106.11539

Constructors

DocFormer(NeuralNetworkArchitecture<T>, ITokenizer?, int, int, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

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

public DocFormer(NeuralNetworkArchitecture<T> architecture, ITokenizer? tokenizer = null, int numClasses = 16, int imageSize = 224, int maxSequenceLength = 512, int hiddenDim = 768, int numLayers = 12, int numHeads = 12, int vocabSize = 30522, int spatialDim = 128, 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 processing (optional).

numClasses int

Number of output classes (default: 16 for RVL-CDIP).

imageSize int

Input image size (default: 224).

maxSequenceLength int

Maximum sequence length (default: 512).

hiddenDim int

Hidden dimension (default: 768).

numLayers int

Number of transformer layers (default: 12).

numHeads int

Number of attention heads (default: 12).

vocabSize int

Vocabulary size (default: 30522).

spatialDim int

Spatial embedding dimension (default: 128).

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

Optimizer for training (optional).

lossFunction ILossFunction<T>

Loss function (optional).

Remarks

Default Configuration (DocFormer-Base from ICCV 2021): - Text encoder: BERT-base architecture - Visual encoder: ResNet-50 backbone - Shared spatial encodings for all modalities - Hidden dimension: 768 - Layers: 12, Heads: 12 - Image size: 224x224

DocFormer(NeuralNetworkArchitecture<T>, string, ITokenizer, int, int, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Creates a DocFormer model using a pre-trained ONNX model for inference.

public DocFormer(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, ITokenizer tokenizer, int numClasses = 16, int imageSize = 224, int maxSequenceLength = 512, int hiddenDim = 768, int numLayers = 12, int numHeads = 12, int vocabSize = 30522, int spatialDim = 128, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture.

onnxModelPath string

Path to the ONNX model file.

tokenizer ITokenizer

Tokenizer for text processing.

numClasses int

Number of output classes (default: 16 for RVL-CDIP).

imageSize int

Input image size (default: 224).

maxSequenceLength int

Maximum sequence length (default: 512).

hiddenDim int

Hidden dimension (default: 768).

numLayers int

Number of transformer layers (default: 12).

numHeads int

Number of attention heads (default: 12).

vocabSize int

Vocabulary size (default: 30522).

spatialDim int

Spatial embedding dimension (default: 128).

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

Optimizer for training (optional).

lossFunction ILossFunction<T>

Loss function (optional).

Properties

AvailableCategories

Gets the available document classification categories.

public IReadOnlyList<string> AvailableCategories { get; }

Property Value

IReadOnlyList<string>

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.

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

SupportedElementTypes

Gets the layout element types this detector can identify.

public IReadOnlyList<LayoutElementType> SupportedElementTypes { get; }

Property Value

IReadOnlyList<LayoutElementType>

Methods

ApplyDefaultPostprocessing(Tensor<T>)

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

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

Parameters

modelOutput Tensor<T>

Returns

Tensor<T>

ApplyDefaultPreprocessing(Tensor<T>)

Applies DocFormer's industry-standard preprocessing: ImageNet normalization.

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

Parameters

rawImage Tensor<T>

Returns

Tensor<T>

Remarks

DocFormer uses ImageNet normalization with mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225].

ClassifyDocument(Tensor<T>)

Classifies a document image into predefined categories.

public DocumentClassificationResult<T> ClassifyDocument(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor.

Returns

DocumentClassificationResult<T>

Classification result with predicted category and confidence.

ClassifyDocument(Tensor<T>, int)

Classifies a document and returns top-K predictions.

public DocumentClassificationResult<T> ClassifyDocument(Tensor<T> documentImage, int topK)

Parameters

documentImage Tensor<T>

The document image tensor.

topK int

Number of top predictions to return.

Returns

DocumentClassificationResult<T>

Classification result with top-K predictions.

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.

DetectLayout(Tensor<T>)

Detects layout regions in a document image.

public DocumentLayoutResult<T> DetectLayout(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

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

Returns

DocumentLayoutResult<T>

Layout detection result with regions and their types.

DetectLayout(Tensor<T>, double)

Detects layout regions with a specified confidence threshold.

public DocumentLayoutResult<T> DetectLayout(Tensor<T> documentImage, double confidenceThreshold)

Parameters

documentImage Tensor<T>

The document image tensor.

confidenceThreshold double

Minimum confidence for detected regions (0.0 to 1.0).

Returns

DocumentLayoutResult<T>

Filtered layout detection result.

Remarks

Higher thresholds return fewer but more confident detections. Lower thresholds return more detections but may include false positives.

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.

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.

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).

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.