|
| 1 | +from typing import TYPE_CHECKING |
| 2 | +import os |
| 3 | +import torch |
| 4 | + |
| 5 | +if TYPE_CHECKING: |
| 6 | + from .base import Trainer, TrainingArguments |
| 7 | + |
| 8 | +from swift import TrainerCallback, get_logger |
| 9 | + |
| 10 | +logger = get_logger() |
| 11 | + |
| 12 | + |
| 13 | +class MemorySnapshotCallback(TrainerCallback): |
| 14 | + """ |
| 15 | + Record CUDA memory history and dump snapshot with specified interval steps. |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, args: 'TrainingArguments', trainer: 'Trainer'): |
| 19 | + super().__init__(args, trainer) |
| 20 | + self.dump_interval = args.mem_snapshot_interval |
| 21 | + self.dump_path = args.mem_snapshot_path |
| 22 | + self._recording = False |
| 23 | + |
| 24 | + def _dump_and_visualize(self, step: int, tag: str = ''): |
| 25 | + rank = int(os.environ.get("RANK", 0)) |
| 26 | + raw = f'snapshot_step{step}_rank{rank}' |
| 27 | + pickle_path = os.path.join(self.dump_path, f'{raw}.pickle') |
| 28 | + html_path = os.path.join(self.dump_path, f'{raw}.html') |
| 29 | + |
| 30 | + snapshot = torch.cuda.memory._snapshot() |
| 31 | + os.makedirs(os.path.dirname(os.path.abspath(pickle_path)), exist_ok=True) |
| 32 | + torch.cuda.memory._dump_snapshot(pickle_path) |
| 33 | + logger.info(f"{tag}CUDA memory snapshot dumped: {pickle_path}") |
| 34 | + |
| 35 | + from torch.cuda._memory_viz import trace_plot |
| 36 | + html_content = trace_plot(snapshot) |
| 37 | + with open(html_path, 'w') as f: |
| 38 | + f.write(html_content) |
| 39 | + logger.info(f"{tag}CUDA memory html visualization saved: {html_path}") |
| 40 | + |
| 41 | + def on_train_begin(self, args, state, control, **kwargs): |
| 42 | + if torch.cuda.is_available(): |
| 43 | + torch.cuda.memory._record_memory_history(max_entries=100000) |
| 44 | + self._recording = True |
| 45 | + logger.info("CUDA memory history recording started") |
| 46 | + |
| 47 | + def on_step_end(self, args, state, control, **kwargs): |
| 48 | + if self._recording and self.dump_interval and state.global_step % self.dump_interval == 0: |
| 49 | + self._dump_and_visualize(state.global_step, tag=f"step:{state.global_step}, ") |
| 50 | + |
| 51 | + def on_train_end(self, args, state, control, **kwargs): |
| 52 | + if self._recording: |
| 53 | + self._dump_and_visualize(state.global_step, tag="[final] ") |
| 54 | + torch.cuda.memory._record_memory_history(enabled=None) |
| 55 | + self._recording = False |
0 commit comments