Table of Contents

Class TimeSformer<T>

Namespace
AiDotNet.Video.ActionRecognition
Assembly
AiDotNet.dll

TimeSformer: Is Space-Time Attention All You Need for Video Understanding?

public class TimeSformer<T> : NeuralNetworkBase<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

Type Parameters

T

The numeric type used for calculations (typically float or double).

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

For Beginners: TimeSformer is a transformer-based model for video classification that applies attention across both space and time dimensions. Unlike CNNs that use 3D convolutions, TimeSformer uses pure self-attention to understand video content.

Key capabilities:

  • Video action recognition (classify what action is happening)
  • Temporal reasoning (understand events across time)
  • Scene understanding (understand spatial context)

The model uses "divided space-time attention" where:

  1. First, attention is applied across time (same spatial location, different frames)
  2. Then, attention is applied across space (same frame, different locations)

Example usage (native mode for training):

var arch = new NeuralNetworkArchitecture<double>(
    inputType: InputType.ThreeDimensional,
    inputHeight: 224, inputWidth: 224, inputDepth: 3);
var model = new TimeSformer<double>(arch, numClasses: 400);
model.Train(videoFrames, expectedLabels);
var predictions = model.Classify(videoFrames);

Example usage (ONNX mode for inference only):

var arch = new NeuralNetworkArchitecture<double>(
    inputType: InputType.ThreeDimensional,
    inputHeight: 224, inputWidth: 224, inputDepth: 3);
var model = new TimeSformer<double>(arch, "timesformer.onnx");
var predictions = model.Classify(videoFrames);

Technical Details: - Divided space-time attention for efficiency - Patch embedding similar to ViT - Learnable positional embeddings for space and time - Classification token for final prediction

Reference: "Is Space-Time Attention All You Need for Video Understanding?" https://arxiv.org/abs/2102.05095

Constructors

TimeSformer(NeuralNetworkArchitecture<T>, int, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?, int, int, int, int, int, AttentionType)

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

public TimeSformer(NeuralNetworkArchitecture<T> architecture, int numClasses = 400, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null, int embedDim = 768, int numHeads = 12, int numLayers = 12, int numFrames = 8, int patchSize = 16, AttentionType attentionType = AttentionType.DividedSpaceTime)

Parameters

architecture NeuralNetworkArchitecture<T>

Architecture for the video encoder.

numClasses int

Number of output classes for classification.

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

Optional optimizer for training. Default: Adam.

lossFunction ILossFunction<T>

Optional loss function. Default: CrossEntropy.

embedDim int

Embedding dimension (default: 768).

numHeads int

Number of attention heads (default: 12).

numLayers int

Number of transformer layers (default: 12).

numFrames int

Number of frames to process (default: 8).

patchSize int

Patch size for tokenization (default: 16).

attentionType AttentionType

Type of space-time attention (default: DividedSpaceTime).

TimeSformer(NeuralNetworkArchitecture<T>, string, int, int)

Creates a TimeSformer model using a pretrained ONNX model for inference.

public TimeSformer(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, int numClasses = 400, int embedDim = 768)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture configuration.

onnxModelPath string

Path to the pretrained ONNX model.

numClasses int

Number of output classes (default: 400 for Kinetics).

embedDim int

Embedding dimension of the model (default: 768).

Properties

SupportsTraining

Gets whether training is supported (only in native mode).

public override bool SupportsTraining { get; }

Property Value

bool

Methods

Classify(Tensor<T>)

Classifies video frames into action categories.

public Tensor<T> Classify(Tensor<T> videoFrames)

Parameters

videoFrames Tensor<T>

Video frames tensor [B, T, C, H, W] or [T, C, H, W].

Returns

Tensor<T>

Class probabilities tensor [B, NumClasses] or [NumClasses].

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.

ExtractFeatures(Tensor<T>)

Extracts video features before the classification head.

public Tensor<T> ExtractFeatures(Tensor<T> videoFrames)

Parameters

videoFrames Tensor<T>

Video frames tensor.

Returns

Tensor<T>

Feature embedding tensor.

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.

GetTopKPredictions(Tensor<T>, int)

Gets the top-K predicted action classes with probabilities.

public List<(int ClassIndex, double Probability)> GetTopKPredictions(Tensor<T> videoFrames, int topK = 5)

Parameters

videoFrames Tensor<T>

Video frames tensor.

topK int

Number of top predictions to return.

Returns

List<(int ClassIndex, double Probability)>

List of (classIndex, probability) pairs sorted by probability.

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

Parameters

parameters Vector<T>

The new parameter values to set.

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.