|
1 | 1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 | 2 | # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
|
3 | 3 |
|
| 4 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 5 | +# All rights reserved |
| 6 | + |
4 | 7 | import os
|
| 8 | +from collections import namedtuple |
5 | 9 | from datetime import datetime
|
6 | 10 | from typing import Any, Dict, Optional
|
7 | 11 |
|
8 | 12 | import torch
|
| 13 | +import torch.nn as nn |
9 | 14 | from torch.utils.tensorboard import SummaryWriter
|
10 | 15 |
|
11 | 16 | from torchtrain.logging_utils import rank0_log
|
12 | 17 | from torchtrain.profiling import get_config_from_toml
|
13 | 18 |
|
| 19 | +_gb_in_bytes = 1024 * 1024 * 1024 |
| 20 | +_mb_in_bytes = 1024 * 1024 |
| 21 | + |
| 22 | + |
| 23 | +def format_to_gb(item, precision=4): |
| 24 | + """quick function to format numbers to gigabyte and round to (default) 4 digit precision""" |
| 25 | + metric_num = item / _gb_in_bytes |
| 26 | + metric_num = round(metric_num, ndigits=precision) |
| 27 | + return metric_num |
| 28 | + |
| 29 | + |
| 30 | +def convert_to_gpu_pct(value, total_gpu_memory): |
| 31 | + return round(100 * (value / total_gpu_memory), 2) |
| 32 | + |
| 33 | + |
| 34 | +# named tuple for passing memory stats (as % of device capacity) for Tensorboard logging |
| 35 | +GPUMemStats = namedtuple( |
| 36 | + "GPUMemStats", |
| 37 | + [ |
| 38 | + "allocated_curr", |
| 39 | + "allocated_peak", |
| 40 | + "reserved_curr", |
| 41 | + "reserved_peak", |
| 42 | + "active_curr", |
| 43 | + "active_peak", |
| 44 | + "num_retries", |
| 45 | + ], |
| 46 | +) |
| 47 | + |
| 48 | + |
| 49 | +class GPUMemoryMonitor: |
| 50 | + """ |
| 51 | + Class to monitor GPU memory usage |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__(self, device: str = "cuda:0"): |
| 55 | + self.device = torch.device(device) # device object |
| 56 | + self.device_name = torch.cuda.get_device_name(self.device) |
| 57 | + self.device_index = torch.cuda.current_device() |
| 58 | + self.device_capacity = torch.cuda.get_device_properties( |
| 59 | + self.device |
| 60 | + ).total_memory |
| 61 | + self.device_capacity_gb = format_to_gb(self.device_capacity) |
| 62 | + self.num_retries = 0 |
| 63 | + self.num_ooms = 0 |
| 64 | + self.peak_active_memory = 0 |
| 65 | + self.peak_allocated_memory = 0 |
| 66 | + self.peak_reserved_memory = 0 |
| 67 | + self.curr_reserved_memory = 0 |
| 68 | + |
| 69 | + self.device_reserved_memory_usage = 0 |
| 70 | + self.device_reserved_memory_gb = 0 |
| 71 | + self.device_reserved_memory_pct = 0 |
| 72 | + |
| 73 | + self.device_active_memory_usage = 0 |
| 74 | + self.device_active_memory_gb = 0 |
| 75 | + self.device_active_memory_pct = 0 |
| 76 | + |
| 77 | + # current stats |
| 78 | + self.device_alloc_memory_usage = torch.cuda.memory_allocated(self.device) |
| 79 | + self.device_alloc_memory_gb = format_to_gb(self.device_alloc_memory_usage) |
| 80 | + self.device_alloc_memory_pct = convert_to_gpu_pct( |
| 81 | + self.device_alloc_memory_usage, self.device_capacity |
| 82 | + ) |
| 83 | + |
| 84 | + # reset stats, clear cache |
| 85 | + torch.cuda.reset_peak_memory_stats() |
| 86 | + torch.cuda.empty_cache() |
| 87 | + |
| 88 | + def get_pct_memory(self, memory_num): |
| 89 | + pct_memory = memory_num / self.device_capacity |
| 90 | + pct_memory = round(100 * (pct_memory), 2) |
| 91 | + return pct_memory |
| 92 | + |
| 93 | + def get_gb_memory(self, memory_num): |
| 94 | + gb_memory = memory_num / _gb_in_bytes |
| 95 | + gb_memory = round(gb_memory, 2) |
| 96 | + return gb_memory |
| 97 | + |
| 98 | + def get_current_stats(self, return_data: bool = False): |
| 99 | + """ |
| 100 | + get the CudaCachingAllocator stats for the current device |
| 101 | +
|
| 102 | + return_data: bool, if True, return the data as a named tuple |
| 103 | + """ |
| 104 | + curr_mem = torch.cuda.memory_stats(self.device) |
| 105 | + |
| 106 | + self.device_alloc_memory_usage = curr_mem["allocated_bytes.all.current"] |
| 107 | + self.device_alloc_memory_gb = format_to_gb(self.device_alloc_memory_usage) |
| 108 | + self.device_alloc_memory_pct = convert_to_gpu_pct( |
| 109 | + self.device_alloc_memory_usage, self.device_capacity |
| 110 | + ) |
| 111 | + |
| 112 | + self.device_reserved_memory_usage = curr_mem["reserved_bytes.all.current"] |
| 113 | + self.device_reserved_memory_gb = format_to_gb(self.device_reserved_memory_usage) |
| 114 | + self.device_reserved_memory_pct = convert_to_gpu_pct( |
| 115 | + self.device_reserved_memory_usage, self.device_capacity |
| 116 | + ) |
| 117 | + |
| 118 | + self.device_active_memory_usage = curr_mem["active_bytes.all.current"] |
| 119 | + self.device_active_memory_gb = format_to_gb(self.device_active_memory_usage) |
| 120 | + self.device_active_memory_pct = convert_to_gpu_pct( |
| 121 | + self.device_active_memory_usage, self.device_capacity |
| 122 | + ) |
| 123 | + |
| 124 | + display_str = "" |
| 125 | + display_str += f"Current Memory: {self.device_name} ({self.device_index}): Reserved: {self.device_reserved_memory_pct}%," |
| 126 | + display_str += f"Alloc {self.device_alloc_memory_pct}%, Active: {self.device_active_memory_pct}%\n" |
| 127 | + |
| 128 | + self.get_peak_stats(curr_mem) |
| 129 | + |
| 130 | + peak_active_pct = self.get_pct_memory(self.peak_active_memory) |
| 131 | + peak_allocated_pct = self.get_pct_memory(self.peak_allocated_memory) |
| 132 | + peak_reserved_pct = self.get_pct_memory(self.peak_reserved_memory) |
| 133 | + display_str += f"Peak Memory: Reserved {peak_reserved_pct}%, Alloc {peak_allocated_pct}%, Active: {peak_active_pct}%\n" |
| 134 | + |
| 135 | + display_str += f"num retries: {self.num_retries}, num ooms: {self.num_ooms}" |
| 136 | + if self.num_retries > 0: |
| 137 | + display_str += f"\nWARNING: {self.num_retries} retries -- recommend lowering batch size for max performance\n" |
| 138 | + |
| 139 | + if not return_data: |
| 140 | + return display_str |
| 141 | + |
| 142 | + # return named tuple |
| 143 | + curr_mem_stats = GPUMemStats( |
| 144 | + self.device_alloc_memory_pct, |
| 145 | + peak_active_pct, |
| 146 | + self.device_reserved_memory_pct, |
| 147 | + peak_reserved_pct, |
| 148 | + self.device_active_memory_pct, |
| 149 | + peak_active_pct, |
| 150 | + self.num_retries, |
| 151 | + ) |
| 152 | + return curr_mem_stats |
| 153 | + |
| 154 | + def start_monitoring(self): |
| 155 | + """reset all monitoring stats""" |
| 156 | + self.reset_peak_stats() |
| 157 | + |
| 158 | + def get_peak_stats(self, cuda_info=None): |
| 159 | + """capture current peak memory stats""" |
| 160 | + if not cuda_info: |
| 161 | + cuda_info = torch.cuda.memory_stats() |
| 162 | + |
| 163 | + self.peak_active_memory = cuda_info.get("active_bytes.all.peak", 0) |
| 164 | + self.peak_allocated_memory = cuda_info.get("allocated_bytes.all.peak", 0) |
| 165 | + self.peak_reserved_memory = cuda_info.get("reserved_bytes.all.peak", 0) |
| 166 | + |
| 167 | + self.num_retries = cuda_info.get("num_alloc_retries", 0) |
| 168 | + self.num_ooms = cuda_info.get("num_ooms", 0) |
| 169 | + |
| 170 | + def reset_peak_stats(self): |
| 171 | + """reset peak memory stats""" |
| 172 | + torch.cuda.reset_peak_memory_stats() |
| 173 | + torch.cuda.empty_cache() |
| 174 | + self.num_retries = 0 |
| 175 | + self.num_ooms = 0 |
| 176 | + self.active_peak_memory_utilization_str = "" |
| 177 | + self.peak_memory_utilization_str = "" |
| 178 | + self.peak_reserved_memory_utilization_str = "" |
| 179 | + |
| 180 | + def __str__(self): |
| 181 | + _ = self.get_current_stats() |
| 182 | + display_str = f"{self.device_name} ({self.device_index}): {self.device_capacity_gb} GB capacity, " |
| 183 | + display_str += f"{self.device_alloc_memory_gb} GB in-use, {self.device_alloc_memory_pct}% in-use" |
| 184 | + return f"{display_str}" |
| 185 | + |
| 186 | + |
| 187 | +def get_num_params(model: nn.Module, only_trainable: bool = False) -> int: |
| 188 | + """ |
| 189 | + Get the total model params |
| 190 | + Args : only_trainable: whether to only count trainable params |
| 191 | + """ |
| 192 | + param_list = list(model.parameters()) |
| 193 | + if only_trainable: |
| 194 | + param_list = [p for p in param_list if p.requires_grad] |
| 195 | + unique_params = {p.data_ptr(): p for p in param_list}.values() |
| 196 | + return sum(p.numel() for p in unique_params) |
| 197 | + |
14 | 198 |
|
15 | 199 | class MetricLogger:
|
16 | 200 | def __init__(self, log_dir, tag, enable_tb):
|
|
0 commit comments