High Reliability Preparation: Resumable Training
In this section, you will learn about the principles, configuration methods, recommendations, and precautions for resumable training.
Because there is a lot of content, a quick overview is provided below to help you navigate directly to the topics you care about. Refer to the following categories to read the relevant sections:
- For details about the concept of resumable training and why resumable training is required, see Overview and Why You Need to Configure Resumable Training.
- For details about how to configure resumable training, see How to Configure Checkpoints.
- For details about the precautions for configuring checkpoints, see Precautions for Distributed Training Checkpoints.
- This section provides some suggestions for configuring checkpoints. For details, see Recommended Checkpoint Saving Frequency.
Overview
Resumable training indicates that an interrupted training job can be automatically resumed from the checkpoint where the previous training was interrupted. This method is applicable to model training that takes a long time.
The checkpoint mechanism enables resumable training.
During model training, training results (including but not limited to epochs, model weights, optimizer status, and scheduler status) are continuously saved. In this way, an interrupted training job can be automatically resumed from the checkpoint where the previous training was interrupted.
To resume a training job, load a checkpoint and use the checkpoint information to initialize the training status. To do so, add reload ckpt to the code. Modify the CKPT configuration of the corresponding framework. For details, see Example of Reloading Checkpoints Across Popular Training Frameworks.
Why You Need to Configure Resumable Training
The automatic restart feature provided by ModelArts only guarantees that a job will be re-launched after a failure; it cannot prevent the loss of training progress. If the training script does not support resumable training, the job may start over from scratch upon restarting, leading to the following issues:
- Loss of completed training progress.
- Wasteful re-consumption of compute resources.
- Unexpected or inconsistent training results.
- Inability to recover to the pre-failure state even after multiple automatic restarts.
Therefore, for long-running training tasks, adapting your code for checkpoints should be prioritized.
How to Configure Checkpoints
ModelArts provides storage paths for training job checkpoints alongside an automatic restart mechanism. To enable resumable training, complete the following configurations:
- Configuring Checkpoint Content: Define what data needs to be saved during training.
- Configuring the Checkpoint Save Path: Select an external storage path in ModelArts to ensure checkpoint artifacts are stored safely, persistently, and can be quickly recovered.
- Example of Reloading Checkpoints Across Popular Training Frameworks: Add checkpoint reloading code to your scripts according to the framework you use.
Configuring Checkpoint Content
During training execution, various intermediate states are produced. To ensure smooth recovery, it is recommended that your checkpoints save at least the items listed in Table 1.
The items listed below are recommendations. You do not necessarily need to configure all of them; adapt the configuration to your specific training job.
| Content | Recommended | Description |
|---|---|---|
| Model weights | Required | Restores model parameters. |
| Optimizer state | Required | Restores optimizer momentum, statistics, etc. |
| Current epoch/step | Required | Restores exact training progress. |
| Learning rate scheduler state | Recommended | Maintains consistent learning rate scheduling. |
| AMP GradScaler state | Recommended | Used in mixed-precision training scenarios. |
| Random number state | Recommended | Improves training reproducibility after resumption. |
| Data sampler state | Recommended | Restores data consumption progress in distributed training. |
| Custom training state | Recommended | Includes global steps, evaluation metrics, early stopping states, etc. |
Configuring the Checkpoint Save Path
ModelArts offers several storage paths for secure and stable checkpoint storage. This allows you to quickly resume training if a job restarts.
Enable fault tolerance check (auto restart) for resumable training. On the training job creation page, enable Auto Restart. If the environment pre-check fails, the hardware is not functional, or the training job fails, ModelArts will automatically issue the training job again.
Store checkpoints in stable shared storage or the training output path. Avoid storing them only in the container's local directory.
To improve user experience, ModelArts provides a new console at some regions. The following describes ModelArts New Console and Old Console and how to set the checkpoint storage path.
New Console
To implement resumable training or incremental training in ModelArts, you are advised to use storage mounts.
When creating a training job, you can save and load checkpoint files by mounting a storage path. The procedure is as follows:
- In the training job settings, mount the storage directory (where checkpoints are stored) to a local directory within the training container.
- During the training process, save checkpoint files to the mounted local directory. The data will automatically synchronize to the mounted path.
- To resume from a breakpoint, ensure the mounted storage directory contains the previous checkpoint files. Your training script will then automatically load the latest checkpoint to continue the training.
Using storage mounts ensures persistent data storage and enables model reuse across different training jobs.
When you create a training job in ModelArts, you can choose any of the storage mount options below. The table below shows different storage choices for easy selection based on your needs.
| Storage Type | Performance | Capacity | Scenario | Price | Remarks |
|---|---|---|---|---|---|
| SFS Turbo | High | Large | SFS Turbo is suitable for AI training, AI generated content, autonomous driving, rendering, EDA simulation, and enterprise NAS applications. | Relatively high | General |
| OBS | Medium | Large | Using OBS to decouple storage from compute in big data scenarios. | Moderate | High-frequency read and low-frequency write |
Old Console
To resume model training or incrementally train a model in ModelArts, configure training output.
When creating a training job, set the training Output parameter name to train_output. You can then retrieve this parameter via environment variables or hyperparameters. Once configured, checkpoints can be saved to the specified data storage location. Ensure that Predownload is set to Yes. If you set Predownload to Yes, the system automatically downloads the checkpoint file in the training output data path to a local directory of the training container before the training job is started.
Example of Reloading Checkpoints Across Popular Training Frameworks
This example shows only the main logic. Add exception handling, checkpoint checks, and distributed sync for production. In this example, the checkpoint save path variable is set to train_output.
| Training Framework | Checkpoint Reload Configuration Example |
|---|---|
| VeRL | VeRL is a flexible, efficient, and widely used reinforcement learning training library, serving as the de facto standard framework for post-training. VeRL is an open-source implementation of the paper HybridFlow: A Flexible and Efficient RLHF Framework.
|
| MindSpeed-LLM | MindSpeed LLM is a distributed training framework for large language models (LLMs) based on the Ascend ecosystem. It aims to provide an E2E LLM training solution for Huawei Ascend chip ecosystem partners, including distributed pre-training, distributed instruction fine-tuning, and the corresponding development toolchain, such as data preprocessing, weight transformation, online inference, and baseline evaluation. As the flagship training framework for Ascend computing, it is deeply optimized for performance, particularly for large-scale parameters, large clusters, and Mixture-of-Experts (MoE) models. It is also compatible with Megatron-LM, allowing Megatron users to migrate smoothly.
|
| LLaMa-Factory | LLaMA-Factory is a popular open-source framework for training LLMs. You can easily fine-tune hundreds of models, such as language and multimodal ones, using either the CLI or WebUI. Built on Transformers and DeepSpeed, it works well with various open-source models.
|
| PyTorch |
|
| MindSpore | import os
import argparse
from resnet import resnet50
from mindspore.nn.optim.momentum import Momentum
from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
from mindspore import load_checkpoint, load_param_into_net
from mindspore.train import Model, CheckpointConfig, ModelCheckpoint
from mindspore.train.callback import LossMonitor
parser = argparse.ArgumentParser()
parser.add_argument("--train_output", type=str)
parser.add_argument("--batch_size", type=int, default=32, help="Batch size.")
parser.add_argument("--num_classes", type=int, default=10, help="Num classes.")
parser.add_argument("--do_train", type=bool, default=True, help="Do train or not.")
args_opt, unparsed = parser.parse_known_args()
# train_output is set to /home/ma-user/modelarts/outputs/train_output_0.
train_output = args_opt.train_output
# Initially defined network, loss function, and optimizer
# 1. Define the initial network. ResNet50 is used as an example.
net = resnet50(args_opt.batch_size, args_opt.num_classes)
# 2. Define the loss function.
ls = SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
# 3. Define the optimizer.
opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.01, 0.9)
# Initial epoch value for the first training. The initial value of epoch_size will be customized in MindSpore 1.3 and later versions.
# cur_epoch_num = 0
# Check whether there is a model file in the OBS output path. If there is no file, the model will be trained from the beginning by default. If there is a model file, the CKPT file with the maximum epoch value will be loaded as the pre-trained model.
if os.listdir(train_output):
last_ckpt = sorted([file for file in os.listdir(train_output) if file.endswith(".ckpt")])[-1]
print('last_ckpt:', last_ckpt)
last_ckpt_file = os.path.join(train_output, last_ckpt)
# Load the checkpoint. For details, see "mindspore.load_checkpoint."
param_dict = load_checkpoint(last_ckpt_file)
print('> load last ckpt and continue training!!')
# Load model parameters to the network.
load_param_into_net(net, param_dict)
# Load model parameters to the optimizer.
load_param_into_net(opt, param_dict)
# Obtain the saved epoch value. The model will continue to be trained based on the epoch value. This function will be supported in MindSpore 1.3 and later versions.
# if param_dict.get("epoch_num"):
# cur_epoch_num = int(param_dict["epoch_num"].data.asnumpy())
model = Model(net, loss_fn=ls, optimizer=opt, metrics={'acc'})
# as for train, users could use model.train
if args_opt.do_train:
dataset = create_dataset()
batch_num = dataset.get_dataset_size()
config_ck = CheckpointConfig(save_checkpoint_steps=batch_num,
keep_checkpoint_max=35)
# For append_info=[{"epoch_num": cur_epoch_num}], append_info will be supported in MindSpore 1.3 and later versions to save the epoch value at the current time.
# Save network parameters. For details, see "mindspore.train.ModelCheckpoint."
ckpoint_cb = ModelCheckpoint(prefix="train_resnet_cifar10",
directory=args_opt.train_output,
config=config_ck)
loss_cb = LossMonitor()
model.train(epoch_size, dataset, callbacks=[ckpoint_cb, loss_cb])
# For model.train(epoch_size-cur_epoch_num, dataset, callbacks=[ckpoint_cb, loss_cb]), the training resumed from the breakpoint will be supported in MindSpore 1.3 and later versions. |
Precautions for Distributed Training Checkpoints
In multi-node multi-PU training,you are advised to adhere to the following principles:
- Only rank 0 should save checkpoints to prevent multiple processes from writing to the same file simultaneously.
- Use a barrier to synchronize other processes only after the checkpoint writing is fully completed.
- Write to a temporary file first, and then atomically replace it with the formal file to prevent corrupted or partially-written files from being loaded.
- Keep multiple recent checkpoints to prevent total loss if the latest checkpoint becomes corrupted.
- Include the step or epoch in the checkpoint filename, and maintain a pointer to the latest checkpoint.
- When resuming training, all ranks must load the training progress corresponding to the exact same checkpoint.
- Set the save frequency by balancing training step duration, storage performance, and acceptable progress loss in the event of a failure.
Recommended Checkpoint Saving Frequency
| Training Type | Recommended Frequency |
|---|---|
| Short-term experiments | Save once every epoch. |
| Standard deep learning training | Save once every N steps or every epoch. |
| LLM fine-tuning | Save once every fixed number of steps, retaining multiple versions. |
| LLM pre-training | Set according to per-step execution time and recovery costs (e.g., save every 30 minutes or every set number of steps). |
| Reinforcement learning training | Simultaneously save the model, optimizer, environment state, and rollout-related states. |
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot