Table of Contents

Class ASTModel<T>

Namespace
AiDotNet.Audio.Fingerprinting
Assembly
AiDotNet.dll

AST (Audio Spectrogram Transformer) - A pure attention-based model for audio classification.

public class ASTModel<T> : AudioNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<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>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, IAudioFingerprinter<T>

Type Parameters

T

The numeric type used for calculations.

Inheritance
ASTModel<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

The Audio Spectrogram Transformer applies Vision Transformer (ViT) architecture directly to audio spectrograms. It treats audio as a 2D image (time x frequency) and processes it using self-attention mechanisms, achieving state-of-the-art results on audio classification.

Key features:

  • Pure attention-based architecture (no convolutions)
  • Transfer learning from ImageNet-pretrained ViT
  • Excellent for audio event detection and classification
  • Captures long-range temporal dependencies

For Beginners: AST treats audio like an image and uses the same technology that powers modern image recognition!

How it works:

  1. Audio is converted to a spectrogram (a "picture" of sound frequencies over time)
  2. The spectrogram is divided into small patches (like puzzle pieces)
  3. Each patch is processed through attention layers that learn relationships
  4. The model predicts what sounds are present

Why it's powerful:

  • Attention can capture patterns across the entire audio clip
  • Benefits from decades of vision model research
  • Highly accurate for both short and long audio

Use cases:

  • Audio event detection (gunshot, glass breaking, baby crying)
  • Environmental sound classification
  • Music genre classification
  • Speech command recognition

Reference: Gong, Y., Chung, Y. A., & Glass, J. (2021). AST: Audio Spectrogram Transformer.

Constructors

ASTModel(NeuralNetworkArchitecture<T>, int, int, int, int, int, int, int, int, double, double, bool, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Initializes a new instance of the ASTModel<T> class for native training mode.

public ASTModel(NeuralNetworkArchitecture<T> architecture, int sampleRate = 16000, int numClasses = 527, int embeddingDim = 768, int numLayers = 12, int numHeads = 12, int patchSize = 16, int numMelBands = 128, int targetLength = 1024, double mlpRatio = 4, double dropout = 0, bool useDistillation = true, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture defining input/output dimensions.

sampleRate int

Sample rate of input audio (default: 16000 Hz).

numClasses int

Number of output classes (default: 527 for AudioSet).

embeddingDim int

Embedding dimension (default: 768 for base model).

numLayers int

Number of transformer layers (default: 12).

numHeads int

Number of attention heads (default: 12).

patchSize int

Patch size for embedding (default: 16).

numMelBands int

Number of mel frequency bands (default: 128).

targetLength int

Target spectrogram length in frames (default: 1024).

mlpRatio double

MLP hidden dimension ratio (default: 4.0).

dropout double

Dropout rate (default: 0.0).

useDistillation bool

Whether to use knowledge distillation token (default: true).

optimizer IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>

Optimizer for training. If null, a default Adam optimizer is used.

lossFunction ILossFunction<T>

Loss function. If null, cross-entropy is used.

ASTModel(NeuralNetworkArchitecture<T>, string, int, int, int, OnnxModelOptions?)

Initializes a new instance of the ASTModel<T> class for ONNX inference mode.

public ASTModel(NeuralNetworkArchitecture<T> architecture, string modelPath, int sampleRate = 16000, int numClasses = 527, int embeddingDim = 768, OnnxModelOptions? onnxOptions = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture defining input/output dimensions.

modelPath string

Path to the ONNX model file.

sampleRate int

Sample rate of input audio (default: 16000 Hz).

numClasses int

Number of output classes (default: 527 for AudioSet).

embeddingDim int

Embedding dimension (default: 768).

onnxOptions OnnxModelOptions

Optional ONNX model options.

Exceptions

FileNotFoundException

Thrown when the ONNX model file is not found.

Properties

EmbeddingDimension

Gets the embedding dimension.

public int EmbeddingDimension { get; }

Property Value

int

FingerprintLength

Gets the fingerprint length in bits or elements.

public int FingerprintLength { get; }

Property Value

int

Name

Gets the name of the fingerprinting algorithm.

public string Name { get; }

Property Value

string

NumClasses

Gets the number of output classes.

public int NumClasses { get; }

Property Value

int

NumLayers

Gets the number of transformer layers.

public int NumLayers { get; }

Property Value

int

PatchSize

Gets the patch size used for embedding.

public int PatchSize { get; }

Property Value

int

Methods

Classify(Tensor<T>, int)

Classifies audio into categories.

public List<(string Label, double Probability)> Classify(Tensor<T> audio, int topK = 5)

Parameters

audio Tensor<T>

Audio tensor to classify.

topK int

Number of top predictions to return.

Returns

List<(string Label, double Confidence)>

Top-k predictions with probabilities.

ComputeSimilarity(AudioFingerprint<T>, AudioFingerprint<T>)

Computes the similarity between two fingerprints.

public double ComputeSimilarity(AudioFingerprint<T> fp1, AudioFingerprint<T> fp2)

Parameters

fp1 AudioFingerprint<T>

First fingerprint.

fp2 AudioFingerprint<T>

Second fingerprint.

Returns

double

Similarity score (0-1, higher is more similar).

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.

Deserialize(byte[])

Deserializes the neural network from a byte array.

public override void Deserialize(byte[] data)

Parameters

data byte[]

The byte array containing the serialized neural network data.

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.

ExtractEmbedding(Tensor<T>)

Extracts audio embedding from the CLS token.

public Tensor<T> ExtractEmbedding(Tensor<T> audio)

Parameters

audio Tensor<T>

Audio tensor [samples] or [batch, samples].

Returns

Tensor<T>

Audio embedding [batch, embeddingDim].

FindMatches(AudioFingerprint<T>, AudioFingerprint<T>, int)

Finds matching segments between two fingerprints.

public IReadOnlyList<FingerprintMatch> FindMatches(AudioFingerprint<T> query, AudioFingerprint<T> reference, int minMatchLength = 10)

Parameters

query AudioFingerprint<T>

The query fingerprint.

reference AudioFingerprint<T>

The reference fingerprint to search in.

minMatchLength int

Minimum length of matching segment.

Returns

IReadOnlyList<FingerprintMatch>

List of matching segments with time offsets.

Fingerprint(Tensor<T>)

Generates a fingerprint from audio data.

public AudioFingerprint<T> Fingerprint(Tensor<T> audio)

Parameters

audio Tensor<T>

Audio samples as a tensor (mono audio).

Returns

AudioFingerprint<T>

The audio fingerprint.

Fingerprint(Vector<T>)

Generates a fingerprint from audio data.

public AudioFingerprint<T> Fingerprint(Vector<T> audio)

Parameters

audio Vector<T>

Audio samples as a vector (mono audio).

Returns

AudioFingerprint<T>

The audio fingerprint.

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.

InitializeLayers()

Initializes the neural network layers.

protected override void InitializeLayers()

PostprocessOutput(Tensor<T>)

Postprocesses model output.

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

Parameters

modelOutput Tensor<T>

Returns

Tensor<T>

Predict(Tensor<T>)

Predicts classification logits.

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

Parameters

input Tensor<T>

Returns

Tensor<T>

PreprocessAudio(Tensor<T>)

Preprocesses raw audio waveform for model input.

protected override Tensor<T> PreprocessAudio(Tensor<T> rawAudio)

Parameters

rawAudio Tensor<T>

Returns

Tensor<T>

Serialize()

Serializes the neural network to a byte array.

public override byte[] Serialize()

Returns

byte[]

A byte array representing the serialized neural network.

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 model on audio-label pairs.

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

Parameters

input Tensor<T>
expected Tensor<T>

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.