Class HeterogeneousGraphLayer<T>
- Namespace
- AiDotNet.NeuralNetworks.Layers
- Assembly
- AiDotNet.dll
Implements Heterogeneous Graph Neural Network layer for graphs with multiple node and edge types.
public class HeterogeneousGraphLayer<T> : LayerBase<T>, IDisposable, IGraphConvolutionLayer<T>, ILayer<T>, IJitCompilable<T>, IDiagnosticsProvider, IWeightLoadable<T>
Type Parameters
TThe numeric type used for calculations, typically float or double.
- Inheritance
-
LayerBase<T>HeterogeneousGraphLayer<T>
- Implements
-
ILayer<T>
- Inherited Members
Remarks
Heterogeneous Graph Neural Networks (HGNNs) handle graphs where nodes and edges have different types. Unlike homogeneous GNNs that treat all nodes and edges uniformly, HGNNs use type-specific transformations and aggregations. This layer implements the R-GCN (Relational GCN) approach with type-specific weight matrices.
The layer computes: h_i' = σ(Σ_{r∈R} Σ_{j∈N_r(i)} (1/c_{i,r}) W_r h_j + W_0 h_i) where R is the set of relation types, N_r(i) are neighbors of type r, c_{i,r} is a normalization constant, W_r are relation-specific weights, and W_0 is the self-loop weight.
For Beginners: This layer handles graphs where not all nodes and edges are the same.
Real-world examples:
Knowledge Graph:
- Node types: Person, Place, Event
- Edge types: BornIn, HappenedAt, AttendedBy
- Each type needs different processing
E-commerce:
- Node types: User, Product, Brand, Category
- Edge types: Purchased, Manufactured, BelongsTo, Viewed
- Different relationships have different meanings
Academic Network:
- Node types: Author, Paper, Venue, Topic
- Edge types: Wrote, PublishedIn, About, Cites
- Mixed types of entities and relationships
Why heterogeneous?
- Different semantics: A "User" has different properties than a "Product"
- Type-specific patterns: Relationships mean different things
- Better representation: Specialized processing for each type
The layer learns separate transformations for each edge type, then combines them intelligently.
Constructors
HeterogeneousGraphLayer(HeterogeneousGraphMetadata, int, bool, int, IActivationFunction<T>?)
Initializes a new instance of the HeterogeneousGraphLayer<T> class.
public HeterogeneousGraphLayer(HeterogeneousGraphMetadata metadata, int outputFeatures, bool useBasis = false, int numBases = 4, IActivationFunction<T>? activationFunction = null)
Parameters
metadataHeterogeneousGraphMetadataMetadata describing node and edge types.
outputFeaturesintNumber of output features per node.
useBasisboolWhether to use basis decomposition (default: false).
numBasesintNumber of basis matrices if using decomposition (default: 4).
activationFunctionIActivationFunction<T>Activation function to apply.
Remarks
Creates a heterogeneous graph layer. If useBasis is true, weights are decomposed as W_r = Σ_b a_{rb} V_b, reducing parameters for graphs with many edge types.
For Beginners: This creates a new heterogeneous graph layer.
Key parameters:
- metadata: Describes your graph structure (what types exist)
- useBasis: Memory-saving technique for graphs with many edge types
- false: Each edge type has its own weights (more expressive)
- true: Edge types share basis matrices (fewer parameters)
- numBases: How many shared patterns to use (if useBasis=true)
Example setup:
var metadata = new HeterogeneousGraphMetadata
{
NodeTypes = ["user", "product"],
EdgeTypes = ["purchased", "viewed", "rated"],
NodeTypeFeatures = { ["user"] = 32, ["product"] = 64 },
EdgeTypeSchema = {
["purchased"] = ("user", "product"),
["viewed"] = ("user", "product"),
["rated"] = ("user", "product")
}
};
var layer = new HeterogeneousGraphLayer(metadata, 128);
Properties
InputFeatures
Gets the number of input features per node.
public int InputFeatures { get; }
Property Value
Remarks
This property indicates how many features each node in the graph has as input. For example, in a molecular graph, this might be properties of each atom.
For Beginners: This tells you how many pieces of information each node starts with.
Examples:
- In a social network: age, location, interests (3 features)
- In a molecule: atomic number, charge, mass (3 features)
- In a citation network: word embeddings (300 features)
Each node has the same number of input features.
OutputFeatures
Gets the number of output features per node.
public int OutputFeatures { get; }
Property Value
Remarks
This property indicates how many features each node will have after processing through this layer. The layer transforms each node's input features into output features through learned transformations.
For Beginners: This tells you how many pieces of information each node will have after processing.
The layer learns to:
- Combine input features in useful ways
- Extract important patterns
- Create new representations that are better for the task
For example, if you start with 10 features per node and the layer has 16 output features, each node's 10 numbers will be transformed into 16 numbers that hopefully capture more useful information for your specific task.
SupportsGpuExecution
Gets whether this layer has a GPU execution implementation for inference.
protected override bool SupportsGpuExecution { get; }
Property Value
Remarks
Override this to return true when the layer implements ForwardGpu(params IGpuTensor<T>[]). The actual CanExecuteOnGpu property combines this with engine availability.
For Beginners: This flag indicates if the layer has GPU code for the forward pass. Set this to true in derived classes that implement ForwardGpu.
SupportsJitCompilation
Gets whether this layer supports JIT compilation.
public override bool SupportsJitCompilation { get; }
Property Value
- bool
True if the layer can be JIT compiled, false otherwise.
Remarks
This property indicates whether the layer has implemented ExportComputationGraph() and can benefit from JIT compilation. All layers MUST implement this property.
For Beginners: JIT compilation can make inference 5-10x faster by converting the layer's operations into optimized native code.
Layers should return false if they:
- Have not yet implemented a working ExportComputationGraph()
- Use dynamic operations that change based on input data
- Are too simple to benefit from JIT compilation
When false, the layer will use the standard Forward() method instead.
SupportsTraining
Gets a value indicating whether this layer supports training.
public override bool SupportsTraining { get; }
Property Value
- bool
trueif the layer has trainable parameters and supports backpropagation; otherwise,false.
Remarks
This property indicates whether the layer can be trained through backpropagation. Layers with trainable parameters such as weights and biases typically return true, while layers that only perform fixed transformations (like pooling or activation layers) typically return false.
For Beginners: This property tells you if the layer can learn from data.
A value of true means:
- The layer has parameters that can be adjusted during training
- It will improve its performance as it sees more data
- It participates in the learning process
A value of false means:
- The layer doesn't have any adjustable parameters
- It performs the same operation regardless of training
- It doesn't need to learn (but may still be useful)
Methods
Backward(Tensor<T>)
Computes the backward pass for this Heterogeneous Graph layer.
public override Tensor<T> Backward(Tensor<T> outputGradient)
Parameters
outputGradientTensor<T>The gradient of the loss with respect to this layer's output.
Returns
- Tensor<T>
The gradient of the loss with respect to this layer's input.
Remarks
This method computes gradients for all type-specific parameters including edge type weights, self-loop weights, biases, and basis decomposition parameters if enabled.
ExportComputationGraph(List<ComputationNode<T>>)
Exports the layer's computation graph for JIT compilation.
public override ComputationNode<T> ExportComputationGraph(List<ComputationNode<T>> inputNodes)
Parameters
inputNodesList<ComputationNode<T>>List to populate with input computation nodes.
Returns
- ComputationNode<T>
The output computation node representing the layer's operation.
Remarks
This method constructs a computation graph representation of the layer's forward pass that can be JIT compiled for faster inference. All layers MUST implement this method to support JIT compilation.
For Beginners: JIT (Just-In-Time) compilation converts the layer's operations into optimized native code for 5-10x faster inference.
To support JIT compilation, a layer must:
- Implement this method to export its computation graph
- Set SupportsJitCompilation to true
- Use ComputationNode and TensorOperations to build the graph
All layers are required to implement this method, even if they set SupportsJitCompilation = false.
Forward(Tensor<T>)
Performs the forward pass of the layer.
public override Tensor<T> Forward(Tensor<T> input)
Parameters
inputTensor<T>The input tensor to process.
Returns
- Tensor<T>
The output tensor after processing.
Remarks
This abstract method must be implemented by derived classes to define the forward pass of the layer. The forward pass transforms the input tensor according to the layer's operation and activation function.
For Beginners: This method processes your data through the layer.
The forward pass:
- Takes input data from the previous layer or the network input
- Applies the layer's specific transformation (like convolution or matrix multiplication)
- Applies any activation function
- Passes the result to the next layer
This is where the actual data processing happens during both training and prediction.
ForwardGpu(params IGpuTensor<T>[])
GPU-accelerated forward pass for HeterogeneousGraphLayer. Implements type-specific graph convolution with fully GPU-native operations.
public override IGpuTensor<T> ForwardGpu(params IGpuTensor<T>[] inputs)
Parameters
inputsIGpuTensor<T>[]
Returns
- IGpuTensor<T>
GetAdjacencyMatrix()
Gets the adjacency matrix currently being used by this layer.
public Tensor<T>? GetAdjacencyMatrix()
Returns
- Tensor<T>
The adjacency matrix tensor, or null if not set.
Remarks
This method retrieves the adjacency matrix that was set using SetAdjacencyMatrix. It may return null if the adjacency matrix has not been set yet.
For Beginners: This method lets you check what graph structure the layer is using.
This can be useful for:
- Verifying the correct graph was loaded
- Debugging graph connectivity issues
- Visualizing the graph structure
GetParameterTensors()
Gets all trainable parameters of the layer as a list of tensors.
public List<Tensor<T>> GetParameterTensors()
Returns
- List<Tensor<T>>
A list containing all trainable parameter tensors.
GetParameters()
Gets all trainable parameters of the layer as a single vector.
public override Vector<T> GetParameters()
Returns
- Vector<T>
A vector containing all trainable parameters.
Remarks
This abstract method must be implemented by derived classes to provide access to all trainable parameters of the layer as a single vector. This is useful for optimization algorithms that operate on all parameters at once, or for saving and loading model weights.
For Beginners: This method collects all the learnable values from the layer.
The parameters:
- Are the numbers that the neural network learns during training
- Include weights, biases, and other learnable values
- Are combined into a single long list (vector)
This is useful for:
- Saving the model to disk
- Loading parameters from a previously trained model
- Advanced optimization techniques that need access to all parameters
ResetState()
Resets the internal state of the layer.
public override void ResetState()
Remarks
This abstract method must be implemented by derived classes to reset any internal state the layer maintains between forward and backward passes. This is useful when starting to process a new sequence or when implementing stateful recurrent networks.
For Beginners: This method clears the layer's memory to start fresh.
When resetting the state:
- Cached inputs and outputs are cleared
- Any temporary calculations are discarded
- The layer is ready to process new data without being influenced by previous data
This is important for:
- Processing a new, unrelated sequence
- Preventing information from one sequence affecting another
- Starting a new training episode
SetAdjacencyMatrices(Dictionary<string, Tensor<T>>)
Sets the adjacency matrices for all edge types.
public void SetAdjacencyMatrices(Dictionary<string, Tensor<T>> adjacencyMatrices)
Parameters
adjacencyMatricesDictionary<string, Tensor<T>>Dictionary mapping edge types to their adjacency matrices.
SetAdjacencyMatrix(Tensor<T>)
Sets the adjacency matrix that defines the graph structure.
public void SetAdjacencyMatrix(Tensor<T> adjacencyMatrix)
Parameters
adjacencyMatrixTensor<T>The adjacency matrix tensor representing node connections.
Remarks
The adjacency matrix is a square matrix where element [i,j] indicates whether and how strongly node i is connected to node j. Common formats include: - Binary adjacency: 1 if connected, 0 otherwise - Weighted adjacency: connection strength as a value - Normalized adjacency: preprocessed for better training
For Beginners: This method tells the layer how nodes in the graph are connected.
Think of the adjacency matrix as a map:
- Each row represents a node
- Each column represents a potential connection
- The value at position [i,j] tells if node i connects to node j
For example, in a social network:
- adjacencyMatrix[Alice, Bob] = 1 means Alice is friends with Bob
- adjacencyMatrix[Alice, Charlie] = 0 means Alice is not friends with Charlie
This connectivity information is crucial for graph neural networks to propagate information between connected nodes.
SetNodeTypeMap(Dictionary<int, string>)
Sets the node type mapping.
public void SetNodeTypeMap(Dictionary<int, string> nodeTypeMap)
Parameters
nodeTypeMapDictionary<int, string>Dictionary mapping node indices to their types.
SetParameterTensors(List<Tensor<T>>)
Sets the trainable parameters of the layer from a list of tensors.
public void SetParameterTensors(List<Tensor<T>> parameters)
Parameters
parametersList<Tensor<T>>A list containing all parameter tensors to set.
SetParameters(Vector<T>)
Sets the trainable parameters of the layer.
public override void SetParameters(Vector<T> parameters)
Parameters
parametersVector<T>A vector containing all parameters to set.
Remarks
This method sets all the trainable parameters of the layer from a single vector of parameters. The parameters vector must have the correct length to match the total number of parameters in the layer. By default, it simply assigns the parameters vector to the Parameters field, but derived classes may override this to handle the parameters differently.
For Beginners: This method updates all the learnable values in the layer.
When setting parameters:
- The input must be a vector with the correct length
- The layer parses this vector to set all its internal parameters
- Throws an error if the input doesn't match the expected number of parameters
This is useful for:
- Loading a previously saved model
- Transferring parameters from another model
- Setting specific parameter values for testing
Exceptions
- ArgumentException
Thrown when the parameters vector has incorrect length.
UpdateParameters(T)
Updates the layer parameters based on computed gradients.
public override void UpdateParameters(T learningRate)
Parameters
learningRateTThe learning rate for parameter updates.