Skip to content

Commit 0f65420

Browse files
xrennvidiaclaudetimmoon10
authored
[Common] Compute the capturable FusedAdam bias corrections once per block (#3872)
* [Common] Compute the capturable FusedAdam bias corrections once per block With capturable=True the step count lives in device memory, so the bias corrections cannot be computed on the host as in the regular kernel. Every thread computed them with two pow() calls, which costs about a fifth of the kernel. Compute them in one thread per block and share them instead; the values are the same. On 8 tensors of 134M fp32 elements the capturable step goes from 7.5 ms to 6.0 ms (regular kernel: 5.4 ms), with bit-identical weights, moments and gradients. This follows #3782, which removed the other two costs of the capturable kernel. Add tests for the paths this touches: capturable against non-capturable on a multi-block tensor over several captured replays, with and without master weights and bias correction, and a step skipped by the grad scaler leaving the parameters and optimizer state untouched. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Xiaowei Ren <xren@nvidia.com> * Tweak comments Co-authored-by: Tim Moon <4406448+timmoon10@users.noreply.github.com> Signed-off-by: Tim Moon <4406448+timmoon10@users.noreply.github.com> --------- Signed-off-by: Xiaowei Ren <xren@nvidia.com> Signed-off-by: Tim Moon <4406448+timmoon10@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Tim Moon <4406448+timmoon10@users.noreply.github.com>
1 parent 277f2ff commit 0f65420

2 files changed

Lines changed: 174 additions & 12 deletions

File tree

‎tests/pytorch/test_fused_optimizer.py‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,148 @@ def backward():
247247
ref_param,
248248
)
249249

250+
@pytest.mark.parametrize("bias_correction", [True, False])
251+
@pytest.mark.parametrize(
252+
"param_dtype,master_weights",
253+
[
254+
(torch.float32, False),
255+
(torch.bfloat16, True),
256+
],
257+
)
258+
def test_capturable_large_parameter_multi_step(
259+
self, param_dtype, master_weights, bias_correction
260+
):
261+
"""Capturable Adam matches the non-capturable kernels on a multi-block tensor.
262+
263+
The capturable kernels read the step count on the device and derive the bias
264+
corrections from it once per CUDA block. Use a tensor that spans many blocks and
265+
is not a multiple of the block or chunk size, and replay several steps so the
266+
corrections are exercised at more than one step count.
267+
"""
268+
if param_dtype == torch.bfloat16 and not is_bf16_available():
269+
pytest.skip("BF16 is not supported")
270+
271+
numel = (1 << 20) + 3
272+
num_replays = 5
273+
init = torch.randn(numel, device="cuda").to(param_dtype)
274+
ref_param = torch.nn.Parameter(init.clone())
275+
tst_param = torch.nn.Parameter(init.clone())
276+
options = dict(self.options, bias_correction=bias_correction)
277+
ref_optim = self.fused_optim(
278+
[ref_param], capturable=False, master_weights=master_weights, **options
279+
)
280+
tst_optim = self.fused_optim(
281+
[tst_param], capturable=True, master_weights=master_weights, **options
282+
)
283+
284+
def set_grads():
285+
# Write in place: the captured graph reads the gradient from a fixed buffer.
286+
grad = torch.randn(numel, device="cuda").to(param_dtype)
287+
for param in (ref_param, tst_param):
288+
if param.grad is None:
289+
param.grad = grad.clone()
290+
else:
291+
param.grad.copy_(grad)
292+
293+
# Initialize optimizer state before CUDA graph capture.
294+
set_grads()
295+
ref_optim.step()
296+
tst_optim.step()
297+
298+
graph = torch.cuda.CUDAGraph()
299+
with torch.cuda.graph(graph):
300+
tst_optim.step()
301+
for _ in range(num_replays):
302+
set_grads()
303+
graph.replay()
304+
ref_optim.step()
305+
306+
assert tst_optim.param_groups[0]["step"].item() == num_replays + 1
307+
assert ref_optim.param_groups[0]["step"] == num_replays + 1
308+
assert not torch.equal(tst_param.detach(), init), "the replayed steps did not update"
309+
torch.testing.assert_close(tst_param, ref_param)
310+
for name in ("exp_avg", "exp_avg_sq") + (("master_param",) if master_weights else ()):
311+
torch.testing.assert_close(
312+
tst_optim.state[tst_param][name], ref_optim.state[ref_param][name]
313+
)
314+
315+
@pytest.mark.parametrize(
316+
"param_dtype,master_weights",
317+
[
318+
(torch.float32, False),
319+
# FP16 rather than BF16: the grad scaler's non-finite check has no BF16 kernel.
320+
(torch.float16, True),
321+
],
322+
)
323+
def test_capturable_skips_step_on_nonfinite_grad(self, param_dtype, master_weights):
324+
"""Capturable Adam leaves all state untouched when the grad scaler finds an inf.
325+
326+
The skip is decided on the device, inside the kernel, so that it survives CUDA
327+
graph capture. A skipped step must not move the parameters, the moments or the
328+
master weights, must not count as a step, and the optimizer must keep working
329+
afterwards.
330+
331+
The reference takes only the finite steps and uses no grad scaler: the scale is a
332+
power of two, so unscaling is exact.
333+
"""
334+
numel = 4099
335+
init = torch.randn(numel, device="cuda").to(param_dtype)
336+
ref_param = torch.nn.Parameter(init.clone())
337+
tst_param = torch.nn.Parameter(init.clone())
338+
ref_optim = self.fused_optim(
339+
[ref_param], capturable=False, master_weights=master_weights, **self.options
340+
)
341+
tst_optim = self.fused_optim(
342+
[tst_param], capturable=True, master_weights=master_weights, **self.options
343+
)
344+
# A small scale keeps the scaled FP16 gradients finite; the default 2**16 would
345+
# overflow them and turn every step into a skipped one.
346+
scaler = torch.amp.GradScaler("cuda", enabled=True, init_scale=16.0)
347+
348+
def scaled_step(coefficients):
349+
tst_optim.zero_grad()
350+
loss = (tst_param.float() * coefficients).sum()
351+
scaler.scale(loss).backward()
352+
scaler.step(tst_optim)
353+
scaler.update()
354+
355+
def ref_step(coefficients):
356+
ref_param.grad = coefficients.to(param_dtype)
357+
ref_optim.step()
358+
359+
def tst_state():
360+
names = ("exp_avg", "exp_avg_sq") + (("master_param",) if master_weights else ())
361+
state = {name: tst_optim.state[tst_param][name].clone() for name in names}
362+
state["param"] = tst_param.detach().clone()
363+
return state
364+
365+
finite = torch.randn(numel, device="cuda")
366+
nonfinite = finite.clone()
367+
nonfinite[numel // 2] = float("inf")
368+
369+
scaled_step(finite)
370+
ref_step(finite)
371+
before = tst_state()
372+
assert tst_optim.param_groups[0]["step"].item() == 1
373+
assert not torch.equal(before["param"], init), "the first, finite step did not update"
374+
375+
scaled_step(nonfinite)
376+
after = tst_state()
377+
for name, expected in before.items():
378+
assert torch.equal(after[name], expected), f"{name} changed in a skipped step"
379+
380+
# The step counter lags the skip decision by one call (it is advanced from the
381+
# previous call's overflow flag), so check it once a finite step has followed.
382+
scaled_step(finite)
383+
ref_step(finite)
384+
assert tst_optim.param_groups[0]["step"].item() == 2
385+
assert not torch.equal(tst_param.detach(), before["param"]), "step after a skip was lost"
386+
torch.testing.assert_close(tst_param, ref_param)
387+
for name in ("exp_avg", "exp_avg_sq") + (("master_param",) if master_weights else ()):
388+
torch.testing.assert_close(
389+
tst_optim.state[tst_param][name], ref_optim.state[ref_param][name]
390+
)
391+
250392
def test_adam_option(self):
251393
nelem = 1
252394
adam_option = {

‎transformer_engine/common/multi_tensor/adam.cu‎

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -388,18 +388,28 @@ struct AdamCapturableFunctor {
388388
const int bias_correction, const float epsilon,
389389
const float *lr_ptr, adamMode_t mode,
390390
const float decay, const float *inv_scale_ptr) {
391+
// Compute bias corrections on thread 0
392+
__shared__ float bias_corrections[2];
393+
if (threadIdx.x == 0) {
394+
bias_corrections[0] = 1.0f;
395+
bias_corrections[1] = 1.0f;
396+
if (bias_correction == 1) {
397+
bias_corrections[0] = 1 - pow(beta1, *step);
398+
bias_corrections[1] = 1 - pow(beta2, *step);
399+
}
400+
}
401+
__syncthreads();
402+
const float beta1_correction = bias_corrections[0];
403+
const float beta2_correction = bias_corrections[1];
404+
405+
// Exit early if noop flag is set
406+
// Note: Check after __syncthreads to ensure all threads enter sync
391407
if (*noop_gmem == 1) return;
392408

393409
const float lr = *lr_ptr;
394410
const float inv_scale = *inv_scale_ptr;
395411
const bool write_unscaled_grads = inv_scale != 1.0f;
396412

397-
float beta1_correction = 1.0f, beta2_correction = 1.0f;
398-
if (bias_correction == 1) {
399-
beta1_correction = 1 - pow(beta1, *step);
400-
beta2_correction = 1 - pow(beta2, *step);
401-
}
402-
403413
index_t tensor_loc = tl.block_to_tensor[blockIdx.x];
404414

405415
// potentially use to pass in list of scalar
@@ -494,18 +504,28 @@ struct AdamCapturableMasterFunctor {
494504
const int bias_correction, const float epsilon,
495505
const float *lr_ptr, adamMode_t mode,
496506
const float decay, const float *inv_scale_ptr) {
507+
// Compute bias corrections on thread 0
508+
__shared__ float bias_corrections[2];
509+
if (threadIdx.x == 0) {
510+
bias_corrections[0] = 1.0f;
511+
bias_corrections[1] = 1.0f;
512+
if (bias_correction == 1) {
513+
bias_corrections[0] = 1 - pow(beta1, *step);
514+
bias_corrections[1] = 1 - pow(beta2, *step);
515+
}
516+
}
517+
__syncthreads();
518+
const float beta1_correction = bias_corrections[0];
519+
const float beta2_correction = bias_corrections[1];
520+
521+
// Exit early if noop flag is set
522+
// Note: Check after __syncthreads to ensure all threads enter sync
497523
if (*noop_gmem == 1) return;
498524

499525
const float lr = *lr_ptr;
500526
const float inv_scale = *inv_scale_ptr;
501527
const bool write_unscaled_grads = inv_scale != 1.0f;
502528

503-
float beta1_correction = 1.0f, beta2_correction = 1.0f;
504-
if (bias_correction == 1) {
505-
beta1_correction = 1 - pow(beta1, *step);
506-
beta2_correction = 1 - pow(beta2, *step);
507-
}
508-
509529
index_t tensor_loc = tl.block_to_tensor[blockIdx.x];
510530

511531
// potentially use to pass in list of scalar

0 commit comments

Comments
 (0)