Before You Begin
Before starting, ensure you meet the following prerequisites and requirements:- Familiarity with PyTorch and neural network architectures.
- Access to Cerebras systems and the necessary permissions.
- Basic understanding of YAML for configuration files.
Pathways for Porting Models
We offer two tailored pathways depending on the complexity of the task and your level of comfort: 1. Straightforward approach: This pathway is ideal for those who wish to adapt existing models from the Cerebras Model Zoo. It involves making necessary changes to the model’s architecture or its data preprocessing components. This approach leverages the pre-built models and scripts available in the Model Zoo, minimizing the effort required to get started. 2. Moderately complex pathway: This pathway is suited for users who intend to create new models and develop custom data preprocessing scripts. It involves starting with the robust foundation provided by the Cerebras Model Zoo and building upon it. This approach offers more flexibility and allows for extensive customization to meet specific needs.Customizing Models from the Cerebras Model Zoo
If you intend to use models from the Cerebras Model Zoo and need to modify the model architecture or data preprocessing, it is recommended to start with the resources available in the Cerebras Model Zoo. This starting point allows you to make the necessary customizations to fit your specific requirements. This section guides users on adapting these pre-built models, which might involve changes to the model architecture or adjustments in data preprocessing.Example: Modifying a Dataloader
The data loader is a crucial element that feeds data into the model for training and evaluation. By modifying the dataloader, users can customize how the data is processed, presented, or augmented before being used by the model. In this example, we focus on modifying the dataloader within the PyTorch implementation of FC_MNIST from the Cerebras Model Zoo. The goal is to create a synthetic dataloader that will help assess the network’s performance with varying input sizes and class counts.Define the Data Loader Function
Indata.py
, we’re going to define a function named get_random_dataloader
:
params.yaml
file.
Configuring the Dataloader
In theparams.yaml
, we can specify several important parameters that will influence the behavior of our synthetic data loader:
-
num_examples
: This parameter sets how many random images and labels the data loader should generate. -
batch_size
: This defines how many examples will be included in a single batch during the training or evaluation of the model. -
seed
: A seed for the random number generator ensures the reproducibility of our experiments by generating the same sequence of random images and labels for a given seed value. -
image_size
: This specifies the dimensions of the generated random images. -
num_classes
: This determines how many different classes the labels can take, which is crucial for classification tasks.
params.yaml
file, we can tailor the behavior of the get_random_dataloader
function to meet our specific experimental needs, allowing for a flexible and dynamic approach to evaluating the network’s performance under different conditions.
Adapting the Model
Inmodel.py
, change the fix number of classes to a parameter in the params.yaml
file:
configs/params.yaml
, add the additional fields used in the dataloader and model definition.
Developing New Models and Preprocessing Scripts
Utilizing the Cerebras Run Function
If you aim to create new models and data preprocessing scripts, we recommend beginning with the Cerebras Model Zoo’s shared foundation, specifically therun
function. This approach allows you to utilize an established structure, streamlining the development process for your custom models and preprocessing routines.
All PyTorch models in the Cerebras Model Zoo share a standard framework that facilitates running them on the Cerebras Systems (CS) platform or other hardware types like CPUs/GPUs. This framework handles the modifications required to compile and execute a model on a Cerebras cluster. It offers a unified training and evaluation interface, allowing users to integrate their models and data preprocessing scripts seamlessly. With this setup, users don’t need to make detailed code adjustments for compatibility with Cerebras systems.
Porting a PyTorch Dense Neural Network for MNIST
To utilize therun
function effectively, ensure that the Cerebras Model Zoo repository, compatible with your target Cerebras cluster’s release, is installed. You can import the run function with the following code snippet:
run
function simplifies and organizes various aspects of your model’s workflow, including its implementation, data loading processes, hyperparameter settings, and overall execution. To effectively use the run
function, you should have:
- A params YAML file, which specifies the optimizers and the runtime configuration.
-
An implementation that encompasses:
- The definition of your model.
- Dataloaders that are responsible for both training and evaluation.
Define Model
To define the model architecture, therun
function requires a callable class or function that takes as input a dictionary of params and returns a torch.nn.Module
whose forward
implementation returns a loss tensor.
For example, let’s implement FC_MNIST parametrized by the depth and the hidden size of the network. Let’s assume that the input size is 784 and the last output dimension is 10. We use ReLU
as non linearity, and a negative log likelihood loss.
In model.py
:
-
The input to a
torch.nn.Module
object defined in therun
function includes both the inputs and the labels to compute the loss. It is up to the model to extract the inputs and labels from the batch before using them. - The output of the model is expected to be the loss of that forward pass.
Define Dataloaders
To define the data loaders, the run function requires a callable (either class or function) that takes as input a dictionary of params, and returns atorch.utils.data.DataLoader
. When running training, the train_data_fn
must be provided. When running evaluation, the eval_data_fn
must be provided.
For example, to implement FC_MNIST, we create two different functions for training and evaluation. We use torchvision.datasets
functionality to download MNIST dataset. Each of these functions returns a torch.utils.data.DataLoader
.
In data.py
:
Set Up the run
Function
The run function must be imported from run_utils.py. Always remember to append the parent directory of the Cerebras Model Zoo repository in your local setup.
All the input parameters of run
function are callables that take a dictionary as input, called params
. params
is a dictionary containing all of the model and data parameters specified by the params YAML file of the model.
Parameter | Type | Notes |
---|---|---|
model_fn | Callable[[dict], torch.nn.Module] | Required. A callable that takes in a dictionary of parameters. Returns a torch.nn.Module . |
train_data_fn | Callable[[dict], torch.utils.data.DataLoader] | Required during training run. |
eval_data_fn | Callable[[dict], torch.utils.data.DataLoader] | Required during evaluation run. |
default_params_fn | Callable[[dict], Optional[dict]] | Optional. A callable that takes in a dictionary of parameters. Sets default parameters. |
run.py
:
Manage Common Params
To avoid params replication between multiple similar experiments, therun
function has an optional input parameter called default_params_fn
. This parameter modifies the dictionary of the params YAML file, adding default values of unspecified params.
Setting up a default_params_fn
could be beneficial if the user is planning multiple experiments in which only a small subset of the params YAML file changes. The default_params_fn
sets up the values shared in all of the experiments. The user can create different configuration YAML files to only address the changes between experiments.
The default_params_fn
should be a callable that takes in the params
dictionary and returns a new dictionary. If the default_params_fn
is omitted, the params
dictionary will be used as is.
Create Params YAML File
At runtime, therun
function requires a separate params YAML. This file is specified during execution with the flag --params
in the command line.
For example, this is the params.yaml
file for the FC_MNIST implementation. You can see both the new YAML specification (since release 2.3.0) and the legacy YAML specification.
Since release 2.3.0, the legacy YAML specification is deprecated and its use is no longer recommended.
Execute Script with Run Function
All models in Cerebras Model Zoo use therun
function inside the script run.py
. Therefore, once you have ported your model to use the run
function, you can follow the steps in Launch your job section to launch your training or evaluation job.
Logging and Evaluation Metrics
By default, the run function logs training information to the console and to TensorBoard, as explained in Measure throughput of your model. You can also define your your own scalar and tensor summaries. The Cerebras Model Zoo git repository uses a base class to compute evaluation metrics calledCBMetric
. Metrics already defined in the Model Zoo git repository can be imported as:
-
Registration: All metrics must be registered with the corresponding
torch.nn.Module
class. This is automatically done when theCBMetric
object is constructed. That is, to register a metric to atorch.nn.Module
class, construct the metric object in thetorch.nn.Module
class’ constructor. - Update: The metrics are stateful. This means that every call to the metric object with the appropriate arguments automatically the latest metric value and save it in the metric’s internal state.
-
Logging: At the very end of the run, the final metrics values will be computed and then logged both to the console and to the TensorBoard
SummaryWriter
.
Conclusion
Porting PyTorch models to Cerebras systems offers significant advantages in terms of performance, scalability, and efficiency. By leveraging the specialized hardware and extensive resources provided by Cerebras, you can optimize your neural network models for large-scale data processing and complex computations. This guide has outlined the essential steps for successfully porting and adapting PyTorch models to run on Cerebras systems, including:- Setting Up the Cerebras Environment: Ensuring all necessary installations and configurations are in place.
- Configuring Data Processing: Preparing and customizing datasets for pre-training and fine-tuning.
- Adapting Model Architecture: Modifying existing models or creating new ones to be compatible with Cerebras hardware.
- Running Training and Evaluation Scripts: Utilizing the run function and managing parameters for efficient experimentation.