Table of Contents

Class HybridShardedModel<T, TInput, TOutput>

Namespace
AiDotNet.DistributedTraining
Assembly
AiDotNet.dll

Implements 3D Parallelism (Hybrid Sharded) model - combines data, tensor, and pipeline parallelism.

public class HybridShardedModel<T, TInput, TOutput> : ShardedModelBase<T, TInput, TOutput>, IShardedModel<T, TInput, TOutput>, IFullModel<T, TInput, TOutput>, IModel<TInput, TOutput, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, TInput, TOutput>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, TInput, TOutput>>, IGradientComputable<T, TInput, TOutput>, IJitCompilable<T>

Type Parameters

T

The numeric type

TInput

The input type for the model

TOutput

The output type for the model

Inheritance
ShardedModelBase<T, TInput, TOutput>
HybridShardedModel<T, TInput, TOutput>
Implements
IShardedModel<T, TInput, TOutput>
IFullModel<T, TInput, TOutput>
IModel<TInput, TOutput, ModelMetadata<T>>
IParameterizable<T, TInput, TOutput>
ICloneable<IFullModel<T, TInput, TOutput>>
IGradientComputable<T, TInput, TOutput>
Inherited Members
Extension Methods

Remarks

Strategy Overview: 3D Parallelism combines all three major parallelism strategies for maximum scalability: - Data Parallelism: Different data batches across replicas - Tensor Parallelism: Layer-wise partitioning within each pipeline stage - Pipeline Parallelism: Model depth partitioning across stages

This enables training extremely large models (100B+ parameters) on thousands of GPUs by exploiting parallelism in all dimensions. This is the strategy used for training models like GPT-3, Megatron-Turing NLG, and other frontier models.

For Beginners: 3D Parallelism is the ultimate distributed training strategy - it combines ALL the techniques:

Imagine training a MASSIVE model across 512 GPUs:

  • Pipeline Parallel (depth): Split model into 8 stages (64 GPUs per stage)
  • Tensor Parallel (width): Within each stage, split layers 8 ways (8 GPUs per tensor group)
  • Data Parallel (batches): Remaining 8 GPUs in each tensor group process different data

Layout example for 512 GPUs = 8 pipeline × 8 tensor × 8 data:

  • Stage 0: GPUs 0-63 (layers 0-12)
    • Tensor group 0: GPUs 0-7 (data replicas)
    • Tensor group 1: GPUs 8-15 (data replicas)
    • ... 8 tensor groups total
  • Stage 1: GPUs 64-127 (layers 13-25)
    • ...and so on

Use Cases: - Training frontier models (GPT-3 scale: 100B-1T parameters) - Requires 100s to 1000s of GPUs - When single parallelism dimension isn't enough - Production training at largest scales (OpenAI, Google, Meta)

Trade-offs: - Memory: Excellent - exploits all memory-saving strategies - Communication: Complex - requires careful network topology optimization - Complexity: Very High - most complex distributed strategy - Best for: Frontier-scale models (100B+ params), massive GPU clusters - Requires: Careful tuning of all three parallelism dimensions for efficiency

Implementation Note: This is a production-ready framework providing the 3D parallelism infrastructure. Full production deployment requires: 1. Process group management (separate groups for data/tensor/pipeline) 2. Model-specific layer partitioning 3. Careful configuration tuning for your specific cluster topology This implementation demonstrates the pattern and provides the foundation.

Example:

// Training a 175B parameter model on 512 GPUs
// 8 pipeline stages × 8 tensor parallel × 8 data parallel = 512
var model = new MassiveTransformer<double>(...);
var backend = new InMemoryCommunicationBackend<double>(rank: myRank, worldSize: 512);
var config = new ShardingConfiguration<double>(backend);

var hybridModel = new HybridShardedModel<double, Tensor<double>, Tensor<double>>( model, config, pipelineParallelSize: 8, tensorParallelSize: 8, dataParallelSize: 8);

Constructors

HybridShardedModel(IFullModel<T, TInput, TOutput>, IShardingConfiguration<T>, int, int, int)

Creates a new 3D Parallel (Hybrid Sharded) model.

public HybridShardedModel(IFullModel<T, TInput, TOutput> wrappedModel, IShardingConfiguration<T> config, int pipelineParallelSize = 1, int tensorParallelSize = 1, int dataParallelSize = -1)

Parameters

wrappedModel IFullModel<T, TInput, TOutput>

The model to partition with 3D parallelism

config IShardingConfiguration<T>

Configuration for sharding and communication

pipelineParallelSize int

Number of pipeline stages (default: 1)

tensorParallelSize int

Tensor parallelism degree (default: 1)

dataParallelSize int

Data parallelism degree (default: uses remaining GPUs)

Methods

Clone()

Creates a shallow copy of this object.

public override IFullModel<T, TInput, TOutput> Clone()

Returns

IFullModel<T, TInput, TOutput>

Deserialize(byte[])

Loads a previously serialized model from binary data.

public override void Deserialize(byte[] data)

Parameters

data byte[]

The byte array containing the serialized model data.

Remarks

This method takes binary data created by the Serialize method and uses it to restore a model to its previous state.

For Beginners: This is like opening a saved file to continue your work.

When you call this method:

  • You provide the binary data (bytes) that was previously created by Serialize
  • The model rebuilds itself using this data
  • After deserializing, the model is exactly as it was when serialized
  • It's ready to make predictions without needing to be trained again

For example:

  • You download a pre-trained model file for detecting spam emails
  • You deserialize this file into your application
  • Immediately, your application can detect spam without any training
  • The model has all the knowledge that was built into it by its original creator

This is particularly useful when:

  • You want to use a model that took days to train
  • You need to deploy the same model across multiple devices
  • You're creating an application that non-technical users will use

Think of it like installing the brain of a trained expert directly into your application.

GetModelMetadata()

Retrieves metadata and performance metrics about the trained model.

public override ModelMetadata<T> GetModelMetadata()

Returns

ModelMetadata<T>

An object containing metadata and performance metrics about the trained model.

Remarks

This method provides information about the model's structure, parameters, and performance metrics.

For Beginners: Model metadata is like a report card for your machine learning model.

Just as a report card shows how well a student is performing in different subjects, model metadata shows how well your model is performing and provides details about its structure.

This information typically includes:

  • Accuracy measures: How well does the model's predictions match actual values?
  • Error metrics: How far off are the model's predictions on average?
  • Model parameters: What patterns did the model learn from the data?
  • Training information: How long did training take? How many iterations were needed?

For example, in a house price prediction model, metadata might include:

  • Average prediction error (e.g., off by $15,000 on average)
  • How strongly each feature (bedrooms, location) influences the prediction
  • How well the model fits the training data

This information helps you understand your model's strengths and weaknesses, and decide if it's ready to use or needs more training.

InitializeSharding()

Initializes 3D parallelism by partitioning along all dimensions.

protected override void InitializeSharding()

LoadModel(string)

Loads the model from a file.

public override void LoadModel(string filePath)

Parameters

filePath string

The path to the file containing the saved model.

Remarks

This method provides a convenient way to load a model directly from disk. It combines file I/O operations with deserialization.

For Beginners: This is like clicking "Open" in a document editor. Instead of manually reading from a file and then calling Deserialize(), this method does both steps for you.

Exceptions

FileNotFoundException

Thrown when the specified file does not exist.

IOException

Thrown when an I/O error occurs while reading from the file or when the file contains corrupted or invalid model data.

OnBeforeInitializeSharding()

Called before InitializeSharding to set up derived class state.

protected override void OnBeforeInitializeSharding()

Predict(TInput)

Uses the trained model to make predictions for new input data.

public override TOutput Predict(TInput input)

Parameters

input TInput

A matrix where each row represents a new example to predict and each column represents a feature.

Returns

TOutput

A vector containing the predicted values for each input example.

Remarks

After training, this method applies the learned patterns to new data to predict outcomes.

For Beginners: Prediction is when the model uses what it learned to make educated guesses about new information.

Continuing the fruit identification example:

  • After learning from many examples, the child (model) can now identify new fruits they haven't seen before
  • They look at the color, shape, and size to make their best guess

In machine learning:

  • You give the model new data it hasn't seen during training
  • The model applies the patterns it learned to make predictions
  • The output is the model's best estimate based on its training

For example, in a house price prediction model:

  • You provide features of a new house (square footage, bedrooms, location)
  • The model predicts what price that house might sell for

This method is used after training is complete, when you want to apply your model to real-world data.

SaveModel(string)

Saves the model to a file.

public override void SaveModel(string filePath)

Parameters

filePath string

The path where the model should be saved.

Remarks

This method provides a convenient way to save the model directly to disk. It combines serialization with file I/O operations.

For Beginners: This is like clicking "Save As" in a document editor. Instead of manually calling Serialize() and then writing to a file, this method does both steps for you.

Exceptions

IOException

Thrown when an I/O error occurs while writing to the file.

UnauthorizedAccessException

Thrown when the caller does not have the required permission to write to the specified file path.

Serialize()

Converts the current state of a machine learning model into a binary format.

public override byte[] Serialize()

Returns

byte[]

A byte array containing the serialized model data.

Remarks

This method captures all the essential information about a trained model and converts it into a sequence of bytes that can be stored or transmitted.

For Beginners: This is like exporting your work to a file.

When you call this method:

  • The model's current state (all its learned patterns and parameters) is captured
  • This information is converted into a compact binary format (bytes)
  • You can then save these bytes to a file, database, or send them over a network

For example:

  • After training a model to recognize cats vs. dogs in images
  • You can serialize the model to save all its learned knowledge
  • Later, you can use this saved data to recreate the model exactly as it was
  • The recreated model will make the same predictions as the original

Think of it like taking a snapshot of your model's brain at a specific moment in time.

SynchronizeGradients()

Synchronizes gradients across all processes using AllReduce.

public override void SynchronizeGradients()

Remarks

After this operation, all processes have the same averaged gradients.

For Beginners: During training, each process calculates gradients based on its portion of the data. This method combines (averages) those gradients so that everyone is learning from everyone else's experiences. It's like a team meeting where everyone shares what they learned.

Train(TInput, TOutput)

Trains the model using input features and their corresponding target values.

public override void Train(TInput input, TOutput expectedOutput)

Parameters

input TInput
expectedOutput TOutput

Remarks

This method takes training data and adjusts the model's internal parameters to learn patterns in the data.

For Beginners: Training is like teaching the model by showing it examples.

Imagine teaching a child to identify fruits:

  • You show them many examples of apples, oranges, and bananas (input features x)
  • You tell them the correct name for each fruit (target values y)
  • Over time, they learn to recognize the patterns that distinguish each fruit

In machine learning:

  • The x parameter contains features (characteristics) of your data
  • The y parameter contains the correct answers you want the model to learn
  • During training, the model adjusts its internal calculations to get better at predicting y from x

For example, in a house price prediction model:

  • x would contain features like square footage, number of bedrooms, location
  • y would contain the actual sale prices of those houses

WithParameters(Vector<T>)

Creates a new instance with the specified parameters.

public override IFullModel<T, TInput, TOutput> WithParameters(Vector<T> parameters)

Parameters

parameters Vector<T>

Returns

IFullModel<T, TInput, TOutput>