蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 CPU BF16 autocast、FP16 溢出对比、FP32 保护与梯度累积等价实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。explore-amp-mixed-precision.py
explore-amp-mixed-precision.py167 行
"""Independent PyTorch 2.10 CPU AMP mixed-precision lab (bfloat16 autocast, GradScaler fallback, gradient accumulation)."""
import json
import platform

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim


def run_cases():
    torch.manual_seed(2026)
    cases = []

    # 1. FP32 vs FP16 vs BF16 numerical limits + real CPU bfloat16 autocast dtype rules
    f32 = torch.finfo(torch.float32)
    f16 = torch.finfo(torch.float16)
    bf16 = torch.finfo(torch.bfloat16)
    fp16_overflow = bool(torch.isinf(torch.tensor(70000.0, dtype=torch.float16)).item())
    bf16_finite = bool(torch.isfinite(torch.tensor(70000.0, dtype=torch.bfloat16)).item())

    lin = nn.Linear(16, 4)
    x = torch.randn(8, 16)
    y = torch.randint(0, 4, (8,))
    with torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16):
        logits = lin(x)
        probs = F.softmax(logits, dim=-1)
        ce_loss = F.cross_entropy(logits, y)
    c1_ok = (
        fp16_overflow
        and bf16_finite
        and logits.dtype == torch.bfloat16
        and probs.dtype == torch.bfloat16
        and ce_loss.dtype == torch.float32
    )
    cases.append(dict(
        name="float_format_ranges_and_cpu_bf16_autocast",
        inputs=dict(test_value=70000.0, autocast_device="cpu", autocast_dtype="bfloat16"),
        prerequisites="使用 PyTorch 2.4+ 统一接口 torch.amp.autocast(device_type='cpu', dtype=torch.bfloat16)",
        action="验证 FP16 在 70000 溢出而 BF16 保持有限,并核对 CPU BF16 autocast 下线性层与 Softmax 走 bfloat16 而 CrossEntropyLoss 保持 float32。",
        expected=dict(fp16_overflows_70000=True, bf16_keeps_70000=True, linear_dtype="torch.bfloat16", softmax_dtype="torch.bfloat16", ce_dtype="torch.float32"),
        actual=dict(fp16_overflows_70000=fp16_overflow, bf16_keeps_70000=bf16_finite, linear_dtype=str(logits.dtype), softmax_dtype=str(probs.dtype), ce_dtype=str(ce_loss.dtype)),
        measurements=dict(fp16_max=float(f16.max), bf16_max=float(bf16.max), fp32_max=float(f32.max)),
        passed=c1_ok,
    ))

    # 2. Manual FP32 guard via autocast(device_type='cpu', enabled=False) & CrossEntropy target dtype bug proof
    missing_device_type_err = False
    try:
        torch.amp.autocast(enabled=False)  # type: ignore[call-arg]
    except TypeError:
        missing_device_type_err = True

    with torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16):
        low_prec = lin(x)
        with torch.amp.autocast(device_type="cpu", enabled=False):
            guarded = lin(x.float())
            ce_float_target_err = False
            try:
                F.cross_entropy(guarded, y.float())
            except RuntimeError:
                ce_float_target_err = True
            ce_int_target = F.cross_entropy(guarded, y)
    c2_ok = missing_device_type_err and low_prec.dtype == torch.bfloat16 and guarded.dtype == torch.float32 and ce_float_target_err and ce_int_target.dtype == torch.float32
    cases.append(dict(
        name="manual_fp32_guard_and_ce_target_fix",
        inputs=dict(inner_enabled=False, target_dtype_bug="y.float()"),
        prerequisites="核对 torch.amp.autocast 强制 device_type 参数、局部 FP32 保护与分类标签保持 int64",
        action="验证缺少 device_type 触发 TypeError、内层关闭 autocast 恢复 FP32,且 CrossEntropyLoss 传入浮点标签报 RuntimeError 而 int64 正常。",
        expected=dict(missing_device_type_raises=True, guarded_fp32=True, float_target_errors=True, int_target_fp32_loss=True),
        actual=dict(missing_device_type_raises=missing_device_type_err, guarded_fp32=guarded.dtype == torch.float32, float_target_errors=ce_float_target_err, int_target_fp32_loss=ce_int_target.dtype == torch.float32),
        passed=c2_ok,
    ))

    # 3. GradScaler portable CPU fallback (enabled=False) + unscale -> clip -> step -> update order
    torch.manual_seed(7)
    mlp = nn.Sequential(nn.Linear(12, 24), nn.ReLU(), nn.Linear(24, 3))
    opt = optim.AdamW(mlp.parameters(), lr=2e-2)
    scaler = torch.amp.GradScaler(device="cpu", enabled=False)
    xb = torch.randn(32, 12)
    yb = (xb[:, 0] > 0).long() + (xb[:, 1] > 0).long()
    losses = []
    for _ in range(15):
        opt.zero_grad(set_to_none=True)
        with torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16):
            loss = F.cross_entropy(mlp(xb), yb)
        scaler.scale(loss).backward()
        scaler.unscale_(opt)
        nn.utils.clip_grad_norm_(mlp.parameters(), max_norm=1.0)
        scaler.step(opt)
        scaler.update()
        losses.append(round(float(loss.item()), 5))

    nonexistent_allow_bf16 = not hasattr(torch.backends.cuda.matmul, "allow_bf16")
    c3_ok = (not scaler.is_enabled()) and scaler.get_scale() == 1.0 and losses[-1] < losses[0] * 0.6 and nonexistent_allow_bf16
    cases.append(dict(
        name="grad_scaler_cpu_fallback_and_clip_order",
        inputs=dict(steps=15, scaler_enabled=False, max_norm=1.0),
        prerequisites="CPU/BF16 下设置 GradScaler(enabled=False) 保持统一训练模板,按 scale->unscale_->clip->step->update 执行",
        action="验证 GradScaler 禁用态恒返回 scale=1.0、15 步训练损失下降,并确认 2.10 中不存在虚构的 matmul.allow_bf16 属性。",
        expected=dict(scaler_disabled=True, scale_is_1=True, loss_dropped=True, allow_bf16_attr_absent=True),
        actual=dict(scaler_disabled=not scaler.is_enabled(), scale_is_1=scaler.get_scale() == 1.0, loss_dropped=losses[-1] < losses[0] * 0.6, allow_bf16_attr_absent=nonexistent_allow_bf16),
        measurements=dict(step1_loss=losses[0], step15_loss=losses[-1]),
        passed=c3_ok,
    ))

    # 4. Gradient accumulation equivalence: full batch vs 4 micro-batches divided by accum_steps
    torch.manual_seed(19)
    base_m = nn.Sequential(nn.Linear(8, 12), nn.ReLU(), nn.Linear(12, 2))
    acc_m = nn.Sequential(nn.Linear(8, 12), nn.ReLU(), nn.Linear(12, 2))
    acc_m.load_state_dict(base_m.state_dict())
    wrong_m = nn.Sequential(nn.Linear(8, 12), nn.ReLU(), nn.Linear(12, 2))
    wrong_m.load_state_dict(base_m.state_dict())

    x_all = torch.randn(16, 8)
    y_all = torch.randint(0, 2, (16,))
    F.cross_entropy(base_m(x_all), y_all).backward()

    accum_steps = 4
    for i in range(accum_steps):
        sl = slice(i * 4, (i + 1) * 4)
        (F.cross_entropy(acc_m(x_all[sl]), y_all[sl]) / accum_steps).backward()
        F.cross_entropy(wrong_m(x_all[sl]), y_all[sl]).backward()

    max_diff_correct = max((p1.grad - p2.grad).abs().max().item() for p1, p2 in zip(base_m.parameters(), acc_m.parameters()))
    grad_ratio_wrong = float(wrong_m[0].weight.grad.norm().item() / base_m[0].weight.grad.norm().item())
    c4_ok = max_diff_correct < 1e-5 and abs(grad_ratio_wrong - 4.0) < 1e-4
    cases.append(dict(
        name="amp_with_gradient_accumulation",
        inputs=dict(full_batch=16, micro_batch=4, accum_steps=4),
        prerequisites="对比整批反向传播、4 步微批除以 accum_steps 累积与未除 accum_steps 的梯度范数",
        action="验证除以累积步数后梯度与大批量完全等价(误差 <1e-5),而漏除会把梯度放大 4 倍。",
        expected=dict(correct_accum_matches_full=True, missing_div_scales_4x=True),
        actual=dict(correct_accum_matches_full=max_diff_correct < 1e-5, missing_div_scales_4x=abs(grad_ratio_wrong - 4.0) < 1e-4),
        measurements=dict(max_grad_diff=round(max_diff_correct, 7), wrong_grad_ratio=round(grad_ratio_wrong, 4)),
        passed=c4_ok,
    ))

    # 5. Inference mode + CPU bfloat16 autocast vs FP32 top-1 agreement + CUDA boundary
    torch.manual_seed(29)
    conv_net = nn.Sequential(nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(8, 5))
    conv_net.eval()
    imgs = torch.randn(6, 3, 12, 12)
    with torch.inference_mode():
        out_fp32 = conv_net(imgs)
    with torch.inference_mode(), torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16):
        out_bf16 = conv_net(imgs)
    top1_agree = bool(torch.equal(out_fp32.argmax(dim=1), out_bf16.float().argmax(dim=1)))
    max_logit_diff = round(float((out_fp32 - out_bf16.float()).abs().max().item()), 5)
    c5_ok = (not out_bf16.requires_grad) and out_bf16.dtype == torch.bfloat16 and top1_agree and (not torch.cuda.is_available())
    cases.append(dict(
        name="amp_inference_mode_and_cuda_boundary",
        inputs=dict(batch=6, input_shape=[6, 3, 12, 12]),
        prerequisites="torch.inference_mode() + torch.amp.autocast('cpu', bfloat16) 推理对比,并明确记录无 GPU 边界",
        action="验证推理输出无梯度、dtype 为 bfloat16 且 Top-1 预测与 FP32 一致。",
        expected=dict(no_grad=True, bf16_output=True, top1_matches_fp32=True, cuda_available=False),
        actual=dict(no_grad=not out_bf16.requires_grad, bf16_output=out_bf16.dtype == torch.bfloat16, top1_matches_fp32=top1_agree, cuda_available=bool(torch.cuda.is_available())),
        measurements=dict(max_logit_diff=max_logit_diff),
        passed=c5_ok,
    ))

    print(json.dumps(dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-amp-lab/explore-amp-mixed-precision.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-amp-mixed-precision.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a407.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习