Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
cmake_minimum_required(VERSION 3.28)

option(USE_CUDA "Support NVIDIA CUDA" OFF)
option(USE_CUDNN "Use cuDNN for accelerated Conv2d on CUDA" OFF)
option(PROFILE_MODE "ENABLE PROFILE MODE" OFF)
option(USE_OMP "Use OpenMP as backend for Eigen" ON)
option(USE_NCCL "Build project for distributed running on CUDA using NCCL" ON)
Expand Down Expand Up @@ -115,7 +116,11 @@ if(USE_CUDA)
file(GLOB_RECURSE CUDA_KERNELS ${PROJECT_SOURCE_DIR}/infini_train/src/*.cu)

add_library(infini_train_cuda_kernels STATIC ${CUDA_KERNELS})
set_target_properties(infini_train_cuda_kernels PROPERTIES CUDA_ARCHITECTURES "75;80;90")
if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES OR CMAKE_CUDA_ARCHITECTURES STREQUAL "")
set_target_properties(infini_train_cuda_kernels PROPERTIES CUDA_ARCHITECTURES "75;80;90")
else()
set_target_properties(infini_train_cuda_kernels PROPERTIES CUDA_ARCHITECTURES "${CMAKE_CUDA_ARCHITECTURES}")
endif()

target_link_libraries(infini_train_cuda_kernels
PUBLIC
Expand All @@ -132,6 +137,22 @@ if(USE_CUDA)
add_compile_definitions(USE_NCCL=1)
target_link_libraries(infini_train_cuda_kernels PUBLIC nccl)
endif()

if(USE_CUDNN)
find_path(CUDNN_INCLUDE_DIR cudnn.h
HINTS ${CUDNN_ROOT} $ENV{CUDNN_ROOT} ${CUDAToolkit_INCLUDE_DIRS} /usr/include /usr/local/cuda/include
PATH_SUFFIXES include)
find_library(CUDNN_LIBRARY cudnn
HINTS ${CUDNN_ROOT} $ENV{CUDNN_ROOT} ${CUDAToolkit_LIBRARY_DIR} /usr/lib /usr/lib/x86_64-linux-gnu /usr/local/cuda/lib64
PATH_SUFFIXES lib lib64)
if(NOT CUDNN_INCLUDE_DIR OR NOT CUDNN_LIBRARY)
message(FATAL_ERROR "USE_CUDNN=ON but cuDNN not found. Set -DCUDNN_ROOT=<path>.")
endif()
message(STATUS "Add USE_CUDNN: include=${CUDNN_INCLUDE_DIR}, lib=${CUDNN_LIBRARY}")
add_compile_definitions(USE_CUDNN=1)
target_include_directories(infini_train_cuda_kernels PUBLIC ${CUDNN_INCLUDE_DIR})
target_link_libraries(infini_train_cuda_kernels PUBLIC ${CUDNN_LIBRARY})
endif()
endif()

# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -240,6 +261,14 @@ add_executable(mnist
)
link_infini_train_exe(mnist)

add_executable(cifar10
example/cifar10/main.cc
example/cifar10/dataset.cc
example/cifar10/models.cc
example/cifar10/checkpoint_io.cc
)
link_infini_train_exe(cifar10)

add_executable(gpt2
example/gpt2/main.cc
example/common/tiny_shakespeare_dataset.cc
Expand Down
38 changes: 38 additions & 0 deletions example/cifar10/HONOR_CODE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# 2026 秋季启元人工智能大赛诚信守则(Honor Code)

本人作为 2026 秋季启元人工智能大赛(以下简称“比赛”)的参赛选手,郑重承诺严格遵守比赛规则及本诚信守则,秉持诚信、公正、廉洁的参赛原则,自觉维护比赛的公平性与严肃性。本人充分理解并认可,违反本准则将导致参赛资格被取消、比赛成绩作废等相应后果,且愿意承担由此产生的一切责任。

## 一、参赛诚信承诺

1. 本人保证所提交的赛题PR(Pull Request)中包含的算子实现代码及相关文档,均为本人(及参赛团队,如为团队参赛)在比赛期间独立完成或在明确标注参考来源的基础上进行开发,不存在任何欺诈、抄袭、作弊行为。

2. 本人承诺主动、全面、真实地披露赛题实现过程中所有参考的外部资源,尤其是开源代码资源,不隐瞒任何可能影响比赛公平性的信息。

3. 本人保证不采用任何不正当手段获取比赛优势,包括但不限于窃取其他参赛选手的代码成果、利用非比赛允许的工具或技术、与他人串通作弊等。

## 二、参考资源说明

本人确认已按比赛要求,将本次赛题实现过程中涉及的参考资源信息单独撰写至 `REFERENCE.md` 文件中,该文件将与本诚信守则一同作为 PR 附件提交。

## 三、禁止行为确认

本人明确知晓并承诺避免以下违反比赛公平性的行为,若存在以下任一情况,自愿接受比赛组委会的相应处罚:

1. 未经授权复制、抄袭他人(包括其他参赛选手、开源项目、商业代码)的代码、算法或技术方案,且未进行明确标注;
2. 隐瞒或虚假披露参考资源信息,包括遗漏重要参考来源、伪造参考内容说明等;
3. 与其他参赛选手或第三方串通,进行代码共享、成果交换等违规协作;
4. 利用比赛平台漏洞、技术缺陷或非比赛允许的工具获取不正当利益;
5. 伪造比赛相关证明材料、提交虚假信息;
6. 其他违反比赛规则及公序良俗的不诚信行为。

## 四、责任与确认

1. 本人充分理解,比赛组委会将对所有提交的 PR 进行代码溯源、参考信息核查等公平性审查,若发现本人存在违反本准则的行为,有权随时取消本人的参赛资格、作废比赛成绩,情节严重的将在比赛相关平台进行公示。
2. 若因本人违反本准则导致比赛争议或第三方权益受损(如开源协议侵权等),本人将独立承担全部法律责任及相关损失,与比赛组委会无关。
3. 本人确认已仔细阅读并完全理解本诚信守则的全部内容,自愿签署本准则,接受比赛组委会的监督与审查。

## 五、签署信息

参赛选手姓名:闫超美(Solo 队伍:启忆智存,GitHub ID: `yanchaomei`)

签署日期:2026年11月27日
173 changes: 173 additions & 0 deletions example/cifar10/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
# InfiniTrain CIFAR-10 Vision Training (`ResNet-18` & `MobileNetV2`)

End-to-end small vision model training support for InfiniTrain on CIFAR-10, covering CPU, single-GPU CUDA, optional cuDNN acceleration, and multi-GPU DistributedDataParallel (DDP) training.

## Implemented Framework Components

- **Vision Operators (CPU + CUDA, Forward + Backward, FP32)**
- `Conv2d` (`stride`, `padding`, `groups` including depthwise `groups == in_channels`, optional `bias`)
- Zero-dependency custom CUDA backend (`USE_CUDNN=OFF`): specialized direct depthwise convolution kernel, zero-`im2col` 1×1 strided-batched GEMM, chunked `im2col + cuBLAS SGEMM`, deterministic gather `col2im`, 32-bit indexing, and per-thread/per-device reusable workspace.
- Optional cuDNN backend (`USE_CUDNN=ON`, `-DCUDNN_ROOT=/path/to/cudnn`): per-device handle/descriptor cache, strict FP32 (`CUDNN_FMA_MATH`), and reusable workspace.
- `BatchNorm2d` (separate `Train()` / `Eval()` behavior, unbiased `running_var` update, FP64 statistics accumulation on CPU & CUDA)
- `ReLU`, `ReLU6`
- `MaxPool2d` (with argmax index saving), `AdaptiveAvgPool2d` (general + fast `1x1` global average pooling)
- `nn::Flatten`
- **Module & Training Infrastructure**
- Recursive `Module::Train(bool)` / `Module::Eval()` / `is_training()`, plus buffer accessors (`has_buffer`, `mutable_buffer`, `buffer`).
- `nn::init::KaimingNormal` initialization.
- `optimizers::SGD` with PyTorch-exact `momentum`, `weight_decay`, fused CPU/CUDA `SGDAccumulateGrad` kernel, and full `StateDict()` / `LoadStateDict()` (returning empty state when `momentum == 0` for backward compatibility).
- Portable full training checkpoints (model weights + BN running buffers + SGD momentum buffers + epoch/step/LR metadata).
- Deterministic non-overlapping DDP dataset sharding with per-rank coverage verification.

## Build Instructions

### Standard Zero-Dependency CUDA + NCCL Build

```bash
# Set CMAKE_CUDA_ARCHITECTURES for your target GPU:
# NVIDIA A40: 86 | RTX 4090: 89 | H100: 90 | RTX 5090 (Blackwell): 120
cmake -S . -B build \
-DUSE_CUDA=ON \
-DUSE_NCCL=ON \
-DUSE_CUDNN=OFF \
-DBUILD_TEST=ON \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CUDA_ARCHITECTURES=86
cmake --build build -j$(nproc) --target cifar10 test_autograd_cpu test_autograd_cuda
```

### Optional cuDNN-Accelerated Build

```bash
cmake -S . -B build_cudnn \
-DUSE_CUDA=ON \
-DUSE_NCCL=ON \
-DUSE_CUDNN=ON \
-DCUDNN_ROOT=/path/to/cudnn \
-DBUILD_TEST=ON \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CUDA_ARCHITECTURES=86
cmake --build build_cudnn -j$(nproc) --target cifar10 test_autograd_cuda
```

### CPU-Only Build

```bash
cmake -S . -B build_cpu \
-DUSE_CUDA=OFF \
-DUSE_NCCL=OFF \
-DBUILD_TEST=ON \
-DCMAKE_BUILD_TYPE=Release
cmake --build build_cpu -j$(nproc)
ctest --test-dir build_cpu --output-on-failure
```

## Dataset Preparation

Download and extract the official CIFAR-10 binary distribution (`cifar-10-binary.tar.gz`) so that `cifar-10-batches-bin/data_batch_{1..5}.bin` and `test_batch.bin` reside under `<DATASET_DIR>`:

```bash
mkdir -p data/cifar10 && cd data/cifar10
curl -LO https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz
tar -xzf cifar-10-binary.tar.gz
```

## Training Examples

### Single-GPU Training (20 Epochs, Baseline Augmentation)

```bash
# ResNet-18 (CIFAR-10 3x3 stride-1 stem)
./build/cifar10 \
--dataset=data/cifar10 \
--model=resnet18 \
--device=cuda \
--bs=128 --epochs=20 \
--lr=0.1 --momentum=0.9 --weight_decay=5e-4 \
--augment=true \
--save_ckpt=ckpts/resnet18_e20.bin

# MobileNetV2 (width_mult=1.0, CIFAR-10 adapted strides)
./build/cifar10 \
--dataset=data/cifar10 \
--model=mobilenetv2 \
--device=cuda \
--bs=128 --epochs=20 \
--lr=0.1 --momentum=0.9 --weight_decay=5e-4 \
--augment=true \
--save_ckpt=ckpts/mobilenetv2_e20.bin
```

### 2-GPU DDP Training

```bash
CUDA_VISIBLE_DEVICES=0,1 ./build/cifar10 \
--dataset=data/cifar10 \
--model=resnet18 \
--device=cuda \
--nthread_per_process=2 \
--bs=128 --epochs=20 \
--lr=0.1 --momentum=0.9 --weight_decay=5e-4 \
--augment=true \
--save_ckpt=ckpts/resnet18_ddp2_e20.bin
```

### Checkpoint Resume & Single-CPU Smoke Run

```bash
# Resume training from saved checkpoint
./build/cifar10 --dataset=data/cifar10 --model=resnet18 --device=cuda \
--load_ckpt=ckpts/resnet18_e20.bin --epochs=25

# CPU smoke test
./build/cifar10 --dataset=data/cifar10 --model=resnet18 --device=cpu --bs=16 --epochs=1
```

## Numerical Alignment & Throughput Verification

```bash
# Run operator unit tests (CPU + CUDA)
./build/tests/autograd/test_autograd_cpu --gtest_filter='*AutogradCVTest*'
./build/tests/autograd/test_autograd_cuda --gtest_filter='*AutogradCVTest*'

# Run end-to-end PyTorch alignment, checkpoint resume, 2-GPU DDP grad check, and throughput benchmark
python3 example/cifar10/verify_pytorch_alignment.py --binary=./build/cifar10

# (Optional) Export standalone PyTorch reference weights to example/cifar10/weights/
python3 example/cifar10/export_alignment_weights.py
```

## Verified Results (NVIDIA A40 46GB, FP32, TF32=OFF)

### 20-Epoch CIFAR-10 Convergence (`bs=128`, SGD `momentum=0.9`, `wd=5e-4`, Cosine LR `0.1`, Baseline Augment)

| Model | Config | Final Test Acc (Epoch 20) | Peak Test Acc | Target |
| --- | --- | --- | --- | --- |
| **ResNet-18** | 1× A40 | **91.94%** (9194/10000) | **92.02%** | ≥ 80% |
| **ResNet-18** | 2× A40 DDP | **91.12%** (9112/10000) | **91.12%** | ≥ 80% |
| **MobileNetV2** | 1× A40 | **91.38%** (9138/10000) | **91.38%** | ≥ 70% |
| **MobileNetV2** | 2× A40 DDP | **90.44%** (9044/10000) | **90.44%** | ≥ 70% |

### Single-GPU CUDA Throughput vs PyTorch (FP32, `3x32x32`, deterministic cuDNN)

| Model | Batch Size | PyTorch (cuDNN) | InfiniTrain (`USE_CUDNN=OFF`) | InfiniTrain (`USE_CUDNN=ON`, deterministic) |
| --- | --- | --- | --- | --- |
| **ResNet-18** | 32 | 2,800.0 img/s | 1,727.4 img/s (61.7%) | **1,988.7 img/s (71.0%)** |
| **ResNet-18** | 64 | 3,269.1 img/s | 1,794.1 img/s (54.9%) | **2,350.3 img/s (71.9%)** |
| **ResNet-18** | 128 | 3,651.5 img/s | 1,828.2 img/s (50.1%) | **2,816.8 img/s (77.1%)** |
| **ResNet-18** | 256 | 3,732.7 img/s | 1,839.8 img/s (49.3%) | **2,854.5 img/s (76.5%)** |
| **MobileNetV2** | 32 | 2,385.5 img/s | 1,839.0 img/s (77.1%) | **1,352.8 img/s (56.7%)** |
| **MobileNetV2** | 64 | 2,896.8 img/s | 1,997.4 img/s (69.0%) | **1,826.2 img/s (63.0%)** |
| **MobileNetV2** | 128 | 3,394.3 img/s | 2,129.5 img/s (62.7%) | **2,165.9 img/s (63.8%)** |
| **MobileNetV2** | 256 | 3,491.3 img/s | 2,179.1 img/s (62.4%) | **2,419.3 img/s (69.3%)** |

*(With non-deterministic cuDNN backward algorithms enabled, single-GPU ResNet-18 reaches up to 3,144.7 img/s / 91.6% of PyTorch and 2-GPU DDP reaches 6,039.3 img/s; deterministic cuDNN is selected by default so checkpoint resume is bitwise-identical.)*

### 2-GPU DDP Scaling (`bs_per_rank=128`, FP32)

| Model | Backend | 1-GPU | 2-GPU DDP | Speedup | DDP Grad Max Diff |
| --- | --- | --- | --- | --- | --- |
| **ResNet-18** | Custom CUDA (`USE_CUDNN=OFF`) | 1,828.2 img/s | 3,476.1 img/s | **1.90×** | `0.00e+00` |
| **ResNet-18** | cuDNN (`USE_CUDNN=ON`, det.) | 2,792.9 img/s | **5,378.3 img/s** | **1.93×** | `0.00e+00` |
| **MobileNetV2** | Custom CUDA (`USE_CUDNN=OFF`) | 2,129.5 img/s | 4,152.2 img/s | **1.95×** | `0.00e+00` |
| **MobileNetV2** | cuDNN (`USE_CUDNN=ON`, det.) | 2,166.6 img/s | **4,095.0 img/s** | **1.89×** | `0.00e+00` |
21 changes: 21 additions & 0 deletions example/cifar10/REFERENCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 参考资源说明(REFERENCE.md)

本次赛题(2026 秋季启元人工智能大赛 — 赛道二 赛题二:InfiniTrain 小型视觉模型训练支持)提交的全部 C++/CUDA 算子实现、Autograd 封装、Module/Optimizer 扩展、CIFAR-10 数据集加载与 DDP 训练示例、Checkpoint 读写及数值对齐验证脚本均由参赛选手 **闫超美(启忆智存 / `yanchaomei`)** 独立设计与编写。

实现过程中参考的公开学术论文、官方框架数学定义及标准数据集规范如下:

1. **PyTorch & TorchVision 官方文档与数学定义**
- **链接**:https://github.com/pytorch/pytorch 、https://github.com/pytorch/vision
- **开源协议**:BSD-3-Clause
- **参考内容**:`nn.Conv2d`、`nn.BatchNorm2d`(含无偏方差更新 `running_var` 与 train/eval 行为)、`nn.ReLU`、`nn.ReLU6`、`nn.MaxPool2d`、`nn.AdaptiveAvgPool2d`、`nn.Flatten`、`nn.init.kaiming_normal_` 及 `torch.optim.SGD`(含 `momentum` 与 `weight_decay` 更新公式)的公开数学定义与接口语义;`ResNet-18`(CIFAR-10 3×3 stride-1 stem 变体)与 `MobileNetV2`(CIFAR-10 适配 stride)的层结构与权重命名规范,用于确保与 PyTorch 参考模型的 1:1 数值对齐验证。
- **独立开发与优化说明**:全部 CPU/CUDA 前反向内核、InfiniTrain Autograd/Module/Dispatcher 注册、`Conv2d` 零依赖自研多路径 CUDA 内核(Depthwise 专用 kernel、1×1 零 im2col Strided-Batched GEMM、分块 im2col + cuBLAS SGEMM、确定性 gather col2im、线程局部可复用显存工作区)与可选确定性 cuDNN 后端、FP64 统计累加 `BatchNorm2d`、融合 `SGDAccumulateGrad` 内核及完整 DDP 训练/Checkpoint 续训流程均为独立从零实现。

2. **Deep Residual Learning for Image Recognition (ResNet) & MobileNetV2 原始论文**
- **链接**:https://arxiv.org/abs/1512.03385 、https://arxiv.org/abs/1801.04381
- **参考内容**:残差块(BasicBlock)与倒残差块(InvertedResidual)结构定义及超参数配置。
- **独立开发说明**:基于 InfiniTrain `nn::CloneableModule` 与 `nn::Sequential` 独立构建 C++ 模型实现。

3. **CIFAR-10 官方二进制数据集格式**
- **链接**:https://www.cs.toronto.edu/~kriz/cifar.html
- **参考内容**:`data_batch_{1..5}.bin` / `test_batch.bin` 每条样本 `1 byte label + 3072 bytes CHW uint8` 的标准二进制格式说明。
- **独立开发说明**:在 `example/cifar10/dataset.{h,cc}` 中独立实现 OpenMP 批构建、数据增强与无重叠确定性 DDP 分片逻辑。
Loading