Table of Contents

Class VariationalContinualLearning<T>

Namespace
AiDotNet.ContinualLearning
Assembly
AiDotNet.dll

Implements Variational Continual Learning (VCL) for Bayesian continual learning.

public class VariationalContinualLearning<T> : IContinualLearningStrategy<T>

Type Parameters

T

The numeric type for calculations.

Inheritance
VariationalContinualLearning<T>
Implements
Inherited Members

Remarks

For Beginners: VCL uses Bayesian neural networks where each weight has a probability distribution (mean and variance) rather than a single value. This allows the network to represent uncertainty and naturally prevents forgetting by using the posterior from previous tasks as the prior for new tasks.

How it works:

  1. Represent weights as Gaussian distributions: w ~ N(μ, σ²).
  2. Train using variational inference, optimizing the ELBO (Evidence Lower Bound).
  3. After each task, the posterior becomes the prior for the next task.
  4. The KL divergence between current and previous posterior prevents forgetting.

Key Formula:

Loss = E_q[log p(D|w)] - KL(q(w|D_new) || p(w|D_old))

where q(w|D_new) is the current posterior and p(w|D_old) is the previous posterior (now prior).

Advantages:

  • Principled Bayesian approach to continual learning.
  • Natural uncertainty quantification.
  • Sequential posterior updates match online learning.

Reference: Nguyen, C.V., Li, Y., Bui, T.D., and Turner, R.E. "Variational Continual Learning" (2018). ICLR.

Constructors

VariationalContinualLearning(double, double, int?)

Initializes a new instance of the VariationalContinualLearning class.

public VariationalContinualLearning(double lambda = 1, double initialLogVar = -3, int? seed = null)

Parameters

lambda double

KL divergence weight (default: 1.0).

initialLogVar double

Initial log-variance for weight distributions (default: -3.0).

seed int?

Random seed for sampling (default: null).

Remarks

For Beginners:

  • Lambda controls how much to penalize deviation from the prior (previous posterior).
  • Initial log-variance controls initial uncertainty. -3 means σ ≈ 0.22.

Properties

InitialLogVar

Gets the initial log-variance value.

public double InitialLogVar { get; }

Property Value

double

Lambda

Gets the regularization strength parameter (lambda) for loss-based continual learning.

public double Lambda { get; set; }

Property Value

double

Remarks

For Beginners: Lambda controls how strongly the strategy prevents forgetting. A higher lambda means the network is more conservative about changing weights important for previous tasks, but this might make it harder to learn new tasks effectively.

Typical values range from 100 to 10000, depending on the complexity of tasks and how important it is to preserve old knowledge versus learning new knowledge.

TaskCount

Gets the number of tasks processed.

public int TaskCount { get; }

Property Value

int

Methods

AfterTask(INeuralNetwork<T>, (Tensor<T> inputs, Tensor<T> targets), int)

Processes information after completing training on a task.

public void AfterTask(INeuralNetwork<T> network, (Tensor<T> inputs, Tensor<T> targets) taskData, int taskId)

Parameters

network INeuralNetwork<T>

The neural network that was trained.

taskData (Tensor<T> grad1, Tensor<T> grad2)

Data from the completed task for computing importance measures.

taskId int

The identifier for the completed task.

Remarks

For Beginners: This method is called after you finish training on a task. It allows the strategy to compute and store information about what the network learned, which will be used to protect this knowledge when learning future tasks.

For example, in Elastic Weight Consolidation (EWC), this computes the Fisher Information Matrix to identify which weights are most important for the completed task.

BeforeTask(INeuralNetwork<T>, int)

Prepares the strategy before starting to learn a new task.

public void BeforeTask(INeuralNetwork<T> network, int taskId)

Parameters

network INeuralNetwork<T>

The neural network that will be trained.

taskId int

The identifier for the upcoming task (0-indexed).

Remarks

For Beginners: This method is called before you start training on a new task. It allows the strategy to capture the network's current state or prepare any necessary data structures for protecting knowledge from previous tasks.

For example, in Learning without Forgetting (LwF), this might store the network's predictions on the new task's inputs before training begins, so we can later encourage the network to maintain similar predictions.

ComputeLoss(INeuralNetwork<T>)

Computes the regularization loss to prevent forgetting previous tasks.

public T ComputeLoss(INeuralNetwork<T> network)

Parameters

network INeuralNetwork<T>

The neural network being trained.

Returns

T

The regularization loss value that should be added to the task loss.

Remarks

For Beginners: This method calculates an additional loss term that penalizes the network for deviating from its learned knowledge of previous tasks. You add this to your regular task loss during training:

var totalLoss = taskLoss + strategy.ComputeLoss(network);

For example, in EWC, this returns a penalty proportional to how much important weights have changed from their optimal values for previous tasks. Larger changes to important weights result in higher loss, discouraging the network from forgetting.

GetPosterior()

Gets the current posterior distribution parameters.

public (Vector<T> mean, Vector<T> logVar) GetPosterior()

Returns

(Vector<T> mean, Vector<T> logVar)

Tuple of posterior mean and log-variance vectors.

GetPrior()

Gets the current prior distribution parameters.

public (Vector<T> mean, Vector<T> logVar) GetPrior()

Returns

(Vector<T> mean, Vector<T> logVar)

Tuple of prior mean and log-variance vectors.

ModifyGradients(INeuralNetwork<T>, Vector<T>)

Modifies the gradient to prevent catastrophic forgetting.

public Vector<T> ModifyGradients(INeuralNetwork<T> network, Vector<T> gradients)

Parameters

network INeuralNetwork<T>

The neural network being trained.

gradients Vector<T>

The gradients from the current task loss.

Returns

Vector<T>

Modified gradients that protect previous task knowledge.

Remarks

For Beginners: Some continual learning strategies work by modifying the gradients (the update directions for weights) rather than adding a loss term. This method takes the gradients computed from the current task and modifies them to avoid interfering with previously learned tasks.

For example, in Gradient Episodic Memory (GEM), if a gradient would hurt performance on stored examples from previous tasks, it's projected to the closest gradient that doesn't interfere with those examples.

If a strategy doesn't use gradient modification, this should return the gradients unchanged.

Reset()

Resets the strategy, clearing all stored task information.

public void Reset()

Remarks

For Beginners: This method clears all the information the strategy has accumulated about previous tasks. After calling this, the network will be free to learn new tasks without any constraints from previously learned tasks.

Use this when you want to start fresh or when you're done with a sequence of tasks and want to begin a new independent sequence.

SampleWeights(INeuralNetwork<T>)

Samples weights from the posterior distribution for prediction.

public Vector<T> SampleWeights(INeuralNetwork<T> network)

Parameters

network INeuralNetwork<T>

The neural network.

Returns

Vector<T>

Sampled weights.

Remarks

For Beginners: In Bayesian neural networks, we sample weights from their distribution during inference. Multiple samples can be used for Monte Carlo estimation of predictions and uncertainty.

UpdateVariance(Vector<T>, double)

Updates the posterior log-variance based on gradient information.

public void UpdateVariance(Vector<T> gradients, double learningRate)

Parameters

gradients Vector<T>

Parameter gradients.

learningRate double

Learning rate for variance update.