Spaces:
Running
on
Zero
Running
on
Zero
File size: 7,112 Bytes
bcc039b afedb16 bcc039b afedb16 7517ac2 afedb16 bcc039b afedb16 bcc039b afedb16 bcc039b 7cf8fab bcc039b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
import json
import logging
from collections import namedtuple
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Union
import fsspec
import torch
import torch.nn as nn
import wandb
from pydantic import BaseModel, ConfigDict
from bytelatent.distributed import get_is_master
logger = logging.getLogger()
class WandbArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
job_type: str | None = None
dir: str | None = None
project: str | None = None
entity: str | None = None
tags: list | None = None
group: str | None = None
name: str | None = None
notes: str | None = None
config_exclude_keys: list[str] | None = None
config_include_keys: list[str] | None = None
anonymous: str | None = None
mode: str | None = None
allow_val_change: bool | None = None
resume: Union[bool, str] | None = None
force: bool | None = None
tensorboard: bool | None = None
sync_tensorboard: bool | None = None
monitor_gym: bool | None = None
save_code: bool | None = None
id: str | None = None
fork_from: str | None = None
resume_from: str | None = None
class LoggingArgs(BaseModel):
model_config = ConfigDict(extra="forbid")
freq: int = 10 # Log every freq optimizer steps
acc_freq: int | None = None # Log every acc_freq gradient accumulation steps
wandb: WandbArgs | None = None
class MetricLogger:
def __init__(
self,
outdir: str,
# args: TrainArgs
args: Any | None = None,
fs: fsspec.AbstractFileSystem | None = None,
):
self.outdir = outdir
self.jsonl_writer = None
self.fs = fs
self.args = args
def open(self):
if self.jsonl_writer is None:
if self.fs is None:
self.jsonl_writer = open(self.outdir, "a")
else:
self.jsonl_writer = self.fs.open(self.outdir, "a")
if (
self.args is not None
and self.args.logging.wandb is not None
and get_is_master()
):
run = wandb.init(
config=self.args.model_dump(),
**self.args.logging.wandb.model_dump(),
)
def log(self, metrics: dict[str, Any]):
if (
self.args is not None
and self.args.logging.wandb is not None
and (wandb.run is not None)
):
wandb.log(metrics, step=metrics["global_step"])
metrics.update({"created_at": datetime.now(timezone.utc).isoformat()})
print(json.dumps(metrics), file=self.jsonl_writer, flush=True)
def close(self):
if self.jsonl_writer is not None:
self.jsonl_writer.close()
self.jsonl_writer = None
def __enter__(self):
self.open()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __del__(self):
self.close()
GPUMemStats = namedtuple(
"GPUMemStats",
[
"max_active_gib",
"max_active_pct",
"max_reserved_gib",
"max_reserved_pct",
"num_alloc_retries",
"num_ooms",
"power_draw",
],
)
class GPUMemoryMonitor:
"""
Class to monitor GPU memory usage
"""
def __init__(self, device: str = "cuda:0"):
self.device = torch.device(device) # device object
self.device_name = torch.cuda.get_device_name(self.device)
self.device_index = torch.cuda.current_device()
self.device_capacity = torch.cuda.get_device_properties(
self.device
).total_memory
self.device_capacity_gib = self._to_gib(self.device_capacity)
# reset stats, clear cache
torch.cuda.reset_peak_memory_stats()
torch.cuda.empty_cache()
def _to_gib(self, memory_in_bytes):
# NOTE: GiB (gibibyte) is 1024, vs GB is 1000
_gib_in_bytes = 1024 * 1024 * 1024
memory_in_gib = memory_in_bytes / _gib_in_bytes
return memory_in_gib
def _to_pct(self, memory):
return 100 * memory / self.device_capacity
def get_peak_stats(self):
cuda_info = torch.cuda.memory_stats(self.device)
max_active = cuda_info["active_bytes.all.peak"]
max_active_gib = self._to_gib(max_active)
max_active_pct = self._to_pct(max_active)
max_reserved = cuda_info["reserved_bytes.all.peak"]
max_reserved_gib = self._to_gib(max_reserved)
max_reserved_pct = self._to_pct(max_reserved)
num_retries = cuda_info["num_alloc_retries"]
num_ooms = cuda_info["num_ooms"]
power_draw = torch.cuda.power_draw()
if num_retries > 0:
logger.warning(f"{num_retries} CUDA memory allocation retries.")
if num_ooms > 0:
logger.warning(f"{num_ooms} CUDA OOM errors thrown.")
return GPUMemStats(
max_active_gib,
max_active_pct,
max_reserved_gib,
max_reserved_pct,
num_retries,
num_ooms,
power_draw,
)
def reset_peak_stats(self):
torch.cuda.reset_peak_memory_stats()
torch.cuda.reset_accumulated_memory_stats()
def __str__(self):
mem_stats = self.get_peak_stats()
display_str = f"{self.device_name} ({self.device_index}): {self.device_capacity_gib} GiB capacity, "
display_str += (
f"{mem_stats.max_reserved_gib} GiB peak, {mem_stats.max_reserved_pct}% peak"
)
return f"{display_str}"
def upload_train_to_wandb(
ckpt_dir, project="lingua", entity="codegen-team", train=True, eval=True
):
import json
from pathlib import Path
import wandb
from omegaconf import OmegaConf
cfg = OmegaConf.load(Path(ckpt_dir) / "config.yaml")
cfg = OmegaConf.to_container(cfg)
if train:
wandb.init(config=cfg, name=cfg["name"], project=project, entity=entity)
with open(Path(ckpt_dir) / "metrics.jsonl") as f:
for l in f:
m = json.loads(l)
wandb.log(m, step=m["global_step"])
wandb.finish()
if eval:
wandb.init(config=cfg, name=cfg["name"], project=project, entity=entity)
with open(Path(ckpt_dir) / "metrics.eval.jsonl") as f:
for l in f:
m = json.loads(l)
wandb.log(
{
f"evals/{name.replace('/','.')}": value
for name, value in m.items()
if "/" in name
},
step=m["global_step"],
)
wandb.finish()
def get_num_params(model: nn.Module) -> int:
"""
Get the total model params
Args : only_trainable: whether to only count trainable params
"""
numel = {n: p.numel() for n, p in model.named_parameters()}
return sum(numel.values())
|