|
| 1 | + |
| 2 | +# Checkpoints in ML/AI libraries |
| 3 | + |
| 4 | +Let's explore how `@checkpoint` works in a real-world scenario when checkpointing training progress with popular ML |
| 5 | +libraries. |
| 6 | + |
| 7 | +## Checkpointing XGBoost |
| 8 | + |
| 9 | +Like many other ML libraries, [XGBoost](https://xgboost.readthedocs.io/en/stable/) allows you to define custom callbacks |
| 10 | +that are called periodically during training. We can create a custom checkpointer that saves the model to a file, using |
| 11 | +`pickle`, [as recommended by XGBoost](https://xgboost.readthedocs.io/en/stable/tutorials/saving_model.html), and calls |
| 12 | +`current.checkpoint.save()` to persist it. |
| 13 | + |
| 14 | +Save this snippet in a file, `xgboost_checkpointer.py`: |
| 15 | + |
| 16 | +```python |
| 17 | +import os |
| 18 | +import pickle |
| 19 | +from metaflow import current |
| 20 | +import xgboost |
| 21 | + |
| 22 | +class Checkpointer(xgboost.callback.TrainingCallback): |
| 23 | + |
| 24 | + @classmethod |
| 25 | + def _path(cls): |
| 26 | + return os.path.join(current.checkpoint.directory, 'xgb_cp.pkl') |
| 27 | + |
| 28 | + def __init__(self, interval=10): |
| 29 | + self._interval = interval |
| 30 | + |
| 31 | + def after_iteration(self, model, epoch, evals_log): |
| 32 | + if epoch > 0 and epoch % self._interval == 0: |
| 33 | + with open(self._path(), 'wb') as f: |
| 34 | + pickle.dump(model, f) |
| 35 | + current.checkpoint.save() |
| 36 | + |
| 37 | + @classmethod |
| 38 | + def load(cls): |
| 39 | + with open(cls._path(), 'rb') as f: |
| 40 | + return pickle.load(f) |
| 41 | +``` |
| 42 | + |
| 43 | +:::tip |
| 44 | +Make sure that the checkpoint directory doesn't accumulate files across invocations, which would make the `save` |
| 45 | +operation become slower over time. Either overwrite the same files or clean up the directory between checkpoints. |
| 46 | +The `save` call will create a uniquely named checkpoint directory automatically, so you can keep overwriting files |
| 47 | +across iterations. |
| 48 | +::: |
| 49 | + |
| 50 | +We can then train an XGboost model using `Checkpointer`: |
| 51 | + |
| 52 | +```python |
| 53 | +from metaflow import FlowSpec, step, current, Flow,\ |
| 54 | + Parameter, conda, retry, checkpoint, card, timeout |
| 55 | + |
| 56 | +class CheckpointXGBoost(FlowSpec): |
| 57 | + rounds = Parameter("rounds", help="number of boosting rounds", default=128) |
| 58 | + |
| 59 | + @conda(packages={"scikit-learn": "1.6.1"}) |
| 60 | + @step |
| 61 | + def start(self): |
| 62 | + from sklearn.datasets import load_breast_cancer |
| 63 | + |
| 64 | + self.X, self.y = load_breast_cancer(return_X_y=True) |
| 65 | + self.next(self.train) |
| 66 | + |
| 67 | + @timeout(seconds=15) |
| 68 | + @conda(packages={"xgboost": "2.1.4"}) |
| 69 | + @card |
| 70 | + @retry |
| 71 | + @checkpoint |
| 72 | + @step |
| 73 | + def train(self): |
| 74 | + import xgboost as xgb |
| 75 | + from xgboost_checkpointer import Checkpointer |
| 76 | + |
| 77 | + if current.checkpoint.is_loaded: |
| 78 | + cp_model = Checkpointer.load() |
| 79 | + cp_rounds = cp_model.num_boosted_rounds() |
| 80 | + print(f"Checkpoint was trained for {cp_rounds} rounds") |
| 81 | + else: |
| 82 | + cp_model = None |
| 83 | + cp_rounds = 0 |
| 84 | + |
| 85 | + model = xgb.XGBClassifier( |
| 86 | + n_estimators=self.rounds - cp_rounds, |
| 87 | + eval_metric="logloss", |
| 88 | + callbacks=[Checkpointer()]) |
| 89 | + model.fit(self.X, self.y, eval_set=[(self.X, self.y)], xgb_model=cp_model) |
| 90 | + |
| 91 | + assert model.get_booster().num_boosted_rounds() == self.rounds |
| 92 | + print("Training completed!") |
| 93 | + self.next(self.end) |
| 94 | + |
| 95 | + @step |
| 96 | + def end(self): |
| 97 | + pass |
| 98 | + |
| 99 | +if __name__ == "__main__": |
| 100 | + CheckpointXGBoost() |
| 101 | +``` |
| 102 | + |
| 103 | +You can run the flow, saved to `xgboostflow.py`, as usual: |
| 104 | + |
| 105 | +``` |
| 106 | +python xgboostflow.py --environment=conda run |
| 107 | +``` |
| 108 | + |
| 109 | +To demonstrate checkpoints in action, [the `@timeout` |
| 110 | +decorator](/scaling/failures#timing-out-with-the-timeout-decorator) interrupts training every 15 seconds. |
| 111 | +You can adjust the time |
| 112 | +depending on how fast the training progresses on your workstation. The `@retry` decorator will then start the task |
| 113 | +again, allowing `@checkpoint` to load the latest checkpoint and resume training. |
| 114 | + |
| 115 | +## Checkpointing PyTorch |
| 116 | + |
| 117 | +Using `@checkpoint` with [PyTorch](https://pytorch.org/) is straightforward. Within your training loop, periodically |
| 118 | +serialize the model and use `current.checkpoint.save()` to create a checkpoint, along these lines: |
| 119 | + |
| 120 | +```python |
| 121 | +model_path = os.path.join(current.checkpoint.directory, 'model') |
| 122 | +torch.save(model.state_dict(), model_path) |
| 123 | +current.checkpoint.save() |
| 124 | +``` |
| 125 | + |
| 126 | +Before starting training, check for an available checkpoint and load the model from it if found: |
| 127 | + |
| 128 | +```python |
| 129 | +if current.checkpoint.is_loaded: |
| 130 | + model.load_state_dict(torch.load(model_path)) |
| 131 | +``` |
| 132 | + |
| 133 | +Take a look at [this reference repository for a complete |
| 134 | +example](https://github.com/outerbounds/metaflow-checkpoint-examples/tree/master/mnist_torch_vanilla) showing this pattern in action, in addition to examples for many other frameworks. |
| 135 | + |
| 136 | +## Checkpointing GenAI/LLM fine-tuning |
| 137 | + |
| 138 | +Fine-tuning large language models and other large foundation models for generative AI can easily take hours, running on expensive GPU instances. Take a look at the following examples to learn how `@checkpoint` can be applied to various fine-tuning use cases: |
| 139 | + |
| 140 | +- [Finetuning a LoRA from a model downloaded from |
| 141 | +HuggingFace](https://github.com/outerbounds/metaflow-checkpoint-examples/tree/master/lora_huggingface) |
| 142 | + |
| 143 | +- [Finetuning an LLM using LLaMA |
| 144 | +Factory](https://github.com/outerbounds/metaflow-checkpoint-examples/tree/master/llama_factory) |
| 145 | + |
| 146 | +- [Finetuning an LLM and serve it with NVIDIA |
| 147 | +NIM](https://github.com/outerbounds/metaflow-checkpoint-examples/tree/master/nim_lora) |
| 148 | + |
| 149 | +## Checkpointing distributed workloads |
| 150 | + |
| 151 | +[Metaflow supports distributed training](/scaling/remote-tasks/distributed-computing) and other distributed workloads |
| 152 | +which execute across multiple instances in a cluster. When training large models over extended periods across multiple |
| 153 | +instances, which greatly increases the likelihood of hitting spurious failures, checkpointing becomes essential to |
| 154 | +ensure efficient recovery. |
| 155 | + |
| 156 | +Checkpointing works smoothly when only the control node in a training cluster is designated to handle it, preventing |
| 157 | +race conditions that could arise from multiple instances attempting to save progress simultaneously. For reference, |
| 158 | +[take a look at this |
| 159 | +example](https://github.com/outerbounds/metaflow-checkpoint-examples/tree/master/cifar_distributed) that uses [PyTorch Data Distributed Parallel (DDP)](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) mode to train a vision model on CIFAR-10 dataset, checkpointing progress with `@checkpoint`. |
| 160 | + |
| 161 | +:::info |
| 162 | +Large-scale distributed computing can be challenging. If you need help setting up `@checkpoint` in distributed setups, don’t hesitate to [ask for guidance on Metaflow Slack](http://slack.outerbounds.co). |
| 163 | +::: |
| 164 | + |
0 commit comments