Compare commits

...
Author SHA1 Message Date
NeoandGitHub 0164aab72c perf(metrics): count attention FLOPs with the real head dim and report SFT MFU per step (#3755)
For discussion: this is the MFU accounting used in the Qwen3-235B
prime-rl vs torchtitan benchmarks (#3753, #3754), so that both stacks
report comparable numbers. Opening it as its own PR so we can decide
whether to adopt it as the trainer's metric.

## What changes

1. **Attention FLOPs use the real head dim.** `PerfCounter` counted
attention as `12 * layers * heads * (hidden_size / heads) * seq`. For
models whose `head_dim` is not `hidden_size / num_attention_heads` that
undercounts: Qwen3-235B-A22B has head_dim 128 but hidden/heads = 64. The
new term is torchtitan's `quadratic_attention_flops_per_token`: `6 *
layers * heads * (qk_head_dim + v_head_dim) * seq`, with the MLA qk/v
head dims when the config has them. Identical to the old value when
head_dim == hidden/heads.
2. **SFT throughput and MFU are per step over the full step wall time**,
including the optimizer step, as torchtitan reports with `log_freq=1`.
Before, they came from a 10-step sliding window over forward/backward
time only. The RL trainer is unchanged and still reports over
forward/backward time.

## Effect

- Qwen3-235B-A22B at seq 8192: 167.3 -> 205.1 GFLOP/token; at 16384:
280.8 GFLOP/token. Logged MFU on such models goes up accordingly, so
dashboards and the benchmark tables in
`benchmarks/results/BENCHMARKS.md` are not directly comparable across
this change.
- Two expected values in `tests/unit/train/test_perf.py` updated
(Qwen3-0.6B: head_dim 128 vs hidden/heads 64; the debug MoE likewise).

## Caveat worth discussing

Both formulas charge dense causal attention. On packed short documents
with varlen attention the executed attention FLOPs are far lower, so
absolute MFU is overstated for both stacks (roughly 2x at seq 16k on the
235B bench). Counting executed FLOPs from the packed sequence lengths
would be a separate change.
2026-10-03 13:26:42 -07:00
faresobeidandGitHub 243cfba0fb chore(trainer): remove torch full-offload backend, fold gradient offload managers (#3781)
Removes the full-offload `cpu_optimizer_backend = "torch"` path and
folds the two gradient offload managers in `trainer/optim/offload.py`
into one.

**Why:** there were two offload pipelines doing the same job. The native
backend covers the same optimizers (AdamW, SignSGD). `test_cpu_adam.py`
already checks native AdamW directly against fused torch AdamW. The
torch backend was only a debug/parity fallback (#3234).

**Changes**
- `GradientOffloadManager` is now the former
`BoundedGradientOffloadManager` (pageable FP32 accumulators, bounded
pinned transfer rings). The base methods it still used
(`optimizer_overlapped`, `gradient_scale`, `scale_`, `clip_grad_norm_`,
`load_cpu_chunk`) are moved into it. The base-only slab-pinned
accumulator/staging pipeline is deleted. `load_cpu_chunk` drops the
scale/assign/staging options that only the torch path used.
`release_chunk` is removed: on the native path it only cleared grads
that were already `None`.
- `FullCPUOffloadOptimizer`: removed the fused/foreach torch-AdamW step
(`_step_chunk`, `_prepare_fused_cpu_adamw`), the torch state warm-up
step, and all native/torch branching.
- `_create_cpu_master_weights`: removed the `pin_memory` option. FP32
masters are always pageable, as they already were on the native path.
- Removed `model.full_offload.cpu_optimizer_backend` from
`OptimizerInBackwardOffloadConfig`, plus its config test and the mention
in `skills/training/start-run/SKILL.md`.

Native AdamW and native SignSGD numerics and pipeline order are
unchanged.

**Breaking:** `model.full_offload.cpu_optimizer_backend` is removed. Any
value, including `"native"`, now fails config validation.

**Validation**
- `ruff check .` and `ruff format --check .`
- `pytest tests/unit/train/test_cpu_adam.py tests/unit/test_configs.py
tests/unit/train/test_state_offload.py -m "not gpu"`: 209 passed. This
includes the 3 `test_cpu_adam.py` tests (C++ extension built on CPU).
- Not run (no GPU on this machine). GPU checks still needed:
- `reverse-text-sft/full-offload-resume` integration test, including the
resume step
- one RL full-offload step each with AdamW and SignSGD: loss matches
main, and the `Offload pipeline` timing logs appear
  - synchronous `step()` path at validation and checkpoint boundaries

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large refactor of full CPU optimizer offload (gradients, stepping,
checkpoint load) with a breaking config removal; native numerics are
claimed unchanged but GPU integration tests are still needed.
> 
> **Overview**
> Removes the debug **Torch** full-offload path and makes **native** CPU
AdamW/SignSGD the only implementation for `model.full_offload`.
> 
> **Breaking:** `model.full_offload.cpu_optimizer_backend` is gone
(including `"native"`). `[model.full_offload]` now only exposes options
like **`numa_bind`**.
> 
> The two gradient offload implementations are collapsed into a single
**`GradientOffloadManager`**: the old slab-pinned accumulator/staging
hook pipeline is deleted; the bounded pinned D2H/H2D ring with pageable
FP32 accumulators becomes the only manager.
**`FullCPUOffloadOptimizer`** no longer branches on backend—no fused
Torch `optimizer.step()` per chunk, no torch state warm-up, and
**`load_cpu_chunk`** is simplified.
> 
> FP32 CPU master weights are always **pageable** (`pin_memory` removed
from `_create_cpu_master_weights`). Docs and the config test for the
torch backend are updated accordingly.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
530cc3c380f44229c16374963a85ccf5bd0371bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 12:58:04 -07:00
8 changed files with 118 additions and 614 deletions
@@ -61,9 +61,6 @@ class OptimizerInBackwardOffloadConfig(BaseConfig):
bit-faithful to that path, disable offloading.
"""
cpu_optimizer_backend: Literal["native", "torch"] = "native"
"""CPU optimizer implementation used by full offload (AdamW or SignSGD). ``native`` is the production kernel; ``torch`` is a slower debugging and parity fallback."""
numa_bind: bool = True
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
+1 -1
View File
@@ -31,7 +31,7 @@ SLURM launches write generated scripts and coordination files under `<run_dir>/l
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
halves the host RAM footprint), and disables gradient clipping. Use a
`[model.full_offload]` table only to select the Torch debugging backend or disable NUMA binding.
`[model.full_offload]` table only to disable NUMA binding.
## `rl` — RL training
+1 -6
View File
@@ -71,12 +71,7 @@ def setup_optimizer(
if full_offload_dtype_policy is None:
raise ValueError("CPU optimizer offload requires an explicit per-parameter dtype policy")
optimizer_named_params, master_weights = _create_cpu_master_weights(
model,
named_params,
pin_memory=not (
config.type in ("adamw", "sign_sgd") and full_offload_config.cpu_optimizer_backend == "native"
),
dtype_policy=full_offload_dtype_policy,
model, named_params, dtype_policy=full_offload_dtype_policy
)
optimizer = _create_optimizer(
+98 -578
View File
@@ -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
+12 -4
View File
@@ -179,19 +179,27 @@ class PerfCounter:
if hasattr(model_config, "text_config"):
model_config = model_config.text_config
l, h, q, t = ( # noqa: E741
l, h, t = ( # noqa: E741
model_config.num_hidden_layers,
model_config.num_attention_heads,
model_config.hidden_size // model_config.num_attention_heads,
seq_len,
)
# Reasoning behind the factor of 12 for the self-attention part of the formula:
# Head dims as torchtitan's quadratic_attention_flops_per_token: the real head_dim (e.g. 128 for
# Qwen3-235B, whose hidden_size / num_attention_heads is 64), or the MLA qk / v head dims.
if hasattr(model_config, "qk_head_dim") and hasattr(model_config, "v_head_dim"):
qk_head_dim, v_head_dim = model_config.qk_head_dim, model_config.v_head_dim
else:
qk_head_dim = v_head_dim = (
getattr(model_config, "head_dim", None) or model_config.hidden_size // model_config.num_attention_heads
)
# Reasoning behind the factor of 6 for the self-attention part of the formula:
# 1. each self-attention has 2 matmul in the forward and 4 in the backward (6)
# (q @ K^T over qk_head_dim, then scores @ V over v_head_dim, per head and attended token)
# 2. the flash attention does 1 more matmul recomputation in the backward
# but recomputation should not be counted in calculating MFU (+0)
# 3. each matmul performs 1 multiplication and 1 addition (*2)
# 4. we follow the convention and do not account for sparsity in causal attention
attention_flops = 12 * l * h * q * t
attention_flops = 6 * l * h * (qk_head_dim + v_head_dim) * t
if has_lora_layers(self.model):
# LoRA case:
+5 -3
View File
@@ -556,15 +556,17 @@ def train(config: SFTConfig):
progress.total_tokens += num_tokens
dataset_progress = get_dataset_progress(dataloader)
progress.total_samples = dataset_progress["step"]
# Throughput / MFU per step over the full step wall time, as torchtitan reports them with
# log_freq=1 (tokens since last log / elapsed time), instead of a smoothed sliding window.
step_time = time.perf_counter() - step_start_time
perf_counter = get_perf_counter(model, config.data.seq_len)
perf_counter.count_tokens(num_tokens)
throughput = perf_counter.get_tokens_per_second() or 0
mfu = perf_counter.get_mfu() or 0
throughput = perf_counter.get_step_tokens_per_second(num_tokens, step_time)
mfu = perf_counter.get_step_mfu(num_tokens, step_time)
peak_memory = torch.cuda.max_memory_reserved() / 1024**3 # GiB
max_peak_memory = max(max_peak_memory, peak_memory)
# Log step metrics
step_time = time.perf_counter() - step_start_time
step_message = f"Step {progress.step} | {format_time(step_time):>7} | Loss {batch_loss:.4f}"
if grad_norm is not None:
step_message += f" | Grad. Norm {grad_norm:.4f}"
-18
View File
@@ -356,24 +356,6 @@ def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
assert config.optim.max_norm is None
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
def test_full_optimizer_offload_accepts_debug_backend(config_cls):
config = config_cls.model_validate(
{
"model": {
"optim_cpu_offload": False,
"full_offload": {
"cpu_optimizer_backend": "torch",
},
},
"optim": {"max_norm": None},
}
)
assert config.model.full_offload is not None
assert config.model.full_offload.cpu_optimizer_backend == "torch"
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
@pytest.mark.parametrize("optimizer_type", ["sgd", "muon"])
def test_full_optimizer_offload_requires_supported_optimizer(config_cls, optimizer_type):
+1 -1
View File
@@ -7,7 +7,7 @@ from prime_rl.trainer.perf import PerfCounter
@pytest.mark.parametrize(
"model_name, active_params, flops_per_token",
[("Qwen/Qwen3-0.6B", 595_984_384, 3_928_227_840), ("Jackmin108/debug-moe-0.5B", 256_442_368, 1_689_649_152)],
[("Qwen/Qwen3-0.6B", 595_984_384, 4_280_549_376), ("Jackmin108/debug-moe-0.5B", 256_442_368, 1_840_644_096)],
)
def test_perf_counter(model_name: str, active_params: int, flops_per_token: int):
# This speeds up the model loading as its a fake device