Class MATCHA<T>
- Namespace
- AiDotNet.Document.PixelToSequence
- Assembly
- AiDotNet.dll
MATCHA (Math-Aware Transformer for Chart Harvesting and Analysis) for chart understanding.
public class MATCHA<T> : DocumentNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, IDocumentQA<T>, ITableExtractor<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
TThe numeric type used for calculations.
- Inheritance
-
MATCHA<T>
- Implements
-
IDocumentQA<T>
- Inherited Members
- Extension Methods
Remarks
MATCHA is designed specifically for understanding charts and plots, combining math-aware pre-training with visual encoding to extract data, answer questions, and summarize chart content.
For Beginners: MATCHA specializes in understanding charts: 1. Reads bar charts, line graphs, pie charts, scatter plots 2. Extracts underlying numerical data 3. Answers questions about chart content 4. Generates summaries of chart insights
Key features:
- Math-aware pre-training for numerical reasoning
- Pix2Struct-based architecture
- Chart derendering (image to data table)
- Chart QA and summarization
Example usage:
var model = new MATCHA<float>(architecture);
var result = model.AnswerQuestion(chartImage, "What is the highest value?");
Reference: "MatCha: Enhancing Visual Language Pretraining with Math Reasoning and Chart Derendering" (ACL 2023) https://arxiv.org/abs/2212.09662
Constructors
MATCHA(NeuralNetworkArchitecture<T>, int, int, int, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Creates a MATCHA model using native layers for training and inference.
public MATCHA(NeuralNetworkArchitecture<T> architecture, int imageSize = 2048, int maxSequenceLength = 512, int encoderDim = 1536, int decoderDim = 1536, int encoderLayers = 18, int decoderLayers = 18, int numHeads = 24, int vocabSize = 50265, int maxPatchesPerImage = 4096, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)
Parameters
architectureNeuralNetworkArchitecture<T>imageSizeintmaxSequenceLengthintencoderDimintdecoderDimintencoderLayersintdecoderLayersintnumHeadsintvocabSizeintmaxPatchesPerImageintoptimizerIOptimizer<T, Tensor<T>, Tensor<T>>lossFunctionILossFunction<T>
Remarks
Default Configuration (MATCHA from ACL 2023): - Based on Pix2Struct architecture - Variable-resolution patch encoding - Math-aware pre-training - Chart derendering capability - 18 encoder + 18 decoder layers
MATCHA(NeuralNetworkArchitecture<T>, string, int, int, int, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Creates a MATCHA model using a pre-trained ONNX model for inference.
public MATCHA(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, int imageSize = 2048, int maxSequenceLength = 512, int encoderDim = 1536, int decoderDim = 1536, int encoderLayers = 18, int decoderLayers = 18, int numHeads = 24, int vocabSize = 50265, int maxPatchesPerImage = 4096, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)
Parameters
architectureNeuralNetworkArchitecture<T>onnxModelPathstringimageSizeintmaxSequenceLengthintencoderDimintdecoderDimintencoderLayersintdecoderLayersintnumHeadsintvocabSizeintmaxPatchesPerImageintoptimizerIOptimizer<T, Tensor<T>, Tensor<T>>lossFunctionILossFunction<T>
Properties
ExpectedImageSize
Gets the expected input image size (assumes square images).
public int ExpectedImageSize { get; }
Property Value
Remarks
Common values: 224 (ViT base), 384, 448, 512, 768, 1024. Input images will be resized to [ImageSize x ImageSize] before processing.
MaxPatchesPerImage
Gets the maximum patches per image.
public int MaxPatchesPerImage { get; }
Property Value
RequiresOCR
Gets whether this model requires OCR preprocessing.
public override bool RequiresOCR { get; }
Property Value
Remarks
Layout-aware models (LayoutLM, etc.) require OCR to provide text and bounding boxes. OCR-free models (Donut, Pix2Struct) process raw pixels directly.
SupportedChartTypes
Gets the supported chart types.
public IReadOnlyList<string> SupportedChartTypes { get; }
Property Value
SupportedDocumentTypes
Gets the supported document types for this model.
public override DocumentType SupportedDocumentTypes { get; }
Property Value
SupportsBorderedTables
Gets whether this model supports bordered tables.
public bool SupportsBorderedTables { get; }
Property Value
SupportsBorderlessTables
Gets whether this model supports borderless tables.
public bool SupportsBorderlessTables { get; }
Property Value
SupportsMergedCells
Gets whether this model can detect merged cells (row/column spans).
public bool SupportsMergedCells { get; }
Property Value
Methods
AnswerQuestion(Tensor<T>, string)
Answers a question about a document.
public DocumentQAResult<T> AnswerQuestion(Tensor<T> documentImage, string question)
Parameters
documentImageTensor<T>The document image tensor.
questionstringThe 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
documentImageTensor<T>The document image tensor.
questionstringThe question to answer.
maxAnswerLengthintMaximum length of the generated answer.
temperaturedoubleSampling 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
documentImageTensor<T>The document image tensor.
questionsIEnumerable<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 MATCHA's industry-standard postprocessing: pass-through (chart QA outputs are already final).
protected override Tensor<T> ApplyDefaultPostprocessing(Tensor<T> modelOutput)
Parameters
modelOutputTensor<T>
Returns
- Tensor<T>
ApplyDefaultPreprocessing(Tensor<T>)
Applies MATCHA's industry-standard preprocessing: ImageNet normalization.
protected override Tensor<T> ApplyDefaultPreprocessing(Tensor<T> rawImage)
Parameters
rawImageTensor<T>
Returns
- Tensor<T>
Remarks
MATCHA (Math-Aware Chart Handling Architecture) uses ImageNet normalization with mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225] (Google paper).
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
readerBinaryReaderThe 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.
DetectTables(Tensor<T>)
Detects tables in a document image.
public IEnumerable<TableRegion<T>> DetectTables(Tensor<T> documentImage)
Parameters
documentImageTensor<T>The document image tensor.
Returns
- IEnumerable<TableRegion<T>>
List of detected table regions with bounding boxes.
Dispose(bool)
Disposes of resources used by this model.
protected override void Dispose(bool disposing)
Parameters
disposingboolTrue if disposing managed resources.
EncodeDocument(Tensor<T>)
Processes a document image and returns encoded features.
public Tensor<T> EncodeDocument(Tensor<T> documentImage)
Parameters
documentImageTensor<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.
ExportTables(Tensor<T>, TableExportFormat)
Exports detected tables to a specific format.
public string ExportTables(Tensor<T> documentImage, TableExportFormat format)
Parameters
documentImageTensor<T>The document image tensor.
formatTableExportFormatOutput format (CSV, JSON, HTML, Markdown, Excel).
Returns
- string
Serialized table data in the specified format.
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
documentImageTensor<T>The document image tensor.
fieldPromptsIEnumerable<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.
ExtractTableContent(Tensor<T>)
Extracts table content as structured data.
public IEnumerable<List<List<string>>> ExtractTableContent(Tensor<T> documentImage)
Parameters
documentImageTensor<T>The document image tensor.
Returns
- IEnumerable<List<List<string>>>
Tables as lists of rows, where each row is a list of cell contents.
Remarks
This is a convenience method that combines table detection, structure recognition, and OCR to return the final table content.
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
inputTensor<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).
RecognizeStructure(Tensor<T>)
Recognizes the structure of a table (rows, columns, cells).
public TableStructureResult<T> RecognizeStructure(Tensor<T> tableImage)
Parameters
tableImageTensor<T>Cropped table image tensor (from DetectTables).
Returns
- TableStructureResult<T>
Table structure with cell positions and spans.
SerializeNetworkSpecificData(BinaryWriter)
Serializes network-specific data that is not covered by the general serialization process.
protected override void SerializeNetworkSpecificData(BinaryWriter writer)
Parameters
writerBinaryWriterThe 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
inputTensor<T>The input data.
expectedOutputTensor<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:
- Makes a prediction based on the input
- Compares its prediction to the expected output
- Calculates how wrong it was (the loss)
- 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
gradientsVector<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
documentImageTensor<T>The tensor to validate.
Exceptions
- ArgumentException
Thrown if the tensor shape is invalid.