# Saving and Loading Model Parameters in the Hybrid Parallel Scenario
<!-- TOC -->
-[Saving and Loading Model Parameters in the Hybrid Parallel Scenario](#saving-and-loading-model-parameters-in-the-hybrid-parallel-scenario)
-[Overview](#overview)
-[Background](#background)
-[Application Scenario](#application-scenario)
-[Integrating the Saved Checkpoint Files](#integrating-the-saved-checkpoint-files)
-[Overall Process](#overall-process)
-[Preparations](#preparations)
-[Importing the Checkpoint Files to the Network](#importing-the-checkpoint-files-to-the-network)
-[Obtaining a List of All Parameters on the Network](#obtaining-a-list-of-all-parameters-on-the-network)
-[Integrate the Model Parallel Parameters](#integrate-the-model-parallel-parameters)
-[Saving the Data and Generating a New Checkpoint File](#saving-the-data-and-generating-a-new-checkpoint-file)
-[Loading the Integrated and Saved Checkpoint File](#loading-the-integrated-and-saved-checkpoint-file)
-[Overall Process](#overall-process-1)
-[Step 1: Loading the Checkpoint File](#step-1-loading-the-checkpoint-file)
-[Step 2: Dividing a Model Parallel Parameter](#step-2-dividing-a-model-parallel-parameter)
-[Step 3: Loading the Modified Parameter Data to the Network](#step-3-loading-the-modified-parameter-data-to-the-network)
-[Example](#example)
-[Scenario Description](#scenario-description)
-[Example Code](#example-code)
<!-- /TOC -->
## Overview
### Background
In the MindSpore model parallel scenario, each instance process stores only the parameter data on the current node. The parameter data of a model parallel Cell on each node is a slice of the complete parameter data. For example, the complete parameter data shape is \[8, 8], and the parameter data on each node is a part of the data, for example, shape \[2, 8].
In the auto parallel scenario, MindSpore automatically generates the dividing strategy. The MindSpore checkpoint module supports automatic integrating, saving, and loading.
In the hybrid parallel scenario, the dividing strategy is implemented by users. MindSpore saves only the data corresponding to each node. Users need to integrate, save, and load the checkpoint files by themselves. This tutorial describes how to integrate, save, and load checkpoint files in the hybrid parallel scenario.
### Application Scenario
If you encounter the following scenarios, refer to this tutorial to integrate, save, and load checkpoint files:
Scenario 1: multi-device training and single-device inference
The following describes the overall process of training on 64 devices and inference on a single device:
1. Execute the training to automatically generate the checkpoint files.
2. Integrate the saved checkpoint files.
Integrate the divided model parameters based on the specific dividing strategy to generate a new checkpoint file.
3. Load the new checkpoint file in the single-GPU environment and call the export API to export the model for inference as required.
If the number of GPUs in a cluster in the checkpoint saving environment is the same as that in the loading environment, for example, if the checkpoint files are saved and loaded in the same training environment or training and inference is performed on a single device, you do not need to perform integration, saving and loading.
Scenario 2: The training is divided into multiple stages, and the cluster size in each stage is different.
For example, in the training stage 1, the training environment with 64 devices is used, and in the training stage 2, the training environment with 56 devices is used. The overall operation process is as follows:
1. Execute the training in stage 1 to automatically generate the checkpoint files.
2. Integrate the saved checkpoint files.
Integrate the divided model parameters based on the specific dividing strategy to generate a new checkpoint file.
3. Load the checkpoint file that is integrated and saved in the stage 2 cluster.
During the loading, you need to redivide the parameter data in the checkpoint file based on the new training environment configuration.
4. Perform stage 2 training.
## Integrating the Saved Checkpoint Files
### Overall Process
Import the checkpoint files to be integrated to the network and obtain the list of all parameters through the API provided by MindSpore. See steps 1 and 2 in the following figure.
Then, update the parameter list and integrate the model parallel parameters. See step 3 in the following figure.
Finally, save the updated parameter list to a file through the API provided by MindSpore to generate a new checkpoint file. See step 4 in the following figure.
-`load_checkpoint()`: loads the checkpoint model parameter file and returns a parameter dictionary.
-`load_param_into_net()`: loads model parameter data to the network.
-`CKP_1-4_32.ckpt`: name of the saved checkpoint model parameter file.
> If a new checkpoint file is directly saved in the training environment based on the current training data and the parameter values already exist on the network, skip this step and you do not need to import the checkpoint files.
#### Obtaining a List of All Parameters on the Network
Call the `parameters_and_names` API to obtain all parameter data on the network.
```
param_dict = {}
for _, param in net.parameters_and_names():
param_dict[param.name] = param
```
### Integrate the Model Parallel Parameters
The following uses a model parameter as an example to describe a specific integration process.
The parameter name is model\_parallel\_weight and the data is Tensor \[\[1, 2, 3, 4], \[5, 6, 7, 8]].
The dividing strategy is to perform dividing in a 4-device scenario based on \[2, 2]. That is, the data is first divided into two slices in the row dimension, then the two slices are respectively divided into two smaller slices in the column dimension, and finally four slices are obtained. Data distribution after dividing is as follows:
> To ensure that the parameter update speed remains unchanged, you need to integrate the parameters saved in the optimizer, for example, moments.model\_parallel\_weight.
2. Define, instantiate, and execute the AllGather Cell, and obtain data on all devices.
```
from mindspore.nn.cell import Cell
from mindspore.ops.operations.comm_ops import AllGather
class AllGatherCell(Cell):
"""
Allgather cell, used in model parallel scenario.
To allgather the selected parameter slice from each device.
The value of param\_data is the integration of data on each device in dimension 0. The data value is \[\[1, 2], \[3, 4], \[5, 6], \[7, 8]], and the shape is \[4, 2]. The raw data value of param\_data is \[\[1, 2, 3, 4], \[5, 6, 7, 8]], and the shape is \[2, 4]. The data needs to be redivided and integrated.
3. Divide the data obtained from AllGather.
```
slice_list = np.split(param_data.asnumpy(), 4, axis=0) # 4:group_size, number of nodes in cluster
slice_lis_moments = np.split(param_data_moments.asnumpy(), 4, axis=0) # 4: group_size, number of nodes in cluster
```
The result of param\_data is as follows:
slice_list[0] --- [1, 2] Slice data on device0
slice_list[1] --- [3, 4] Slice data on device1
slice_list[2] --- [5, 6] Slice data on device2
slice_list[3] --- [7, 8] Slice data on device3
4. Reassemble data based on the site requirements.
In the following code, slice 1 and slice 2, slice 3 and slice 4 are first spliced by column, and then the obtained data is spliced by row.
```
slice_line1 = np.concatenate((slice_list[0], slice_list[1]), axis=1) # result [1,2,3,4]
slice_line2 = np.concatenate((slice_list[2], slice_list[3]), axis=1) # result [5,6,7,8]
> 1. If there are multiple model parallel parameters, repeat steps 1 to 5 to process them one by one.
> 2. If the data obtained in step 2 is the final data, skip the following steps. That is, the dividing strategy is to perform dividing only on shape0 and each device loads different slice data.
### Saving the Data and Generating a New Checkpoint File
1. Convert param\_dict to param\_list.
```
param_list = []
for (key, value) in param_dict.items():
each_param = {}
each_param["name"] = key
if isinstance(value.data, Tensor):
param_data = value.data
else:
param_data = Tensor(value.data)
each_param["data"] = param_data
param_list.append(each_param)
```
2. Call the `save_checkpoint` API to write the parameter data to a file and generate a new checkpoint file.
-`save_checkpoint`: saves network model parameters to a file.
-`CKP-Integrated_1-4_32.ckpt`: name of the generated checkpoint model parameter file.
## Loading the Integrated and Saved Checkpoint File
### Overall Process
If you need to load the integrated and saved checkpoint file to multi-device training or inference, divide the parallel parameter data based on the new strategy before loading the model parameters to the network. The following steps are implemented in the pre-training script. Steps 1 and 3 are the same as the strategy of checkpoint loading in a single-node system. Step 2 is added to divide model parallel parameters. In the single-device training/inference scenario, data dividing is not involved. In this case, step 2 can be skipped.
### Step 1: Loading the Checkpoint File
Call the `load_checkpoint` API to load model parameter data from the checkpoint file.
-`load_checkpoint()`: loads the checkpoint model parameter file and returns a parameter dictionary.
-`CKP-Integrated_1-4_32.ckpt`: name of the checkpoint model parameter file to be loaded.
### Step 2: Dividing a Model Parallel Parameter
The following uses a specific model parameter as an example. The parameter name is model\_parallel\_weight, the data value is Tensor \[\[1, 2, 3, 4], \[5, 6, 7, 8]], and the dividing strategy is to perform dividing in the two-device scenario based on \[2, 1]. Data distribution after dividing is as follows:
| Device0 | Device1 |
|--------------------|---------------------|
| Value [1, 2, 3, 4] | Value \[5, 6, 7, 8] |
1. Divide the model parameter data.
In the following code example, data is divided into two slices in dimension 0.
Overall scenario: The training is divided into two stages. The cluster scales in the two stages are different. The MatMul operator at the FC layer is simulated to run in parallel.
User process:
1. Execute stage 1 training. There are four devices in stage 1 training environment. The weight shape of the MatMul operator on each device is \[2, 8]. Checkpoint files are automatically exported during the training.
2. Execute the script to integrate checkpoint files. Based on the specific dividing strategy, integrate the divided model parameters to generate the integrated checkpoint file.
3. Execute stage 2 training: There are two devices in stage 2 training environment. The weight shape of the MatMul operator on each device is \[4, 8]. Load the initialized model parameter data from the integrated checkpoint file and then perform training.
> For details about the distributed environment configuration and training code, see [Distributed Training](https://www.mindspore.cn/tutorial/en/master/advanced_use/distributed_training.html).
>
> This document provides the example code for integrating checkpoint files and loading checkpoint files before distributed training. The code is for reference only.
### Example Code
1. Run the following script to integrate the checkpoint files:
```
python ./integrate_checkpoint.py "Path and name of the checkpoint file to be integrated" "Path and name of the checkpoint file generated after integration"
```
integrate\_checkpoint.py:
```
import numpy as np
import os
import mindspore.nn as nn
from mindspore import context
from mindspore import Tensor, Parameter
from mindspore.ops import operations as P
from mindspore.ops.operations.comm_ops import AllGather
from mindspore.communication.management import init
from mindspore.train.serialization import save_checkpoint, load_checkpoint