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

运行设备无关训练模板、CPU BF16 AMP、梯度检查点与 Profiler 实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。explore-device-and-amp.py
explore-device-and-amp.py160 行
"""Independent Windows CPU observations for device-agnostic PyTorch code, AMP CPU path, checkpointing and profiling."""
import json
import platform
import time

import torch
import torch.nn as nn
import torch.optim as optim
from torch.profiler import ProfilerActivity, profile
from torch.utils.checkpoint import checkpoint
from torch.utils.data import DataLoader, TensorDataset


class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(64, 128),
            nn.ReLU(),
            nn.Linear(128, 64),
            nn.ReLU(),
            nn.Linear(64, 4),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x)


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

    # 1. Honest CUDA / MPS / CPU detection on CPU-only Windows build
    cuda_avail = torch.cuda.is_available()
    cuda_count = torch.cuda.device_count()
    cuda_ver = torch.version.cuda
    mps_avail = bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available())
    device = torch.device("cuda" if cuda_avail else "mps" if mps_avail else "cpu")
    c1_ok = (not cuda_avail) and cuda_count == 0 and cuda_ver is None and (not mps_avail) and device.type == "cpu"
    cases.append(dict(
        name="device_detection_cpu_build",
        inputs=dict(build=torch.__version__),
        prerequisites="Windows CPU-only 构建(未安装 CUDA/MPS GPU)",
        action="验证设备无关选择逻辑在无 GPU 环境平滑回落到 cpu,并诚实记录 CUDA 不可用状态。",
        expected=dict(cuda_available=False, device_count=0, mps_available=False, selected="cpu"),
        actual=dict(cuda_available=cuda_avail, device_count=cuda_count, mps_available=mps_avail, selected=device.type),
        passed=c1_ok,
    ))

    # 2. Device-agnostic tensor & model movement + numpy detach rule + matmul CPU timing
    t = torch.tensor([1.0, 2.0, 3.0], requires_grad=True).to(device)
    model = SimpleNet().to(device)
    all_on_device = all(p.device == device for p in model.parameters())
    numpy_err = False
    try:
        t.numpy()
    except RuntimeError:
        numpy_err = True
    arr = t.detach().cpu().numpy().tolist()
    t0 = time.perf_counter()
    a = torch.randn(512, 512, device=device)
    b = torch.randn(512, 512, device=device)
    c = torch.matmul(a, b)
    cpu_ms = round((time.perf_counter() - t0) * 1000.0, 2)
    c2_ok = all_on_device and (not t.is_cuda) and numpy_err and arr == [1.0, 2.0, 3.0] and list(c.shape) == [512, 512]
    cases.append(dict(
        name="tensor_model_movement_and_numpy",
        inputs=dict(matmul_size=[512, 512], device="cpu"),
        prerequisites="统一 .to(device) 与 detach().cpu().numpy()",
        action="核对模型参数与张量设备一致、带梯度张量直接 numpy() 报错、detach().cpu().numpy() 正常及 512×512 CPU 矩阵乘耗时。",
        expected=dict(all_params_on_device=True, is_cuda=False, numpy_blocked_on_grad=True, arr_match=True),
        actual=dict(all_params_on_device=all_on_device, is_cuda=t.is_cuda, numpy_blocked_on_grad=numpy_err, arr_match=arr == [1.0, 2.0, 3.0]),
        measurements=dict(matmul_512_cpu_ms=cpu_ms),
        passed=c2_ok,
    ))

    # 3. Device-agnostic training + eval + loss.item() graph release + gradient accumulation
    x = torch.randn(128, 64)
    y = (x[:, 0] > 0).long() + 2 * (x[:, 1] > 0).long()
    loader = DataLoader(TensorDataset(x, y), batch_size=16, shuffle=True, generator=torch.Generator().manual_seed(7))
    crit = nn.CrossEntropyLoss()
    opt = optim.Adam(model.parameters(), lr=1e-2)
    losses = []
    for _ in range(8):
        model.train()
        opt.zero_grad(set_to_none=True)
        total_loss = 0.0
        for step, (bx, by) in enumerate(loader):
            bx, by = bx.to(device, non_blocking=False), by.to(device, non_blocking=False)
            loss = crit(model(bx), by) / 2.0
            loss.backward()
            total_loss += float(loss.item()) * 2.0 * bx.size(0)
            if (step + 1) % 2 == 0:
                opt.step()
                opt.zero_grad(set_to_none=True)
        losses.append(round(total_loss / len(x), 5))
    model.eval()
    with torch.inference_mode():
        acc = round(float((model(x.to(device)).argmax(dim=1) == y.to(device)).float().mean().item()), 4)
    c3_ok = losses[-1] < losses[0] * 0.4 and acc >= 0.85
    cases.append(dict(
        name="device_agnostic_training_and_accum",
        inputs=dict(samples=128, micro_batch=16, accum_steps=2, epochs=8),
        prerequisites="统一 .to(device)、loss.item() 标量累计与 inference_mode 验证",
        action="运行 2 步梯度累积训练循环 8 轮,验证损失下降与准确率提升。",
        expected=dict(loss_dropped_60pct=True, acc_ge_85=True),
        actual=dict(loss_dropped_60pct=losses[-1] < losses[0] * 0.4, acc_ge_85=acc >= 0.85),
        measurements=dict(epoch1_loss=losses[0], epoch8_loss=losses[-1], train_acc=acc),
        passed=c3_ok,
    ))

    # 4. Modern torch.amp.autocast('cpu', dtype=torch.bfloat16) & gradient checkpointing
    block = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 64))
    inp = torch.randn(8, 64, requires_grad=True)
    with torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16):
        bf16_out = block(inp)
    bf16_dtype = str(bf16_out.dtype)
    # Gradient checkpointing with use_reentrant=False matches standard backward gradients
    inp_ref = inp.detach().clone().requires_grad_(True)
    inp_chk = inp.detach().clone().requires_grad_(True)
    block(inp_ref).sum().backward()
    checkpoint(block, inp_chk, use_reentrant=False).sum().backward()
    chk_grad_diff = float((inp_ref.grad - inp_chk.grad).abs().max().item())
    c4_ok = bf16_dtype == "torch.bfloat16" and chk_grad_diff < 1e-5
    cases.append(dict(
        name="amp_cpu_bf16_and_checkpoint",
        inputs=dict(device_type="cpu", dtype="bfloat16", use_reentrant=False),
        prerequisites="新版 torch.amp.autocast 替代旧 torch.cuda.amp.autocast;梯度检查点显式指定 use_reentrant=False",
        action="验证 CPU bfloat16 自动混合精度输出类型,以及梯度检查点反传梯度与常规前向一致。",
        expected=dict(bf16_dtype="torch.bfloat16", checkpoint_grad_exact=True),
        actual=dict(bf16_dtype=bf16_dtype, checkpoint_grad_exact=chk_grad_diff < 1e-5),
        measurements=dict(checkpoint_max_grad_diff=round(chk_grad_diff, 8)),
        passed=c4_ok,
    ))

    # 5. PyTorch Profiler CPU activity real trace
    with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof:
        for _ in range(3):
            out_p = model(x[:16])
            crit(out_p, y[:16]).backward()
    table_text = prof.key_averages().table(sort_by="cpu_time_total", row_limit=5)
    has_addmm_or_linear = ("linear" in table_text.lower()) or ("addmm" in table_text.lower()) or ("mm" in table_text.lower())
    c5_ok = len(prof.key_averages()) > 0 and has_addmm_or_linear
    cases.append(dict(
        name="profiler_cpu_bottleneck_trace",
        inputs=dict(activities=["CPU"], steps=3),
        prerequisites="torch.profiler.profile 记录算子 CPU 耗时表",
        action="运行 3 步前反向剖析,验证 profiler 捕获线性层/矩阵乘算子统计。",
        expected=dict(events_recorded=True, has_linear_or_mm=True),
        actual=dict(events_recorded=len(prof.key_averages()) > 0, has_linear_or_mm=has_addmm_or_linear),
        measurements=dict(unique_ops=len(prof.key_averages())),
        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-gpu-cuda-lab/explore-device-and-amp.py

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

下载课程关联工程包:PyTorch

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

下载课程关联工程包:PyTorch

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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