Checkpointing and Recovery
local graph
Chapter 9 — Checkpointing and Recovery
Section titled “Chapter 9 — Checkpointing and Recovery”Checkpointing and recovery refer to the process of saving the state of a system, application, or model at specific intervals (checkpointing) and restoring it from a saved state in case of failure (recovery). In machine learning, checkpointing involves periodically saving model parameters, optimizer states, and training progress so that training can resume from the last checkpoint instead of starting over. This is especially useful for long-running tasks, where interruptions due to system crashes, power failures, or preempted cloud instances can otherwise result in significant losses.
Checkpointing and recovery are crucial for ensuring fault tolerance, efficiency, and reproducibility in training large-scale models. Without checkpointing, an unexpected failure could waste hours or even days of computation. Additionally, it allows for experiment reproducibility, enabling researchers to revisit and fine-tune models from intermediate states, rather than redoing entire training runs. Efficient checkpointing strategies (e.g., saving at fixed intervals or when validation performance improves) help balance storage overhead while minimizing retraining costs.
In this chapter, we’ll explore strategies for determining optimal checkpoint frequency, efficient storage formats for large models, and techniques for recovering from various types of failures. You’ll also gain insights into checkpointing in distributed training scenarios and version control for model checkpoints.
In this chapter, we’ll be covering the following topics:
- Why is checkpointing important?
- Checkpoint frequency and storage strategies
- Efficient checkpoint formats
- Recovering from failures
- Checkpointing in distributed LLM training
- Version control for LLM checkpoints
- Automated checkpointing and recovery systems
Why is checkpointing important?
Section titled “Why is checkpointing important?”Checkpointing is a common practice in LLM training due to the long duration and resource-intensive nature of the LLM training process.
Let’s implement a basic checkpointing system:
import torchfrom transformers import GPT2LMHeadModel, GPT2Configimport osclass LLMTrainer: def __init__( self, model, optimizer, checkpoint_dir='checkpoints' ): self.model = model self.optimizer = optimizer self.checkpoint_dir = checkpoint_dir os.makedirs(checkpoint_dir, exist_ok=True) def save_checkpoint(self, epoch, step, loss): checkpoint = { 'epoch': epoch, 'step': step, 'model_state_dict': self.model.state_dict(), 'optimizer_state_dict': self.optimizer.state_dict(), 'loss': loss } checkpoint_path = os.path.join(self.checkpoint_dir, f'checkpoint_epoch_{epoch}_step_{step}.pt') torch.save(checkpoint, checkpoint_path) print(f"Checkpoint saved: {checkpoint_path}") def load_checkpoint(self, checkpoint_path): checkpoint = torch.load(checkpoint_path) self.model.load_state_dict(checkpoint['model_state_dict']) self.optimizer.load_state_dict( checkpoint['optimizer_state_dict']) return ( checkpoint['epoch'], checkpoint['step'], checkpoint['loss'] )# Simulating training loopfor epoch in range(10): for step in range(1000): # ... training code ... if step % 100 == 0: trainer.save_checkpoint(epoch, step, loss.item())# Loading a checkpointepoch, step, loss = trainer.load_checkpoint( 'checkpoints/checkpoint_epoch_5_step_500.pt')print(f"Resumed training from epoch {epoch}, step {step}, with loss {loss}")This implementation demonstrates the basic structure of a checkpointing system. The save_checkpoint method saves the model state, optimizer state, and training progress information. The load_checkpoint method allows you to resume training from a saved checkpoint.
Checkpoint frequency and storage strategies
Section titled “Checkpoint frequency and storage strategies”Determining the optimal checkpoint frequency involves striking a balance between safety and efficiency. Let’s explore different strategies and their implementation:
import timeimport shutilclass AdvancedLLMTrainer(LLMTrainer): def __init__( self, model, optimizer, checkpoint_dir='checkpoints', max_checkpoints=5 ): super().__init__(model, optimizer, checkpoint_dir) self.max_checkpoints = max_checkpoints self.checkpoints = [] def save_checkpoint(self, epoch, step, loss): checkpoint_path = super().save_checkpoint(epoch, step, loss) self.checkpoints.append(checkpoint_path) if len(self.checkpoints) > self.max_checkpoints: oldest_checkpoint = self.checkpoints.pop(0) os.remove(oldest_checkpoint) print(f"Removed old checkpoint: {oldest_checkpoint}") def save_checkpoint_by_time( self, epoch, step, loss, interval_minutes=60 ): current_time = time.time() if ( not hasattr(self, 'last_checkpoint_time') or current_time - self.last_checkpoint_time >= interval_minutes * 60 ): self.save_checkpoint(epoch, step, loss) self.last_checkpoint_time = current_time def save_best_checkpoint(self, epoch, step, loss): if not hasattr(self, 'best_loss') or loss < self.best_loss: self.best_loss = loss checkpoint_path = os.path.join( self.checkpoint_dir, 'best_model.pt') torch.save({ 'epoch': epoch, 'step': step, 'model_state_dict': self.model.state_dict(), 'optimizer_state_dict': self.optimizer.state_dict(), 'loss': loss }, checkpoint_path) print(f"Best model saved: {checkpoint_path}")# Usage exampletrainer = AdvancedLLMTrainer(model, optimizer)for epoch in range(10): for step in range(1000): # ... training code ... trainer.save_checkpoint_by_time(epoch, step, loss.item(), interval_minutes=30) trainer.save_best_checkpoint(epoch, step, loss.item())This implementation introduces several checkpointing strategies:
- Regular checkpointing with a maximum number of checkpoints: This prevents excessive disk usage by removing old checkpoints when the limit is reached
- Time-based checkpointing: This saves checkpoints at regular time intervals, which can be useful for long-running training processes
- Best model checkpointing: This saves the model with the best performance (lowest loss in this case), which is useful for model selection
Here’s a trade-off analysis of the three checkpointing strategies:
- Regular checkpointing with a maximum number of checkpoints:
- Pros: Prevents excessive storage usage and ensures periodic snapshots of training progress
- Cons: Might overwrite useful older checkpoints, potentially losing good models if performance fluctuates
- Best use case: When storage is a constraint and periodic snapshots are needed for resumption
- Pros: Prevents excessive storage usage and ensures periodic snapshots of training progress
- Time-based checkpointing:
- Pros: Ensures checkpoints are spaced out over time, which is useful for monitoring long training runs
- Cons: Can be inefficient if checkpoints are saved too frequently (wasting storage) or too infrequently (missing critical states)
- Best use case: For long-running training processes where consistent snapshots are needed for debugging or rollback
- Pros: Ensures checkpoints are spaced out over time, which is useful for monitoring long training runs
- Best model checkpointing:
- Pros: Retains the most promising model, which is useful for final model selection.
- Cons: If loss is noisy, a single “best” checkpoint may not be truly representative. Can fail to capture intermediate learning dynamics.
- Best use case: When selecting the most performant model is the priority over periodic snapshots.
- Pros: Retains the most promising model, which is useful for final model selection.
Here are some factors to consider when selecting the strategy you wish to adopt:
- Computational cost: Frequent checkpointing increases disk I/O and CPU overhead
- Failure recovery: Regular and time-based checkpointing help resume training after interruptions, whereas best-model checkpointing may not provide recent progress
- Storage constraints: Maintaining many checkpoints consumes storage; regular checkpointing with a limit is most efficient in managing this
- Rate of model improvement: If the model improves rapidly, frequent checkpoints may be useful; if the progress is slow, fewer but more strategic checkpoints may suffice
The recommended approach for checkpointing LLMs is to combine strategies:
- Use regular checkpointing (e.g., every few hours) to ensure progress is saved
- Use best model checkpointing to retain the best-performing model
- Use a rolling window of recent checkpoints to balance storage efficiency and recovery options
Efficient checkpoint formats
Section titled “Efficient checkpoint formats”For LLMs with billions of parameters, checkpoint size can become a significant concern. Let’s explore some strategies for efficient checkpoint storage:
- Import the necessary libraries and
EfficientLLMTrainerThis code defines animport torchimport ioimport zipfileclass EfficientLLMTrainer(AdvancedLLMTrainer):def save_checkpoint_efficient(self, epoch, step, loss):checkpoint = {'epoch': epoch,'step': step,'model_state_dict': self.model.state_dict(),'optimizer_state_dict': self.optimizer.state_dict(),'loss': loss}checkpoint_path = os.path.join(self.checkpoint_dir,f'checkpoint_epoch_{epoch}_step_{step}.zip')with zipfile.ZipFile(checkpoint_path,'w', zipfile.ZIP_DEFLATED) as zipf:for key, value in checkpoint.items():if isinstance(value, dict): # For model and optimizer state_dictsbuffer = io.BytesIO()torch.save(value, buffer)zipf.writestr(f'{key}.pt',buffer.getvalue())else:zipf.writestr(f'{key}.txt', str(value))print(f"Efficient checkpoint saved: {checkpoint_path}")EfficientLLMTrainerclass that extendsAdvancedLLMTrainer(presumably a pre-existing class for training LLMs). The key function implemented issave_checkpoint_efficient, which efficiently saves model checkpoints in a compressed ZIP format. - Let’s define the function (
load_checkpoint_efficient) to load the checkpoint inThis function,def load_checkpoint_efficient(self, checkpoint_path):checkpoint = {}with zipfile.ZipFile(checkpoint_path, 'r') as zipf:for filename in zipf.namelist():if filename.endswith('.pt'):with zipf.open(filename) as f:key = filename[:-3]# Remove .pt extensioncheckpoint[key] = torch.load(io.BytesIO(f.read()))else:with zipf.open(filename) as f:key = filename[:-4]# Remove .txt extensionvalue = f.read().decode('utf-8')checkpoint[key] = (int(value) if key in['epoch', 'step']else float(value))self.model.load_state_dict(checkpoint['model_state_dict'])self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])return (checkpoint['epoch'], checkpoint['step'],checkpoint['loss'])load_checkpoint_efficient, is responsible for loading a previously saved checkpoint from a ZIP file and restoring the model and optimizer states. See the following example usage. -
This implementation uses ZIP compression to reduce the size of checkpoints. It also separates the model and optimizer state dictionaries from other metadata, allowing for more efficient storage and loading.trainer = EfficientLLMTrainer(model, optimizer)trainer.save_checkpoint_efficient(epoch, step, loss.item())epoch, step, loss = trainer.load_checkpoint_ efficient('checkpoints/checkpoint_epoch_5_step_500.zip')
Other strategies for efficient checkpoint storage include the following:
- Quantization: Reducing the precision of model weights (e.g., from float32 to float16) can significantly reduce the checkpoint size (see more about this strategy in Chapter 13)
- Incremental checkpointing: Only save the changes since the last checkpoint, rather than the entire model state
- Distributed storage: In multi-GPU or multi-node setups, distribute the checkpoint across multiple storage devices
- Cloud storage: Use cloud storage solutions that offer fast I/O and automatic compression
For very large models, you might also consider more advanced techniques, such as model sharding, where different parts of the model are saved separately and can be loaded on demand.
Recovering from failures
Section titled “Recovering from failures”Robust recovery mechanisms are crucial for LLM training. Let’s implement a system that can handle various types of failures:
import signalimport sysclass RobustLLMTrainer(EfficientLLMTrainer): def __init__( self, model, optimizer, checkpoint_dir='checkpoints', autosave_interval=15 ): super().__init__(model, optimizer, checkpoint_dir) self.autosave_interval = autosave_interval self.setup_signal_handlers() def setup_signal_handlers(self): signal.signal(signal.SIGINT, self.handle_interrupt) signal.signal(signal.SIGTERM, self.handle_interrupt) def handle_interrupt(self, signum, frame): print("Interrupted! Saving checkpoint before exiting...") self.save_checkpoint_efficient(self.current_epoch, self.current_step, self.current_loss) sys.exit(0) def train(self, epochs, steps_per_epoch, train_fn): try: start_epoch, start_step = 0, 0 latest_checkpoint = self.get_latest_checkpoint() if latest_checkpoint: start_epoch, start_step, _ = \ self.load_checkpoint_efficient(latest_checkpoint) print( f"Resuming from epoch {start_epoch}, " f"step {start_step}" ) for epoch in range(start_epoch, epochs): self.current_epoch = epoch for step in range(start_step, steps_per_epoch): self.current_step = step self.current_loss = train_fn( self.model, epoch, step) if step % self.autosave_interval == 0: self.save_checkpoint_efficient( epoch, step, self.current_loss) start_step = 0 # Reset step counter at the start of each epoch except Exception as e: print(f"Error occurred: {e}") print("Saving checkpoint before exiting...") self.save_checkpoint_efficient(self.current_epoch, self.current_step, self.current_loss) raise def get_latest_checkpoint(self): checkpoints = sorted(os.listdir(self.checkpoint_dir)) return ( os.path.join(self.checkpoint_dir, checkpoints[-1]) if checkpoints else None )# Usagedef train_step(model, epoch, step): # Simulated training step loss = 1 / (epoch + 1 + step + 1) # Dummy loss that decreases over time return losstrainer = RobustLLMTrainer(model, optimizer)trainer.train(epochs=10, steps_per_epoch=1000, train_fn=train_step)The RobustLLMTrainer class extends EfficientLLMTrainer to add resilience by handling interruptions (such as SIGINT for Ctrl + C and SIGTERM for termination) and saving checkpoints to prevent data loss. It initializes with a model, optimizer, checkpoint directory, and auto-save interval, then sets up signal handlers to trigger a graceful shutdown by saving progress before exiting.
During training, it attempts to resume from the latest checkpoint if available. It loops through epochs and steps, running train_fn to compute loss and periodically saving checkpoints based on autosave_interval. If an exception occurs, it catches the error, saves the progress, and re-raises the exception to avoid silent failures.
The get_latest_checkpoint() method retrieves the most recent checkpoint by sorting files in the checkpoint directory (though os is missing and should be imported). The script concludes with an example usage where a dummy loss function is defined, and training is started with trainer.train(epochs=10, ``steps_per_epoch=1000, train_fn=train_step).
This implementation includes several robustness features:
- Signal handling: The trainer catches interrupt signals (Ctrl + C) and gracefully saves a checkpoint before exiting
- Automatic resumption: The trainer automatically finds and loads the latest checkpoint when starting training
- Regular auto-saves: Checkpoints are saved at regular intervals during training
- Exception handling: If an error occurs during training, a checkpoint is saved before the exception is re-raised
These features help recover from various types of failures:
- System crashes or power outages: Regular auto-saves ensure that not too much progress is lost
- User interruptions: Signal handling allows for graceful exits with the state saved
- Code errors: Exception handling ensures that progress is saved even if an unexpected error occurs
For even more robust recovery, consider implementing the following:
- Checkpoint validation: Verify the integrity of checkpoints before loading them
- Multiple backup checkpoints: Keep several recent checkpoints in case the latest one is corrupted
- Distributed checkpointing: In multi-node setups, ensure that checkpoints are consistent across all nodes
Checkpointing in distributed LLM training
Section titled “Checkpointing in distributed LLM training”Distributed training introduces additional complexity to checkpointing.
Let’s break down the implementation of a basic distributed checkpointing system and understand each component:
- We first define the
DistributedLLMTrainerclass, which inherits fromRobustLLMTrainer. TheDistributedLLMTrainerclass is designed for the distributed training of LLMs using PyTorch’storch.distributedframework. It ensures that the model is trained across multiple devices (e.g., GPUs) or nodes efficiently:The initialization does the following:import torch.distributed as distclass DistributedLLMTrainer(RobustLLMTrainer):def __init__(self, model, optimizer, checkpoint_dir='checkpoints',autosave_interval=15):super().__init__(model, optimizer, checkpoint_dir,autosave_interval)self.rank = dist.get_rank()self.world_size = dist.get_world_size()- Calls the parent class initializer.
2. Sets up distributed training attributes:
self.rank: Identifies the current process 2.self.world_size: Indicates the total number of processes
- Calls the parent class initializer.
2. Sets up distributed training attributes:
- We then use the following methods to save and load checkpoints during
The following methods handle distributed checkpointing:def save_checkpoint_distributed(self, epoch, step, loss):if self.rank == 0: # Only the main process saves checkpointsself.save_checkpoint_efficient(epoch, step, loss)dist.barrier() # Synchronize all processesdef load_checkpoint_distributed(self, checkpoint_path):if self.rank == 0:epoch, step, loss = \self.load_checkpoint_efficient(checkpoint_path)else:epoch, step, loss = 0, 0, 0.0# Broadcast the loaded data to all processesepoch = torch.tensor(epoch).to(self.rank)step = torch.tensor(step).to(self.rank)loss = torch.tensor(loss).to(self.rank)dist.broadcast(epoch, 0)dist.broadcast(step, 0)dist.broadcast(loss, 0)# Make sure all processes have loaded the checkpointdist.barrier()return epoch.item(), step.item(), loss.item()
save_checkpoint_distributed: Only the main process (rank0) saves the checkpoint to avoid redundant writes, reduce disk I/O, and ensure consistency across processes. If all ranks are saved independently, it could lead to storage inefficiencies and potential race conditions. After saving,dist.barrier()synchronizes all processes to ensure they wait for the checkpoint to be written. When loading, only rank0reads the checkpoint to prevent redundant disk access; then, it broadcasts the loaded values to all other ranks usingdist.broadcast(), ensuring every process starts from the same state before resuming training.load_checkpoint_distributed:- Only the main process loads the checkpoint - It broadcasts the loaded values to all other processes - It ensures all processes have the same checkpoint data
- Next, we implement distributed training:
Thedef train_distributed(self, epochs, steps_per_epoch, train_fn):try:start_epoch, start_step = 0, 0if self.rank == 0:latest_checkpoint = self.get_latest_checkpoint()if latest_checkpoint:start_epoch, start_step, _ = \self.load_checkpoint_efficient(latest_checkpoint)# Broadcast the starting epoch and step to all processesstart_epoch = torch.tensor(start_epoch).to(self.rank)start_step = torch.tensor(start_step).to(self.rank)dist.broadcast(start_epoch, 0)dist.broadcast(start_step, 0)start_epoch = start_epoch.item()start_step = start_step.item()if self.rank == 0:print(f"Resuming from epoch {start_epoch}, "f"step {start_step}")for epoch in range(start_epoch, epochs):self.current_epoch = epochfor step in range(start_step, steps_per_epoch):self.current_step = stepself.current_loss = train_fn(self.model, epoch, step)if step % self.autosave_interval == 0:self.save_checkpoint_distributed(epoch, step, self.current_loss)start_step = 0 # Reset step counter at the start of each epochexcept Exception as e:print(f"Error occurred on rank {self.rank}: {e}")self.save_checkpoint_distributed(self.current_epoch,self.current_step, self.current_loss)dist.destroy_process_group()raise
train_distributedmethod does the following:- Determines the starting point (epoch and step) 2. Broadcasts this information to all processes 3. Runs the training loop with periodic checkpointing 4. Handles exceptions by saving a final checkpoint and cleaning up
- We then employ the following code to initialize distributed training with PyTorch, set up your model for parallel execution, and perform a simple distributed
This code includes the following:def init_distributed():dist.init_process_group(backend='nccl')rank = dist.get_rank()torch.cuda.set_device(rank)return rankdef distributed_train_step(model, epoch, step):# Simulated distributed training steploss = 1 / (epoch + 1 + step + 1) # Dummy loss that decreases over timereturn lossdef main():rank = init_distributed()model = GPT2LMHeadModel(GPT2Config()).to(rank)model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[rank])optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)trainer = DistributedLLMTrainer(model, optimizer)trainer.train_distributed(epochs=10, steps_per_epoch=1000,train_fn=distributed_train_step)if __name__ == "__main__":main()
init_distributed: Initializes the distributed training environmentdistributed_train_step: A dummy training function for demonstrationmain: Shows how to useDistributedLLMTrainerin practice
Key considerations for distributed checkpointing include maintaining consistency by synchronizing all processes using barriers during checkpointing, ensuring that only the main process handles I/O operations to avoid conflicts, and effectively sharing important data by broadcasting it from the main process to the other processes. Additionally, the system incorporates robust error handling, allowing it to gracefully save checkpoints and clean up distributed resources in case of failures.
Next, let us focus on the version control aspect.
Version control for LLM checkpoints
Section titled “Version control for LLM checkpoints”Version control for LLM checkpoints can help with managing different versions of your model during the development process. Here’s a simple implementation:
import osimport jsonimport shutilclass VersionControlledLLMTrainer(DistributedLLMTrainer): def __init__( self, model, optimizer, checkpoint_dir='checkpoints', version_file='versions.json' ): super().__init__(model, optimizer, checkpoint_dir) self.version_file = version_file self.versions = self.load_versions() def load_versions(self): if os.path.exists(self.version_file): with open(self.version_file, 'r') as f: return json.load(f) return {} def save_versions(self): with open(self.version_file, 'w') as f: json.dump(self.versions, f, indent=2) def save_checkpoint_versioned( self, epoch, step, loss, version_name ): checkpoint_path = self.save_checkpoint_efficient( epoch, step, loss) self.versions[version_name] = { 'path': checkpoint_path, 'epoch': epoch, 'step': step, 'loss': loss } self.save_versions() print(f"Saved version '{version_name}': {checkpoint_path}") def load_checkpoint_versioned(self, version_name): if version_name not in self.versions: raise ValueError(f"Version '{version_name}' not found") version_info = self.versions[version_name] return self.load_checkpoint_efficient(version_info['path']) def create_branch(self, base_version, new_version): if base_version not in self.versions: raise ValueError( f"Base version '{base_version}' not found") base_info = self.versions[base_version] new_path = f"{self.checkpoint_dir}/branch_{new_version}.pt" shutil.copy(base_info['path'], new_path) self.versions[new_version] = { 'path': new_path, 'epoch': base_info['epoch'], 'step': base_info['step'], 'loss': base_info['loss'], 'branched_from': base_version } self.save_versions() print(f"Created branch '{new_version}' from '{base_version}'")# Usagetrainer = VersionControlledLLMTrainer(model, optimizer)trainer.save_checkpoint_versioned(epoch=10, step=500, loss=0.1, version_name="v1.0")trainer.create_branch("v1.0", "experimental_branch")epoch, step, loss = trainer.load_checkpoint_versioned( "experimental_branch")This implementation provides basic version control features:
- Version tracking: Each saved checkpoint can be associated with a version name
- Branching: You can create new branches from existing checkpoints, allowing for experimentation
- Version history: The version information is stored in a JSON file for easy inspection and management
The key benefits of version control for LLM checkpoints are as follows:
- Experimentation: You can easily try different training strategies or hyperparameters from a common starting point
- Collaboration: Team members can share and work on different versions of the model
- Reproducibility: Specific versions of the model can be referenced and recreated
Automated checkpointing and recovery systems
Section titled “Automated checkpointing and recovery systems”To make the checkpointing and recovery process more robust and hands-off, we can implement an automated system:
- First, import the
We imported two key modules here:import threadingimport time
threading: Enables the creation of threads for running tasks (such as auto-save and health checks) concurrently with the main training processtime: Used to manage intervals between auto-saves and health checks, as well as timestamping saved checkpoints
- Next, we define and initialize the class:
Theclass AutomatedLLMTrainer(VersionControlledLLMTrainer):def __init__(self, model, optimizer, checkpoint_dir='checkpoints',autosave_interval=15, version_file='versions.json',health_check_interval=60):super().__init__(model, optimizer, checkpoint_dir,version_file)self.autosave_interval = autosave_intervalself.health_check_interval = health_check_intervalself.training_active = False
AutomatedLLMTrainerclass inherits from a base class,VersionControlledLLMTrainer, which handles basic checkpointing logic. This class introduces automation for checkpointing and system health monitoring. The following is a list of parameters that manage auto-saving, system health checks, and training execution control:autosave_interval: The time (in seconds) between auto-save checkpoints.health_check_interval: The time between system health checks.training_active: A flag to indicate whether the training is ongoing. It is used to control the threads’ execution. The constructor callssuper().__init__()to inherit functionality from the parent class and sets up intervals for auto-saving and health checks.
- Auto-save the thread
This method starts a separate thread that periodically saves a checkpoint during training. The following is a list of components responsible for handling periodic auto-saving during training:def start_autosave_thread(self):def autosave_loop():while self.training_active:time.sleep(self.autosave_interval)if self.training_active:self.save_checkpoint_versioned(self.current_epoch, self.current_step,self.current_loss,f"autosave_{time.time()}")self.autosave_thread = threading.Thread(target=autosave_loop)self.autosave_thread.start()
autosave_loop: A function that continuously runs whiletraining_activeisTrue. Everyautosave_intervalseconds, it calls thesave_checkpoint_versioned()method to save the current state.threading.Thread: The thread runsautosave_loopin the background, ensuring that auto-saves happen concurrently with the training process.
- Next, we implement a health check thread. This method starts a health check thread that monitors system performance at
Here are the main elements of the preceding snippet:def start_health_check_thread(self):def health_check_loop():while self.training_active:time.sleep(self.health_check_interval)if self.training_active:if not self.check_system_health():print("System health check failed.Initiating recovery...")self.initiate_recovery()self.health_check_thread = threading.Thread(target=health_check_loop)self.health_check_thread.start()
health_check_loop: A function that continuously runs during training. Everyhealth_check_intervalseconds, it checks the system health by callingcheck_system_health(). If a problem is detected, it triggers the recovery process.check_system_health(): This method needs to be defined to check the system’s performance metrics (e.g., GPU memory or CPU usage). If the health check fails, it callsinitiate_recovery().
- We perform system health check and recovery. The following placeholder method is where the system health checks will be implemented, for example, checking GPU memory, CPU utilization, disk space, or any other resource critical to the training process. It returns
Trueif everything is fine, andFalseif there’s a problem:The following method will contain logic for what to do if the system health check fails. It could, for instance, reload the last checkpoint, reduce the batch size, or take other corrective actions depending on the issue detected:def check_system_health(self):# Implement system health checks here# For example, check GPU memory, CPU usage, disk space, etc.return True # Return False if health check failsdef initiate_recovery(self):# Implement recovery logic here# For example, reload from the last checkpoint, reduce batch size, etc.pass - Finally, we conduct automated training with checkpointing and health checks. This method manages the overall training process with automation. It activates the auto-save and health check threads and initiates distributed training via the parent class’s
train_distributed()Here’s a breakdown of the main code elements:def train_with_automation(self, epochs, steps_per_epoch, train_fn):self.training_active = Trueself.start_autosave_thread()self.start_health_check_thread()try:super().train_distributed(epochs, steps_per_epoch,train_fn)finally:self.training_active = Falseself.autosave_thread.join()self.health_check_thread.join()self.training_active: Set toTrueto indicate that training is runningtry-finally block: Ensures that no matter how the training ends (whether it completes or crashes), thetraining_activeflag is set toFalseand both threads are properly terminated
This approach reduces manual intervention, enhances reliability, and offers flexibility in defining recovery logic based on the specific training needs.
Summary
Section titled “Summary”Implementing robust checkpointing and recovery systems is common practice for successful LLM training. By incorporating these techniques, you can ensure that your long-running training processes are resilient to failures, easily manageable, and conducive to experimentation and collaboration.
To expand our discussion, Table 10.1 lists checkpointing strategies, trade-offs, and use cases:
| Checkpointing Strategy | Description | Trade-Offs | Use Cases |
|---|---|---|---|
| Regular (with max limit) | Saves at intervals (steps/epochs); keeps a maximum number. | Pros: Saves storage; periodic snapshots. Cons: Might overwrite good checkpoints. | Iterative model development; monitoring training progress; preventing complete data loss during long training runs. |
| Time-based | Saves at specified intervals (e.g., every 30 minutes). | Pros: Time-spaced snapshots. Cons: Inefficient if the interval is too short/long. | Long-running experiments where consistent, time-stamped checkpoints are crucial for debugging and analysis; ensuring recoverability in case of system failures. |
| Best model | Saves only when the model achieves the best performance. | Pros: Retains the best model. Cons: May not be representative if loss is noisy; no intermediate snapshots. | Selecting the most performant model. |
| Efficient (compression) | Uses compression (e.g., ZIP) to reduce size. | Storage-constrained environments; handling large models where storage is a primary concern; archiving models for long-term storage. | Storage-constrained environments; archiving models for long-term storage. |
| Efficient (quantization) | Reduces precision of weights (e.g., float32 to float16). | Pros: Reduces size. Cons: Potential accuracy loss. | Deploying models on resource-limited devices; reducing checkpoint size for faster transfer and storage; accelerating model loading. |
| Efficient (incremental) | Saves only changes since the last checkpoint. | Pros: Can significantly reduce size. Cons: Complex; potentially fragile. | Training models with gradual parameter updates; large models where frequent full checkpoints are impractical; continuous learning scenarios. |
| Distributed | In distributed training, only the main process (rank 0) saves; data is broadcast to others. | Pros: Avoids redundant writes; ensures consistency. Cons: Requires coordination. | Large-scale distributed training jobs; ensuring consistent model states across multiple workers; minimizing network overhead. |
| Version-controlled | Associates checkpoints with versions; supports branching. | Pros: Experimentation; reproducibility; rollback. Cons: Adds complexity. | Collaborative model development; tracking experimental variations; ensuring reproducibility for scientific research; managing model evolution. |
| Automated (with health checks) | Auto-saves checkpoints; performs health checks; can initiate recovery. | Pros: Reduces manual work; enhances reliability. Cons: Requires health check/recovery implementation. | Mission-critical training jobs; automated recovery from failures; long-running experiments requiring high reliability. |
Table 10.1 – Checkpointing strategies, trade-offs, and use cases
In the next chapter, we’ll explore effective techniques for adapting pre-trained language models to specific tasks or domains.