|
|
|
@@ -17,7 +17,6 @@ from torch.optim import AdamW, Optimizer
|
|
|
|
|
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
|
|
|
|
|
from prime_rl.trainer.optim.base import OffloadOptimizer
|
|
|
|
|
from prime_rl.trainer.optim.cpu_adam import adamw_step as native_cpu_adamw_step
|
|
|
|
|
from prime_rl.trainer.optim.cpu_adam import add_bfloat16_ as native_add_bfloat16_
|
|
|
|
|
from prime_rl.trainer.optim.cpu_adam import copy_or_add_bfloat16_multi_ as native_copy_or_add_bfloat16_multi_
|
|
|
|
|
from prime_rl.trainer.optim.cpu_adam import load_cpu_adamw_kernel
|
|
|
|
|
from prime_rl.trainer.optim.cpu_adam import sign_sgd_step as native_cpu_sign_sgd_step
|
|
|
|
@@ -29,28 +28,14 @@ from prime_rl.utils.logger import get_logger
|
|
|
|
|
class _CPUGradientBuffer:
|
|
|
|
|
template: DTensor
|
|
|
|
|
accumulator: torch.Tensor
|
|
|
|
|
staging: torch.Tensor | None = None
|
|
|
|
|
initialized: bool = False
|
|
|
|
|
pending: bool = False
|
|
|
|
|
staging_holds_final: bool = False
|
|
|
|
|
pending_step: int = -1
|
|
|
|
|
pending_backward: int = -1
|
|
|
|
|
last_enqueued_backward: int = -1
|
|
|
|
|
pending_generations: set[tuple[int, int]] = field(default_factory=set)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class _GradientCopyTask:
|
|
|
|
|
event: torch.cuda.Event
|
|
|
|
|
buffers: list[tuple[int, _CPUGradientBuffer, bool, bool]]
|
|
|
|
|
final_backward: bool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class _OptimizerChunkTask:
|
|
|
|
|
chunk_idx: int
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class _PinnedTransferSlot:
|
|
|
|
|
index: int
|
|
|
|
@@ -69,7 +54,7 @@ class _GradientTransferRequest:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class _BoundedGradientCopyTask:
|
|
|
|
|
class _GradientCopyTask:
|
|
|
|
|
request: _GradientTransferRequest
|
|
|
|
|
slot: _PinnedTransferSlot
|
|
|
|
|
|
|
|
|
@@ -91,388 +76,7 @@ class _MasterWeight:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class GradientOffloadManager:
|
|
|
|
|
"""Offloads finalized FSDP2 sharded gradients from post-accumulate hooks."""
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
chunks: list[list[nn.Parameter]],
|
|
|
|
|
dp_replicate: int,
|
|
|
|
|
cpu_dtype: torch.dtype | None = None,
|
|
|
|
|
preserve_staging_dtype: bool = False,
|
|
|
|
|
chunk_ready_callback: Callable[[int], None] | None = None,
|
|
|
|
|
):
|
|
|
|
|
self._chunks = chunks
|
|
|
|
|
self._dp_replicate = dp_replicate
|
|
|
|
|
self._cpu_dtype = cpu_dtype
|
|
|
|
|
self._preserve_staging_dtype = preserve_staging_dtype
|
|
|
|
|
self._optimizer_param_ids = {id(param) for chunk in chunks for param in chunk}
|
|
|
|
|
self._chunk_param_ids = [{id(param) for param in chunk} for chunk in chunks]
|
|
|
|
|
self._chunk_by_param_id = {
|
|
|
|
|
param_id: chunk_idx for chunk_idx, param_ids in enumerate(self._chunk_param_ids) for param_id in param_ids
|
|
|
|
|
}
|
|
|
|
|
self._buffers: dict[int, _CPUGradientBuffer] = {}
|
|
|
|
|
self._chunk_ready_callback = chunk_ready_callback
|
|
|
|
|
|
|
|
|
|
self._d2h_stream = torch.cuda.Stream()
|
|
|
|
|
self._tasks: queue.SimpleQueue[_GradientCopyTask | _OptimizerChunkTask | None] = queue.SimpleQueue()
|
|
|
|
|
self._condition = threading.Condition()
|
|
|
|
|
self._gradient_scale = 1.0
|
|
|
|
|
self._final_backward = False
|
|
|
|
|
self._overlap_optimizer = False
|
|
|
|
|
self._final_enqueued_param_ids: set[int] = set()
|
|
|
|
|
self._pending_chunk_param_ids: list[set[int]] = []
|
|
|
|
|
self._scheduled_chunks: set[int] = set()
|
|
|
|
|
self._completed_chunks = 0
|
|
|
|
|
self._worker_error: BaseException | None = None
|
|
|
|
|
self._logged_cpu_allocation = 0
|
|
|
|
|
self._closed = False
|
|
|
|
|
|
|
|
|
|
params = {id(param): param for chunk in chunks for param in chunk}
|
|
|
|
|
# Pin every buffer NOW, before the first collective of the job. The
|
|
|
|
|
# post-accumulate hook runs inside FSDP's foreach_reduce on the autograd
|
|
|
|
|
# thread; a lazy cudaHostAlloc there stalls against the device while
|
|
|
|
|
# peer ranks' NCCL kernels spin waiting for this rank's next collective
|
|
|
|
|
# — a distributed deadlock (deterministic at 78 layers, seen from 30k to
|
|
|
|
|
# 131k tokens). Init-time pinning is the only safe window.
|
|
|
|
|
#
|
|
|
|
|
# Slab-allocate: one pinned block per dtype for accumulators and one for
|
|
|
|
|
# staging, carved into per-param views. ~800 per-param cudaHostAllocs
|
|
|
|
|
# (~1.4 TiB/node) took 10-20 min with large node skew; a handful of huge
|
|
|
|
|
# allocations pins the same bytes in well under a minute.
|
|
|
|
|
dtensor_params = [p for p in params.values() if isinstance(p.data, DTensor)]
|
|
|
|
|
ALIGN = 256 # bytes; keeps carved views DMA-friendly
|
|
|
|
|
acc_slab_numel: dict[torch.dtype, int] = {}
|
|
|
|
|
stage_slab_numel: dict[torch.dtype, int] = {}
|
|
|
|
|
offsets: dict[int, tuple[torch.dtype, int, torch.dtype, int, int]] = {}
|
|
|
|
|
for param in dtensor_params:
|
|
|
|
|
local = param.data.to_local()
|
|
|
|
|
acc_dtype = self._cpu_dtype or local.dtype
|
|
|
|
|
stage_dtype = local.dtype if preserve_staging_dtype else acc_dtype
|
|
|
|
|
acc_align = max(1, ALIGN // torch.empty((), dtype=acc_dtype).element_size())
|
|
|
|
|
stage_align = max(1, ALIGN // torch.empty((), dtype=stage_dtype).element_size())
|
|
|
|
|
acc_start = acc_slab_numel.get(acc_dtype, 0)
|
|
|
|
|
stage_start = stage_slab_numel.get(stage_dtype, 0)
|
|
|
|
|
offsets[id(param)] = (acc_dtype, acc_start, stage_dtype, stage_start, local.numel())
|
|
|
|
|
acc_slab_numel[acc_dtype] = acc_start + ((local.numel() + acc_align - 1) // acc_align * acc_align)
|
|
|
|
|
stage_slab_numel[stage_dtype] = stage_start + (
|
|
|
|
|
(local.numel() + stage_align - 1) // stage_align * stage_align
|
|
|
|
|
)
|
|
|
|
|
acc_slabs = {
|
|
|
|
|
dtype: torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True)
|
|
|
|
|
for dtype, numel in acc_slab_numel.items()
|
|
|
|
|
}
|
|
|
|
|
stage_slabs = {
|
|
|
|
|
dtype: torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True)
|
|
|
|
|
for dtype, numel in stage_slab_numel.items()
|
|
|
|
|
}
|
|
|
|
|
for param in dtensor_params:
|
|
|
|
|
data = param.data
|
|
|
|
|
local = data.to_local()
|
|
|
|
|
acc_dtype, acc_start, stage_dtype, stage_start, numel = offsets[id(param)]
|
|
|
|
|
accumulator = acc_slabs[acc_dtype].narrow(0, acc_start, numel).view(local.shape)
|
|
|
|
|
staging = stage_slabs[stage_dtype].narrow(0, stage_start, numel).view(local.shape)
|
|
|
|
|
template = copy.copy(data.detach())
|
|
|
|
|
template._local_tensor = accumulator
|
|
|
|
|
self._buffers[id(param)] = _CPUGradientBuffer(template, accumulator, staging=staging)
|
|
|
|
|
preallocated = sum(s.nbytes for s in acc_slabs.values()) + sum(s.nbytes for s in stage_slabs.values())
|
|
|
|
|
self._hook_handles = [param.register_post_accumulate_grad_hook(self._offload_hook) for param in params.values()]
|
|
|
|
|
self._worker = threading.Thread(target=self._copy_worker, name="grad-offload", daemon=True)
|
|
|
|
|
self._worker.start()
|
|
|
|
|
get_logger().info(
|
|
|
|
|
"Gradient CPU offload uses FSDP sharded-parameter post-accumulate hooks "
|
|
|
|
|
f"({preallocated / 1024**3:.2f} GiB pinned accumulator+staging preallocated)"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def _copy_worker(self) -> None:
|
|
|
|
|
try:
|
|
|
|
|
self._copy_worker_loop()
|
|
|
|
|
except BaseException as error:
|
|
|
|
|
with self._condition:
|
|
|
|
|
self._worker_error = error
|
|
|
|
|
self._condition.notify_all()
|
|
|
|
|
|
|
|
|
|
def _copy_worker_loop(self) -> None:
|
|
|
|
|
while True:
|
|
|
|
|
task = self._tasks.get()
|
|
|
|
|
if task is None:
|
|
|
|
|
return
|
|
|
|
|
if isinstance(task, _OptimizerChunkTask):
|
|
|
|
|
self._run_optimizer_chunk(task.chunk_idx)
|
|
|
|
|
continue
|
|
|
|
|
task.event.synchronize()
|
|
|
|
|
for param_id, buffer, accumulate, copied_to_staging in task.buffers:
|
|
|
|
|
assert buffer.staging is not None
|
|
|
|
|
if task.final_backward and not accumulate and copied_to_staging:
|
|
|
|
|
buffer.staging_holds_final = True
|
|
|
|
|
elif accumulate:
|
|
|
|
|
if buffer.accumulator.dtype == torch.float32 and buffer.staging.dtype == torch.bfloat16:
|
|
|
|
|
native_add_bfloat16_(buffer.accumulator, buffer.staging)
|
|
|
|
|
else:
|
|
|
|
|
buffer.accumulator.add_(buffer.staging)
|
|
|
|
|
buffer.staging_holds_final = False
|
|
|
|
|
elif copied_to_staging:
|
|
|
|
|
buffer.accumulator.copy_(buffer.staging)
|
|
|
|
|
buffer.staging_holds_final = False
|
|
|
|
|
with self._condition:
|
|
|
|
|
buffer.initialized = True
|
|
|
|
|
buffer.pending = False
|
|
|
|
|
self._condition.notify_all()
|
|
|
|
|
if task.final_backward:
|
|
|
|
|
self._mark_final_param_ready(param_id)
|
|
|
|
|
|
|
|
|
|
def _raise_worker_error(self) -> None:
|
|
|
|
|
if self._worker_error is not None:
|
|
|
|
|
raise RuntimeError("Gradient offload worker failed") from self._worker_error
|
|
|
|
|
|
|
|
|
|
def _mark_final_param_ready(self, param_id: int) -> None:
|
|
|
|
|
chunk_idx = self._chunk_by_param_id[param_id]
|
|
|
|
|
should_run = False
|
|
|
|
|
with self._condition:
|
|
|
|
|
pending = self._pending_chunk_param_ids[chunk_idx]
|
|
|
|
|
pending.discard(param_id)
|
|
|
|
|
if not pending and chunk_idx not in self._scheduled_chunks:
|
|
|
|
|
self._scheduled_chunks.add(chunk_idx)
|
|
|
|
|
should_run = True
|
|
|
|
|
if should_run:
|
|
|
|
|
self._run_optimizer_chunk(chunk_idx)
|
|
|
|
|
|
|
|
|
|
def _run_optimizer_chunk(self, chunk_idx: int) -> None:
|
|
|
|
|
if self._chunk_ready_callback is None:
|
|
|
|
|
return
|
|
|
|
|
self._chunk_ready_callback(chunk_idx)
|
|
|
|
|
with self._condition:
|
|
|
|
|
self._completed_chunks += 1
|
|
|
|
|
self._condition.notify_all()
|
|
|
|
|
|
|
|
|
|
def begin_step(self, gradient_scale: float, *, overlap_optimizer: bool) -> None:
|
|
|
|
|
self.wait()
|
|
|
|
|
with self._condition:
|
|
|
|
|
self._raise_worker_error()
|
|
|
|
|
self._gradient_scale = gradient_scale
|
|
|
|
|
self._overlap_optimizer = overlap_optimizer and self._chunk_ready_callback is not None
|
|
|
|
|
self._final_backward = False
|
|
|
|
|
self._final_enqueued_param_ids.clear()
|
|
|
|
|
self._pending_chunk_param_ids = []
|
|
|
|
|
self._scheduled_chunks.clear()
|
|
|
|
|
self._completed_chunks = 0
|
|
|
|
|
|
|
|
|
|
def begin_backward(self, *, final_backward: bool) -> None:
|
|
|
|
|
self._final_backward = final_backward
|
|
|
|
|
if final_backward and self._overlap_optimizer:
|
|
|
|
|
with self._condition:
|
|
|
|
|
self._final_enqueued_param_ids.clear()
|
|
|
|
|
self._pending_chunk_param_ids = [set(param_ids) for param_ids in self._chunk_param_ids]
|
|
|
|
|
self._scheduled_chunks.clear()
|
|
|
|
|
self._completed_chunks = 0
|
|
|
|
|
|
|
|
|
|
def _get_buffer(self, param: nn.Parameter, grad: DTensor) -> _CPUGradientBuffer:
|
|
|
|
|
param_id = id(param)
|
|
|
|
|
if param_id not in self._buffers:
|
|
|
|
|
local_grad = grad.to_local()
|
|
|
|
|
accumulator = torch.empty_like(
|
|
|
|
|
local_grad,
|
|
|
|
|
dtype=self._cpu_dtype or local_grad.dtype,
|
|
|
|
|
device="cpu",
|
|
|
|
|
pin_memory=True,
|
|
|
|
|
)
|
|
|
|
|
template = copy.copy(grad)
|
|
|
|
|
template._local_tensor = accumulator
|
|
|
|
|
staging = torch.empty_like(
|
|
|
|
|
local_grad,
|
|
|
|
|
dtype=local_grad.dtype if self._preserve_staging_dtype else accumulator.dtype,
|
|
|
|
|
device="cpu",
|
|
|
|
|
pin_memory=True,
|
|
|
|
|
)
|
|
|
|
|
self._buffers[param_id] = _CPUGradientBuffer(template, accumulator, staging)
|
|
|
|
|
return self._buffers[param_id]
|
|
|
|
|
|
|
|
|
|
def _wait_buffer(self, buffer: _CPUGradientBuffer) -> None:
|
|
|
|
|
with self._condition:
|
|
|
|
|
self._condition.wait_for(lambda: self._worker_error is not None or not buffer.pending)
|
|
|
|
|
self._raise_worker_error()
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
|
def _offload_params(
|
|
|
|
|
self,
|
|
|
|
|
params: list[nn.Parameter],
|
|
|
|
|
) -> None:
|
|
|
|
|
copies: list[tuple[int, _CPUGradientBuffer, bool, bool]] = []
|
|
|
|
|
current_stream = torch.cuda.current_stream()
|
|
|
|
|
self._d2h_stream.wait_stream(current_stream)
|
|
|
|
|
with torch.cuda.stream(self._d2h_stream):
|
|
|
|
|
for param in params:
|
|
|
|
|
if id(param) not in self._optimizer_param_ids or param.grad is None:
|
|
|
|
|
continue
|
|
|
|
|
if not isinstance(param.grad, DTensor):
|
|
|
|
|
raise TypeError(f"Expected FSDP2 DTensor gradient, got {type(param.grad)}")
|
|
|
|
|
buffer = self._get_buffer(param, param.grad)
|
|
|
|
|
self._wait_buffer(buffer)
|
|
|
|
|
local_grad = param.grad.to_local()
|
|
|
|
|
accumulate = buffer.initialized
|
|
|
|
|
if buffer.staging is None:
|
|
|
|
|
buffer.staging = torch.empty_like(buffer.accumulator, pin_memory=True)
|
|
|
|
|
copied_to_staging = accumulate or (
|
|
|
|
|
self._preserve_staging_dtype
|
|
|
|
|
and self._final_backward
|
|
|
|
|
and self._overlap_optimizer
|
|
|
|
|
and buffer.staging.dtype != buffer.accumulator.dtype
|
|
|
|
|
)
|
|
|
|
|
destination = buffer.staging if copied_to_staging else buffer.accumulator
|
|
|
|
|
assert destination is not None
|
|
|
|
|
destination.copy_(local_grad, non_blocking=True)
|
|
|
|
|
local_grad.record_stream(self._d2h_stream)
|
|
|
|
|
buffer.pending = True
|
|
|
|
|
param_id = id(param)
|
|
|
|
|
copies.append((param_id, buffer, accumulate, copied_to_staging))
|
|
|
|
|
if self._final_backward and self._overlap_optimizer:
|
|
|
|
|
self._final_enqueued_param_ids.add(param_id)
|
|
|
|
|
param.grad = None
|
|
|
|
|
if copies:
|
|
|
|
|
event = self._d2h_stream.record_event()
|
|
|
|
|
self._tasks.put(_GradientCopyTask(event, copies, self._final_backward and self._overlap_optimizer))
|
|
|
|
|
|
|
|
|
|
def _offload_hook(self, param: torch.Tensor) -> None:
|
|
|
|
|
if not isinstance(param, nn.Parameter):
|
|
|
|
|
raise TypeError(f"Expected parameter in post-accumulate hook, got {type(param)}")
|
|
|
|
|
self._offload_params([param])
|
|
|
|
|
|
|
|
|
|
def finish_backward(self, *, wait_for_copies: bool = True) -> None:
|
|
|
|
|
remaining = [param for chunk in self._chunks for param in chunk if param.grad is not None]
|
|
|
|
|
self._offload_params(remaining)
|
|
|
|
|
if self._final_backward and self._overlap_optimizer:
|
|
|
|
|
missing_param_ids = self._optimizer_param_ids - self._final_enqueued_param_ids
|
|
|
|
|
ready_chunks = []
|
|
|
|
|
with self._condition:
|
|
|
|
|
for param_id in missing_param_ids:
|
|
|
|
|
chunk_idx = self._chunk_by_param_id[param_id]
|
|
|
|
|
pending = self._pending_chunk_param_ids[chunk_idx]
|
|
|
|
|
pending.discard(param_id)
|
|
|
|
|
if not pending and chunk_idx not in self._scheduled_chunks:
|
|
|
|
|
self._scheduled_chunks.add(chunk_idx)
|
|
|
|
|
ready_chunks.append(chunk_idx)
|
|
|
|
|
for chunk_idx in ready_chunks:
|
|
|
|
|
self._tasks.put(_OptimizerChunkTask(chunk_idx))
|
|
|
|
|
if wait_for_copies:
|
|
|
|
|
self.wait()
|
|
|
|
|
if wait_for_copies:
|
|
|
|
|
allocated = sum(
|
|
|
|
|
buffer.accumulator.nbytes + (buffer.staging.nbytes if buffer.staging is not None else 0)
|
|
|
|
|
for buffer in self._buffers.values()
|
|
|
|
|
)
|
|
|
|
|
if allocated != self._logged_cpu_allocation:
|
|
|
|
|
get_logger().info(f"Gradient CPU offload allocated {allocated / 1024**3:.2f} GiB pinned RAM")
|
|
|
|
|
self._logged_cpu_allocation = allocated
|
|
|
|
|
|
|
|
|
|
def wait(self) -> None:
|
|
|
|
|
with self._condition:
|
|
|
|
|
self._condition.wait_for(
|
|
|
|
|
lambda: self._worker_error is not None or not any(buffer.pending for buffer in self._buffers.values())
|
|
|
|
|
)
|
|
|
|
|
self._raise_worker_error()
|
|
|
|
|
|
|
|
|
|
def wait_for_optimizer(self) -> None:
|
|
|
|
|
if not self._overlap_optimizer:
|
|
|
|
|
return
|
|
|
|
|
with self._condition:
|
|
|
|
|
self._condition.wait_for(
|
|
|
|
|
lambda: self._worker_error is not None or self._completed_chunks == len(self._chunks)
|
|
|
|
|
)
|
|
|
|
|
self._raise_worker_error()
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def optimizer_overlapped(self) -> bool:
|
|
|
|
|
return self._overlap_optimizer
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def gradient_scale(self) -> float:
|
|
|
|
|
return self._gradient_scale
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
|
def scale_(self, factor: float) -> None:
|
|
|
|
|
self.wait()
|
|
|
|
|
self._gradient_scale *= factor
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
|
def clip_grad_norm_(self, max_norm: float) -> torch.Tensor:
|
|
|
|
|
if self._overlap_optimizer:
|
|
|
|
|
raise RuntimeError("Gradient clipping cannot run after optimizer-in-backward has started")
|
|
|
|
|
self.wait()
|
|
|
|
|
local_squared_norm = sum(
|
|
|
|
|
torch.linalg.vector_norm(buffer.accumulator, dtype=torch.float32).square().item()
|
|
|
|
|
for buffer in self._buffers.values()
|
|
|
|
|
if buffer.initialized
|
|
|
|
|
)
|
|
|
|
|
local_squared_norm *= self._gradient_scale**2
|
|
|
|
|
total_norm = torch.tensor(local_squared_norm, dtype=torch.float32, device="cuda")
|
|
|
|
|
dist.all_reduce(total_norm, op=dist.ReduceOp.SUM)
|
|
|
|
|
total_norm.div_(self._dp_replicate).sqrt_()
|
|
|
|
|
clip_coefficient = torch.clamp(max_norm / (total_norm + 1e-6), max=1.0).item()
|
|
|
|
|
self._gradient_scale *= clip_coefficient
|
|
|
|
|
return total_norm
|
|
|
|
|
|
|
|
|
|
def load_cpu_chunk(
|
|
|
|
|
self,
|
|
|
|
|
chunk_idx: int,
|
|
|
|
|
target_params: list[nn.Parameter],
|
|
|
|
|
*,
|
|
|
|
|
wait: bool = True,
|
|
|
|
|
apply_scale: bool = True,
|
|
|
|
|
allow_staging_gradient: bool = False,
|
|
|
|
|
assign_grad: bool = True,
|
|
|
|
|
) -> list[torch.Tensor | None]:
|
|
|
|
|
if wait:
|
|
|
|
|
self.wait()
|
|
|
|
|
source_params = self._chunks[chunk_idx]
|
|
|
|
|
if len(source_params) != len(target_params):
|
|
|
|
|
raise ValueError("Gradient source and target chunks must have the same size")
|
|
|
|
|
gradients: list[torch.Tensor | None] = []
|
|
|
|
|
for source_param, target_param in zip(source_params, target_params):
|
|
|
|
|
buffer = self._buffers.get(id(source_param))
|
|
|
|
|
if buffer is None or not buffer.initialized:
|
|
|
|
|
gradients.append(None)
|
|
|
|
|
if assign_grad:
|
|
|
|
|
target_param.grad = None
|
|
|
|
|
continue
|
|
|
|
|
grad = (
|
|
|
|
|
buffer.staging
|
|
|
|
|
if allow_staging_gradient and buffer.staging_holds_final and buffer.staging is not None
|
|
|
|
|
else buffer.accumulator.float()
|
|
|
|
|
)
|
|
|
|
|
if apply_scale and self._gradient_scale != 1.0:
|
|
|
|
|
grad.mul_(self._gradient_scale)
|
|
|
|
|
gradients.append(grad)
|
|
|
|
|
if assign_grad:
|
|
|
|
|
target_param.grad = grad
|
|
|
|
|
return gradients
|
|
|
|
|
|
|
|
|
|
def release_chunk(self, chunk_idx: int, target_params: list[nn.Parameter] | None = None) -> None:
|
|
|
|
|
for param in self._chunks[chunk_idx]:
|
|
|
|
|
param.grad = None
|
|
|
|
|
if target_params is not None:
|
|
|
|
|
for param in target_params:
|
|
|
|
|
param.grad = None
|
|
|
|
|
|
|
|
|
|
def zero_grad(self) -> None:
|
|
|
|
|
self.wait()
|
|
|
|
|
for buffer in self._buffers.values():
|
|
|
|
|
buffer.initialized = False
|
|
|
|
|
buffer.staging_holds_final = False
|
|
|
|
|
self._gradient_scale = 1.0
|
|
|
|
|
|
|
|
|
|
def close(self) -> None:
|
|
|
|
|
if self._closed:
|
|
|
|
|
return
|
|
|
|
|
self.wait_for_optimizer()
|
|
|
|
|
self.wait()
|
|
|
|
|
for handle in self._hook_handles:
|
|
|
|
|
handle.remove()
|
|
|
|
|
self._tasks.put(None)
|
|
|
|
|
self._worker.join()
|
|
|
|
|
self._closed = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
"""Native full-offload pipeline with pageable state and bounded pinned transfer buffers."""
|
|
|
|
|
"""Full-offload gradient pipeline with pageable FP32 accumulators and bounded pinned transfer buffers."""
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
@@ -488,8 +92,6 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
):
|
|
|
|
|
self._chunks = chunks
|
|
|
|
|
self._dp_replicate = dp_replicate
|
|
|
|
|
self._cpu_dtype = torch.float32
|
|
|
|
|
self._preserve_staging_dtype = False
|
|
|
|
|
self._chunk_ready_callback = chunk_ready_callback
|
|
|
|
|
self._timeout_seconds = timeout_seconds
|
|
|
|
|
# Per-step wall-time accumulators; each key is written by exactly one pipeline thread.
|
|
|
|
@@ -512,7 +114,7 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
self._compute_dtypes = compute_dtypes
|
|
|
|
|
dtensor_params = [param for param in params.values() if isinstance(param.data, DTensor)]
|
|
|
|
|
if len(dtensor_params) != len(params):
|
|
|
|
|
raise TypeError("Bounded gradient offload requires FSDP2 DTensor parameters")
|
|
|
|
|
raise TypeError("Gradient offload requires FSDP2 DTensor parameters")
|
|
|
|
|
|
|
|
|
|
alignment = 256 // torch.empty((), dtype=torch.float32).element_size()
|
|
|
|
|
offsets: dict[int, int] = {}
|
|
|
|
@@ -566,7 +168,7 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
self._transfer_requests: queue.SimpleQueue[_GradientTransferRequest | _BackwardBoundaryTask | None] = (
|
|
|
|
|
queue.SimpleQueue()
|
|
|
|
|
)
|
|
|
|
|
self._tasks: queue.SimpleQueue[_BoundedGradientCopyTask | _BackwardBoundaryTask | None] = queue.SimpleQueue()
|
|
|
|
|
self._tasks: queue.SimpleQueue[_GradientCopyTask | _BackwardBoundaryTask | None] = queue.SimpleQueue()
|
|
|
|
|
self._release_tasks: queue.SimpleQueue[_PinnedTransferSlot | None] = queue.SimpleQueue()
|
|
|
|
|
self._condition = threading.Condition()
|
|
|
|
|
self._gradient_scale = 1.0
|
|
|
|
@@ -651,7 +253,7 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
def _total_free_slot_count(
|
|
|
|
|
slots_by_dtype: dict[torch.dtype, dict[str, queue.Queue[_PinnedTransferSlot]]],
|
|
|
|
|
) -> int:
|
|
|
|
|
return sum(BoundedGradientOffloadManager._free_slot_count(slots) for slots in slots_by_dtype.values())
|
|
|
|
|
return sum(GradientOffloadManager._free_slot_count(slots) for slots in slots_by_dtype.values())
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _total_slot_count(slots_by_dtype: dict[torch.dtype, list[_PinnedTransferSlot]]) -> int:
|
|
|
|
@@ -750,10 +352,10 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
destination.copy_(task.local_grad, non_blocking=True)
|
|
|
|
|
task.local_grad.record_stream(self._d2h_stream)
|
|
|
|
|
slot.event.record(self._d2h_stream)
|
|
|
|
|
self._tasks.put(_BoundedGradientCopyTask(task, slot))
|
|
|
|
|
self._tasks.put(_GradientCopyTask(task, slot))
|
|
|
|
|
|
|
|
|
|
def _copy_worker_loop(self) -> None:
|
|
|
|
|
deferred: _BoundedGradientCopyTask | _BackwardBoundaryTask | None = None
|
|
|
|
|
deferred: _GradientCopyTask | _BackwardBoundaryTask | None = None
|
|
|
|
|
stop_after_batch = False
|
|
|
|
|
while True:
|
|
|
|
|
task = deferred if deferred is not None else self._tasks.get()
|
|
|
|
@@ -995,6 +597,46 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
if self._overlap_optimizer:
|
|
|
|
|
self._wait_for(lambda: self._completed_chunks == len(self._chunks), "CPU optimizer chunks")
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def optimizer_overlapped(self) -> bool:
|
|
|
|
|
return self._overlap_optimizer
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def gradient_scale(self) -> float:
|
|
|
|
|
return self._gradient_scale
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
|
def scale_(self, factor: float) -> None:
|
|
|
|
|
self.wait()
|
|
|
|
|
self._gradient_scale *= factor
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
|
def clip_grad_norm_(self, max_norm: float) -> torch.Tensor:
|
|
|
|
|
if self._overlap_optimizer:
|
|
|
|
|
raise RuntimeError("Gradient clipping cannot run after optimizer-in-backward has started")
|
|
|
|
|
self.wait()
|
|
|
|
|
local_squared_norm = sum(
|
|
|
|
|
torch.linalg.vector_norm(buffer.accumulator, dtype=torch.float32).square().item()
|
|
|
|
|
for buffer in self._buffers.values()
|
|
|
|
|
if buffer.initialized
|
|
|
|
|
)
|
|
|
|
|
local_squared_norm *= self._gradient_scale**2
|
|
|
|
|
total_norm = torch.tensor(local_squared_norm, dtype=torch.float32, device="cuda")
|
|
|
|
|
dist.all_reduce(total_norm, op=dist.ReduceOp.SUM)
|
|
|
|
|
total_norm.div_(self._dp_replicate).sqrt_()
|
|
|
|
|
clip_coefficient = torch.clamp(max_norm / (total_norm + 1e-6), max=1.0).item()
|
|
|
|
|
self._gradient_scale *= clip_coefficient
|
|
|
|
|
return total_norm
|
|
|
|
|
|
|
|
|
|
def load_cpu_chunk(self, chunk_idx: int, *, wait: bool = True) -> list[torch.Tensor | None]:
|
|
|
|
|
if wait:
|
|
|
|
|
self.wait()
|
|
|
|
|
gradients: list[torch.Tensor | None] = []
|
|
|
|
|
for param in self._chunks[chunk_idx]:
|
|
|
|
|
buffer = self._buffers[id(param)]
|
|
|
|
|
gradients.append(buffer.accumulator if buffer.initialized else None)
|
|
|
|
|
return gradients
|
|
|
|
|
|
|
|
|
|
def acquire_output_chunk(self, chunk_idx: int) -> tuple[list[_PinnedTransferSlot], list[torch.Tensor]]:
|
|
|
|
|
chunk_numel: dict[torch.dtype, int] = defaultdict(int)
|
|
|
|
|
for param in self._chunks[chunk_idx]:
|
|
|
|
@@ -1032,7 +674,6 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
|
|
|
|
self.wait()
|
|
|
|
|
for buffer in self._buffers.values():
|
|
|
|
|
buffer.initialized = False
|
|
|
|
|
buffer.staging_holds_final = False
|
|
|
|
|
buffer.pending_generations.clear()
|
|
|
|
|
self._gradient_scale = 1.0
|
|
|
|
|
|
|
|
|
@@ -1088,44 +729,23 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
|
|
|
|
self._h2d_stream = torch.cuda.Stream()
|
|
|
|
|
self._d2h_stream = torch.cuda.Stream()
|
|
|
|
|
self._cuda_device = torch.cuda.current_device()
|
|
|
|
|
self._all_param_groups = self.optimizer.param_groups
|
|
|
|
|
self._chunk_groups = self._build_chunk_groups()
|
|
|
|
|
self._native_cpu_adamw = isinstance(optimizer, AdamW) and offload_config.cpu_optimizer_backend == "native"
|
|
|
|
|
self._native_cpu_sign_sgd = isinstance(optimizer, SignSGD) and offload_config.cpu_optimizer_backend == "native"
|
|
|
|
|
self._native_cpu_optimizer = self._native_cpu_adamw or self._native_cpu_sign_sgd
|
|
|
|
|
self._fused_cpu_adamw = (
|
|
|
|
|
isinstance(optimizer, AdamW)
|
|
|
|
|
and all(group["fused"] for group in optimizer.param_groups)
|
|
|
|
|
and not self._native_cpu_adamw
|
|
|
|
|
self._adamw = isinstance(optimizer, AdamW)
|
|
|
|
|
get_logger().info(
|
|
|
|
|
f"Loading native read-only-gradient multi-tensor CPU {'AdamW' if self._adamw else 'SignSGD'} kernel"
|
|
|
|
|
)
|
|
|
|
|
load_cpu_adamw_kernel()
|
|
|
|
|
self._gradient_manager = GradientOffloadManager(
|
|
|
|
|
[[master_weights[id(param)].model_param for param in chunk] for chunk in self._chunks],
|
|
|
|
|
dp_replicate,
|
|
|
|
|
buffer_count=self._TRANSFER_BUFFER_COUNT,
|
|
|
|
|
max_inflight_backwards=self._MAX_INFLIGHT_BACKWARDS,
|
|
|
|
|
timeout_seconds=self._TIMEOUT_SECONDS,
|
|
|
|
|
target_chunk_numel=self._TARGET_CPU_CHUNK_NUMEL,
|
|
|
|
|
chunk_ready_callback=self._step_cpu_chunk,
|
|
|
|
|
gradient_dtypes={id(master.model_param): master.gradient_dtype for master in master_weights.values()},
|
|
|
|
|
compute_dtypes={id(master.model_param): master.compute_dtype for master in master_weights.values()},
|
|
|
|
|
)
|
|
|
|
|
self._adamw_grad_scale = torch.ones((), dtype=torch.float32) if self._fused_cpu_adamw else None
|
|
|
|
|
self._adamw_found_inf = torch.zeros((), dtype=torch.float32) if self._fused_cpu_adamw else None
|
|
|
|
|
if self._native_cpu_optimizer:
|
|
|
|
|
kernel_name = "AdamW" if self._native_cpu_adamw else "SignSGD"
|
|
|
|
|
get_logger().info(f"Loading native read-only-gradient multi-tensor CPU {kernel_name} kernel")
|
|
|
|
|
load_cpu_adamw_kernel()
|
|
|
|
|
gradient_chunks = [[master_weights[id(param)].model_param for param in chunk] for chunk in self._chunks]
|
|
|
|
|
if self._native_cpu_optimizer:
|
|
|
|
|
gradient_dtypes = {id(master.model_param): master.gradient_dtype for master in master_weights.values()}
|
|
|
|
|
compute_dtypes = {id(master.model_param): master.compute_dtype for master in master_weights.values()}
|
|
|
|
|
self._gradient_manager = BoundedGradientOffloadManager(
|
|
|
|
|
gradient_chunks,
|
|
|
|
|
dp_replicate,
|
|
|
|
|
buffer_count=self._TRANSFER_BUFFER_COUNT,
|
|
|
|
|
max_inflight_backwards=self._MAX_INFLIGHT_BACKWARDS,
|
|
|
|
|
timeout_seconds=self._TIMEOUT_SECONDS,
|
|
|
|
|
target_chunk_numel=self._TARGET_CPU_CHUNK_NUMEL,
|
|
|
|
|
chunk_ready_callback=self._step_cpu_chunk,
|
|
|
|
|
gradient_dtypes=gradient_dtypes,
|
|
|
|
|
compute_dtypes=compute_dtypes,
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
self._gradient_manager = GradientOffloadManager(
|
|
|
|
|
gradient_chunks,
|
|
|
|
|
dp_replicate,
|
|
|
|
|
cpu_dtype=torch.float32,
|
|
|
|
|
chunk_ready_callback=self._step_cpu_chunk,
|
|
|
|
|
)
|
|
|
|
|
self._initialize_cpu_optimizer_state()
|
|
|
|
|
|
|
|
|
|
def _build_chunks(self) -> list[list[nn.Parameter]]:
|
|
|
|
@@ -1162,41 +782,26 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
|
|
|
|
self,
|
|
|
|
|
chunk_idx: int,
|
|
|
|
|
stream: torch.cuda.Stream,
|
|
|
|
|
sources: list[torch.Tensor] | None = None,
|
|
|
|
|
sources: list[torch.Tensor],
|
|
|
|
|
) -> None:
|
|
|
|
|
assert self._master_weights is not None
|
|
|
|
|
if sources is not None and len(sources) != len(self._chunks[chunk_idx]):
|
|
|
|
|
raise ValueError("Compute-weight sources must match the optimizer chunk")
|
|
|
|
|
with torch.cuda.stream(stream):
|
|
|
|
|
for param_idx, param in enumerate(self._chunks[chunk_idx]):
|
|
|
|
|
master = self._master_weights[id(param)]
|
|
|
|
|
if not isinstance(master.model_param, DTensor):
|
|
|
|
|
raise TypeError(f"Expected FSDP2 DTensor parameter, got {type(master.model_param)}")
|
|
|
|
|
source = sources[param_idx] if sources is not None else master.cpu_tensor
|
|
|
|
|
source = sources[param_idx]
|
|
|
|
|
local_param = master.model_param.to_local()
|
|
|
|
|
if local_param.dtype != master.compute_dtype:
|
|
|
|
|
raise TypeError(
|
|
|
|
|
f"Full-offload compute dtype changed: expected {master.compute_dtype}, got {local_param.dtype}"
|
|
|
|
|
)
|
|
|
|
|
if sources is not None and source.dtype != master.compute_dtype:
|
|
|
|
|
if source.dtype != master.compute_dtype:
|
|
|
|
|
raise TypeError(
|
|
|
|
|
f"Full-offload H2D source dtype mismatch: expected {master.compute_dtype}, got {source.dtype}"
|
|
|
|
|
)
|
|
|
|
|
local_param.copy_(source, non_blocking=True)
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
|
def _step_chunk(self, chunk_idx: int):
|
|
|
|
|
"""Run optimizer.step() for a single chunk by temporarily swapping param_groups."""
|
|
|
|
|
chunk_groups = []
|
|
|
|
|
for group, params in self._chunk_groups[chunk_idx]:
|
|
|
|
|
new_group = {k: v for k, v in group.items() if k != "params"}
|
|
|
|
|
new_group["params"] = params
|
|
|
|
|
chunk_groups.append(new_group)
|
|
|
|
|
self.optimizer.param_groups = chunk_groups
|
|
|
|
|
result = self.optimizer.step()
|
|
|
|
|
self.optimizer.param_groups = self._all_param_groups
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
def _step_native_cpu_adamw_chunk(
|
|
|
|
|
self,
|
|
|
|
|
chunk_idx: int,
|
|
|
|
@@ -1274,57 +879,23 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
|
|
|
|
gradients: list[torch.Tensor | None],
|
|
|
|
|
compute_params: list[torch.Tensor],
|
|
|
|
|
) -> None:
|
|
|
|
|
if self._native_cpu_adamw:
|
|
|
|
|
if self._adamw:
|
|
|
|
|
self._step_native_cpu_adamw_chunk(chunk_idx, gradients, compute_params)
|
|
|
|
|
else:
|
|
|
|
|
self._step_native_cpu_sign_sgd_chunk(chunk_idx, gradients, compute_params)
|
|
|
|
|
|
|
|
|
|
def _step_cpu_chunk(self, chunk_idx: int) -> None:
|
|
|
|
|
assert self._gradient_manager is not None
|
|
|
|
|
self._prepare_fused_cpu_adamw()
|
|
|
|
|
gradients = self._gradient_manager.load_cpu_chunk(
|
|
|
|
|
chunk_idx,
|
|
|
|
|
self._chunks[chunk_idx],
|
|
|
|
|
wait=False,
|
|
|
|
|
apply_scale=not (self._native_cpu_optimizer or self._fused_cpu_adamw),
|
|
|
|
|
assign_grad=not self._native_cpu_optimizer,
|
|
|
|
|
)
|
|
|
|
|
if self._native_cpu_optimizer:
|
|
|
|
|
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
|
|
|
|
raise TypeError("Native CPU optimizers require bounded gradient offload")
|
|
|
|
|
timings = self._gradient_manager._timings
|
|
|
|
|
acquire_start = time.perf_counter()
|
|
|
|
|
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(chunk_idx)
|
|
|
|
|
kernel_start = time.perf_counter()
|
|
|
|
|
timings["output_slot_wait"] = timings.get("output_slot_wait", 0.0) + kernel_start - acquire_start
|
|
|
|
|
self._step_native_cpu_chunk(chunk_idx, gradients, compute_params)
|
|
|
|
|
timings["optimizer_kernel"] = timings.get("optimizer_kernel", 0.0) + time.perf_counter() - kernel_start
|
|
|
|
|
else:
|
|
|
|
|
self._step_chunk(chunk_idx)
|
|
|
|
|
self._gradient_manager.release_chunk(chunk_idx, self._chunks[chunk_idx])
|
|
|
|
|
gradients = self._gradient_manager.load_cpu_chunk(chunk_idx, wait=False)
|
|
|
|
|
timings = self._gradient_manager._timings
|
|
|
|
|
acquire_start = time.perf_counter()
|
|
|
|
|
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(chunk_idx)
|
|
|
|
|
kernel_start = time.perf_counter()
|
|
|
|
|
timings["output_slot_wait"] = timings.get("output_slot_wait", 0.0) + kernel_start - acquire_start
|
|
|
|
|
self._step_native_cpu_chunk(chunk_idx, gradients, compute_params)
|
|
|
|
|
timings["optimizer_kernel"] = timings.get("optimizer_kernel", 0.0) + time.perf_counter() - kernel_start
|
|
|
|
|
with torch.cuda.device(self._cuda_device):
|
|
|
|
|
self._update_compute_weights(
|
|
|
|
|
chunk_idx,
|
|
|
|
|
self._h2d_stream,
|
|
|
|
|
compute_params if self._native_cpu_optimizer else None,
|
|
|
|
|
)
|
|
|
|
|
if self._native_cpu_optimizer:
|
|
|
|
|
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
|
|
|
|
|
|
|
|
|
def _prepare_fused_cpu_adamw(self) -> None:
|
|
|
|
|
if not self._fused_cpu_adamw:
|
|
|
|
|
return
|
|
|
|
|
assert self._gradient_manager is not None
|
|
|
|
|
assert self._adamw_grad_scale is not None
|
|
|
|
|
assert self._adamw_found_inf is not None
|
|
|
|
|
self._adamw_grad_scale.fill_(1.0 / self._gradient_manager.gradient_scale)
|
|
|
|
|
self.optimizer.grad_scale = self._adamw_grad_scale
|
|
|
|
|
self.optimizer.found_inf = self._adamw_found_inf
|
|
|
|
|
|
|
|
|
|
def _record_native_optimizer_step(self) -> None:
|
|
|
|
|
if self._native_cpu_optimizer:
|
|
|
|
|
# LRScheduler normally sets this marker through its optimizer.step wrapper.
|
|
|
|
|
self.optimizer._opt_called = True
|
|
|
|
|
self._update_compute_weights(chunk_idx, self._h2d_stream, compute_params)
|
|
|
|
|
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
|
|
|
|
|
|
|
|
|
def step(self, closure=None):
|
|
|
|
|
if closure is not None:
|
|
|
|
@@ -1333,44 +904,25 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
|
|
|
|
drain_start = time.perf_counter()
|
|
|
|
|
self._gradient_manager.wait_for_optimizer()
|
|
|
|
|
torch.cuda.current_stream().wait_stream(self._h2d_stream)
|
|
|
|
|
if isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
|
|
|
|
timings = self._gradient_manager.consume_timings()
|
|
|
|
|
timings["drain"] = time.perf_counter() - drain_start
|
|
|
|
|
get_logger().debug(
|
|
|
|
|
"Offload pipeline: " + " ".join(f"{key}={value:.3f}s" for key, value in sorted(timings.items()))
|
|
|
|
|
)
|
|
|
|
|
self._record_native_optimizer_step()
|
|
|
|
|
timings = self._gradient_manager.consume_timings()
|
|
|
|
|
timings["drain"] = time.perf_counter() - drain_start
|
|
|
|
|
get_logger().debug(
|
|
|
|
|
"Offload pipeline: " + " ".join(f"{key}={value:.3f}s" for key, value in sorted(timings.items()))
|
|
|
|
|
)
|
|
|
|
|
# LRScheduler normally sets this marker through its optimizer.step wrapper.
|
|
|
|
|
self.optimizer._opt_called = True
|
|
|
|
|
self._initialized = True
|
|
|
|
|
return
|
|
|
|
|
# Synchronous path (validation steps and checkpoint boundaries).
|
|
|
|
|
self._prepare_fused_cpu_adamw()
|
|
|
|
|
gradients_by_chunk = []
|
|
|
|
|
gradients_by_chunk = [self._gradient_manager.load_cpu_chunk(i) for i in range(len(self._chunks))]
|
|
|
|
|
for i in range(len(self._chunks)):
|
|
|
|
|
gradients_by_chunk.append(
|
|
|
|
|
self._gradient_manager.load_cpu_chunk(
|
|
|
|
|
i,
|
|
|
|
|
self._chunks[i],
|
|
|
|
|
apply_scale=not (self._native_cpu_optimizer or self._fused_cpu_adamw),
|
|
|
|
|
assign_grad=not self._native_cpu_optimizer,
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
if self._native_cpu_optimizer:
|
|
|
|
|
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
|
|
|
|
raise TypeError("Native CPU optimizers require bounded gradient offload")
|
|
|
|
|
for i in range(len(self._chunks)):
|
|
|
|
|
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
|
|
|
|
self._step_native_cpu_chunk(i, gradients_by_chunk[i], compute_params)
|
|
|
|
|
self._gradient_manager.release_chunk(i, self._chunks[i])
|
|
|
|
|
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
|
|
|
|
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
|
|
|
|
else:
|
|
|
|
|
self.optimizer.step()
|
|
|
|
|
for i in range(len(self._chunks)):
|
|
|
|
|
self._gradient_manager.release_chunk(i, self._chunks[i])
|
|
|
|
|
self._update_compute_weights(i, self._h2d_stream)
|
|
|
|
|
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
|
|
|
|
self._step_native_cpu_chunk(i, gradients_by_chunk[i], compute_params)
|
|
|
|
|
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
|
|
|
|
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
|
|
|
|
torch.cuda.current_stream().wait_stream(self._h2d_stream)
|
|
|
|
|
torch.cuda.synchronize()
|
|
|
|
|
self._record_native_optimizer_step()
|
|
|
|
|
self.optimizer._opt_called = True
|
|
|
|
|
self._initialized = True
|
|
|
|
|
|
|
|
|
|
def zero_grad(self, set_to_none: bool = True):
|
|
|
|
@@ -1407,30 +959,6 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
|
|
|
|
return
|
|
|
|
|
if self.optimizer.state:
|
|
|
|
|
return
|
|
|
|
|
if self._native_cpu_adamw:
|
|
|
|
|
self._initialize_native_cpu_adamw_state()
|
|
|
|
|
return
|
|
|
|
|
lrs = []
|
|
|
|
|
for group in self.optimizer.param_groups:
|
|
|
|
|
lrs.append(group["lr"])
|
|
|
|
|
group["lr"] = 0.0
|
|
|
|
|
for param in group["params"]:
|
|
|
|
|
if param.requires_grad:
|
|
|
|
|
param.grad = torch.zeros_like(param)
|
|
|
|
|
self.optimizer.step()
|
|
|
|
|
self.optimizer.zero_grad(set_to_none=True)
|
|
|
|
|
for state in self.optimizer.state.values():
|
|
|
|
|
step = state.get("step")
|
|
|
|
|
if isinstance(step, torch.Tensor):
|
|
|
|
|
step.zero_()
|
|
|
|
|
elif step is not None:
|
|
|
|
|
state["step"] = 0
|
|
|
|
|
for group, lr in zip(self.optimizer.param_groups, lrs):
|
|
|
|
|
group["lr"] = lr
|
|
|
|
|
if "step" in group:
|
|
|
|
|
group["step"] = 0
|
|
|
|
|
|
|
|
|
|
def _initialize_native_cpu_adamw_state(self) -> None:
|
|
|
|
|
alignment = 256 // torch.empty((), dtype=torch.float32).element_size()
|
|
|
|
|
offsets = {}
|
|
|
|
|
slab_numel = 0
|
|
|
|
@@ -1490,22 +1018,15 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
|
|
|
|
@torch.no_grad()
|
|
|
|
|
def finish_checkpoint_load(self) -> None:
|
|
|
|
|
if self._master_weights is not None:
|
|
|
|
|
if self._native_cpu_optimizer:
|
|
|
|
|
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
|
|
|
|
raise TypeError("Native CPU optimizers require bounded gradient offload")
|
|
|
|
|
for i in range(len(self._chunks)):
|
|
|
|
|
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
|
|
|
|
for param, compute_param in zip(self._chunks[i], compute_params):
|
|
|
|
|
compute_param.copy_(self._master_weights[id(param)].cpu_tensor)
|
|
|
|
|
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
|
|
|
|
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
|
|
|
|
else:
|
|
|
|
|
for i in range(len(self._chunks)):
|
|
|
|
|
self._update_compute_weights(i, self._h2d_stream)
|
|
|
|
|
for i in range(len(self._chunks)):
|
|
|
|
|
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
|
|
|
|
for param, compute_param in zip(self._chunks[i], compute_params):
|
|
|
|
|
compute_param.copy_(self._master_weights[id(param)].cpu_tensor)
|
|
|
|
|
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
|
|
|
|
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
|
|
|
|
torch.cuda.current_stream().wait_stream(self._h2d_stream)
|
|
|
|
|
torch.cuda.synchronize()
|
|
|
|
|
if isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
|
|
|
|
self._gradient_manager.wait_for_output_slots()
|
|
|
|
|
self._gradient_manager.wait_for_output_slots()
|
|
|
|
|
self._initialized = True
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
@@ -1570,7 +1091,6 @@ def _create_cpu_master_weights(
|
|
|
|
|
model: nn.Module,
|
|
|
|
|
named_params: list[tuple[str, nn.Parameter]],
|
|
|
|
|
*,
|
|
|
|
|
pin_memory: bool = True,
|
|
|
|
|
dtype_policy: dict[int, tuple[torch.dtype, torch.dtype]] | None = None,
|
|
|
|
|
) -> tuple[list[tuple[str, nn.Parameter]], dict[int, _MasterWeight]]:
|
|
|
|
|
trainable_params = [(name, model_param) for name, model_param in named_params if model_param.requires_grad]
|
|
|
|
@@ -1585,7 +1105,7 @@ def _create_cpu_master_weights(
|
|
|
|
|
offsets[name] = slab_numel
|
|
|
|
|
local_numel = model_param.to_local().numel()
|
|
|
|
|
slab_numel += (local_numel + alignment - 1) // alignment * alignment
|
|
|
|
|
master_slab = torch.empty(slab_numel, dtype=torch.float32, device="cpu", pin_memory=pin_memory)
|
|
|
|
|
master_slab = torch.empty(slab_numel, dtype=torch.float32, device="cpu")
|
|
|
|
|
master_named_params = []
|
|
|
|
|
master_weights = {}
|
|
|
|
|
for name, model_param in trainable_params:
|
|
|
|
@@ -1611,6 +1131,6 @@ def _create_cpu_master_weights(
|
|
|
|
|
master_allocation = sum(master.cpu_tensor.nbytes for master in master_weights.values())
|
|
|
|
|
get_logger().info(
|
|
|
|
|
f"CPU optimizer step allocated {master_allocation / 1024**3:.2f} GiB of "
|
|
|
|
|
f"{'pinned' if pin_memory else 'pageable'} FP32 masters; persistent GPU parameters use configured compute dtypes"
|
|
|
|
|
"pageable FP32 masters; persistent GPU parameters use configured compute dtypes"
|
|
|
|
|
)
|
|
|
|
|
return master_named_params, master_weights
|
|
|
|
|