Skip to content

[2026秋季][T2-2-2] Xio-Shark - #283

Open
Xio-Shark wants to merge 8 commits into
InfiniTensor:masterfrom
Xio-Shark:2026-fall-Xio-Shark-T2-2-2
Open

Xio-Shark wants to merge 8 commits into
InfiniTensor:masterfrom
Xio-Shark:2026-fall-Xio-Shark-T2-2-2

Conversation

@Xio-Shark

@Xio-Shark Xio-Shark commented Dec 3, 2026 •

Copy link
Copy Markdown

Summary

本 PR 为 InfiniTrain 新增面向小型视觉模型训练的端到端高性能支持(CIFAR-10 ResNet-18 与 MobileNetV2 width_mult=1.0,并附 ViT PatchEmbed 扩展性验证),在不引入 cuDNN 外部依赖的前提下覆盖框架底座、CPU/CUDA 自研高性能视觉算子、全链路混合精度(BF16 + FP16 GradScaler + 可选 TF32)、32 路多张量批量优化器、CUDA MemPool 优化、常驻单线程确定性异步数据预取、多卡 DDP 与 PyTorch 数值对齐工具链。

example/cifar10/ (main / trainer / eval_and_align / grad_scaler[32-way batch + stream sync] / net / dataset / vision_dataloader[persistent worker, 11.5x])
        │
        ▼
CifarResNet18 / CifarMobileNetV2 (shared model_config.json <-> PyTorch) + ViT PatchEmbed Test + self-diff Tool
        │
        ▼
Conv2d (Coalesced Winograd F(2x2,3x3) / 32MiB L2-Resident NHW-Packed / Multi-Plane 4x4&8x8 DW3x3 + S2 + 2048-blk Split-N / 1x1 Zero-Copy)
BatchNorm2d (Block-Shifted Zero-Div + Warp-FP32 Shuffle / 8-Warp FP64 Merge + 128-bit Vec + Mixed-Precision)
MaxPool2d · AdaptiveAvgPool2d · 128-bit Vec ReLU/ReLU6 · Flatten · FP16 Linear/Elementwise
        │
        ▼
Module::Train/Eval + NamedBuffers · 32-Way Batched SGD(momentum, wd, StateDict) · MemPool ReleaseThreshold · Checkpoint(TrainerState) · DDP

主要变更模块

  • 框架与运行时底座:Module(Train/Eval、NamedBuffers、To(DataType) 保护非浮点 buffer)、nn/vision_utils、init::KaimingNormal、optimizers::SGD(momentum/weight_decay/StateDict + Parameters() + 32 路多张量批量 CUDA SGDAccumulateGradBatch + CPU numel >= 4096 OpenMP 门槛)、cuda_guard_impl.cc(cudaMemPoolAttrReleaseThreshold = UINT64_MAX)、Checkpoint/SavePlanner(sgd. 前缀 + TrainerState{epoch, rng_state, batch_cursor, grad_scaler_*} 向后兼容持久化)、autocast.h(Conv2d 低精度、BatchNorm2d 保留激活精度并内部使用 FP32/FP64 统计)、CMakeLists.txt(尊重外部 CMAKE_CUDA_ARCHITECTURES 与 CUDA>=12.8 默认 120)。
  • 视觉算子(CPU + CUDA + Autograd + Module):Conv2d(INFINI_CONV2D_ALGO=auto|winograd|packed|batched|naive、INFINI_CONV2D_WORKSPACE_MB=32 与可选 INFINI_ALLOW_TF32=1;含输出合并写 Winograd 滤波变换、2 的幂次无除法索引、奇偶展开 Col2ImPacked3x3S2P1、多平面 4×4/8×8 Depthwise 3×3、stride=2 奇偶展开反向输入、2048-block 多图 Split-N 权梯度及 CPU 端按线程复用 col_buf)、BatchNorm2d(面向 1/64 FP64 消费级 Blackwell 的 Warp-FP32 洗牌 + 8-Warp FP64 合并块平移归约 + 128-bit 向量化 + 混合精度支持)、MaxPool2d、AdaptiveAvgPool2d、ReLU、ReLU6、Flatten,并补齐 Linear/Elementwise/AccumulateGrad 的 kFLOAT16 分派。
  • CIFAR-10 示例与工具:模块化拆分 example/cifar10/{main,trainer,eval_and_align,grad_scaler,net,dataset,vision_dataloader}(含 32 路批量 UnscaleGradsAndCheckInfBatch + 流级异步同步 + LoadState 断点恢复、DDP 评测前 SynchronizeModelBuffers 同步 BN 统计量、常驻单线程异步预取 + 对齐 DistributedSampler 的 DDP 等长分片与 max_steps 断点 cursor 恢复)、model_config.json、scripts/{model_configs,export_pytorch_ref,verify_alignment(含 self-diff),download_cifar10,benchmark_pytorch,run_container_pipeline}、README.md。
  • 双端单元测试:tests/module/test_train_eval_and_buffers.cc、tests/optimizer/test_sgd_momentum_wd.cc(含 40 张量跨 chunk 批量 SGD 单测)、tests/checkpoint/test_sgd_and_trainer_state_ckpt.cc(含 batch_cursor/GradScaler 状态与旧版 JSON 兼容单测)、tests/autograd/test_autograd_{vision_ops,batchnorm2d,conv2d}.cc、tests/vision/test_cifar10_models_and_loader.cc(含 ViT PatchEmbed、DDP 均衡分片、mid-epoch cursor 恢复、40 张量批量与状态恢复 GradScaler 单测)。

Evidence

1. 官方 GitHub Actions 3/3 CI 门禁全绿(Fork 自检 PR,Commit 9035ba9)

  • Format Check(clang-format-16 + black 14/14 files,success)
  • clang-tidy(clang-tidy-18 + InfiniTrainTidy.so,230 compile commands 0 diagnostics,success)
  • IWYU(clang-17, -Xiwyu --error=1,202 TUs 0 error,success)

2. 官方平台 2×NVIDIA GeForce RTX 5090(sm_120, CUDA 12.8.61, Driver 610.43.02, NCCL 2.32.7)终验结果(v2 深度优化版)

同机参照为 PyTorch 2.6.0+cu128 + cuDNN 9.7(InfiniTrain 编译与运行时零 cuDNN 依赖)。注:模力方舟基础镜像内置的 libnccl2 2.25.1 在 Driver 610.43.02 + RTX 5090 上存在 enqueue.cc:1500 Cuda failure 1 'invalid argument' 兼容问题(原生 PyTorch dist.all_reduce 同样复现),通过 nvidia-nccl-cu12 2.32.7(LD_PRELOAD)恢复全绿。

  • 全量构建与双端测试:
    • CUDA 12.8.61 + NCCL + sm_120 全量 ctest 372/372 PASSED (100%, 0 failed)(19.48s,含新增 40 张量多块批量 SGD/GradScaler 单测);
    • 纯 CPU-only 构建(-DUSE_CUDA=OFF -DUSE_NCCL=OFF)全量 ctest 346/346 PASSED (100%, 0 failed)(1.01s,由 55.33s 提速 54×);
    • 单算子 PyTorch 数值对齐(CPU + RTX 5090 CUDA):49/49 PASS(op_forward <= 5.72e-6,op_bn_stats <= 2.38e-7);
    • 官方 RTX 5090 同机 verify_alignment.py self-diff 根因实证(bs=8, 32×32):同权重同输入下,InfiniTrain CUDA 在 ResNet-18(全项通过 108/167 vs PyTorch 自误差 65/167,中位 rel_L2 7.44e-3 vs 8.17e-3)与 MobileNetV2(254/423 vs 222/423,最差 rel_L2 1.561 vs 2.090)上双双优于 PyTorch 自身 CPU vs CUDA 差异。
  • 2×RTX 5090 NCCL DDP 核心验收与 11.5× 真实训练提速(ResNet-18 必选 + MobileNetV2 加分项全绿):
    • 梯度同步 & 无重叠分片 & 位级续训:Split-batch ddp-grads worst_sync_max_abs = 0.0、worst_avg_max_abs = 0.0;Same-input 62/158 张量 0.000e+00;数据分片 50,000 / 50,000(overlaps = []);Ep10→Ep20 DDP 断点续训 122 张量 0.000e+00。
    • 20-Epoch CIFAR-10 端到端实训收敛(BS=128/卡, lr=0.1 cosine,重构常驻 Worker DataLoader 提速 11.5×):
      • 1 GPU ResNet-18 BF16:92.84%,2.45 s/epoch(20,404 img/s),20 轮全流程 49 秒,峰值 441 MB(FP32 单卡 92.76%);
      • 1 GPU MobileNetV2 FP16 + GradScaler:91.09%,2.21 s/epoch(22,632 img/s),20 轮 44 秒,scale 65536→131072(仅 skip=2),峰值 1,204 MB;
      • 2-GPU DDP ResNet-18 BF16:91.44%,1.49 s/epoch(33,467 img/s),20 轮 30 秒,峰值 480 MB(DDP FP32 91.70%);
      • 2-GPU DDP MobileNetV2 BF16:90.26%,1.25 s/epoch(40,043 img/s),20 轮 25 秒,峰值 1,204 MB(DDP FP32 90.30%)。
    • 1-GPU → 2-GPU DDP 加速比(v2 实测 8 组全超 1.50× 门槛):
      • ResNet-18:224×224 BS=64 BF16 1.995×(99.8% 扩展效率,410.5 → 819.0 img/s)、32×32 BS=128 FP32 1.96×(7,164.9 → 14,050.0)、BF16 1.63×(20,986.5 → 34,255.9)、FP16 1.56×(24,546.5 → 38,398.8);
      • MobileNetV2:224×224 BS=64 BF16 1.983×(99.2% 扩展效率,384.9 → 763.2 img/s)、32×32 BS=128 FP32 1.96×(9,534.9 → 18,700.0)、BF16 1.79×(22,971.8 → 41,225.1)、FP16 1.78×(23,766.0 → 42,318.3 img/s)。
  • 单卡 RTX 5090 (v2) vs 同机 PyTorch 2.6 + cuDNN 9.7 关键对比(InfiniTrain 纯自研零 cuDNN):
    • ResNet-18 (32×32 BS=128):FP16 24,570.1 vs 15,544.4 img/s(158.1%,反超 +58.1%)、BF16 20,966.5 vs 19,334.8(108.4%,反超 +8.4%)、TF32 13,261.8 vs 12,687.3(104.5%)、FP32 strict 7,165.0 vs 10,267.8(69.8%,省 191 MB;BS=32 达 116.2%);224×224 BS=64 BF16 410.5 vs 396.5(103.5%,反超 cuDNN)。
    • MobileNetV2(全精度、全 BS 32–256 全面反超 cuDNN):32×32 BS=128 FP16 22,965.1(DDP 1G 峰 23,766.0)vs 11,653.3 img/s(197.1% / 峰 203.9%)、BF16 23,576.0 vs 12,169.2(193.7%)、TF32 14,859.6 vs 12,287.3(120.9%)、FP32 9,512.2 vs 9,318.4(102.1%;BS=32/64/256 分别为 180.2% / 104.6% / 101.1%);224×224 BS=32 BF16 达 140.2%。
    • Nsight Systems (nsys) 内核级演进(RTX 5090 32×32 BS=128):ResNet-18 BF16 GEMM 占比由 35.7% → 53.4%(BatchNorm2d 13.8% → 7.9%);MobileNetV2 BF16 Depthwise 3×3 绝对 GPU 耗时砍去 66%(占比 46.6% → 29.7%,32 路批量 SGD 压至 2.8%)。
    • CPU 端(Intel Xeon Platinum 8358P, OMP_NUM_THREADS=16):ResNet-18 34.9 img/s(vs PyTorch 309.9)、MobileNetV2 114.6 img/s(vs PyTorch 200.7, 57.1%)。

3. 官方 2×RTX 5090 实测终端截图

2xRTX 5090 CTest and DDP Verification

2xRTX 5090 20-Epoch DDP and PyTorch Comparison

4. 赛题报告与合规声明

Merge Danger

  • 可逆性:双向门(所有新视觉算子、示例与测试均为增量新增;对 Module、SGD、Checkpoint、Autocast、CudaGuardImpl、CMakeLists.txt 的扩展均保持默认参数与既有 LLM/MNIST 行为 100% 向后兼容)。
  • 爆炸半径:
    • SGD 在 momentum == 0 且 weight_decay == 0 时与原更新公式等价且保持空 StateDict(),不影响既有 LLM 示例与 SGDStateDictEmpty 单测;
    • TrainerState 新增字段位于结构体尾部并带默认值,兼容读取旧版 trainer_state.json;
    • Module::To(DataType) 仅跳过非浮点 buffer,对既有纯浮点模型无影响;
    • cudaMemPoolAttrReleaseThreshold = UINT64_MAX 仅避免训练过程中频繁向 OS 归还缓存池,不改变显存语义;
    • INFINI_ALLOW_TF32 默认关闭,不改变任何既有 FP32 GEMM 的严格精度语义。

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-06T10:51:08.065667Z 9035ba9 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Xio-Shark

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 532615d0d0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread example/cifar10/vision_dataloader.cc Outdated
Comment on lines +159 to +162
for (size_t i = static_cast<size_t>(ddp_rank_); i < total;
i += static_cast<size_t>(ddp_world_size_)) {
rank_indices_.push_back(perm[i]);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Equalize per-rank batch counts before DDP training

When shards straddle a batch boundary, ranks can execute different numbers of training steps. For example, CIFAR-10’s 50,000 training samples with 3 ranks and --batch_size=2 gives ranks 0/1 8,334 batches and rank 2 8,333. RunTrainMode calls FinalizeModelGrads each batch, so the shorter rank exits while the others enter another gradient collective and training hangs. Ensure all ranks have the same step count or handle the uneven tail without mismatched collectives.

Useful? React with 👍 / 👎.

Comment on lines +132 to +135
running_mean[ch] = common::cuda::Cast<TStat>(
static_cast<float>((1.0 - mom) * prev_mean + mom * mean_d));
running_var[ch] = common::cuda::Cast<TStat>(
static_cast<float>((1.0 - mom) * prev_var + mom * var_unbiased));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Synchronize BatchNorm buffers before DDP evaluation

During multi-GPU training, these updates use each rank’s local batch, and the DDP model does not synchronize running statistics after the initial buffer broadcast. Evaluate then reduces metrics computed with rank-specific running_mean and running_var, while checkpoint saving keeps the DP rank-0 copy, so the logged test accuracy does not describe the checkpointed model. Synchronize buffers before evaluation or use synchronized BatchNorm.

Useful? React with 👍 / 👎.

Comment thread example/cifar10/trainer.cc Outdated
save_state.global_step = global_step;
save_state.consumed_train_samples = consumed_samples;
save_state.ddp_size = ddp_world_size;
save_state.epoch = epoch + 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the data-loader cursor when saving at max_steps

When max_steps stops the inner loop mid-epoch, the checkpoint records epoch + 1; on resume, the loader starts that next epoch from its beginning and no batch cursor is restored. The unconsumed batches from the interrupted epoch are therefore silently skipped, changing the experiment’s data coverage. Save the current epoch and cursor, or mark the epoch complete only after exhausting the loader.

Useful? React with 👍 / 👎.

Comment on lines +145 to +148
GradScaler scaler(compute_dtype == DataType::kFLOAT16 && cfg.grad_scaler,
static_cast<float>(cfg.grad_scaler_init_scale),
/*growth_factor=*/2.0f,
/*backoff_factor=*/0.5f, cfg.grad_scaler_growth_interval);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist GradScaler state in checkpoints

For an FP16 run resumed after the scale has grown or backed off, this constructs a fresh scaler at grad_scaler_init_scale, while checkpoint loading restores no scaler scale or growth tracker. The resumed run can therefore make different overflow decisions and skip different optimizer steps than uninterrupted training. Include the scaler state in the checkpoint and restore it on resume.

Useful? React with 👍 / 👎.

@Xio-Shark

Copy link
Copy Markdown
Author

Addressed all 4 P2 findings in commit 9035ba9 (all 3/3 GitHub Actions workflows — Format Check, clang-tidy, and IWYU — passed on the fork self-check PR):

  1. Equalize per-rank DDP batch counts (example/cifar10/vision_dataloader.{h,cc}): Added equalize_ddp_shards (enabled for training, disabled for evaluation) matching PyTorch DistributedSampler semantics so every DDP rank runs the exact same number of batches per epoch (zero padding when total % world_size == 0, exact coverage with no duplicates on evaluation).
  2. Synchronize BatchNorm buffers before DDP evaluation (example/cifar10/eval_and_align.{h,cc}): Added SynchronizeModelBuffers (AllReduce with kAvg over floating-point buffers in deterministic NamedBuffers() order) invoked at the start of Evaluate, keeping logged test metrics and the subsequent DP rank-0 checkpoint consistent.
  3. Preserve mid-epoch data-loader cursor on max_steps stop (infini_train/{include,src}/checkpoint/checkpoint.{h,cc}, example/cifar10/trainer.cc): Extended TrainerState backwards-compatibly with batch_cursor, recording epoch + 1 / cursor = 0 only when the epoch is exhausted (!train_loader.HasNext()) and restoring SetBatchCursor on resume.
  4. Persist GradScaler state in checkpoints (example/cifar10/grad_scaler.{h,cc}, infini_train/{include,src}/checkpoint/checkpoint.{h,cc}, example/cifar10/trainer.cc): Added growth_tracker() / LoadState(...) and serialized grad_scaler_scale, grad_scaler_growth_tracker, and grad_scaler_skipped_steps in TrainerState with backward-compatible defaults.

Added unit tests covering all 4 fixes and legacy checkpoint compatibility in tests/vision/test_cifar10_models_and_loader.cc and tests/checkpoint/test_sgd_and_trainer_state_ckpt.cc.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Xio-Shark

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Xio-Shark

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9035ba9af8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (!IsFloatingPointDType(buf->Dtype())) {
continue;
}
nn::parallel::comm::AllReduce(buf, nn::parallel::comm::ReduceOpType::kAvg,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Merge per-rank BatchNorm moments, not variances

When DDP ranks see different activation means, averaging their running_var buffers omits the between-rank mean term required for the pooled variance. This leaves evaluation—and any checkpoint saved afterward—using under-dispersed normalization statistics. Synchronize sufficient statistics or use synchronized BatchNorm rather than averaging the running variances.

Useful? React with 👍 / 👎.

{
std::optional<AutocastGuard> autocast_guard;
if (compute_dtype != DataType::kFLOAT32) {
autocast_guard.emplace(device.type(), compute_dtype);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject unsupported CPU autocast dtypes

When --device=cpu is combined with --dtype=bfloat16 or float16, this enables CPU autocast and casts the first Conv2d operands away from FP32, but the CPU Conv2dForward kernel only accepts FP32 and aborts before training or evaluation can run. Reject this device/dtype combination or keep the CPU path in FP32.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant