Skip to content
Marco Vasko-Klima edited this page Sep 7, 2026 · 34 revisions

Complete C# API documentation - only shows publicly exposed classes, functions, interfaces, and properties.
Also refer to the Mathematical Definitions Documentation for the exact formulas used by the API's functions.

Trainers

Classes for handling the training of neural networks.

(Standard) Trainer - Class

Overview

Provides standard supervised training functionality using predefined training datasets and optional testing datasets.

Using Directive

using NNNCSharp.Components.Trainers;

Properties

  • public Model Model { get; private set; } - stores the neural network being trained by the instance - updated to the best-performing version after every Train() call

Constructor

Signature:
public Trainer(Model model, Optimizer optimizer, Cost cost, float maxGradNorm = 1.0f);
Parameters:
  • Model model - neural network to train
  • Optimizer optimizer - optimizer instance to use for parameter updates
  • Cost cost - cost function instance to use during loss calculation
  • float maxGradNorm - maximum gradient norm to clip gradients to
Purpose / Functionality:

Initializes a new Trainer instance to train the given neural network model.

Train - Function

Signature:
public void Train(BatchBuffer batchBuffer, int batchSize, int epochs, bool batchAllInputs = true,
    Func<Model, int, bool>? testFunc = null, bool decayLR = true, float minLRFraction = 0.1f,
    int testEvery = 100, int testLength = 1000, string? saveTo = null);
Parameters:
  • BatchBuffer batchBuffer - BatchBuffer instance to sample training batches from
  • int batchSize - number of input-target pairs to use per training batch
  • int epochs - total number of epochs to train for
  • bool batchAllInputs - whether to train on the maximum possible number of training batches every epoch - does not repeat any input-target pairs in a single epoch
  • Func<Model, int, bool>? testFunc - optional fitness test function to use for performance evaluation - should receive the training neural network and test index as arguments and return whether the model successfully past the performance test - performance tests will be skipped if left null
  • bool decayLR - whether to decay the learning rate over the course of training - uses a single-cycle Cosine Annealing Learning Rate Decay function
  • float minLRFraction - minimum fraction of its initial value to which the learning rate is allowed to decay - will be reached on the final epoch
  • int testEvery - number of epochs to run between performance evaluations
  • int testLength - number of times to run the fitness test function for each performance evaluation
  • string? saveTo - optional file name to which intermediate models will be saved to during training
Purpose / Functionality:

Trains the model contained in the instance for a given number of epochs. If provided with a fitness function (testFunc), will cache the best-performing model at each performance evaluation and will store the overall best-performing version in the instance's Model property after the final training epoch. The trained model should always be read from the instance's Model property after calling Train().

StopTraining - Function

Signature:
public void StopTraining();
Purpose / Functionality:

Terminates the current training session early. If a fitness function was provided, stores the best-performing cached model in the instance's Model property.

DQNTrainer - Class

Overview

Provides Deep Q-Learning (DQN) training functionality for environments with discrete action spaces. Supports both solo and self-play environments.

Using Directive

using NNNCSharp.Components.Trainers;

Properties

  • public Model Agent { get; private set; } - stores the neural network agent being trained by the instance - updated to the best-performing version after every Train() call

Constructor

Signature:
public DQNTrainer(Model agent, DQNEnvironment environment, Optimizer optimizer, Cost cost,
    int trainEvery = 4, float discount = 0.995f, float exploration = 1.0f, float explorationDecay = 0.99f,
    float minExploration = 0.01f, int replayBufferSize = 10000, int batchSize = 64, int agentBufferSize = 5,
    int opponentCopyRate = 100, int minRandomOpponentEpisodes = 200, float tau = 0.005f,
    float maxGradNorm = 1.0f, int minExperiences = 1000);
Parameters:
  • Model agent - neural network to train
  • DQNEnvironment environment - discrete environment instance to train the agent in
  • Optimizer optimizer - optimizer instance to use for parameter updates
  • Cost cost - cost function instance to use during loss calculation
  • int trainEvery - number of environment steps between agent training steps
  • float discount - discount factor to apply during Q-Value estimation
  • float exploration - initial exploration rate to use
  • float explorationDecay - factor by which to decay the learning rate after every training episode
  • float minExploration - minimum exploration rate to decay to
  • int replayBufferSize - number of experiences to store for replay during training
  • int batchSize - number of experiences to include in each training batch
  • int agentBufferSize - number of frozen past agent versions to store - used as opponents in self-play environments
  • int opponentCopyRate - number of training episodes between agent versions being frozen to use as opponents - only applicable to self-play environments
  • int minRandomOpponentEpisodes - minimum number of episodes which must be played against a random opponent - only applicable to self-play environments
  • float tau - tau value to use during smooth target model parameter updates
  • float maxGradNorm - maximum gradient norm to clip gradients to
  • int minExperiences - minimum number of stored experiences required prior to starting training
Purpose / Functionality:

Initializes a new DQNTrainer instance to train the given neural network.

Train - Function

Signature:
public void Train(ref FIFOBuffer<Episode>? episodeBuffer, int episodes = 1000, int testEvery = 100,
    int testEpisodes = 5000, string? saveTo = null);
Parameters:
  • ref FIFOBuffer? episodeBuffer - optional buffer to store recent training episodes in - can be used to view previous episodes after training is completed
  • int episodes - number of episodes to train for
  • int testEvery - number of episodes between performance evaluations
  • int testEpisodes - number of episodes to run during each performance evaluation
  • string? saveTo - optional file name to which intermediate agents will be saved to during training
Purpose / Functionality:

Trains the agent contained in the instance for a given number of episodes. Will use the environment's fitness function to cache the best-performing agent at each performance evaluation and will store the overall best-performing version in the instance's Model property after the final training episode. The trained agent should always be read from the instance's Model property after calling Train().

StopTraining - Function

Signature:
public void StopTraining();
Purpose / Functionality:

Terminates the current training session early. Stores the best-performing cached agent in the instance's Agent property.

Optimizers

Classes for handling neural network parameter updates.

Optimizer - Abstract Class

Overview

Base class defining general optimizer functionality and signatures. Can be inherited from to define custom optimizer functions.

Using Directive

using NNNCSharp.Components.Optimizers;

Properties

  • public float LR { get; set; } - learning rate factor applied during parameter updates

Constructor

Signature:
public Optimizer(float learningRate);
Parameters:
  • float learningRate - learning rate factor to apply during parameter updates
Purpose / Functionality:

Serves as the default constructor for all optimizers.

Step - Abstract Function

Signature:
public abstract void Step(Tensor parameter, int iterations);
Parameters:
  • Tensor parameter - parameter tensor to update values of
  • int iterations - number of times the neural network's parameters have been updated - used as part of certain optimizer step functions
Purpose / Functionality:

Abstract function declaration used by all optimizer parameter update functions.

SGD - Class

Overview

Stochastic Gradient Descent optimizer. Inherits from Optimizer.

Using Directive

using NNNCSharp.Components.Optimizers;

Properties

  • public float LR { get; set; } - learning rate factor applied during parameter updates

Constructor

Signature:
public SGD(float learningRate) : base(learningRate);
Parameters:
  • float learningRate - learning rate factor to apply during parameter updates
Purpose / Functionality:

Creates a new Stochastic Gradient Descent optimizer instance.

Step - Overridden Function

Signature:
public override void Step(Tensor parameter, int iterations);
Parameters:
  • Tensor parameter - parameter tensor to update values of
  • int iterations - number of times the neural network's parameters have been updated - not used for SGD optimization
Purpose / Functionality:

Updates the parameter tensor's values based on the current stored gradients using the Stochastic Gradient Descent optimizer function.

Adam - Class

Overview

Adaptive Moment Estimation optimizer. Inherits from Optimizer.

Using Directive

using NNNCSharp.Components.Optimizers;

Properties

  • public float LR { get; set; } - learning rate factor applied during parameter updates

Constructor

Signature:
public Adam(float learningRate, float beta1 = 0.9f, float beta2 = 0.999f, float epsilon = 1e-8f,
    float weightDecay = 0.0f) : base(learningRate);
Parameters:
  • float learningRate - learning rate factor to apply during parameter updates
  • float beta1 - exponential decay rate of first moment estimates
  • float beta2 - exponential decay rate of second moment estimates
  • float epsilon - epsilon value to use in calculations
  • float weightDecay - AdamW-style weight decay rate to use
Purpose / Functionality:

Creates a new Adaptive Moment Estimation optimizer instance.

Step - Overridden Function

Signature:
public override void Step(Tensor parameter, int iterations);
Parameters:
  • Tensor parameter - parameter tensor to update values of
  • int iterations - number of times the neural network's parameters have been updated - used to correct bias in moment estimates
Purpose / Functionality:

Updates the parameter tensor's values based on the current stored gradients using the Adaptive Moment Estimation optimizer function with AdamW-style weight decay applied.

Cost Functions

Classes for calculating loss values.

Cost - Abstract Class

Overview

Base class defining general cost functionality and signatures. Can be inherited from to define custom cost functions.

Using Directive

using NNNCSharp.Components.Costs;

Constructor

Signature:
public Cost();
Purpose / Functionality:

Serves as the default constructor for all costs.

CalculateCost - Abstract Function

Signature:
public abstract Tensor CalculateCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing a single value representing the average loss of all predictions in the batch.

Purpose / Functionality:

Abstract function declaration used by all cost calculation functions. Expects both predictions and targets to have a leading batch dimension.

CalculatePerSampleCost - Abstract Function

Signature:
public abstract Tensor CalculatePerSampleCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing the individual loss values for each prediction in the batch.

Purpose / Functionality:

Abstract function declaration used by all cost calculation functions. Expects both predictions and targets to have a leading batch dimension.

CalculateCostWithPriority - Virtual Function

Signature:
public virtual CostResult CalculateCostWithPriority(Tensor predictions, Tensor targets, double[]? weights = null);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
  • doublep[]? weights - Prioritized Experience Replay (PER) sampling weights for each experience in the batch
Returns:

CostResult instance containing the per-prediction losses tensor and corresponding Prioritized Experience Replay (PER) sampling priorities.

Purpose / Functionality:

Calculates the per-prediction losses of the given experience batch, scales each loss by the corresponding Prioritized Experience Replay (PER) sampling weight (if weights are passed), and computes the corresponding PER sampling priorities of each experience. Expects both predictions and targets to have a leading batch dimension. Used for DQN training.

CostResult - Record

Overview

Stores the per-prediction losses and corresponding Prioritized Experience Replay (PER) sampling priorities computed by a Cost instance.

Using Directive

using NNNCSharp.Components.Costs;

Properties

  • public Tensor Losses { get; init; } - per-prediction losses tensor
  • public double[] Priorities { get; init; } - corresponding per-experience Prioritized Experience Replay (PER) sampling priorities

Constructor

Signature:
public CostResult(Tensor Losses, double[] Priorities);
Parameters:
  • Tensor Losses - per-prediction losses tensor to store
  • double[] Priorities - corresponding per-experience Prioritized Experience Replay (PER) sampling priorities to store
Purpose / Functionality:

Creates a new CostResult record instance storing the given losses and Prioritized Experience Replay (PER) sampling priorities.

MSE - Class

Overview

Mean Squared Error cost. Inherits from Cost.

Using Directive

using NNNCSharp.Components.Costs;

Constructor

Signature:
public MSE();
Purpose / Functionality:

Creates a new Mean Squared Error cost instance.

CalculateCost - Overridden Function

Signature:
public override Tensor CalculateCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing a single value representing the average loss of all predictions in the batch.

Purpose / Functionality:

Calculates the average loss of all predictions in a batch using the Mean Squared Error cost function. Expects both predictions and targets to have a leading batch dimension.

CalculatePerSampleCost - Overridden Function

Signature:
public override Tensor CalculatePerSampleCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing the individual loss values for each prediction in the batch.

Purpose / Functionality:

Calculates the loss of each prediction in a batch using the Mean Squared Error cost function. Expects both predictions and targets to have a leading batch dimension.

CalculateCostWithPriority - Inherited Virtual Function

Signature:
public virtual CostResult CalculateCostWithPriority(Tensor predictions, Tensor targets, double[]? weights = null);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
  • doublep[]? weights - Prioritized Experience Replay (PER) sampling weights for each experience in the batch
Returns:

CostResult instance containing the per-prediction losses tensor and corresponding Prioritized Experience Replay (PER) sampling priorities.

Purpose / Functionality:

Calculates the per-prediction losses of the given experience batch using the Mean Squared Error cost function, scales each loss by the corresponding Prioritized Experience Replay (PER) sampling weight (if weights are passed), and computes the corresponding PER sampling priorities of each experience. Expects both predictions and targets to have a leading batch dimension. Used for DQN training.

Huber - Class

Overview

Pseudo-Huber cost. Inherits from Cost.

Using Directive

using NNNCSharp.Components.Costs;

Constructor

Signature:
public Huber(float delta = 1.0f);
Parameters:
  • float delta - delta value at which to transition from Mean Squared Error to Mean Absolute Error
Purpose / Functionality:

Creates a new pseudo-Huber cost instance.

CalculateCost - Overridden Function

Signature:
public override Tensor CalculateCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing a single value representing the average loss of all predictions in the batch.

Purpose / Functionality:

Calculates the average loss of all predictions in a batch using the pseudo-Huber cost function. Expects both predictions and targets to have a leading batch dimension.

CalculatePerSampleCost - Overridden Function

Signature:
public override Tensor CalculatePerSampleCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing the individual loss values for each prediction in the batch.

Purpose / Functionality:

Calculates the loss of each prediction in a batch using the pseudo-Huber cost function. Expects both predictions and targets to have a leading batch dimension.

CalculateCostWithPriority - Inherited Virtual Function

Signature:
public virtual CostResult CalculateCostWithPriority(Tensor predictions, Tensor targets, double[]? weights = null);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
  • doublep[]? weights - Prioritized Experience Replay (PER) sampling weights for each experience in the batch
Returns:

CostResult instance containing the per-prediction losses tensor and corresponding Prioritized Experience Replay (PER) sampling priorities.

Purpose / Functionality:

Calculates the per-prediction losses of the given experience batch using the pseudo-Huber cost function, scales each loss by the corresponding Prioritized Experience Replay (PER) sampling weight (if weights are passed), and computes the corresponding PER sampling priorities of each experience. Expects both predictions and targets to have a leading batch dimension. Used for DQN training.

SoftmaxCrossEntropy - Class

Overview

Softmax Cross-Entropy cost. Inherits from Cost.

Using Directive

using NNNCSharp.Components.Costs;

Constructor

Signature:
public SoftmaxCrossEntropy();
Purpose / Functionality:

Creates a Softmax Cross-Entropy cost instance.

CalculateCost - Overridden Function

Signature:
public override Tensor CalculateCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing a single value representing the average loss of all predictions in the batch.

Purpose / Functionality:

Calculates the average loss of all predictions in a batch using the Softmax Cross-Entropy cost function. Expects both predictions and targets to have a leading batch dimension.

CalculatePerSampleCost - Overridden Function

Signature:
public override Tensor CalculatePerSampleCost(Tensor predictions, Tensor targets);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
Returns:

Tensor containing the individual loss values for each prediction in the batch.

Purpose / Functionality:

Calculates the loss of each prediction in a batch using the Softmax Cross-Entropy cost function. Expects both predictions and targets to have a leading batch dimension.

CalculateCostWithPriority - Inherited Virtual Function

Signature:
public virtual CostResult CalculateCostWithPriority(Tensor predictions, Tensor targets, double[]? weights = null);
Parameters:
  • Tensor predictions - predictions generated by the neural network for an input batch
  • Tensor targets - target outputs corresponding to the input batch
  • doublep[]? weights - Prioritized Experience Replay (PER) sampling weights for each experience in the batch
Returns:

CostResult instance containing the per-prediction losses tensor and corresponding Prioritized Experience Replay (PER) sampling priorities.

Purpose / Functionality:

Calculates the per-prediction losses of the given experience batch using the Softmax Cross-Entropy cost function, scales each loss by the corresponding Prioritized Experience Replay (PER) sampling weight (if weights are passed), and computes the corresponding PER sampling priorities of each experience. Expects both predictions and targets to have a leading batch dimension. Used for DQN training.

Models

Neural Network container classes.

Model - Class

Overview

Represents a complete neural network comprised of a sequence of layers. Implements IDisposable.

Using Directive

using NNNCSharp.Components.Models;

Properties

  • public Layer[] Layers { get; private set; } - sequence of layers used by the neural network
  • public List<Tensor> Parameters { get; } - list of all parameter tensors across all of the neural network's layers
  • public int ParameterCount { get; } - number of parameter tensors across all of the neural network's layers

Constructor - Full Initialization

Signature:
public Model(Layer[] layers, Tensor inputFormat);
Parameters:
  • Layer[] layers - sequence of layers the neural network will contain
  • Tensor inputFormat - general format of the input the neural network will receive - should have the dimensions [batch, input dimensions] where the batch dimension can simply equal 1
Purpose / Functionality:

Creates a new sequential Model instance with the given sequence of layers and initializes all of its layers to receive the given input format. Used to initialize a completely new neural network.

Constructor - No Initialization

Signature:
public Model(Layer[] layers);
Parameters:
  • Layer[] layers - sequence of layers the neural network will contain
Purpose / Functionality:

Creates a new sequential Model instance with the given sequence of layers. Does not initialize its layers. Used to initialize a new neural network containing layers with already-initialized / trained parameters.

Predict - Function

Signature:
public Tensor Predict(Tensor input);
Parameters:
  • Tensor input - input for the neural network to process - must match the input format dimensions provided during Model initialization - requires a batch dimension of 1 if processing a single input (consider using Tensor.WrapBatch())
Returns:

Tensor containing the outputs predicted by the model for the given input.

Purpose / Functionality:

Gets the neural network's predictions for a given input. Does not construct an Autograd graph for the forward pass. More performance and memory efficient for getting predictions when not training.

Forward - Function

Signature:
public Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input for the neural network to process - must match the input format dimensions provided during Model initialization - requires a batch dimension of 1 if processing a single input (consider using Tensor.WrapBatch())
Returns:

Tensor containing the outputs predicted by the model for the given input.

Purpose / Functionality:

Gets the neural network's predictions for a given input. Constructs a complete Autograd graph for the forward pass. Allows for gradients to be subsequently calculated during training.

Dispose - Function

Signature:
public void Dispose();
Purpose / Functionality:

Frees all memory used by the neural network, its layers, and their parameter tensors, effectively deleting the instance. Should be used whenever a Model instance is no longer being used, such as when creating a copy and discarding the original. Failure to use may lead to memory leaks.

Copy - Function

Signature:
public Model Copy();
Returns:

Deep-copy of the neural network containing identical parameters.

Purpose / Functionality:

Can be used to create a new (deep-copy) Model instance with identical parameters to an existing instance. Recommended to be used in conjunction with Dispose().

GetParameters - Function

Signature:
public IEnumerable<Tensor> GetParameters();
Returns:

IEnumerable instance containing all of the neural network's parameter tensors.

Purpose / Functionality:

Can be used to iterate through all of the parameter tensors of a neural network directly. Functionally equivalent to the Parameters property.

GetTotalParameterSize - Function

Signature:
public ulong GetTotalParameterSize();
Returns:

Unsigned 64-bit integer representing the total number of individual values across all of the neural network's parameter tensors.

Purpose / Functionality:

Can be used to determine the overall size of a model. Primarily used to provide additional data in .nnn files.

Layers

Classes representing layers of neurons in a neural network.

Layer - Abstract Class

Overview

General class defining neural network layer functionality. Can be inherited from to create custom neuron layers. Implements IDisposable.

Using Directive

using NNNCSharp.Components.Models.Layers;

Properties

  • public Tensor Biases { get; protected set; } - bias parameter tensor of the layer
  • public Activation Activation { get; protected set; } - activation function used by the layer
  • public Tensor OutputFormat { get; protected set; } - format of the tensor the layer will output - will have a leading batch dimension of 1
  • public float Dropout { get; protected set; } - parameter dropout rate of the layer

Constructor - Full Initialization

Signature:
public Layer(Activation activation, float dropout = 0.0f);
Parameters:
  • Activation activation - activation function to be used by the layer
  • float dropout - parameter dropout rate to be used by the layer
Purpose / Functionality:

Serves as the primary constructor to be extended by layer subclasses.

Constructor - No Initialization

Signature:
public Layer();
Purpose / Functionality:

Used when loading layers from .nnn files.

SetUpLayer - Abstract Function

Signature:
public abstract void SetUpLayer(Tensor inputFormat);
Parameters:
  • Tensor inputFormat - general format of the input the layer will receive - should have the dimensions [batch, input dimensions] where the batch dimension can simply equal 1
Purpose / Functionality:

Abstract function for layer subclasses to initialize their parameter tensors to accept the given input format. Must also update the layer's OutputFormat property.

Forward - Abstract Function

Signature:
public abstract Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input to be processed by the layer - must match the input format dimensions provided during Model initialization - requires a batch dimension of 1 if processing a single input (consider using Tensor.WrapBatch())
Returns:

Tensor containing the result of passing the input through the layer.

Purpose / Functionality:

Abstract function for layer subclasses to process inputs. Using the Forward and Predict functions of the Model class is recommended over directly calling Forward on layers.

Dispose - Virtual Function

Signature:
public virtual void Dispose();
Purpose / Functionality:

Frees all memory used by the layer, and its parameter tensors, effectively deleting the instance. Should be used whenever a Layer instance is no longer being used, such as when creating a copy and discarding the original. Failure to use may lead to memory leaks. Extended by layer subclasses to dispose any additional parameter tensors they introduce.

Copy - Abstract Function

Signature:
public abstract Layer Copy();
Returns:

Deep-copy of the layer containing identical parameters.

Purpose / Functionality:

Abstract function for layer subclasses to implement deep-copy functionality. Recommended to be used in conjunction with Dispose().

GetParameters - Abstract Function

Signature:
public abstract IEnumerable<Tensor> GetParameters();
Returns:

IEnumerable instance containing all of the layer's parameter tensors.

Purpose / Functionality:

Abstract function for layer subclasses to expose their parameter tensors in an iterable format.

BuildFromData - Function

Signature:
public void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Loads all of the layer's parameters from the given file stream starting at the stream's current position. Used when loading layers from .nnn files.

PrintLayer - Function

Signature:
public string PrintLayer(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Returns:

String containing a human-readable summary of the layer data contained in the file stream starting at the stream's current position.

Purpose / Functionality:

Parses the layer data contained in the file stream starting at the stream's current position. Provides a human-readable summary of the data found.

Dense - Class

Overview

Represents a fully connected neural network layer. Inherits from Layer and implements IDisposable.

Using Directive

using NNNCSharp.Components.Models.Layers;

Properties

  • public int NeuronCount { get; private set; } - number of neurons contained in the layer
  • public bool Flatten { get; private set; } - whether the layer flattens its input prior to processing
  • public Tensor Weights { get; private set; } - weights parameter tensor of the layer
  • public Tensor Biases { get; protected set; } - bias parameter tensor of the layer
  • public Activation Activation { get; protected set; } - activation function used by the layer
  • public Tensor OutputFormat { get; protected set; } - format of the tensor the layer will output - will have a leading batch dimension of 1
  • public float Dropout { get; protected set; } - parameter dropout rate of the layer

Constructor - Full Initialization

Signature:
public Dense(int neuronCount, Activation activation, bool flatten = false, float dropout = 0.0f)
    : base(activation, dropout);
Parameters:
  • int neuronCount - number of neurons the layer will contain
  • Activation activation - activation function to be used by the layer
  • bool flatten - whether the layer will flatten its input prior to processing
  • float dropout - parameter dropout rate to be used by the layer
Purpose / Functionality:

Serves as the default constructor for Dense layers. Creates a new Dense layer instance with the given parameters. Does not automatically initialize parameter tensors.

Constructor - Complete Data

Signature:
public Dense(int neuronCount, Tensor weights, Tensor biases, Activation activation, bool flatten, float dropout)
    : base(activation, dropout);
Parameters:
  • int neuronCount - number of neurons the layer will contain
  • Tensor weights - weights parameter tensor to be used by the layer
  • Tensor biases - bias parameter tensor to be used by the layer
  • Activation activation - activation function to be used by the layer
  • bool flatten - whether the layer will flatten its input prior to processing
  • float dropout - parameter dropout rate to be used by the layer
Purpose / Functionality:

Creates a new Dense layer instance with the given complete parameters. All parameter tensors must be correctly initialized prior to the constructor being used. Used to create deep-copies of Dense layers.

Constructor - No Initialization

Signature:
public Dense();
Purpose / Functionality:

Used when loading Dense layers from .nnn files.

SetUpLayer - Overridden Function

Signature:
public override void SetUpLayer(Tensor inputFormat);
Parameters:
  • Tensor inputFormat - general format of the input the layer will receive - should have the dimensions [batch, input dimensions] where the batch dimension can simply equal 1
Purpose / Functionality:

Initializes the layer's parameter tensors based on the given input format. Also initializes the layer's OutputFormat property.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input to be processed by the layer - must match the input format dimensions provided during Model initialization - requires a batch dimension of 1 if processing a single input (consider using Tensor.WrapBatch())
Returns:

Tensor containing the result of passing the input through the layer.

Purpose / Functionality:

Performs a matrix multiplication between the input and the layer's weights parameter tensor, and adds the layer's bias parameter tensor. Using the Forward and Predict functions of the Model class is recommended over directly calling Forward on layers.

Dispose - Overridden Function

Signature:
public override void Dispose();
Purpose / Functionality:

Frees all memory used by the layer, and its parameter tensors, effectively deleting the instance. Should be used whenever a Layer instance is no longer being used, such as when creating a copy and discarding the original. Failure to use may lead to memory leaks.

Copy - Overridden Function

Signature:
public override Layer Copy();
Returns:

Deep-copy of the layer containing identical parameters.

Purpose / Functionality:

Can be used to create a new (deep-copy) layer instance with identical parameters to an existing instance. Recommended to be used in conjunction with Dispose().

GetParameters - Overridden Function

Signature:
public override IEnumerable<Tensor> GetParameters();
Returns:

IEnumerable instance containing all of the layer's parameter tensors.

Purpose / Functionality:

Can be used to iterate through all of the parameter tensors of a Dense layer.

BuildFromData - Function

Signature:
public void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Loads all of the layer's parameters from the given file stream starting at the stream's current position. Used when loading layers from .nnn files.

PrintLayer - Function

Signature:
public string PrintLayer(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Returns:

String containing a human-readable summary of the layer data contained in the file stream starting at the stream's current position.

Purpose / Functionality:

Parses the layer data contained in the file stream starting at the stream's current position. Provides a human-readable summary of the data found.

Conv - Class

Overview

Represents a convolutional neural network layer. Inherits from Layer and implements IDisposable.

Properties

  • public int FilterCount { get; private set; } - number of filters in the layer
  • public int[] KernelDims { get; private set; } - dimensions of the layer's kernels
  • public Tensor Kernels { get; private set; } - kernels parameter tensor of the layer
  • public Tensor Biases { get; protected set; } - bias parameter tensor of the layer
  • public Activation Activation { get; protected set; } - activation function used by the layer
  • public Tensor OutputFormat { get; protected set; } - format of the tensor the layer will output - will have a leading batch dimension of 1
  • public float Dropout { get; protected set; } - spatial parameter dropout rate used by the layer

Using Directive

using NNNCSharp.Components.Models.Layers;

Constructor - Full Initialization

Signature:
public Conv(int filterCount, int[] kernelDims, Activation activation, Padding padding, float dropout = 0.0f)
    : base(activation, dropout);
Parameters:
  • int filterCount - number of filters the layer will contain
  • int[] kernelDims - kernel dimensions to be used by the layer
  • Activation activation - activation function to be used by the layer
  • Padding padding - type of input padding to be used by the layer
  • float dropout - spatial parameter dropout rate to be used by the layer
Purpose / Functionality:

Serves as the default constructor for Conv layers. Creates a new Conv layer instance with the given parameters. Does not automatically initialize parameter tensors.

Constructor - Complete Data

Signature:
public Conv(int filterCount, int[] kernelDims, Tensor kernels, Tensor biases, Activation activation, Padding padding,
    int[] paddingDims, float dropout)
    : base(activation, dropout);
Parameters:
  • int filterCount - number of filters the layer will contain
  • int[] kernelDims - kernel dimensions to be used by the layer
  • Tensor kernels - kernels parameter tensor to be used by the layer
  • Tensor biases - bias parameter tensor to be used by the layer
  • Activation activation - activation function to be used by the layer
  • Padding padding - type of input padding to be used by the layer
  • int[] paddingDims - dimensions of input padding applied by the layer
  • float dropout - spatial parameter dropout rate to be used by the layer
Purpose / Functionality:

Creates a new Conv layer instance with the given complete parameters. All parameter tensors must be correctly initialized prior to the constructor being used. Used to create deep-copies of Conv layers.

Constructor - No Initialization

Signature:
public Conv();
Purpose / Functionality:

Used when loading Conv layers from .nnn files.

SetUpLayer - Overridden Function

Signature:
public override void SetUpLayer(Tensor inputFormat);
Parameters:
  • Tensor inputFormat - general format of the input the layer will receive - should have the dimensions [batch, input dimensions] where the batch dimension can simply equal 1
Purpose / Functionality:

Initializes the layer's parameter tensors based on the given input format. Also initializes the layer's OutputFormat property.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input to be processed by the layer - must match the input format dimensions provided during Model initialization - requires a batch dimension of 1 if processing a single input (consider using Tensor.WrapBatch())
Returns:

Tensor containing the result of passing the input through the layer.

Purpose / Functionality:

Performs a convolution between the input and the layer's kernels parameter tensor, and adds the layer's bias parameter tensor. Using the Forward and Predict functions of the Model class is recommended over directly calling Forward on layers.

Dispose - Overridden Function

Signature:
public override void Dispose();
Purpose / Functionality:

Frees all memory used by the layer, and its parameter tensors, effectively deleting the instance. Should be used whenever a Layer instance is no longer being used, such as when creating a copy and discarding the original. Failure to use may lead to memory leaks.

Copy - Overridden Function

Signature:
public override Layer Copy();
Returns:

Deep-copy of the layer containing identical parameters.

Purpose / Functionality:

Can be used to create a new (deep-copy) layer instance with identical parameters to an existing instance. Recommended to be used in conjunction with Dispose().

GetParameters - Overridden Function

Signature:
public override IEnumerable<Tensor> GetParameters();
Returns:

IEnumerable instance containing all of the layer's parameter tensors.

Purpose / Functionality:

Can be used to iterate through all of the parameter tensors of a Conv layer.

BuildFromData - Function

Signature:
public void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Loads all of the layer's parameters from the given file stream starting at the stream's current position. Used when loading layers from .nnn files.

PrintLayer - Function

Signature:
public string PrintLayer(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Returns:

String containing a human-readable summary of the layer data contained in the file stream starting at the stream's current position.

Purpose / Functionality:

Parses the layer data contained in the file stream starting at the stream's current position. Provides a human-readable summary of the data found.

Padding - Enum

Overview

Enumeration of available padding types for Conv layers. Contained inside the Conv class.

Using Directive
using NNNCSharp.Components.Models.Layers;

or

using static NNNCSharp.Components.Models.Layers.Conv;

Enumerators
  • Valid - standard 'valid' padding type - equivalent to no padding
  • Same - padding type which ensures the output of a convolution has the same dimensions as the input

Activation Functions

Classes providing neural network activation functions.

Activation - Abstract Class

Overview

Base class defining activation function functionality and signatures. Can be inherited from to create custom activation functions.

Using Directive

using NNNCSharp.Components.Activations;

Constructor

Signature:
public Activation();
Purpose / Functionality:

Serves as the default constructor for all activation functions.

Forward - Abstract Function

Signature:
public abstract Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input tensor to apply activation function to
Returns:

Tensor containing the result of applying the activation function to the input.

Purpose / Functionality:

Abstract function for activation subclasses to implement their activation function logic.

Copy - Abstract Function

Signature:
public abstract Activation Copy();
Returns:

Deep-copy of the activation function.

Purpose / Functionality:

Can be used to create a new (deep-copy) instance of an activation function with identical parameters.

BuildFromData - Virtual Function

Signature:
public virtual void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Loads all of the activation's parameters from the given file stream starting at the stream's current position. Used when loading activations from .nnn files. Has no effect unless the specific activation function subclass requires parameters to be loaded from the file.

PrintActivation - Virtual Function

Signature:
public virtual string PrintActivation(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Returns:

String containing a human-readable summary of the activation data contained in the file stream starting at the stream's current position.

Purpose / Functionality:

Parses the activation data contained in the file stream starting at the stream's current position. Provides a human-readable summary of the data found. Returns an empty string unless the specific activation function subclass includes parameters.

Linear - Class

Overview

Represents the linear activation function - equivalent to not applying any activation function. Inherits from Activation.

Using Directive

using NNNCSharp.Components.Activations;

Constructor

Signature:
public Linear();
Purpose / Functionality:

Creates a new Linear activation function instance.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input tensor to apply the linear activation function to
Returns:

Tensor containing the result of applying the linear activation function to the input.

Purpose / Functionality:

Used to apply the linear activation function to an input while retaining autograd graph connections.

Copy - Overridden Function

Signature:
public override Activation Copy();
Returns:

Deep-copy of the Linear activation function instance.

Purpose / Functionality:

Can be used to create a new (deep-copy) instance of a Linear activation function.

BuildFromData - Virtual Function

Signature:
public virtual void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Inherited from parent Activation class. Has no effect due to the Linear activation function not including parameters.

PrintActivation - Virtual Function

Signature:
public virtual string PrintActivation(FileStream stream);
Returns:

An empty string due to the Linear activation function not including parameters.

Purpose / Functionality:

Inherited from parent Activation class. Returns an empty string due to the Linear activation function not including parameters.

Sigmoid - Class

Overview

Represents the sigmoid activation function. Inherits from Activation.

Using Directive

using NNNCSharp.Components.Activations;

Constructor

Signature:
public Sigmoid();
Purpose / Functionality:

Creates a new Sigmoid activation function instance.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input tensor to apply the sigmoid activation function to
Returns:

Tensor containing the result of applying the sigmoid activation function to the input.

Purpose / Functionality:

Used to apply the sigmoid activation function to an input.

Copy - Overridden Function

Signature:
public override Activation Copy();
Returns:

Deep-copy of the Sigmoid activation function instance.

Purpose / Functionality:

Can be used to create a new (deep-copy) instance of a Sigmoid activation function.

BuildFromData - Virtual Function

Signature:
public virtual void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Inherited from parent Activation class. Has no effect due to the Sigmoid activation function not including parameters.

PrintActivation - Virtual Function

Signature:
public virtual string PrintActivation(FileStream stream);
Returns:

An empty string due to the Sigmoid activation function not including parameters.

Purpose / Functionality:

Inherited from parent Activation class. Returns an empty string due to the Sigmoid activation function not including parameters.

Tanh - Class

Overview

Represents the hyperbolic tangent activation function. Inherits from Activation.

Using Directive

using NNNCSharp.Components.Activations;

Constructor

Signature:
public Tanh();
Purpose / Functionality:

Creates a new Tanh activation function instance.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input tensor to apply the hyperbolic tangent activation function to
Returns:

Tensor containing the result of applying the hyperbolic tangent activation function to the input.

Purpose / Functionality:

Used to apply the hyperbolic tangent activation function to an input.

Copy - Overridden Function

Signature:
public override Activation Copy();
Returns:

Deep-copy of the Tanh activation function instance.

Purpose / Functionality:

Can be used to create a new (deep-copy) instance of a Tanh activation function.

BuildFromData - Virtual Function

Signature:
public virtual void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Inherited from parent Activation class. Has no effect due to the Tanh activation function not including parameters.

PrintActivation - Virtual Function

Signature:
public virtual string PrintActivation(FileStream stream);
Returns:

An empty string due to the Tanh activation function not including parameters.

Purpose / Functionality:

Inherited from parent Activation class. Returns an empty string due to the Tanh activation function not including parameters.

ReLU - Class

Overview

Represents the Rectified Linear Unit activation function. Inherits from Activation.

Using Directive

using NNNCSharp.Components.Activations;

Constructor

Signature:
public ReLU();
Purpose / Functionality:

Creates a new ReLU activation function instance.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input tensor to apply the Rectified Linear Unit activation function to
Returns:

Tensor containing the result of applying the Rectified Linear Unit activation function to the input.

Purpose / Functionality:

Used to apply the Rectified Linear Unit activation function to an input.

Copy - Overridden Function

Signature:
public override Activation Copy();
Returns:

Deep-copy of the ReLU activation function instance.

Purpose / Functionality:

Can be used to create a new (deep-copy) instance of a ReLU activation function.

BuildFromData - Virtual Function

Signature:
public virtual void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Inherited from parent Activation class. Has no effect due to the ReLU activation function not including parameters.

PrintActivation - Virtual Function

Signature:
public virtual string PrintActivation(FileStream stream);
Returns:

An empty string due to the ReLU activation function not including parameters.

Purpose / Functionality:

Inherited from parent Activation class. Returns an empty string due to the ReLU activation function not including parameters.

LeakyReLU - Class

Overview

Represents the Leaky Rectified Linear Unit activation function. Inherits from Activation.

Constructor - Full Initialization

Signature:
public LeakyReLU(float tau = 0.05f);
Parameters:
  • float tau - tau (factor) parameter to be used by the Leaky Rectified Linear Unit activation function
Purpose / Functionality:

Creates a new LeakyReLU instance with its tau parameter initialized.

Constructor - No Initialization

Signature:
public LeakyReLU();
Purpose / Functionality:

Used when loading LeakyReLU activation functions from .nnn files.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input tensor to apply the Leaky Rectified Linear Unit activation function to
Returns:

Tensor containing the result of applying the Leaky Rectified Linear Unit activation function to the input.

Purpose / Functionality:

Used to apply the Leaky Rectified Linear Unit activation function to an input.

Copy - Overridden Function

Signature:
public override Activation Copy();
Returns:

Deep-copy of the LeakyReLU activation function instance.

Purpose / Functionality:

Can be used to create a new (deep-copy) instance of a LeakyReLU activation function.

BuildFromData - Overridden Function

Signature:
public override void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Loads all of the activation's parameters from the given file stream starting at the stream's current position. Used when loading activations from .nnn files.

PrintActivation - Overridden Function

Signature:
public override string PrintActivation(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Returns:

String containing a human-readable summary of the activation data contained in the file stream starting at the stream's current position.

Purpose / Functionality:

Parses the activation data contained in the file stream starting at the stream's current position. Provides a human-readable summary of the data found.

Softmax - Class

Overview

Represents the softmax activation function. Inherits from Activation.

Using Directive

using NNNCSharp.Components.Activations;

Constructor

Signature:
public Softmax();
Purpose / Functionality:

Creates a new Softmax activation function instance.

Forward - Overridden Function

Signature:
public override Tensor Forward(Tensor input);
Parameters:
  • Tensor input - input tensor to apply the softmax activation function to
Returns:

Tensor containing the result of applying the softmax activation function to the input.

Purpose / Functionality:

Used to apply the softmax activation function to an input.

Copy - Overridden Function

Signature:
public override Activation Copy();
Returns:

Deep-copy of the Softmax activation function instance.

Purpose / Functionality:

Can be used to create a new (deep-copy) instance of a Softmax activation function.

BuildFromData - Virtual Function

Signature:
public virtual void BuildFromData(FileStream stream);
Parameters:
  • FileStream stream - file stream from which to read data
Purpose / Functionality:

Inherited from parent Activation class. Has no effect due to the Softmax activation function not including parameters.

PrintActivation - Virtual Function

Signature:
public virtual string PrintActivation(FileStream stream);
Returns:

An empty string due to the Softmax activation function not including parameters.

Purpose / Functionality:

Inherited from parent Activation class. Returns an empty string due to the Softmax activation function not including parameters.

Tensors

Tensor data structure and functionality, and autograd engine functionality.

Tensor - Sealed Class

Overview

Class representing a tensor data structure and implementing all of the related functionality. Wraps a native C++ tensor instance. Implements IDisposable.

Using Directive

using NNNCSharp.Components.Autodiff;

Properties

  • public int Rank { get; } - number of dimensions of the tensor
  • public Span Dimensions { get; } - span over the dimensions array of the tensor
  • public Span Strides { get; } - span over the spatial strides array of the tensor
  • public int ElementCount { get; } - total number of elements contained in the tensor
  • public int GradCount { get; } - total number of gradient values contained in the tensor
  • public Span Data { get; } - underlying linear data array of the tensor (row-major)
  • public Span Grad { get; } - underlying linear array of gradient values of the tensor (row-major)
  • public bool RequiresGrad { get; set; } - whether the tensor must be included in gradient caculations
  • public static bool LogDebug { set; } - whether the native C++ tensor implementation should write logs to the console - reserved for debugging purposes
  • public static bool Inference { get; set; } - whether the native C++ autograd engine is in inference mode - skips autograd graph construction when true

Initialization

Constructor - Standard Initialization
Signature:
public Tensor(int[] dims, bool requiresGrad = false);
Parameters:
  • int[] dims - array representing the dimensions the new tensor will have
  • bool requiresGrad - whether the new tensor must be included in gradient calculations
Purpose / Functionality:

Creates a new zero-initialized C++ tensor instance and corresponding C# wrapper instance.

Constructor - No Initialization
Signature:
public Tensor();
Purpose / Functionality:

Creates a new completely empty C++ tensor instance and corresponding C# wrapper instance. Used to allocate lightweight default values. Should not be used in any operations or to store data.

Constructor - Scalar Initialization
Signature:
public Tensor(float value, int[] dims, bool requiresGrad = false);
Parameters:
  • float value - scalar value to initialize all elements in the tensor to
  • int[] dims - array representing the dimensions the new tensor will have
  • bool requiresGrad - whether the new tensor must be included in gradient calculations
Purpose / Functionality:

Creates a new C++ tensor instance with all elements initialized to the given value, along with a corresponding C# wrapper instance.

Scalar - Static Function
Signature:
public static Tensor Scalar(float value, int[] dims, bool requiresGrad = false);
Parameters:
  • float value - scalar value to initialize all elements in the tensor to
  • int[] dims - array representing the dimensions the new tensor will have
  • bool requiresGrad - whether the new tensor must be included in gradient calculations
Returns:

New C# wrapper around a newly created C++ tensor instance with all elements initialized to the given scalar value.

Purpose / Functionality:

Functionally equivalent to the scalar constructor.

InitWeights - Static Function
Signature:
public static Tensor InitWeights(int inputCount, int neuronCount);
Parameters:
  • int inputCount - number of inputs the weights will be applied to (excluding batches)
  • int neuronCount - number of neurons represented by the weights
Returns:

New C# wrapper around a newly created C++ tensor instance representing the weights parameter tensor of a fully-connected neural network layer.

Purpose / Functionality:

Initializes a new weights parameter tensor for a fully-connected neural network layer using He-Initialization.

InitBiases - Static Function
Signature:
public static Tensor InitBiases(int neuronCount);
Parameters:
  • int neuronCount - number of bias values to include
Returns:

New C# wrapper around a newly created C++ tensor instance representing the bias parameter tensor of a neural network layer.

Purpose / Functionality:

Initializes a new bias parameter tensor for a neural network layer. All bias values are initialized to 0.01.

Dispose - Function
Signature:
public void Dispose();
Purpose / Functionality:

Releases the native C++ memory used by the C# wrapper instance. The native memory will continue to be kept alive as long as required by the native C++ functionality. Should be used whenever a tensor instance is no longer being used by the C# code. Failure to use will likely lead to excessive memory usage and/or memory leaks.

Copy - Function
Signature:
public Tensor Copy();
Returns:

Deep-copy of the C# wrapper instance and underlying native C++ tensor instance with identical data.

Purpose / Functionality:

Can be used to create a new (deep-copy) native C++ tensor instance and corresponding C# wrapper instance with data identical to an existing instance.

Data Access

Indexer - Spatial Indices
Signature:
public float this[params int[] indices] { get; set; }
Parameters:
  • params int[] indices - spatial indices to index at
Returns:

Value at the given spatial indices in the tensor.

Purpose / Functionality:

Can be used to get and/or set the value at the given spatial indices in a tensor.

Indexer - Linear Index
Signature:
public float this[int index] { get; set; }
Parameters:
  • int index - linear index (row-major) to index at
Returns:

Value at the given linear index (row-major) in the tensor.

Purpose / Functionality:

Can be used to get and/or set the value at the given linear index (row-major) in a tensor.

LinearIndex - Function
Signature:
public int LinearIndex(params int[] indices);
Parameters:
  • params int[] indices - spatial indices to convert into a linear index
Returns:

Linear index (row-major) corresponding to the given spatial indices in the tensor.

Purpose / Functionality:

Can be used to convert spatial indices into a linear index (row-major) in a tensor.

GetFullIndices - Function
Signatures:
public int[] GetFullIndices(int index);
public void GetFullIndices(int index, Span<int> indices);
Parameters:
  • int index - linear index (row-major) to convert to spatial indices
  • Span indices - span to write spatial indices into
Returns:

Spatial indices array corresponding to the given linear index in the tensor (if no span to write to is provided).

Purpose / Functionality:

Can be used to convert a linear index (row-major) to spatial indices in a tensor, either returned as a new array or written into a provided span.

Autograd

ClearGraph - Function
Signature:
public void ClearGraph();
Purpose / Functionality:

Clears all autograd graph connections held by the tensor instance.

Backward - Function
Signature:
public void Backward();
Purpose / Functionality:

Computes the gradients of all tensors in the current autograd graph, starting at the tensor on which Backward is called.

Tensor Operations

'+' Operator
Signatures:
public static Tensor operator +(Tensor a, Tensor b);
public static Tensor operator +(Tensor a, float b);
public static Tensor operator +(float a, Tensor b);
Parameters:
  • Tensor/float a - first tensor/scalar to add
  • Tensor/float b - second tensor/scalar to add
Returns:

Tensor containing the result of adding the two arguments.

Purpose / Functionality:

Either computes the element-wise sum of two tensors or adds a scalar value to all elements in a tensor.

'-' Operator
Signatures:
public static Tensor operator -(Tensor a, Tensor b);
public static Tensor operator -(Tensor a, float b);
public static Tensor operator -(float a, Tensor b);
Parameters:
  • Tensor/float a - first tensor/scalar to subtract from
  • Tensor/float b - second tensor/scalar to subtract
Returns:

Tensor containing the result of subtracting the second argument from the first argument.

Purpose / Functionality:

Either computes the element-wise difference of two tensors, subtracts a scalar value from every element in a tensor, or subtracts every element in a tensor from a scalar value.

'*' Operator
Signatures:
public static Tensor operator *(Tensor a, Tensor b);
public static Tensor operator *(Tensor a, float b);
public static Tensor operator *(float a, Tensor b);
Parameters:
  • Tensor/float a - first tensor/scalar to multiply
  • Tensor/float b - second tensor/scalar to multiply
Returns:

Tensor containg the result of multiplying the two arguments.

Purpose / Functionality:

Either computes the element-wise product of two tensors or multiplies all elements in a tensor by a scalar value.

'/' Operator
Signatures:
public static Tensor operator /(Tensor a, Tensor b);
public static Tensor operator /(Tensor a, float b);
public static Tensor operator /(float a, Tensor b);
Parameters:
  • Tensor/float a - first argument to divide
  • Tensor/float b - second argument to divide by
Returns:

Tensor containing the result of dividing the first argument by the second argument.

Purpose / Functionality:

Either computes the element-wise quotient of two tensors, divides every element in a tensor by a scalar value, or divides a scalar value by every element in a tensor.

Pow - Static Function
Signatures:
public static Tensor Pow(Tensor a, Tensor exp);
public static Tensor Pow(Tensor a, float exp);
public static Tensor Pow(float a, Tensor exp);
Parameters:
  • Tensor/float a - base tensor/scalar to exponentiate
  • Tensor/float exp - exponent tensor/scalar to raise to
Returns:

Tensor containing the result of raising the base 'a' to the given exponent 'exp'.

Purpose / Functionality:

Either computes the element-wise power of a base 'a' tensor raised to an exponent 'exp' tensor, raises every element in a base 'a' tensor to an exponent 'exp' scalar value, or raises a base 'a' scalar value to the power of every element in an exponent 'exp' tensor.

Exp - Static Function
Signature:
public static Tensor Exp(Tensor t);
Parameters:
  • Tensor t - tensor to raise to the power of
Returns:

Tensor containing the result of raising 'e' to the power of the given tensor.

Purpose / Functionality:

Raises 'e' to the power of every element in a tensor.

Log - Static Function
Signatures:
public static Tensor Log(Tensor arg, Tensor logBase);
public static Tensor Log(Tensor arg, float logBase);
public static Tensor Log(float arg, Tensor logBase);
Parameters:
  • Tensor/float arg - tensor/scalar to use as the argument of the logarithm
  • Tensor/float logBase - tensor/scalar to use as the base of the logarithm
Returns:

Tensor containing the result of the logarithm with base 'logBase' of the argument 'arg'.

Purpose / Functionality:

Computes either the element-wise logarithm with base tensor 'logBase' and argument tensor 'arg', or the logarithm with base scalar 'logBase' and argument tensor 'arg', or the logarithm with base tensor 'logBase' and argument scalar 'arg'.

Ln - Static Function
Signature:
public static Tensor Ln(Tensor t);
Parameters:
  • Tensor t - tensor to compute natural logarithm of
Returns:

Tensor containing the result of the natural logarithm of the given tensor.

Purpose / Functionality:

Computes the element-wise natural logarithm of a tensor.

'^' (matmul) Operator
Signature:
public static Tensor operator ^(Tensor a, Tensor b);
Parameters:
  • Tensor a - first argument to matrix multiply
  • Tensor b - second argument to matrix multiply
Returns:

Tensor containing the result of the matrix multiplication of the first (left) and second (right) tensors.

Purpose / Functionality:

Computes the matrix multiplication product of two tensors. Uses the first argument as the left tensor and the second argument as the right tensor. Does not have higher precedence than element-wise tensor operators.

Convolve - Static Function
Signature:
public static Tensor Convolve(Tensor input, Tensor kernels);
Parameters:
  • Tensor input - input tensor to convolve
  • Tensor kernels - kernels tensor to convolve with
Returns:

Tensor containing the result of the convolution of the given input tensor with the given kernels tensor.

Purpose / Functionality:

Computes the convolution of an input tensor with a kernels tensor.

Tensor Utilities

ArgMax - Static Function
Signature:
public static int ArgMax(Tensor t);
Parameters:
  • Tensor t - tensor to compute argument maximum of
Returns:

Linear index (row-major) of the highest value element in the given tensor.

Purpose / Functionality:

Finds the linear index (row-major) of the highest value in a tensor.

Sum - Static Function
Signature:
public static Tensor Sum(Tensor t);
Parameters:
  • Tensor t - tensor to compute sum of
Returns:

Tensor containing a single element representing the sum of all elements in the given tensor.

Purpose / Functionality:

Computes the sum of all elements in a tensor while retaining autograd graph connections.

Mean - Static Function
Signature:
public static Tensor Mean(Tensor t);
Parameters:
  • Tensor t - tensor to compute mean of
Returns:

Tensor containing a single element representing the mean of all elements in the given tensor.

Purpose / Functionality:

Computes the mean of all elements in a tensor while retaining autograd graph connections.

Transpose - Static Function
Signatures:
public static Tensor Transpose(Tensor t);
public static Tensor Transpose(Tensor t, int[] axes);
Parameters:
  • Tensor t - tensor to transpose
  • int[] axes - specifies the permutation order to transpose with - defaults to reversing all axes
Returns:

Tensor representing the transpose of the given tensor using the given permutation order.

Purpose / Functionality:

Transposes a tensor based on a specific permutation order, or defaulting to reversing all axes, while retaining autograd graph connections.

Broadcast - Static Function
Signature:
public static Tensor Broadcast(Tensor t, int[] targetDims);
Parameters:
  • Tensor t - tensor to broadcast
  • int[] targetDims - dimensions to broadcast to - must end with the dimensions of the input tensor 't'
Returns:

Tensor representing the broadcast of the given tensor to the given target dimensions.

Purpose / Functionality:

Broadcasts a tensor to a new set of dimensions while retaining autograd graph connections.

Reshape - Static Function
Signature:
public static Tensor Reshape(Tensor t, int[] newDims);
Parameters:
  • Tensor t - tensor to reshape
  • int[] newDims - dimensions to reshape to
Returns:

Tensor representing the given tensor reshaped to the given new dimensions.

Purpose / Functionality:

Reshapes a tensor to a new set of dimensions, without modifying the linear ordering of the underlying data, while retaining autograd graph connections.

Flatten - Static Function
Signature:
public static Tensor Flatten(Tensor t, int startAxis = 0);
Parameters:
  • Tensor t - tensor to flatten
  • int startAxis - axis to flatten from
Returns:

Tensor representing the given tensor flattened from the given axis.

Purpose / Functionality:

Flattens a tensor starting at a specific axis, without modifying the linear ordering of the underlying data, while retaining autograd graph connections.

WrapBatch - Static Function
Signature:
public static Tensor WrapBatch(Tensor t);
Parameters:
  • Tensor t - tensor to wrap
Returns:

Tensor representing the given tensor wrapped as a new batch.

Purpose / Functionality:

Wraps a tensor into a new batch by adding a leading dimension with a length of 1 to represent the batch dimension.

MaskActions - Static Function
Signatures:
public static Tensor MaskActions(Tensor qValues, int[] actions);
public static Tensor MaskActions(Tensor qValues, List<Experience> batch);
Parameters:
  • Tensor qValues - Q-Values to mask
  • int[] actions - action indices to mask by
  • List<Experience> batch - list of experiences corresponding to the given Q-Values - masks by the action indices of the corresponding experiences
Returns:

Tensor containing the given Q-Values masked based on the given action indices with all other Q-Values being replaced with 0's.

Purpose / Functionality:

Masks a set of Q-Values based on corresponding action indices or experiences while retaining autograd graph connections.

Clip - Static Function
Signature:
public static Tensor Clip(Tensor t, float min, float max);
Parameters:
  • Tensor t - tensor to clip values of
  • float min - minimum value to clip to
  • float max - maximum value to clip to
Returns:

Tensor containing the elements of the given tensor clipped to the specified range.

Purpose / Functionality:

Clips all elements of a tensor to a specified range while retaining autograd graph connections.

GetDenseDropoutMask - Static Function
Signature:
public static Tensor GetDenseDropoutMask(Tensor t, float dropout);
Parameters:
  • Tensor t - tensor to which the mask will be applied
  • float dropout - dropout rate to use
Returns:

Tensor representing the standard dropout mask for the given tensor.

Purpose / Functionality:

Generates a standard dropout mask for a tensor using a specific dropout rate. Does not apply the dropout mask to the given tensor.

GetSpatialDropoutMask - Static Function
Signature:
public static Tensor GetSpatialDropoutMask(Tensor t, float dropout);
Parameters:
  • Tensor t - tensor to which the mask will be applied
  • float dropout - spatial dropout rate to use
Returns:

Tensor representing the spatial dropout mask for the given tensor.

Purpose / Functionality:

Generates a spatial dropout mask for a tensor using a specific spatial dropout rate. Does not apply the dropout mask to the given tensor.

Activation Functions (wrap native C++ activation function implementations)

Linear - Static Function
Signature:
public static Tensor Linear(Tensor t);
Parameter:
  • Tensor t - tensor to apply the linear activation function to
Returns:

Tensor containing the result of applying the linear activation function to the given tensor.

Purpose / Functionality:

Applies the linear activation function to a tensor while retaining autograd graph connections.

Sigmoid - Static Function
Signature:
public static Tensor Sigmoid(Tensor t);
Parameter:
  • Tensor t - tensor to apply the sigmoid activation function to
Returns:

Tensor containing the result of applying the sigmoid activation function to the given tensor.

Purpose / Functionality:

Applies the sigmoid activation function to a tensor while retaining autograd graph connections.

Tanh - Static Function
Signature:
public static Tensor Tanh(Tensor t);
Parameter:
  • Tensor t - tensor to apply the hyperbolic tangent activation function to
Returns:

Tensor containing the result of applying the hyperbolic tangent activation function to the given tensor.

Purpose / Functionality:

Applies the hyperbolic tangent activation function to a tensor while retaining autograd graph connections.

ReLU - Static Function
Signature:
public static Tensor ReLU(Tensor t);
Parameter:
  • Tensor t - tensor to apply the Rectified Linear Unit activation function to
Returns:

Tensor containing the result of applying the Rectified Linear Unit activation function to the given tensor.

Purpose / Functionality:

Applies the Rectified Linear Unit activation function to a tensor while retaining autograd graph connections.

LeakyReLU - Static Function
Signature:
public static Tensor LeakyReLU(Tensor t, float tau);
Parameter:
  • Tensor t - tensor to apply the Leaky Rectified Linear Unit activation function to
  • float tau - tau coefficient to use
Returns:

Tensor containing the result of applying the Leaky Rectified Linear Unit activation function to the given tensor.

Purpose / Functionality:

Applies the Leaky Rectified Linear Unit activation function to a tensor while retaining autograd graph connections.

Softmax - Static Function
Signature:
public static Tensor Softmax(Tensor t);
Parameter:
  • Tensor t - tensor to apply the softmax activation function to
Returns:

Tensor containing the result of applying the softmax activation function to the given tensor.

Purpose / Functionality:

Applies the softmax activation function to a tensor while retaining autograd graph connections.

Cost Functions (wrap native C++ cost function implementations)

MSE - Static Function
Signature:
public static Tensor MSE(Tensor t, Tensor target);
Parameters:
  • Tensor t - tensor to apply the Mean Squared Error cost function to
  • Tensor target - tensor to use as target for Mean Squared Error cost
Returns:

Tensor containing the result applying the Mean Squared Error cost function to the given tensor based on the given target tensor.

Purpose / Functionality:

Applies the Mean Squared Error cost function to a tensor based on a specific target tensor while retaining autograd graph connections.

Huber - Static Function
Signature:
public static Tensor Huber(Tensor t, Tensor target, float delta);
Parameters:
  • Tensor t - tensor to apply the pseudo-Huber cost function to
  • Tensor target - tensor to use as target for pseudo-Huber cost
  • float delta - delta value to use
Returns:

Tensor containing the result applying the pseudo-Huber cost function to the given tensor based on the given target tensor.

Purpose / Functionality:

Applies the pseudo-Huber cost function to a tensor based on a specific target tensor while retaining autograd graph connections.

SoftmaxCrossEntropy - Static Function
Signature:
public static Tensor SoftmaxCrossEntropy(Tensor t, Tensor target);
Parameters:
  • Tensor t - tensor to apply the Softmax Cross-Entropy cost function to
  • Tensor target - tensor to use as target for Softmax Cross-Entropy cost
Returns:

Tensor containing the result applying the Softmax Cross-Entropy cost function to the given tensor based on the given target tensor.

Purpose / Functionality:

Applies the Softmax Cross-Entropy cost function to a tensor based on a specific target tensor while retaining autograd graph connections.

Utility Functions

DimensionsMatch - Static Function
Signature:
public static bool DimensionsMatch(Span<int> a, Span<int> b);
Parameters:
  • Span a - span over first dimensions array to compare
  • Span b - span over second dimensions array to compare
Returns:

Whether the two given dimensions spans are exactly identical.

Purpose / Functionality:

Determines whether two dimensions spans are exactly identical.

Environments

Classes representing reinforcement learning (RL) training environments.

DQNEnvironment - Abstract Class

Overview

Base class defining Deep Q-Learning (DQN) training environment functionality and sigantures. Can be inherited from to create custom DQN training environments.

Using Directive

using NNNCSharp.Components.DQNEnvironments;

Properties

  • public int StateSize { get; } - total number of elements in the environment's state representation
  • public Tensor StateFormat { get; } - tensor representing the format of the environment's state tensor - will have a leading dimension of 1 to represent the batch dimension
  • public int ActionCount { get; } - number of discrete actions which can be taken in the environment
  • public string EnvironmentName { get; } - display name of the environment

Constructor

Signature:
public DQNEnvironment();
Purpose / Functionality:

Serves as the default constructor for all DQN environments.

GetState - Abstract Function

Signature:
public abstract Tensor GetState();
Returns:

Tensor containing the current state of the environment.

Purpose / Functionality:

Abstract function for DQN environment subclasses to return their current state.

GetNormalizedState - Abstract Function

Signature:
public abstract Tensor GetNormalizedState();
Returns:

Tensor containing the current normalized state of the environment.

Purpose / Functionality:

Abstract function for DQN environment subclasses to return their current state normalized for processing by neural network DQN agents.

Reset - Abstract Function

Signature:
public abstract void Reset();
Purpose / Functionality:

Abstract function for DQN environment subclasses to implement logic for resetting their internal state.

Step - Abstract Function

Signature:
public abstract (float reward, Tensor nextState, bool done) Step(int action, int steps);
Parameters:
  • int action - index of the action to take
  • int steps - number of steps which have been taken in the current episode
Returns:

Reward incrued by the given action, Tensor containing the normalized state after the action was taken, and whether the current DQn training episode has ended.

Purpose / Functionality:

Abstract function for DQN environment subclasses to implement their step logic.

ValidAction - Abstract Function

Signature:
public abstract bool ValidAction(int action, Tensor? state = null);
Parameters:
  • int action - index of the action to check validity of
  • Tensor? state - optional state in which to verify action validity - defaults to environment's current state
Returns:

Whether the given action is valid in the given state.

Purpose / Functionality:

Abstract function for DQN environment subclasses to implement their action validation logic.

PickAgentAction - Abstract Function

Signature:
public abstract int PickAgentAction(Tensor qValues, Tensor? state = null);
Parameters:
  • Tensor qValues - Q-Values predicted by the agent
  • Tensor? state - optional state for which to select agent action - defaults to environment's current state
Returns:

Index of the valid action with the highest Q-Value.

Purpose / Functionality:

Abstract function for DQN environment subclasses to implement their agent action selection logic.

PickRandomAction - Abstract Function

Signature:
public abstract int PickRandomAction();
Returns:

Index of a random valid action for the environment's current state.

Purpose / Functionality:

Abstract function for DQN environment subclasses to implement their random action selection logic.

TestTrainingProgress - Abstract Function

Signature:
public abstract float TestTrainingProgress(Model agent, int testEpisodes);
Parameters:
  • Model agent - agent to test performance of
  • int testEpisodes - number of test episodes to run
Returns:

Average performance of the agent across all test episodes.

Purpose / Functionality:

Abstract function for DQN environment subclasses to implement their performance evaluation logic.

Render - Virtual Function

Signature:
public virtual void Render(Episode episode, int step);
Parameters:
  • Episode episode - episode from which to render state
  • int step - index of the step to render from the given episode
Purpose / Functionality:

Can be used to render steps in a past episode generated by the DQN environment. Allows DQN environment subclasses with simple to represent states to render past states in the logging output. Does nothing unless overridden.

PlayDemo - Virtual Function

Signature:
public virtual void PlayDemo();
Purpose / Functionality:

Plays the DQN environment's dedicated demonstration. Allows DQN environment subclasses to implement fully encapsulated demonstrations. Not required for training functionality. Throws a NotImplementedException unless overridden.

ISelfPlay - Interface

Overview

Interface for Deep Q-Learning (DQN) training environments which require the agent to play against itself during training.

Using Directive

using NNNCSharp.Components.DQNEnvironments;

Properties

  • public bool Won { get; set; } - whether the most recent step resulted in a win
  • public bool AgentTurn { get; set; } - whether it is the training agent's turn to act
  • public int OpponentCount { get; set; } - number of opponent agents currently stored
  • public int OpponentIndex { get; set; } - index of the currently selected opponent agent - values >= OpponentCount indicate a randomly-acting opponent
  • public Random Random { get; init; } - Random instance used by the environment instance

GetAgentAction - Interface Function

Signature:
public int GetAgentAction(Model agent, Tensor? state = null);
Parameters:
  • Model agent - agent to select action with
  • Tensor? state - optional state for which to select action - defaults to environment's current state
Returns:

Index of the valid action with the highest Q-Value predicted by the agent.

Purpose / Functionality:

Interface function which all self-play DQN environments are required to implement.

PickAgentAction - Interface Function

Signature:
public int PickAgentAction(Tensor qValues, Tensor? state = null);
Parameters:
  • Tensor qValues - Q-Values predicted by the agent
  • Tensor? state - optional state for which to select action - defaults to environment's current state
Returns:

Index of the valid action with the highest Q-Value.

Purpose / Functionality:

Interface function which all self-play DQN environments are required to implement. Also part of the standard DQNEnvironment abstract class.

PickRandomAction - Interface Function

Signature:
public int PickRandomAction();
Returns:

Index of a random valid action for the environment's current state.

Purpose / Functionality:

Interface function which all self-play DQN environments are required to implement. Also part of the standard DQNEnvironment abstract class.

MovementGrid2D - Class

Overview

Class representing a 2D movement grid Deep Q-Learning (DQN) environment. Inherits from DQNEnvironment.

Using Directive

using NNNCSharp.Components.DQNEnvironments;

Properties

  • public int StateSize { get; } - total number of elements in the environment's state representation
  • public Tensor StateFormat { get; } - tensor representing the format of the environment's state tensor - will have a leading dimension of 1 to represent the batch dimension - includes 4 inputs: agent x-position, agent y-position, target x-position, target y-position
  • public int ActionCount { get; } - number of discrete actions which can be taken in the environment - includes 4 actions: left, up, right, down
  • public string EnvironmentName { get; } - display name of the environment

Constructor

Signature:
public MovementGrid2D(int xMin, int xMax, int yMin, int yMax, int maxSteps = 50);
Parameters:
  • int xMin - lowest X-coordinate for the grid to have
  • int xMax - highest X-coordinate for the grid to have
  • int yMin - lowest Y-coordinate for the grid to have
  • int yMax - highest Y-coordinate for the grid to have
  • int maxSteps - maximum number of steps the agent will be allowed to take before timing out
Purpose / Functionality:

Creates a new MovementGrid2D DQN environment instance and prepares it for the first training episode.

GetState - Overridden Function

Signature:
public override Tensor GetState();
Returns:

Tensor containing the current state of the environment.

Purpose / Functionality:

Can be used to get the current state of the movement grid DQN environment.

GetNormalizedState - Overridden Function

Signature:
public override Tensor GetNormalizedState();
Returns:

Tensor containing the current normalized state of the environment.

Purpose / Functionality:

Can be used to get the current state of the movement grid DQN environment normalized based on grid size for processing by neural network agents.

Reset - Overridden Function

Signature:
public override void Reset();
Purpose / Functionality:

Resets the movement grid DQN environment and initializes random agent and target positions.

Step - Overridden Function

Signature:
public override (float reward, Tensor nextState, bool done) Step(int action, int steps);
Parameters:
  • int action - index of the action to take
  • int steps - number of steps which have been taken in the current episode
Returns:

Reward incrued by the given action, Tensor containing the normalized state after the action was taken, and whether the current DQn training episode has ended.

Purpose / Functionality:

Moves the agent's x- and y-position coordinates based on the given action.

ValidAction - Overridden Function

Signature:
public override bool ValidAction(int action, Tensor? state = null);
Parameters:
  • int action - index of the action to check validity of
  • Tensor? state - optional state in which to verify action validity - defaults to environment's current state
Returns:

Whether the given action is valid in the given state.

Purpose / Functionality:

Always returns true due to the movement grid DQN environment action space never having invalid actions.

PickAgentAction - Overridden Function

Signature:
public override int PickAgentAction(Tensor qValues, Tensor? state = null);
Parameters:
  • Tensor qValues - Q-Values predicted by the agent
  • Tensor? state - optional state for which to select agent action - defaults to environment's current state
Returns:

Index of the valid action with the highest Q-Value.

Purpose / Functionality:

Always returns the action index with the highest Q-Value due to the movement grid DQN environment action space never having invalid actions.

PickRandomAction - Overridden Function

Signature:
public override int PickRandomAction();
Returns:

Index of a random valid action for the environment's current state.

Purpose / Functionality:

Returns a fully random action due to the movement grid DQN environment action space never having invalid actions.

TestTrainingProgress - Overridden Function

Signature:
public override float TestTrainingProgress(Model agent, int testEpisodes);
Parameters:
  • Model agent - agent to test performance of
  • int testEpisodes - number of test episodes to run
Returns:

Average performance of the agent across all test episodes.

Purpose / Functionality:

Measures the percentage of episodes in which the agent successfully reaches the target over the course of the given number of randomly initialized test episodes.

Render - Overridden Function

Signature:
public override void Render(Episode episode, int step);
Parameters:
  • Episode episode - episode from which to render state
  • int step - index of the step to render from the given episode
Purpose / Functionality:

Can be used to render steps in a past episode generated by the DQN environment.

PlayDemo - Overridden Function

Signature:
public override void PlayDemo();
Purpose / Functionality:

Plays the DQN environment's dedicated demonstration.

Run - Function

Signature:
public bool Run(Model agent);
Parameters:
  • Model agent - agent to use
Returns:

Whether the agent successfully reached the target before timing out.

Purpose / Functionality:

Runs a single episode with the given agent.

TicTacToe - Class

Overview

Class representing a Tic-Tac-Toe Deep Q-Learning (DQN) training environment. Inherits from DQNEnvironment and implements ISelfPlay.

Using Directive

using NNNCSharp.Components.DQNEnvironments;

Properties

  • public int StateSize { get; } - total number of elements in the environment's state representation
  • public Tensor StateFormat { get; } - tensor representing the format of the environment's state tensor - will have a leading dimension of 1 to represent the batch dimension - 9 board positions ordered linearly (row-major), whether X or O is to move
  • public int ActionCount { get; } - number of discrete actions which can be taken in the environment - 1 for each board position
  • public string EnvironmentName { get; } - display name of the environment
  • public bool Won { get; set; } - whether the most recent step resulted in a win
  • public bool AgentTurn { get; set; } - whether it is the training agent's turn to act
  • public int OpponentCount { get; set; } - number of opponent agents currently stored
  • public int OpponentIndex { get; set; } - index of the currently selected opponent agent - values >= OpponentCount indicate a randomly-acting opponent
  • public Random Random { get; init; } - Rnadom instance used by the environment instance

Constructor

Signature:
public TicTacToe();
Purpose / Functionality:

Creates a new TicTacToe DQN environment instance.

GetState - Overridden Function

Signature:
public override Tensor GetState();
Returns:

Tensor containing the current state of the environment.

Purpose / Functionality:

Can be used to get the current state of the TicTacToe DQN environment.

GetNormalizedState - Overridden Function

Signature:
public override Tensor GetNormalizedState();
Returns:

Tensor containing the current normalized state of the environment.

Purpose / Functionality:

Can be used to get the current state of the TicTacToe DQN environment normalized for processing by neural network agents.

Reset - Overridden Function

Signature:
public override void Reset();
Purpose / Functionality:

Resets the TicTacToe DQN environment and prepares a new game.

Step - Overridden Function

Signature:
public override (float reward, Tensor nextState, bool done) Step(int action, int steps);
Parameters:
  • int action - index of the action to take
  • int steps - number of steps which have been taken in the current episode
Returns:

Reward incrued by the given action, Tensor containing the normalized state after the action was taken, and whether the current DQn training episode has ended.

Purpose / Functionality:

Places the corresponding X/O in the position indicated by the action.

ValidAction - Overridden Function

Signature:
public override bool ValidAction(int action, Tensor? state = null);
Parameters:
  • int action - index of the action to check validity of
  • Tensor? state - optional state in which to verify action validity - defaults to environment's current state
Returns:

Whether the given action is valid in the given state.

Purpose / Functionality:

Checks whether the position corresponding to the action is empty.

GetAgentAction - Function

Signature:
public int GetAgentAction(Model agent, Tensor? state = null);
Parameters:
  • Model agent - agent to select action with
  • Tensor? state - optional state for which to select action - defaults to environment's current state
Returns:

Index of the valid action with the highest Q-Value predicted by the agent.

Purpose / Functionality:

Uses the agent to select the highest Q-Value action index corresponding to an empty position.

PickAgentAction - Overridden Function

Signature:
public override int PickAgentAction(Tensor qValues, Tensor? state = null);
Parameters:
  • Tensor qValues - Q-Values predicted by the agent
  • Tensor? state - optional state for which to select agent action - defaults to environment's current state
Returns:

Index of the valid action with the highest Q-Value.

Purpose / Functionality:

Returns the highest Q-Value action index corresponding to an empty position.

PickRandomAction - Overridden Function

Signature:
public override int PickRandomAction();
Returns:

Index of a random valid action for the environment's current state.

Purpose / Functionality:

Returns the idnex of a random action corresponding to an empty position.

TestTrainingProgress - Overridden Function

Signature:
public override float TestTrainingProgress(Model agent, int testEpisodes);
Parameters:
  • Model agent - agent to test performance of
  • int testEpisodes - number of test episodes to run
Returns:

Average performance of the agent across all test episodes.

Purpose / Functionality:

Measures the percentage of episodes in which the agent either won or tied against a randomly acting opponent over the course of the given number of test episodes.

Render - Overridden Function

Signature:
public override void Render(Episode episode, int step);
Parameters:
  • Episode episode - episode from which to render state
  • int step - index of the step to render from the given episode
Purpose / Functionality:

Can be used to render steps in a past episode generated by the DQN environment.

PlayDemo - Overridden Function

Signature:
public override void PlayDemo();
Purpose / Functionality:

Plays the DQN environment's dedicated demonstration.

Play - Function

Signature:
public void Play(Model agent);
Parameters:
  • Model agent - agent to play with
Purpose / Functionality:

Plays a game of Tic-Tac-Toe between the user and the given agent.

Snake - Class

Overview

Class representing a Snake (game) Deep Q-Learning (DQN) training environment. Inherits from DQNEnvironment.

Using Directive

using NNNCSharp.Components.DQNEnvironments;

Properties

  • public int StateSize { get; } - total number of elements in the environment's state representation
  • public Tensor StateFormat { get; } - tensor representing the format of the environment's state tensor - will have a leading dimension of 1 to represent the batch dimension - 2D image representing the game board with 8 channels for one-hot encoding snake pieces / apples and the direction each element will move
  • public int ActionCount { get; } - number of discrete actions which can be taken in the environment - left, forward, right
  • public string EnvironmentName { get; } - display name of the environment

Constructor

Signature:
public Snake(int width = 20, int height = 20);
Parameters:
  • int width - width of the game board
  • int height - height of the game board
Purpose / Functionality:

Creates a new Snake DQN environment instance.

GetState - Overridden Function

Signature:
public override Tensor GetState();
Returns:

Tensor containing the current state of the environment.

Purpose / Functionality:

Can be used to get the current state of the snake DQN environment.

GetNormalizedState - Overridden Function

Signature:
public override Tensor GetNormalizedState();
Returns:

Tensor containing the current normalized state of the environment.

Purpose / Functionality:

Can be used to get the current state of the snake DQN environment normalized for processing by neural network agents.

Reset - Overridden Function

Signature:
public override void Reset();
Purpose / Functionality:

Resets the snake DQN environment and initializes the snake and first apple.

Step - Overridden Function

Signature:
public override (float reward, Tensor nextState, bool done) Step(int action, int steps);
Parameters:
  • int action - index of the action to take
  • int steps - number of steps which have been taken in the current episode
Returns:

Reward incrued by the given action, Tensor containing the normalized state after the action was taken, and whether the current DQn training episode has ended.

Purpose / Functionality:

Moves the snake based on the given action and handles necessary game logic.

ValidAction - Overridden Function

Signature:
public override bool ValidAction(int action, Tensor? state = null);
Parameters:
  • int action - index of the action to check validity of
  • Tensor? state - optional state in which to verify action validity - defaults to environment's current state
Returns:

Whether the given action is valid in the given state.

Purpose / Functionality:

Always returns true due to the snake DQN environment action space never having invalid actions.

PickAgentAction - Overridden Function

Signature:
public override int PickAgentAction(Tensor qValues, Tensor? state = null);
Parameters:
  • Tensor qValues - Q-Values predicted by the agent
  • Tensor? state - optional state for which to select agent action - defaults to environment's current state
Returns:

Index of the valid action with the highest Q-Value.

Purpose / Functionality:

Always returns the action index with the highest Q-Value due to the snake DQN environment action space never having invalid actions.

PickRandomAction - Overridden Function

Signature:
public override int PickRandomAction();
Returns:

Index of a random valid action for the environment's current state.

Purpose / Functionality:

Returns a fully random action due to the snake DQN environment action space never having invalid actions.

TestTrainingProgress - Overridden Function

Signature:
public override float TestTrainingProgress(Model agent, int testEpisodes);
Parameters:
  • Model agent - agent to test performance of
  • int testEpisodes - number of test episodes to run
Returns:

Average performance of the agent across all test episodes.

Purpose / Functionality:

Measures the average snake length reached by the agent across the given number of test episodes.

Render - Overridden Function

Signature:
public override void Render(Episode episode, int step);
Parameters:
  • Episode episode - episode from which to render state
  • int step - index of the step to render from the given episode
Purpose / Functionality:

Can be used to render steps in a past episode generated by the DQN environment.

PlayDemo - Overridden Function

Signature:
public override void PlayDemo();
Purpose / Functionality:

Plays the DQN environment's dedicated demonstration.

Play - Function

Signature:
public void Play(Model agent);
Parameters:
  • Model agent - agent to have play
Purpose / Functionality:

Plays a game of Snake using the given agent.

Buffers / Records

Data structures for storing and managing training data.

BatchBuffer - Class

Overview

Data structure for storing and batching standard supervised training input-target pairs. Automatically handles releasing of native C++ memory used by the tensors in the dataset.

Using Directive

using NNNCSharp.Components.Buffers;

Constructor

Signature:
public ReplayBuffer(Tensor[] data, Tensor[] targets);
Parameters:
  • Tensor[] data - array of all input tensors in the training dataset
  • Tensor[] targets - array of all target tensors in the training dataset - must be in the same order as the data array
Purpose / Functionality:

Creates a new BatchBuffer instance containing the given dataset of input and target tensors.

GetBatch - Function

Signature:
public (Tensor batchInputs, Tensor batchTargets) GetBatch(int batchSize);
Parameters:
  • int batchSize - number of input-target pairs to include in the batch - must be > 0 and <= total number of input-target pairs
Returns:

Tensors containing the batched inputs and corresponding batched targets.

Purpose / Functionality:

Batches inputs and targets from the dataset by randomly sampling input-target pairs without any repeats.

GetBatches - Function

Signature:
public (Tensor[] batchInputs, Tensor[] batchTargets) GetBatches(int batchSize);
Parameters:
  • int batchSize - number of input-target pairs to include in each batch
Returns:

Tensor arrays containing batched tensors of inputs and the corresponding targets.

Purpose / Functionality:

Randomly samples all of the input-target pairs in the dataset into training batches of the given size. Will likely include a tail batch with a smaller size if dataset size is not perfectly divisible by the given batch size.

FIFOBuffer - Class

Overview

Data structure implementing standard First-In First-Out functionality. Automatically disposes stored elements when applicable.

Using Directive

using NNNCSharp.Components.Buffers;

Properties

  • public int MaxSize { get; init; } - maximum number of elements the buffer can hold
  • public int Count { get; } - number of elements currently stored in the buffer

Constructor

Signature:
public FIFOBuffer(int maxSize);
Parameters:
  • int maxSize - maximum number of elements the buffer will be able to hold
Purpose / Functionality:

Creates a new FIFOBuffer instance with the given maximum size.

Add - Function

Signature:
public void Add(T item);
Parameters:
  • T item - new item to add to the buffer
Purpose / Functionality:

Adds the given item to the buffer using standard First-In First-Out rules.

Indexer

Signature:
public T this[int index] { get; }
Parameters:
  • int index - index to index at
Returns:

Element at the given index in the buffer.

Purpose / Functionality:

Can be used to access the element at a specific index in the buffer, with index 0 always corresponding to the oldest element.

ReplayBuffer - Class

Overview

Data structure implementing Deep Q-Learning (DQN) replay buffer functionality with Prioritized Experience Replay (PER) sampling using an underlying sum tree. Automatically releases native C++ memory used by experience instances when applicable.

Using Directive

using NNNCSharp.Components.Buffers;

Properties

  • public int Count { get; } - number of experiences currently stored in the buffer

Constructor

Signature:
public ReplayBuffer(int capacity, double alpha = 0.6);
Parameters:
  • int capacity - maximum number of experiences the buffer will be able to hold
  • double alpha - alpha value to use during PER sampling
Purpose / Functionality:

Creates a new ReplayBuffer instance with the given capacity.

Add - Function

Signature:
public void Add(Experience experience);
Parameters:
  • Experience experience - experience to add to the buffer
Purpose / Functionality:

Adds a new experience to the buffer using standard First-In First-Out rules and updates the underlying PER sampling sum tree.

GetBatch - Function

Signature:
public (List<Experience> batch, int[] indices, double[] weights) GetBatch(int batchSize);
Parameters:
  • int batchSize - number of experiences to include in the batch
Returns:

Experience array containing the sampled experiences, array of corresponding indices of the sampled experiences in the buffer, and array of the corresponding PER sampling weights.

Purpose / Functionality:

Samples a batch with the given number of experiences using Prioritized Experience Replay (PER) sampling.

UpdatePriorities - Function

Signature:
public void UpdatePriorities(int[] indices, double[] priorities);
Parameters:
  • int[] indices - indices of the experiences to update priorities of
  • double[] priorities - new priorities to set for the experiences at the given indices
Purpose / Functionality:

Used to update Prioritized Experience Replay (PER) sampling priorities of experiences following a training step.

SumTree - Class

Overview

Data structure implementing standard sum tree functionality for Deep Q-Learning (DQN) Prioritized Experience Replay (PER) sampling. Automatically disposes stored elements when applicable.

Using Directive

using NNNCSharp.Components.Buffers;

Properties

  • public int Count { get; private set; } - number of elements currently stored in the sum tree
  • public double TotalPriority { get; } - total priority of all elements currently stored in the sum tree

Constructor

Signature:
public SumTree(int capacity);
Parameters:
  • int capacity - maximum number of elements the sum tree will be able to hold
Purpose / Functionality:

Creates a new SumTree instance with the given capacity.

Add - Function

Signature:
public void Add(T item, double priority);
Parameters:
  • T item - item to add to the sum tree
  • double priority - priority to assign to the given item
Purpose / Functionality:

Adds a new item to the sum tree using standard First-In First-Out rules and assigns it the given priority.

Update - Function

Signature:
public void Update(int treeIndex, double priority);
Parameters:
  • int treeIndex - index of the item to update the priority of
  • double priority - value to update the priority to
Purpose / Functionality:

Assigns a new priority to an item in the sum tree and updates the other nodes in the tree correspondingly.

Get - Function

Signature:
public (int treeIndex, double priority, T item) Get(double value);
Parameters:
  • double value - value to use for PER sampling
Returns:

Index, priority, and item sampled using PER sampling.

Purpose / Functionality:

Samples an item from the sum tree using Prioritized Experience Replay (PER) sampling with the given sampling value.

Episode - Record

Overview

Data structure storing a single Deep Q-Learning (DQN) training episode. Implements IDisposable.

Using Directive

using NNNCSharp.Components.Episodes;

Properties

  • public List Experiences { get; init; }

Constructor

Signature:
public Episode(List<Experience> experiences);
Parameters:
  • List<Experience> experiences - experiences encompassed by the episode
Purpose / Functionality:

Creates a new Episode instance wrapping the given set of experiences.

Dispose - Function

Signature:
public void Dispose();
Purpose / Functionality:

Releases all native C++ memory used by the Episode instance and the experiences contained in it.

Experience - Record

Overview

Data structure representing a single Deep Q-Learning (DQN) training experience. Implements IDisposable.

Using Directive

using NNNCSharp.Components.Episodes;

Properties

  • public Tensor State { get; init; } - environment state at the beginning of the experience
  • public int Action { get; init; } - action which the agent took
  • public float Reward { get; init; } - reward accrued by the agent
  • public Tensor NextState { get; init; } - environment state following the action being taken
  • public bool Done { get; init; } - whether the experience terminated the training episode
  • public float Priority { get; set; } - PER sampling priority of the experience

Constructor

Signature:
public Experience(Tensor state, int action, float reward, Tensor nextState, bool done, float priority = 1.0f);
Parameters:
  • Tensor state - environment state at the beginning of the experience
  • int action - action which the agent took
  • float reward - reward accrued by the agent
  • Tensor nextState - environment state following the action being taken
  • bool done - whether the experience terminated the training episode
  • float priority - PER sampling priority of the experience
Purpose / Functionality:

Creates a new Experience instance with the given data.

Dispose - Function

Signature:
public void Dispose();
Purpose / Functionality:

Releases all native C++ memory used by the instance and the contained state tensors.

Save System

Classes providing functionality for reading and writing .nnn file. Refer to the File Format Documentation for the specifications of the .nnn file format used by Neural Network Notions.

Saver - Static Class

Overview

Provides functionality for saving and loading neural network models to and from .nnn files.

Using Directive

using NNNCSharp.Components.Utilities.SaveSystem;

Properties

  • public static string DirectoryPath { get; set; } - full directory path to save and load from
  • public const int MagicNumber - identifiying number used by .nnn files

SaveModel - Static Function

Signature:
public static void SaveModel(Model model, string fileName, string desc = "");
Parameters:
  • Model model - neural network model to save (without file extension)
  • string fileName - file name to save model to
  • string desc - optional description to include in the file
Purpose / Functionality:

Saves a neural network model to a file using the .nnn file format.

LoadModel - Static Function

Signature:
public static Model LoadModel(string fileName);
Parameters:
  • string fileName - name of the file to load neural network model from (without file extension)
Returns:

Model contained in the given .nnn file.

Purpose / Functionality:

Loads a neural network model from a .nnn file.

FileExists - Static Function

Signature:
public static bool FileExists(string fileName);
Parameters:
  • string fileName - name of the file to find (without file extension)
Returns:

Whether a .nnn file with the given name was found.

Purpose / Functionality:

Searches for a .nnn file with a given name and returns whether it was found. Only searches the directory specified by the DirectoryPath property.

GetFullPath - Static Function

Signature:
public static string GetFullPath(string fileName);
Parameters:
  • string fileName - name of the file to get the full path of (without file extension)
Returns:

Full path of the .nnn file with the given name.

Purpose / Functionality:

Generates the full path of a .nnn file with a given name. Assumes the file is in the directory specified by the DirectoryPath property.

FileUtils - Static Class

Overview

Provides functionality for reading and writing data to and from .nnn files.

Using Directive

using NNNCSharp.Components.Utilities.SaveSystem;

Data Writing

WriteBool - Static Function
Signature:
public static void WriteBool(FileStream stream, bool data);
Parameters:
  • FileStream stream - file stream to write to
  • bool data - boolean to write
Purpose / Functionality:

Writes the given boolean to the given file stream using .nnn encoding.

WriteFloat - Static Function
Signature:
public static void WriteFloat(FileStream stream, float data);
Parameters:
  • FileStream stream - file stream to write to
  • float data - float to write
Purpose / Functionality:

Writes the given float to the given file stream using .nnn encoding.

WriteFloatArray - Static Function
Signature:
public static void WriteFloatArray(FileStream stream, float[] data);
Parameters:
  • FileStream stream - file stream to write to
  • float[] data - float array to write
Purpose / Functionality:

Writes the given array of floats to the given file stream using .nnn encoding.

WriteInt32 - Static Function
Signature:
public static void WriteInt32(FileStream stream, int data);
Parameters:
  • FileStream stream - file stream to write to
  • int data - 32-bit integer to write
Purpose / Functionality:

Writes the given 32-bit (signed) integer to the given file stream using .nnn encoding.

WriteInt32Array - Static Function
Signature:
public static void WriteInt32Array(FileStream stream, int[] data);
Parameters:
  • FileStream stream - file stream to write to
  • int[] data - 32-bit integer array to write
Purpose / Functionality:

Writes the given 32-bit (signed) integer array to the given file stream using .nnn encoding.

WriteLayer - Static Function
Signature:
public static void WriteLayer(FileStream stream, Layer layer);
Parameters:
  • FileStream stream - file stream to write to
  • Layer layer - neural network layer to write
Purpose / Functionality:

Writes the given neural network layer to the given file stream using .nnn encoding.

WriteModel(FileStream stream, Model model);
Signature:
public static void WriteModel(FileStream stream, Model model);
Parameters:
  • FileStream stream - file stream to write to
  • Model model - neural network model to write
Purpose / Functionality:

Writes the given neural network model to the given file stream using .nnn encoding.

WriteString - Static Function
Signature:
public static void WriteString(FileStream stream, string data);
Parameters:
  • FileStream stream - file stream to write to
  • string data - string to write
Purpose / Functionality:

Writes the given string to the given file stream using .nnn encoding.

WriteTensor - Static Function
Signature:
public static void WriteTensor(FileStream stream, Tensor data);
Parameters:
  • FileStream stream - file stream to write to
  • Tensor data - tensor to write
Purpose / Functionality:

Writes the given tensor to the given file stream using .nnn encoding.

WriteUInt64 - Static Function
Signature:
public static void WriteUInt64(FileStream stream, ulong data);
Parameters:
  • FileStream stream - file stream to write to
  • ulong data - 64-bit (unsigned) integer to write
Purpose / Functionality:

Writes the given 64-bit (unsigned) integer to the given file stream using .nnn encoding.

Data Reading

ReadBool - Static Function
Signature:
public static bool ReadBool(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Boolean read from the file stream.

Purpose / Functionality:

Reads the boolean stored at the given file stream's current position using .nnn encoding.

ReadFloat - Static Function
Signature:
public static float ReadFloat(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Float read from the file stream.

Purpose / Functionality:

Reads the float stored at the given file stream's current position using .nnn encoding.

ReadFloatArray - Static Function
Signature:
public static float[] ReadFloatArray(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Float array read from the file stream.

Purpose / Functionality:

Reads the array of floats stored at the given file stream's current position using .nnn encoding.

ReadInt32 - Static Function
Signature:
public static int ReadInt32(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

32-bit (signed) integer read from the file stream.

Purpose / Functionality:

Reads the 32-bit (signed) integer stored at the given file stream's current position using .nnn encoding.

ReadInt32Array - Static Function
Signature:
public static int[] ReadInt32Array(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

32-bit (signed) integer array read from the file stream.

Purpose / Functionality:

Reads the array of 32-bit (signed) integers stored at the given file stream's current position using .nnn encoding.

ReadLayer - Static Function
Signature:
public static Layer ReadLayer(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Neural network Layer read from the file stream.

Purpose / Functionality:

Reads the neural network layer stored at the given file stream's current position using .nnn encoding.

ReadModel - Static Function
Signature:
public static Model ReadModel(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Neural network Model read from the file stream.

Purpose / Functionality:

Reads the neural network model stored at the given file stream's current position using .nnn encoding.

ReadString - Static Function
Signature:
public static string ReadString(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

String read from the file stream.

Purpose / Functionality:

Reads the string stored at the given file stream's current position using .nnn encoding.

ReadTensor - Static Function
Signature:
public static Tensor ReadTensor(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Tensor read from the file stream.

Purpose / Functionality:

Reads the tensor stored at the given file stream's current position using .nnn encoding.

ReadUInt64 - Static Function
Signature:
public static ulong ReadUInt64(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

64-bit (unsigned) integer read from the file stream.

Purpose / Functionality:

Reads the 64-bit (unsigned) integer stored at the given file stream's current position using .nnn encoding.

File Viewing

PrintLayer - Static Function
Signature:
public static string PrintLayer(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Human-readable summary of the neural network layer stored in the file stream.

Purpose / Functionality:

Parses the neural network layer stored at the given file stream's current position into a human-readable string using .nnn encoding.

PrintTensor - Static Function
Signature:
public static string PrintTensor(FileStream stream);
Parameters:
  • FileStream stream - file stream to read from
Returns:

Human-readable summary of the tensor stored in the file stream.

Purpose / Functionality:

Parses the tensor stored at the given file stream's current position into a human-readable string using .nnn encoding.

Clone this wiki locally