Table of Contents

Class AnimateDiff<T>

Namespace
AiDotNet.Video.Generation
Assembly
AiDotNet.dll

AnimateDiff: Motion module for animating text-to-image diffusion models.

public class AnimateDiff<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
AnimateDiff<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

AnimateDiff is a motion module that: - Adds temporal coherence to image diffusion models - Converts image generators into video generators - Learns motion patterns from video data

For Beginners: AnimateDiff makes still image generators create videos. It plugs into existing models like Stable Diffusion to add movement. Instead of generating one image, it generates multiple frames that flow smoothly.

Example usage (native mode for training):

var arch = new NeuralNetworkArchitecture<double>(
    inputType: InputType.ThreeDimensional,
    inputHeight: 64, inputWidth: 64, inputDepth: 320);
var model = new AnimateDiff<double>(arch);
model.Train(inputFeatures, motionFeatures);
var animatedFeatures = model.AddMotion(staticFeatures);

Example usage (ONNX mode for inference only):

var arch = new NeuralNetworkArchitecture<double>(
    inputType: InputType.ThreeDimensional,
    inputHeight: 64, inputWidth: 64, inputDepth: 320);
var model = new AnimateDiff<double>(arch, "animatediff.onnx");
var animatedFeatures = model.AddMotion(staticFeatures);

Reference: "AnimateDiff: Animate Your Personalized Text-to-Image Diffusion Models" https://arxiv.org/abs/2307.04725

Constructors

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

Creates an AnimateDiff model using native layers for training and inference.

public AnimateDiff(NeuralNetworkArchitecture<T> architecture, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null, int inputChannels = 320, int numLayers = 8, int numFrames = 16)

Parameters

architecture NeuralNetworkArchitecture<T>

Architecture for the motion module.

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

Optional optimizer for training. Default: Adam.

lossFunction ILossFunction<T>

Optional loss function. Default: MSE.

inputChannels int

Number of input feature channels (default: 320).

numLayers int

Number of motion transformer layers (default: 8).

numFrames int

Number of video frames (default: 16).

Remarks

For Beginners: Create a trainable AnimateDiff model:

var arch = new NeuralNetworkArchitecture<double>(
    inputType: InputType.ThreeDimensional,
    inputHeight: 64, inputWidth: 64, inputDepth: 320);
var model = new AnimateDiff<double>(arch);

AnimateDiff(NeuralNetworkArchitecture<T>, string, int)

Creates an AnimateDiff model using a pretrained ONNX model for inference.

public AnimateDiff(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, int numFrames = 16)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture configuration.

onnxModelPath string

Path to the pretrained ONNX model.

numFrames int

Number of frames the model processes (default: 16).

Remarks

For Beginners: Use this constructor when you have a pretrained model in ONNX format. Training is not supported in ONNX mode.

var arch = new NeuralNetworkArchitecture<double>(
    inputType: InputType.ThreeDimensional,
    inputHeight: 64, inputWidth: 64, inputDepth: 320);
var model = new AnimateDiff<double>(arch, "animatediff.onnx");
var animated = model.AddMotion(features);

Exceptions

FileNotFoundException

Thrown if the ONNX model file is not found.

Properties

SupportsTraining

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

public override bool SupportsTraining { get; }

Property Value

bool

Methods

AddMotion(Tensor<T>)

Adds motion to static features from an image diffusion model.

public Tensor<T> AddMotion(Tensor<T> staticFeatures)

Parameters

staticFeatures Tensor<T>

Static features tensor [B, C, H, W] or [C, H, W].

Returns

Tensor<T>

Motion-enhanced features tensor.

Remarks

For Beginners: This method takes features from a static image generator and adds temporal consistency to create animated output. The input comes from an image diffusion model's intermediate layers.

BlendFeatures(Tensor<T>, Tensor<T>, double)

Blends motion module output with original features.

public Tensor<T> BlendFeatures(Tensor<T> originalFeatures, Tensor<T> motionFeatures, double blendFactor = 1)

Parameters

originalFeatures Tensor<T>

Original static features.

motionFeatures Tensor<T>

Motion module output.

blendFactor double

Blend factor (0-1, default: 1.0).

Returns

Tensor<T>

Blended features.

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.

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

ProcessMotion(Tensor<T>)

Processes temporal features for motion modeling.

public Tensor<T> ProcessMotion(Tensor<T> temporalFeatures)

Parameters

temporalFeatures Tensor<T>

Temporal features spanning multiple frames.

Returns

Tensor<T>

Processed motion features.

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.