Repository navigation
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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]); | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
| 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)); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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; |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
|
Addressed all 4 P2 findings in commit
Added unit tests covering all 4 fixes and legacy checkpoint compatibility in @codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 👍 / 👎.
Summary
本 PR 为
InfiniTrain新增面向小型视觉模型训练的端到端高性能支持(CIFAR-10 ResNet-18 与 MobileNetV2width_mult=1.0,并附 ViTPatchEmbed扩展性验证),在不引入 cuDNN 外部依赖的前提下覆盖框架底座、CPU/CUDA 自研高性能视觉算子、全链路混合精度(BF16 + FP16GradScaler+ 可选 TF32)、32 路多张量批量优化器、CUDA MemPool 优化、常驻单线程确定性异步数据预取、多卡 DDP 与 PyTorch 数值对齐工具链。主要变更模块
Module(Train/Eval、NamedBuffers、To(DataType)保护非浮点 buffer)、nn/vision_utils、init::KaimingNormal、optimizers::SGD(momentum/weight_decay/StateDict+Parameters()+ 32 路多张量批量 CUDASGDAccumulateGradBatch+ CPUnumel >= 4096OpenMP 门槛)、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)。Conv2d(INFINI_CONV2D_ALGO=auto|winograd|packed|batched|naive、INFINI_CONV2D_WORKSPACE_MB=32与可选INFINI_ALLOW_TF32=1;含输出合并写 Winograd 滤波变换、2 的幂次无除法索引、奇偶展开Col2ImPacked3x3S2P1、多平面4×4/8×8Depthwise 3×3、stride=2奇偶展开反向输入、2048-block 多图 Split-N 权梯度及 CPU 端按线程复用col_buf)、BatchNorm2d(面向1/64FP64 消费级 Blackwell 的 Warp-FP32 洗牌 + 8-Warp FP64 合并块平移归约 + 128-bit 向量化 + 混合精度支持)、MaxPool2d、AdaptiveAvgPool2d、ReLU、ReLU6、Flatten,并补齐Linear/Elementwise/AccumulateGrad的kFLOAT16分派。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(含 ViTPatchEmbed、DDP 均衡分片、mid-epoch cursor 恢复、40 张量批量与状态恢复GradScaler单测)。Evidence
1. 官方 GitHub Actions 3/3 CI 门禁全绿(Fork 自检 PR,Commit
9035ba9)clang-format-16+black14/14 files,success)clang-tidy-18+InfiniTrainTidy.so,230 compile commands 0 diagnostics,success)clang-17,-Xiwyu --error=1,202 TUs 0 error,success)2. 官方平台 2×NVIDIA GeForce RTX 5090(
sm_120, CUDA12.8.61, Driver610.43.02, NCCL2.32.7)终验结果(v2 深度优化版)CUDA 12.8.61 + NCCL + sm_120全量ctest372/372 PASSED (100%, 0 failed)(19.48s,含新增 40 张量多块批量 SGD/GradScaler 单测);-DUSE_CUDA=OFF -DUSE_NCCL=OFF)全量ctest346/346 PASSED (100%, 0 failed)(1.01s,由55.33s提速54×);49/49 PASS(op_forward <= 5.72e-6,op_bn_stats <= 2.38e-7);verify_alignment.py self-diff根因实证(bs=8, 32×32):同权重同输入下,InfiniTrain CUDA 在 ResNet-18(全项通过108/167vs PyTorch 自误差65/167,中位rel_L2 7.44e-3vs8.17e-3)与 MobileNetV2(254/423vs222/423,最差rel_L2 1.561vs2.090)上双双优于 PyTorch 自身 CPU vs CUDA 差异。ddp-gradsworst_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。BS=128/卡,lr=0.1cosine,重构常驻 Worker DataLoader 提速11.5×):92.84%,2.45 s/epoch(20,404 img/s),20 轮全流程 49 秒,峰值441 MB(FP32 单卡92.76%);91.09%,2.21 s/epoch(22,632 img/s),20 轮 44 秒,scale 65536→131072(仅skip=2),峰值1,204 MB;91.44%,1.49 s/epoch(33,467 img/s),20 轮 30 秒,峰值480 MB(DDP FP3291.70%);90.26%,1.25 s/epoch(40,043 img/s),20 轮 25 秒,峰值1,204 MB(DDP FP3290.30%)。1.50×门槛):224×224 BS=64BF161.995×(99.8%扩展效率,410.5 → 819.0 img/s)、32×32 BS=128FP321.96×(7,164.9 → 14,050.0)、BF161.63×(20,986.5 → 34,255.9)、FP161.56×(24,546.5 → 38,398.8);224×224 BS=64BF161.983×(99.2%扩展效率,384.9 → 763.2 img/s)、32×32 BS=128FP321.96×(9,534.9 → 18,700.0)、BF161.79×(22,971.8 → 41,225.1)、FP161.78×(23,766.0 → 42,318.3 img/s)。InfiniTrain纯自研零 cuDNN):32×32 BS=128):FP1624,570.1vs15,544.4 img/s(158.1%,反超+58.1%)、BF1620,966.5vs19,334.8(108.4%,反超+8.4%)、TF3213,261.8vs12,687.3(104.5%)、FP32 strict7,165.0vs10,267.8(69.8%,省 191 MB;BS=32达116.2%);224×224 BS=64BF16410.5vs396.5(103.5%,反超 cuDNN)。32×32 BS=128FP1622,965.1(DDP 1G 峰23,766.0)vs11,653.3 img/s(197.1%/ 峰203.9%)、BF1623,576.0vs12,169.2(193.7%)、TF3214,859.6vs12,287.3(120.9%)、FP329,512.2vs9,318.4(102.1%;BS=32/64/256分别为180.2% / 104.6% / 101.1%);224×224 BS=32BF16 达140.2%。nsys) 内核级演进(RTX 509032×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%)。OMP_NUM_THREADS=16):ResNet-1834.9 img/s(vs PyTorch309.9)、MobileNetV2114.6 img/s(vs PyTorch200.7,57.1%)。3. 官方 2×RTX 5090 实测终端截图
4. 赛题报告与合规声明
example/cifar10/README.mdexample/cifar10/HONOR_CODE.mdexample/cifar10/REFERENCE.mdMerge 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 的严格精度语义。