Class PackNet<T>
- Namespace
- AiDotNet.ContinualLearning
- Assembly
- AiDotNet.dll
Implements PackNet for continual learning through parameter isolation.
public class PackNet<T> : IContinualLearningStrategy<T>
Type Parameters
TThe numeric type for calculations.
- Inheritance
-
PackNet<T>
- Implements
- Inherited Members
Remarks
For Beginners: PackNet achieves continual learning by dynamically pruning and freezing network weights. After learning each task, unimportant weights are pruned, and the remaining weights are frozen. New tasks can only use the pruned (free) weights, effectively isolating each task's parameters.
How it works:
- Train the network on Task 1 using all available weights.
- After training, prune weights with smallest magnitude (keep top k%).
- Freeze the remaining (important) weights - they now belong to Task 1.
- For Task 2, only train on the pruned (free) weights.
- Repeat: prune, freeze, move to next task.
Key Concepts:
- Free Weights: Weights available for the current task (pruned in previous tasks).
- Frozen Weights: Weights dedicated to previous tasks (cannot be modified).
- Pruning Ratio: Percentage of free weights to prune after each task.
Advantages:
- Zero forgetting - previous task weights are completely protected.
- No replay or regularization needed during training.
- Network compression as a side effect of pruning.
Reference: Mallya, A. and Lazebnik, S. "PackNet: Adding Multiple Tasks to a Single Network by Iterative Pruning" (2018). CVPR.
Constructors
PackNet(double, double)
Initializes a new instance of the PackNet class.
public PackNet(double pruningRatio = 0.5, double lambda = 1000)
Parameters
pruningRatiodoubleRatio of weights to prune after each task (default: 0.5 = 50%).
lambdadoubleStrength of weight freezing enforcement (default: 1000.0).
Remarks
For Beginners:
- Pruning ratio determines how much of the remaining capacity to use per task.
- With ratio 0.5, you can fit approximately log2(1/ratio) tasks before running out.
- Lambda should be very high to enforce weight freezing.
Properties
FreeWeightCount
Gets the number of free weights available for new tasks.
public int FreeWeightCount { get; }
Property Value
Lambda
Gets the regularization strength parameter (lambda) for loss-based continual learning.
public double Lambda { get; set; }
Property Value
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.
PruningRatio
Gets the pruning ratio.
public double PruningRatio { get; }
Property Value
TaskCount
Gets the number of tasks stored.
public int TaskCount { get; }
Property Value
TotalParameters
Gets the total parameter count.
public int TotalParameters { get; }
Property Value
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
networkINeuralNetwork<T>The neural network that was trained.
taskData(Tensor<T> grad1, Tensor<T> grad2)Data from the completed task for computing importance measures.
taskIdintThe 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.
ApplyTaskMask(INeuralNetwork<T>, int)
Applies the task-specific mask to network parameters for inference.
public void ApplyTaskMask(INeuralNetwork<T> network, int taskId)
Parameters
networkINeuralNetwork<T>The neural network.
taskIdintThe task to configure for.
Remarks
This zeros out weights that don't belong to the specified task, which is useful for task-specific inference.
BeforeTask(INeuralNetwork<T>, int)
Prepares the strategy before starting to learn a new task.
public void BeforeTask(INeuralNetwork<T> network, int taskId)
Parameters
networkINeuralNetwork<T>The neural network that will be trained.
taskIdintThe 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
networkINeuralNetwork<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.
GetTaskMask(int)
Gets the weight mask for a specific task.
public HashSet<int> GetTaskMask(int taskId)
Parameters
taskIdintThe task ID.
Returns
GetWeightAllocationStats()
Gets statistics about weight allocation across tasks.
public Dictionary<int, int> GetWeightAllocationStats()
Returns
- Dictionary<int, int>
Dictionary mapping task IDs to weight counts.
ModifyGradients(INeuralNetwork<T>, Vector<T>)
Modifies the gradient to prevent catastrophic forgetting.
public Vector<T> ModifyGradients(INeuralNetwork<T> network, Vector<T> gradients)
Parameters
networkINeuralNetwork<T>The neural network being trained.
gradientsVector<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.