Files
nvdriver/tools/cuda_ddp_training_parity.c
morebrackets 60b7ef23b3 tools: guard unchecked host allocations, NUL-terminate NVRTC PTX, and replace sprintf in C parity suites
- tools/cuda_parity_suite.c: add must_malloc/must_calloc helpers guarding all 11 previously unchecked host allocations (memset, cuBLAS SGEMM/TensorCore/batched, cuFFT 1D/2D, cuRAND, cuBLASLt, NVRTC PTX), NUL-terminate NVRTC PTX buffer, and replace sprintf with bounded snprintf for UUID hex formatting.
- tools/cuda_ddp_training_parity.c & tools/cuda_ml_training_parity.c: add must_malloc/must_calloc guarding NVRTC compile log, PTX buffer (allocated as ptx_sz + 1 and explicitly NUL-terminated), and host weight buffers; destroy nvrtcProgram on compile failure before returning.
- tools/cuda_multigpu_parity.c: add must_malloc/must_calloc guarding h_tmp, h_expected_sum, h_in[g], and h_out[g].
2026-12-02 03:10:55 -08:00

1136 lines
48 KiB
C

/* N-GPU Distributed Data-Parallel (DDP) FP16/FP32 Tensor Core Transformer-FFN
* Training Parity Test with Direct PCIe BAR1 P2P Ring AllReduce.
*
* Supports arbitrary N = device_count >= 2 GPUs (e.g., 2, 4, 8 Tesla V100s).
*
* Uses unmodified NVIDIA CUDA libraries via dlopen:
* - libcuda.so.1 (CUDA Driver API + bidirectional ring BAR1 P2P)
* - libcublas.so.11 (cublasGemmEx with CUBLAS_COMPUTE_32F_FAST_16F Tensor Cores)
* - libnvrtc.so.11.2 (runtime CUDA C++ -> PTX compilation for compute_70)
* - libcurand.so.10 (CURAND_RNG_PSEUDO_PHILOX4_32_10 weight & micro-batch init)
*
* Build:
* cc -O2 -Wall -Wextra tools/cuda_ddp_training_parity.c -ldl -lm -o target/hardware-hello/cuda-ddp-training-parity
*/
#include <dlfcn.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int CUresult;
typedef int CUdevice;
typedef void *CUcontext;
typedef void *CUmodule;
typedef void *CUfunction;
typedef void *CUstream;
typedef uint64_t CUdeviceptr;
typedef void *cublasHandle_t;
typedef void *curandGenerator_t;
typedef void *nvrtcProgram;
#define CUBLAS_OP_N 0
#define CUBLAS_OP_T 1
#define CUDA_R_32F 0
#define CUDA_R_16F 2
#define CUBLAS_COMPUTE_32F_FAST_16F 74
#define CUBLAS_GEMM_DEFAULT_TENSOR_OP 99
#define CURAND_RNG_PSEUDO_PHILOX4_32_10 161
#define CU_STREAM_NON_BLOCKING 1
#define MAX_GPUS 16
#define MICRO_BATCH 16
#define D_MODEL 256
#define D_FF 512
#define NUM_CLASSES 32
#define NUM_STEPS 8
#define NUM_PARAMS 10
static void *must_sym(void *lib, const char *name) {
void *sym = dlsym(lib, name);
if (!sym) {
fprintf(stderr, "dlsym(%s) failed: %s\n", name, dlerror());
exit(2);
}
return sym;
}
static void *must_malloc(size_t bytes) {
void *p = malloc(bytes ? bytes : 1);
if (!p) {
fprintf(stderr, "malloc(%zu) failed\n", bytes);
exit(2);
}
return p;
}
static void *must_calloc(size_t nmemb, size_t size) {
void *p = calloc(nmemb ? nmemb : 1, size ? size : 1);
if (!p) {
fprintf(stderr, "calloc(%zu, %zu) failed\n", nmemb, size);
exit(2);
}
return p;
}
#define CHECK_CU(expr) \
do { \
CUresult _r = (expr); \
if (_r != 0) { \
fprintf(stderr, "CUDA error %d at %s:%d: %s\n", \
_r, __FILE__, __LINE__, #expr); \
exit(1); \
} \
} while (0)
#define CHECK_LIB(expr) \
do { \
int _r = (expr); \
if (_r != 0) { \
fprintf(stderr, "Library error %d at %s:%d: %s\n", \
_r, __FILE__, __LINE__, #expr); \
exit(1); \
} \
} while (0)
/* NVRTC CUDA C++ training + direct BAR1 P2P Ring AllReduce kernels for compute_70 */
static const char DDP_TRAINING_KERNELS_CU[] =
"__device__ __forceinline__ unsigned short f32_to_f16_bits(float x) {\n"
" unsigned short h;\n"
" asm(\"cvt.rn.f16.f32 %0, %1;\" : \"=h\"(h) : \"f\"(x));\n"
" return h;\n"
"}\n"
"__device__ __forceinline__ float f16_to_f32_bits(unsigned short h) {\n"
" float x;\n"
" asm(\"cvt.f32.f16 %0, %1;\" : \"=f\"(x) : \"h\"(h));\n"
" return x;\n"
"}\n"
"\n"
"extern \"C\" __global__ void cast_f32_to_f16(const float *in, unsigned short *out, int n) {\n"
" int i = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (i < n) out[i] = f32_to_f16_bits(in[i]);\n"
"}\n"
"\n"
"extern \"C\" __global__ void layernorm_fwd(\n"
" const float *x, const float *gamma, const float *beta,\n"
" float *y, float *mean_out, float *rstd_out, int B, int D, float eps\n"
") {\n"
" int b = blockIdx.x;\n"
" if (b >= B) return;\n"
" int tid = threadIdx.x;\n"
" __shared__ float sdata[256];\n"
" const float *row = x + b * D;\n"
" float sum = 0.0f;\n"
" for (int i = tid; i < D; i += blockDim.x) sum += row[i];\n"
" sdata[tid] = sum;\n"
" __syncthreads();\n"
" for (int s = blockDim.x >> 1; s > 0; s >>= 1) {\n"
" if (tid < s) sdata[tid] += sdata[tid + s];\n"
" __syncthreads();\n"
" }\n"
" float mean = sdata[0] / (float)D;\n"
" __syncthreads();\n"
" float vsum = 0.0f;\n"
" for (int i = tid; i < D; i += blockDim.x) {\n"
" float d = row[i] - mean;\n"
" vsum += d * d;\n"
" }\n"
" sdata[tid] = vsum;\n"
" __syncthreads();\n"
" for (int s = blockDim.x >> 1; s > 0; s >>= 1) {\n"
" if (tid < s) sdata[tid] += sdata[tid + s];\n"
" __syncthreads();\n"
" }\n"
" float rstd = rsqrtf(sdata[0] / (float)D + eps);\n"
" if (tid == 0) {\n"
" mean_out[b] = mean;\n"
" rstd_out[b] = rstd;\n"
" }\n"
" float *yrow = y + b * D;\n"
" for (int i = tid; i < D; i += blockDim.x) {\n"
" float norm = (row[i] - mean) * rstd;\n"
" yrow[i] = norm * gamma[i] + beta[i];\n"
" }\n"
"}\n"
"\n"
"extern \"C\" __global__ void layernorm_bwd_dx(\n"
" const float *dy, const float *x, const float *mean_in, const float *rstd_in,\n"
" const float *gamma, float *dx, int B, int D\n"
") {\n"
" int b = blockIdx.x;\n"
" if (b >= B) return;\n"
" int tid = threadIdx.x;\n"
" __shared__ float s1[256];\n"
" __shared__ float s2[256];\n"
" const float *xrow = x + b * D;\n"
" const float *dyrow = dy + b * D;\n"
" float mean = mean_in[b];\n"
" float rstd = rstd_in[b];\n"
" float sum1 = 0.0f, sum2 = 0.0f;\n"
" for (int i = tid; i < D; i += blockDim.x) {\n"
" float xhat = (xrow[i] - mean) * rstd;\n"
" float g = dyrow[i] * gamma[i];\n"
" sum1 += g;\n"
" sum2 += g * xhat;\n"
" }\n"
" s1[tid] = sum1;\n"
" s2[tid] = sum2;\n"
" __syncthreads();\n"
" for (int s = blockDim.x >> 1; s > 0; s >>= 1) {\n"
" if (tid < s) {\n"
" s1[tid] += s1[tid + s];\n"
" s2[tid] += s2[tid + s];\n"
" }\n"
" __syncthreads();\n"
" }\n"
" float mean_g = s1[0] / (float)D;\n"
" float mean_gx = s2[0] / (float)D;\n"
" float *dxrow = dx + b * D;\n"
" for (int i = tid; i < D; i += blockDim.x) {\n"
" float xhat = (xrow[i] - mean) * rstd;\n"
" float g = dyrow[i] * gamma[i];\n"
" dxrow[i] = (g - mean_g - xhat * mean_gx) * rstd;\n"
" }\n"
"}\n"
"\n"
"extern \"C\" __global__ void layernorm_bwd_dgamma_dbeta(\n"
" const float *dy, const float *x, const float *mean_in, const float *rstd_in,\n"
" float *dgamma, float *dbeta, int B, int D\n"
") {\n"
" int d = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (d >= D) return;\n"
" float sg = 0.0f, sb = 0.0f;\n"
" for (int b = 0; b < B; b++) {\n"
" float xhat = (x[b * D + d] - mean_in[b]) * rstd_in[b];\n"
" float g = dy[b * D + d];\n"
" sg += g * xhat;\n"
" sb += g;\n"
" }\n"
" dgamma[d] = sg;\n"
" dbeta[d] = sb;\n"
"}\n"
"\n"
"extern \"C\" __global__ void add_bias_gelu_fwd(\n"
" const float *in, const float *bias, float *pre_out, float *out, int B, int F\n"
") {\n"
" int idx = blockIdx.x * blockDim.x + threadIdx.x;\n"
" int total = B * F;\n"
" if (idx >= total) return;\n"
" float x = in[idx] + bias[idx % F];\n"
" pre_out[idx] = x;\n"
" const float k = 0.7978845608f;\n"
" float c = k * (x + 0.044715f * x * x * x);\n"
" float t = tanhf(c);\n"
" out[idx] = 0.5f * x * (1.0f + t);\n"
"}\n"
"\n"
"extern \"C\" __global__ void gelu_bwd(\n"
" const float *dout, const float *pre_in, float *dpre_out, int n\n"
") {\n"
" int idx = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (idx >= n) return;\n"
" float x = pre_in[idx];\n"
" const float k = 0.7978845608f;\n"
" float x2 = x * x;\n"
" float c = k * (x + 0.044715f * x * x2);\n"
" float t = tanhf(c);\n"
" float sech2 = 1.0f - t * t;\n"
" float dc_dx = k * (1.0f + 0.134145f * x2);\n"
" float dgelu = 0.5f * (1.0f + t) + 0.5f * x * sech2 * dc_dx;\n"
" dpre_out[idx] = dout[idx] * dgelu;\n"
"}\n"
"\n"
"extern \"C\" __global__ void add_residual_bias(\n"
" const float *x, const float *h, const float *bias, float *out, int B, int D\n"
") {\n"
" int idx = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (idx >= B * D) return;\n"
" out[idx] = x[idx] + h[idx] + bias[idx % D];\n"
"}\n"
"\n"
"extern \"C\" __global__ void add_bias_inplace(float *y, const float *bias, int B, int C) {\n"
" int idx = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (idx >= B * C) return;\n"
" y[idx] += bias[idx % C];\n"
"}\n"
"\n"
"extern \"C\" __global__ void reduce_bias_grad(const float *dy, float *db, int B, int C) {\n"
" int c = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (c >= C) return;\n"
" float s = 0.0f;\n"
" for (int b = 0; b < B; b++) s += dy[b * C + c];\n"
" db[c] = s;\n"
"}\n"
"\n"
"extern \"C\" __global__ void softmax_ce_fwd_bwd(\n"
" const float *logits, const int *targets, float *dlogits, float *sample_loss, int B, int C\n"
") {\n"
" int b = blockIdx.x;\n"
" if (b >= B) return;\n"
" int tid = threadIdx.x;\n"
" if (tid >= C) return;\n"
" __shared__ float smax[64];\n"
" __shared__ float ssum[64];\n"
" float val = logits[b * C + tid];\n"
" smax[tid] = val;\n"
" __syncthreads();\n"
" for (int s = C >> 1; s > 0; s >>= 1) {\n"
" if (tid < s && smax[tid + s] > smax[tid]) smax[tid] = smax[tid + s];\n"
" __syncthreads();\n"
" }\n"
" float m = smax[0];\n"
" float e = expf(val - m);\n"
" ssum[tid] = e;\n"
" __syncthreads();\n"
" for (int s = C >> 1; s > 0; s >>= 1) {\n"
" if (tid < s) ssum[tid] += ssum[tid + s];\n"
" __syncthreads();\n"
" }\n"
" float denom = ssum[0];\n"
" float prob = e / denom;\n"
" int tgt = targets[b];\n"
" if (tid == tgt) {\n"
" sample_loss[b] = -logf(fmaxf(prob, 1e-12f));\n"
" }\n"
" float target_ind = (tid == tgt) ? 1.0f : 0.0f;\n"
" dlogits[b * C + tid] = (prob - target_ind) / (float)B;\n"
"}\n"
"\n"
"extern \"C\" __global__ void mean_loss_kernel(const float *sample_loss, float *loss_out, int B) {\n"
" if (threadIdx.x == 0 && blockIdx.x == 0) {\n"
" float s = 0.0f;\n"
" for (int b = 0; b < B; b++) s += sample_loss[b];\n"
" loss_out[0] = s / (float)B;\n"
" }\n"
"}\n"
"\n"
"extern \"C\" __global__ void p2p_ring_add_f32(\n"
" const float *local_grad, const float *peer_buf, float *out,\n"
" int offset, int count, float scale\n"
") {\n"
" int i = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (i < count) {\n"
" int idx = offset + i;\n"
" out[idx] = (local_grad[idx] + peer_buf[idx]) * scale;\n"
" }\n"
"}\n"
"\n"
"extern \"C\" __global__ void p2p_ring_copy_f32(\n"
" const float *peer_buf, float *out, int offset, int count\n"
") {\n"
" int i = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (i < count) {\n"
" int idx = offset + i;\n"
" out[idx] = peer_buf[idx];\n"
" }\n"
"}\n"
"\n"
"extern \"C\" __global__ void adamw_step(\n"
" float *w, const float *g, float *m, float *v, const int *step_ptr,\n"
" int n, float lr, float beta1, float beta2, float eps, float wd\n"
") {\n"
" int i = blockIdx.x * blockDim.x + threadIdx.x;\n"
" if (i >= n) return;\n"
" int step = step_ptr[0];\n"
" float gi = g[i];\n"
" float mi = beta1 * m[i] + (1.0f - beta1) * gi;\n"
" float vi = beta2 * v[i] + (1.0f - beta2) * gi * gi;\n"
" m[i] = mi;\n"
" v[i] = vi;\n"
" float bc1 = 1.0f - powf(beta1, (float)step);\n"
" float bc2 = 1.0f - powf(beta2, (float)step);\n"
" float mhat = mi / bc1;\n"
" float vhat = vi / bc2;\n"
" float wi = w[i];\n"
" wi -= lr * wd * wi;\n"
" wi -= lr * mhat / (sqrtf(vhat) + eps);\n"
" w[i] = wi;\n"
"}\n"
"\n"
"extern \"C\" __global__ void inc_step_kernel(int *step_ptr) {\n"
" if (threadIdx.x == 0 && blockIdx.x == 0) {\n"
" step_ptr[0] += 1;\n"
" }\n"
"}\n";
typedef struct {
CUdevice dev;
CUcontext ctx;
CUmodule mod;
CUstream stream;
cublasHandle_t bh;
CUresult (*cuLaunchKernel)(CUfunction, unsigned int, unsigned int, unsigned int,
unsigned int, unsigned int, unsigned int,
unsigned int, CUstream, void **, void **);
int (*cublasGemmEx)(cublasHandle_t, int, int, int, int, int,
const void *, const void *, int, int,
const void *, int, int,
const void *, void *, int, int, int, int);
CUfunction fn_cast_f32_f16;
CUfunction fn_ln_fwd;
CUfunction fn_ln_bwd_dx;
CUfunction fn_ln_bwd_dg;
CUfunction fn_bias_gelu_fwd;
CUfunction fn_gelu_bwd;
CUfunction fn_res_bias;
CUfunction fn_add_bias;
CUfunction fn_reduce_bias;
CUfunction fn_softmax_ce;
CUfunction fn_mean_loss;
CUfunction fn_p2p_ring_add;
CUfunction fn_p2p_ring_copy;
CUfunction fn_adamw;
CUfunction fn_inc_step;
/* Data */
CUdeviceptr d_x, d_targets, d_step, d_sample_loss, d_loss;
/* Master FP32 parameters, local grads, ring accumulator, P2P-averaged grads, AdamW m/v */
CUdeviceptr d_params[NUM_PARAMS];
CUdeviceptr d_grads[NUM_PARAMS];
CUdeviceptr d_grads_acc[NUM_PARAMS];
CUdeviceptr d_grads_avg[NUM_PARAMS];
CUdeviceptr d_m[NUM_PARAMS];
CUdeviceptr d_v[NUM_PARAMS];
/* Named aliases into d_params / d_grads:
* 0:w1, 1:b1, 2:w2, 3:b2, 4:w3, 5:b3, 6:gamma1, 7:beta1, 8:gamma2, 9:beta2
*/
/* FP16 weight & activation buffers for Tensor Core GEMMs */
CUdeviceptr d_w1_h, d_w2_h, d_w3_h;
CUdeviceptr d_x_ln1, d_x_ln1_h, d_mean1, d_rstd1;
CUdeviceptr d_h1_raw, d_h1_pre, d_h1, d_h1_h;
CUdeviceptr d_h2_raw, d_res;
CUdeviceptr d_x_ln2, d_x_ln2_h, d_mean2, d_rstd2;
CUdeviceptr d_logits;
/* Backward activation buffers */
CUdeviceptr d_dlogits, d_dlogits_h;
CUdeviceptr d_dx_ln2, d_dres, d_dres_h;
CUdeviceptr d_dh1, d_dh1_pre, d_dh1_pre_h;
CUdeviceptr d_dx_ln1, d_dx;
} GpuWorker;
static const size_t PARAM_COUNTS[NUM_PARAMS] = {
D_MODEL * D_FF, /* 0: w1 */
D_FF, /* 1: b1 */
D_FF * D_MODEL, /* 2: w2 */
D_MODEL, /* 3: b2 */
D_MODEL * NUM_CLASSES, /* 4: w3 */
NUM_CLASSES, /* 5: b3 */
D_MODEL, /* 6: gamma1 */
D_MODEL, /* 7: beta1 */
D_MODEL, /* 8: gamma2 */
D_MODEL /* 9: beta2 */
};
static const float PARAM_WD[NUM_PARAMS] = {
1e-2f, 0.0f, 1e-2f, 0.0f, 1e-2f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f
};
static void launch_1d(GpuWorker *w, CUfunction fn, int n, void **args) {
if (n <= 0) return;
unsigned int threads = 256;
unsigned int blocks = (unsigned int)((n + (int)threads - 1) / (int)threads);
CHECK_CU(w->cuLaunchKernel(fn, blocks, 1, 1, threads, 1, 1, 0, w->stream, args, NULL));
}
static void launch_cast_f32_f16(GpuWorker *w, CUdeviceptr in, CUdeviceptr out, int n) {
void *args[] = {&in, &out, &n};
launch_1d(w, w->fn_cast_f32_f16, n, args);
}
static void gemm_fwd_f16_f32(GpuWorker *w, CUdeviceptr A, CUdeviceptr B, CUdeviceptr C,
int M, int N, int K) {
float alpha = 1.0f, beta = 0.0f;
CHECK_LIB(w->cublasGemmEx(
w->bh, CUBLAS_OP_N, CUBLAS_OP_N, N, M, K, &alpha,
(const void *)(uintptr_t)B, CUDA_R_16F, N,
(const void *)(uintptr_t)A, CUDA_R_16F, K,
&beta, (void *)(uintptr_t)C, CUDA_R_32F, N,
CUBLAS_COMPUTE_32F_FAST_16F, CUBLAS_GEMM_DEFAULT_TENSOR_OP));
}
static void gemm_dw_f16_f32(GpuWorker *w, CUdeviceptr A, CUdeviceptr dC, CUdeviceptr dW,
int M, int N, int K) {
float alpha = 1.0f, beta = 0.0f;
CHECK_LIB(w->cublasGemmEx(
w->bh, CUBLAS_OP_N, CUBLAS_OP_T, N, K, M, &alpha,
(const void *)(uintptr_t)dC, CUDA_R_16F, N,
(const void *)(uintptr_t)A, CUDA_R_16F, K,
&beta, (void *)(uintptr_t)dW, CUDA_R_32F, N,
CUBLAS_COMPUTE_32F_FAST_16F, CUBLAS_GEMM_DEFAULT_TENSOR_OP));
}
static void gemm_da_f16_f32(GpuWorker *w, CUdeviceptr dC, CUdeviceptr B, CUdeviceptr dA,
int M, int N, int K) {
float alpha = 1.0f, beta = 0.0f;
CHECK_LIB(w->cublasGemmEx(
w->bh, CUBLAS_OP_T, CUBLAS_OP_N, K, M, N, &alpha,
(const void *)(uintptr_t)B, CUDA_R_16F, N,
(const void *)(uintptr_t)dC, CUDA_R_16F, N,
&beta, (void *)(uintptr_t)dA, CUDA_R_32F, K,
CUBLAS_COMPUTE_32F_FAST_16F, CUBLAS_GEMM_DEFAULT_TENSOR_OP));
}
static void enqueue_fwd_bwd(GpuWorker *w) {
int B = MICRO_BATCH, D = D_MODEL, F = D_FF, C = NUM_CLASSES;
float ln_eps = 1e-5f;
/* 1. LayerNorm 1 forward */
{
void *args[] = {&w->d_x, &w->d_params[6], &w->d_params[7], &w->d_x_ln1,
&w->d_mean1, &w->d_rstd1, &B, &D, &ln_eps};
CHECK_CU(w->cuLaunchKernel(w->fn_ln_fwd, (unsigned int)B, 1, 1, 256, 1, 1, 0, w->stream, args, NULL));
}
/* 2. Cast X_ln1 & W1 to FP16, then Tensor Core GEMM: H1_raw[B, F] = X_ln1_h @ W1_h */
launch_cast_f32_f16(w, w->d_x_ln1, w->d_x_ln1_h, B * D);
launch_cast_f32_f16(w, w->d_params[0], w->d_w1_h, D * F);
gemm_fwd_f16_f32(w, w->d_x_ln1_h, w->d_w1_h, w->d_h1_raw, B, F, D);
/* 3. Add bias1 + GELU forward */
{
void *args[] = {&w->d_h1_raw, &w->d_params[1], &w->d_h1_pre, &w->d_h1, &B, &F};
launch_1d(w, w->fn_bias_gelu_fwd, B * F, args);
}
/* 4. Cast H1 & W2 to FP16, then Tensor Core GEMM: H2_raw[B, D] = H1_h @ W2_h */
launch_cast_f32_f16(w, w->d_h1, w->d_h1_h, B * F);
launch_cast_f32_f16(w, w->d_params[2], w->d_w2_h, F * D);
gemm_fwd_f16_f32(w, w->d_h1_h, w->d_w2_h, w->d_h2_raw, B, D, F);
/* 5. Residual + bias2: Res = X + H2_raw + b2 */
{
void *args[] = {&w->d_x, &w->d_h2_raw, &w->d_params[3], &w->d_res, &B, &D};
launch_1d(w, w->fn_res_bias, B * D, args);
}
/* 6. LayerNorm 2 forward */
{
void *args[] = {&w->d_res, &w->d_params[8], &w->d_params[9], &w->d_x_ln2,
&w->d_mean2, &w->d_rstd2, &B, &D, &ln_eps};
CHECK_CU(w->cuLaunchKernel(w->fn_ln_fwd, (unsigned int)B, 1, 1, 256, 1, 1, 0, w->stream, args, NULL));
}
/* 7. Cast X_ln2 & W3 to FP16, then Tensor Core GEMM: Logits[B, C] = X_ln2_h @ W3_h + b3 */
launch_cast_f32_f16(w, w->d_x_ln2, w->d_x_ln2_h, B * D);
launch_cast_f32_f16(w, w->d_params[4], w->d_w3_h, D * C);
gemm_fwd_f16_f32(w, w->d_x_ln2_h, w->d_w3_h, w->d_logits, B, C, D);
{
void *args[] = {&w->d_logits, &w->d_params[5], &B, &C};
launch_1d(w, w->fn_add_bias, B * C, args);
}
/* 8. Softmax + Cross-Entropy loss & dLogits */
{
void *args[] = {&w->d_logits, &w->d_targets, &w->d_dlogits, &w->d_sample_loss, &B, &C};
CHECK_CU(w->cuLaunchKernel(w->fn_softmax_ce, (unsigned int)B, 1, 1, (unsigned int)C, 1, 1, 0, w->stream, args, NULL));
}
{
void *args[] = {&w->d_sample_loss, &w->d_loss, &B};
CHECK_CU(w->cuLaunchKernel(w->fn_mean_loss, 1, 1, 1, 1, 1, 1, 0, w->stream, args, NULL));
}
/* 9. Backward through Classifier Head */
{
void *args[] = {&w->d_dlogits, &w->d_grads[5], &B, &C};
launch_1d(w, w->fn_reduce_bias, C, args);
}
launch_cast_f32_f16(w, w->d_dlogits, w->d_dlogits_h, B * C);
gemm_dw_f16_f32(w, w->d_x_ln2_h, w->d_dlogits_h, w->d_grads[4], B, C, D);
gemm_da_f16_f32(w, w->d_dlogits_h, w->d_w3_h, w->d_dx_ln2, B, C, D);
/* 10. Backward through LayerNorm 2 */
{
void *args[] = {&w->d_dx_ln2, &w->d_res, &w->d_mean2, &w->d_rstd2,
&w->d_params[8], &w->d_dres, &B, &D};
CHECK_CU(w->cuLaunchKernel(w->fn_ln_bwd_dx, (unsigned int)B, 1, 1, 256, 1, 1, 0, w->stream, args, NULL));
}
{
void *args[] = {&w->d_dx_ln2, &w->d_res, &w->d_mean2, &w->d_rstd2,
&w->d_grads[8], &w->d_grads[9], &B, &D};
launch_1d(w, w->fn_ln_bwd_dg, D, args);
}
/* 11. Backward through FFN Layer 2 */
{
void *args[] = {&w->d_dres, &w->d_grads[3], &B, &D};
launch_1d(w, w->fn_reduce_bias, D, args);
}
launch_cast_f32_f16(w, w->d_dres, w->d_dres_h, B * D);
gemm_dw_f16_f32(w, w->d_h1_h, w->d_dres_h, w->d_grads[2], B, D, F);
gemm_da_f16_f32(w, w->d_dres_h, w->d_w2_h, w->d_dh1, B, D, F);
/* 12. Backward through GELU + FFN Layer 1 */
{
int n = B * F;
void *args[] = {&w->d_dh1, &w->d_h1_pre, &w->d_dh1_pre, &n};
launch_1d(w, w->fn_gelu_bwd, n, args);
}
{
void *args[] = {&w->d_dh1_pre, &w->d_grads[1], &B, &F};
launch_1d(w, w->fn_reduce_bias, F, args);
}
launch_cast_f32_f16(w, w->d_dh1_pre, w->d_dh1_pre_h, B * F);
gemm_dw_f16_f32(w, w->d_x_ln1_h, w->d_dh1_pre_h, w->d_grads[0], B, F, D);
gemm_da_f16_f32(w, w->d_dh1_pre_h, w->d_w1_h, w->d_dx_ln1, B, F, D);
/* 13. Backward through LayerNorm 1 */
{
void *args[] = {&w->d_dx_ln1, &w->d_x, &w->d_mean1, &w->d_rstd1,
&w->d_params[6], &w->d_dx, &B, &D};
CHECK_CU(w->cuLaunchKernel(w->fn_ln_bwd_dx, (unsigned int)B, 1, 1, 256, 1, 1, 0, w->stream, args, NULL));
}
{
void *args[] = {&w->d_dx_ln1, &w->d_x, &w->d_mean1, &w->d_rstd1,
&w->d_grads[6], &w->d_grads[7], &B, &D};
launch_1d(w, w->fn_ln_bwd_dg, D, args);
}
}
/* Direct PCIe BAR1 P2P Ring AllReduce (Reduce-Scatter + AllGather).
*
* Every chunk is reduced along a single deterministic chain around the ring
* (each GPU reads directly from peer (g+1)%N over BAR1 P2P), divided by N once,
* and broadcast bit-for-bit around the ring so all N GPUs observe identical
* averaged gradients with zero floating-point associativity divergence.
*
* Within each ring step, GPUs execute in cycle-free bipartite waves (even GPUs
* concurrently, then odd GPUs concurrently, plus last GPU if N is odd) so no
* cyclic PCIe Non-Posted BAR1 read deadlock can occur across switches/sockets.
*/
static void run_p2p_ring_allreduce(
GpuWorker *workers, int num_gpus,
CUresult (*cuCtxSetCurrent)(CUcontext),
CUresult (*cuStreamSynchronize)(CUstream)
) {
float inv_n = 1.0f / (float)num_gpus;
int num_waves = (num_gpus % 2 == 0) ? 2 : 3;
/* Phase A: Ring Reduce-Scatter (num_gpus - 1 steps) */
for (int s = 0; s < num_gpus - 1; s++) {
int is_last = (s == num_gpus - 2);
float scale = is_last ? inv_n : 1.0f;
for (int wave = 0; wave < num_waves; wave++) {
for (int g = 0; g < num_gpus; g++) {
int g_wave = (num_gpus % 2 == 1 && g == num_gpus - 1) ? 2 : (g % 2);
if (g_wave != wave) continue;
int peer = (g + 1) % num_gpus;
int chunk = (g + s + 1) % num_gpus;
GpuWorker *local = &workers[g];
GpuWorker *remote = &workers[peer];
CHECK_CU(cuCtxSetCurrent(local->ctx));
for (int p = 0; p < NUM_PARAMS; p++) {
int n = (int)PARAM_COUNTS[p];
int offset = (n * chunk) / num_gpus;
int end = (n * (chunk + 1)) / num_gpus;
int count = end - offset;
if (count <= 0) continue;
CUdeviceptr local_g = local->d_grads[p];
CUdeviceptr peer_buf = (s == 0) ? remote->d_grads[p] : remote->d_grads_acc[p];
CUdeviceptr out_buf = is_last ? local->d_grads_avg[p] : local->d_grads_acc[p];
void *args[] = {&local_g, &peer_buf, &out_buf, &offset, &count, &scale};
launch_1d(local, local->fn_p2p_ring_add, count, args);
}
}
for (int g = 0; g < num_gpus; g++) {
int g_wave = (num_gpus % 2 == 1 && g == num_gpus - 1) ? 2 : (g % 2);
if (g_wave != wave) continue;
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
CHECK_CU(cuStreamSynchronize(workers[g].stream));
}
}
}
/* Phase B: Ring AllGather (num_gpus - 1 steps) */
for (int s = 0; s < num_gpus - 1; s++) {
for (int wave = 0; wave < num_waves; wave++) {
for (int g = 0; g < num_gpus; g++) {
int g_wave = (num_gpus % 2 == 1 && g == num_gpus - 1) ? 2 : (g % 2);
if (g_wave != wave) continue;
int peer = (g + 1) % num_gpus;
int chunk = (g + s) % num_gpus;
GpuWorker *local = &workers[g];
GpuWorker *remote = &workers[peer];
CHECK_CU(cuCtxSetCurrent(local->ctx));
for (int p = 0; p < NUM_PARAMS; p++) {
int n = (int)PARAM_COUNTS[p];
int offset = (n * chunk) / num_gpus;
int end = (n * (chunk + 1)) / num_gpus;
int count = end - offset;
if (count <= 0) continue;
CUdeviceptr peer_buf = remote->d_grads_avg[p];
CUdeviceptr out_buf = local->d_grads_avg[p];
void *args[] = {&peer_buf, &out_buf, &offset, &count};
launch_1d(local, local->fn_p2p_ring_copy, count, args);
}
}
for (int g = 0; g < num_gpus; g++) {
int g_wave = (num_gpus % 2 == 1 && g == num_gpus - 1) ? 2 : (g % 2);
if (g_wave != wave) continue;
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
CHECK_CU(cuStreamSynchronize(workers[g].stream));
}
}
}
}
static void enqueue_adamw_update(GpuWorker *w) {
float lr = 3e-3f, beta1 = 0.9f, beta2 = 0.999f, eps = 1e-8f;
for (int p = 0; p < NUM_PARAMS; p++) {
int n = (int)PARAM_COUNTS[p];
float wd = PARAM_WD[p];
void *args[] = {&w->d_params[p], &w->d_grads_avg[p], &w->d_m[p], &w->d_v[p],
&w->d_step, &n, &lr, &beta1, &beta2, &eps, &wd};
launch_1d(w, w->fn_adamw, n, args);
}
void *step_args[] = {&w->d_step};
CHECK_CU(w->cuLaunchKernel(w->fn_inc_step, 1, 1, 1, 1, 1, 1, 0, w->stream, step_args, NULL));
}
static uint32_t fnv1a_update_floats(uint32_t h, const float *buf, size_t count) {
for (size_t i = 0; i < count; i++) {
uint32_t bits = 0;
memcpy(&bits, &buf[i], sizeof(bits));
h ^= bits;
h *= 16777619u;
}
return h;
}
int main(void) {
void *cuda_lib = dlopen("libcuda.so.1", RTLD_NOW);
if (!cuda_lib) {
fprintf(stderr, "dlopen libcuda.so.1 failed: %s\n", dlerror());
return 2;
}
void *cublas_lib = dlopen("libcublas.so.11", RTLD_NOW);
if (!cublas_lib) {
fprintf(stderr, "dlopen libcublas.so.11 failed: %s\n", dlerror());
return 2;
}
void *nvrtc_lib = dlopen("libnvrtc.so.11.2", RTLD_NOW);
if (!nvrtc_lib) {
fprintf(stderr, "dlopen libnvrtc.so.11.2 failed: %s\n", dlerror());
return 2;
}
void *curand_lib = dlopen("libcurand.so.10", RTLD_NOW);
if (!curand_lib) {
fprintf(stderr, "dlopen libcurand.so.10 failed: %s\n", dlerror());
return 2;
}
/* Resolve CUDA Driver API symbols */
CUresult (*cuInit)(unsigned int) = must_sym(cuda_lib, "cuInit");
CUresult (*cuDeviceGetCount)(int *) = must_sym(cuda_lib, "cuDeviceGetCount");
CUresult (*cuDeviceGet)(CUdevice *, int) = must_sym(cuda_lib, "cuDeviceGet");
CUresult (*cuCtxCreate)(CUcontext *, unsigned int, CUdevice) = must_sym(cuda_lib, "cuCtxCreate_v2");
CUresult (*cuCtxDestroy)(CUcontext) = must_sym(cuda_lib, "cuCtxDestroy_v2");
CUresult (*cuCtxSetCurrent)(CUcontext) = must_sym(cuda_lib, "cuCtxSetCurrent");
CUresult (*cuDeviceCanAccessPeer)(int *, CUdevice, CUdevice) = must_sym(cuda_lib, "cuDeviceCanAccessPeer");
CUresult (*cuCtxEnablePeerAccess)(CUcontext, unsigned int) = must_sym(cuda_lib, "cuCtxEnablePeerAccess");
CUresult (*cuCtxDisablePeerAccess)(CUcontext) = must_sym(cuda_lib, "cuCtxDisablePeerAccess");
CUresult (*cuMemAlloc)(CUdeviceptr *, size_t) = must_sym(cuda_lib, "cuMemAlloc_v2");
CUresult (*cuMemFree)(CUdeviceptr) = must_sym(cuda_lib, "cuMemFree_v2");
CUresult (*cuMemsetD32)(CUdeviceptr, unsigned int, size_t) = must_sym(cuda_lib, "cuMemsetD32_v2");
CUresult (*cuMemcpyHtoD)(CUdeviceptr, const void *, size_t) = must_sym(cuda_lib, "cuMemcpyHtoD_v2");
CUresult (*cuMemcpyDtoH)(void *, CUdeviceptr, size_t) = must_sym(cuda_lib, "cuMemcpyDtoH_v2");
CUresult (*cuModuleLoadData)(CUmodule *, const void *) = must_sym(cuda_lib, "cuModuleLoadData");
CUresult (*cuModuleUnload)(CUmodule) = must_sym(cuda_lib, "cuModuleUnload");
CUresult (*cuModuleGetFunction)(CUfunction *, CUmodule, const char *) = must_sym(cuda_lib, "cuModuleGetFunction");
CUresult (*cuStreamCreate)(CUstream *, unsigned int) = must_sym(cuda_lib, "cuStreamCreate");
CUresult (*cuStreamDestroy)(CUstream) = must_sym(cuda_lib, "cuStreamDestroy_v2");
CUresult (*cuStreamSynchronize)(CUstream) = must_sym(cuda_lib, "cuStreamSynchronize");
CUresult (*cuLaunchKernel)(CUfunction, unsigned int, unsigned int, unsigned int,
unsigned int, unsigned int, unsigned int,
unsigned int, CUstream, void **, void **) =
must_sym(cuda_lib, "cuLaunchKernel");
/* Resolve cuBLAS symbols */
int (*cublasCreate)(cublasHandle_t *) = must_sym(cublas_lib, "cublasCreate_v2");
int (*cublasDestroy)(cublasHandle_t) = must_sym(cublas_lib, "cublasDestroy_v2");
int (*cublasSetStream)(cublasHandle_t, CUstream) = must_sym(cublas_lib, "cublasSetStream_v2");
int (*cublasGemmEx)(cublasHandle_t, int, int, int, int, int,
const void *, const void *, int, int,
const void *, int, int,
const void *, void *, int, int, int, int) =
must_sym(cublas_lib, "cublasGemmEx");
/* Resolve NVRTC symbols */
int (*nvrtcCreateProgram)(nvrtcProgram *, const char *, const char *, int,
const char *const *, const char *const *) = must_sym(nvrtc_lib, "nvrtcCreateProgram");
int (*nvrtcCompileProgram)(nvrtcProgram, int, const char *const *) = must_sym(nvrtc_lib, "nvrtcCompileProgram");
int (*nvrtcGetProgramLogSize)(nvrtcProgram, size_t *) = must_sym(nvrtc_lib, "nvrtcGetProgramLogSize");
int (*nvrtcGetProgramLog)(nvrtcProgram, char *) = must_sym(nvrtc_lib, "nvrtcGetProgramLog");
int (*nvrtcGetPTXSize)(nvrtcProgram, size_t *) = must_sym(nvrtc_lib, "nvrtcGetPTXSize");
int (*nvrtcGetPTX)(nvrtcProgram, char *) = must_sym(nvrtc_lib, "nvrtcGetPTX");
int (*nvrtcDestroyProgram)(nvrtcProgram *) = must_sym(nvrtc_lib, "nvrtcDestroyProgram");
/* Resolve cuRAND symbols */
int (*curandCreateGenerator)(curandGenerator_t *, int) = must_sym(curand_lib, "curandCreateGenerator");
int (*curandSetSeed)(curandGenerator_t, unsigned long long) =
must_sym(curand_lib, "curandSetPseudoRandomGeneratorSeed");
int (*curandGenerateNormal)(curandGenerator_t, float *, size_t, float, float) =
must_sym(curand_lib, "curandGenerateNormal");
int (*curandDestroyGenerator)(curandGenerator_t) = must_sym(curand_lib, "curandDestroyGenerator");
CHECK_CU(cuInit(0));
int dev_count = 0;
CHECK_CU(cuDeviceGetCount(&dev_count));
if (dev_count < 2) {
fprintf(stderr, "Need at least 2 GPUs, found %d\n", dev_count);
return 1;
}
int num_gpus = dev_count > MAX_GPUS ? MAX_GPUS : dev_count;
int global_batch = MICRO_BATCH * num_gpus;
/* Compile DDP training + P2P Ring AllReduce kernels at runtime via NVRTC */
nvrtcProgram prog = NULL;
const char *nvrtc_opts[] = {"--gpu-architecture=compute_70"};
CHECK_LIB(nvrtcCreateProgram(&prog, DDP_TRAINING_KERNELS_CU, "ddp_training_kernels.cu", 0, NULL, NULL));
int compile_rc = nvrtcCompileProgram(prog, 1, nvrtc_opts);
if (compile_rc != 0) {
size_t log_sz = 0;
nvrtcGetProgramLogSize(prog, &log_sz);
char *log = must_calloc(log_sz + 1, 1);
nvrtcGetProgramLog(prog, log);
fprintf(stderr, "NVRTC compile failed (%d):\n%s\n", compile_rc, log);
free(log);
nvrtcDestroyProgram(&prog);
return 1;
}
size_t ptx_sz = 0;
CHECK_LIB(nvrtcGetPTXSize(prog, &ptx_sz));
char *ptx = must_malloc(ptx_sz + 1);
CHECK_LIB(nvrtcGetPTX(prog, ptx));
ptx[ptx_sz] = '\0';
CHECK_LIB(nvrtcDestroyProgram(&prog));
GpuWorker workers[MAX_GPUS];
memset(workers, 0, sizeof(workers));
/* Create contexts on all N GPUs */
for (int g = 0; g < num_gpus; g++) {
CHECK_CU(cuDeviceGet(&workers[g].dev, g));
CHECK_CU(cuCtxCreate(&workers[g].ctx, 0, workers[g].dev));
workers[g].cuLaunchKernel = cuLaunchKernel;
workers[g].cublasGemmEx = cublasGemmEx;
}
/* Enable bidirectional direct PCIe BAR1 P2P around the ring: i <-> (i+1)%N */
int p2p_ring_enabled = 1;
for (int g = 0; g < num_gpus; g++) {
int next = (g + 1) % num_gpus;
int prev = (g + num_gpus - 1) % num_gpus;
int can_next = 0;
CHECK_CU(cuDeviceCanAccessPeer(&can_next, workers[g].dev, workers[next].dev));
if (!can_next) {
fprintf(stderr, "Ring P2P unavailable: GPU %d -> GPU %d\n", g, next);
p2p_ring_enabled = 0;
return 1;
}
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
CHECK_CU(cuCtxEnablePeerAccess(workers[next].ctx, 0));
if (prev != next) {
int can_prev = 0;
CHECK_CU(cuDeviceCanAccessPeer(&can_prev, workers[g].dev, workers[prev].dev));
if (!can_prev) {
fprintf(stderr, "Ring P2P unavailable: GPU %d -> GPU %d\n", g, prev);
p2p_ring_enabled = 0;
return 1;
}
CHECK_CU(cuCtxEnablePeerAccess(workers[prev].ctx, 0));
}
}
const size_t B = MICRO_BATCH, D = D_MODEL, F = D_FF, C = NUM_CLASSES;
float ones[D_MODEL];
for (int i = 0; i < D_MODEL; i++) ones[i] = 1.0f;
/* Allocate buffers, load kernels, and initialize identical master weights + split micro-batches */
for (int g = 0; g < num_gpus; g++) {
GpuWorker *w = &workers[g];
CHECK_CU(cuCtxSetCurrent(w->ctx));
CHECK_CU(cuModuleLoadData(&w->mod, ptx));
CHECK_CU(cuModuleGetFunction(&w->fn_cast_f32_f16, w->mod, "cast_f32_to_f16"));
CHECK_CU(cuModuleGetFunction(&w->fn_ln_fwd, w->mod, "layernorm_fwd"));
CHECK_CU(cuModuleGetFunction(&w->fn_ln_bwd_dx, w->mod, "layernorm_bwd_dx"));
CHECK_CU(cuModuleGetFunction(&w->fn_ln_bwd_dg, w->mod, "layernorm_bwd_dgamma_dbeta"));
CHECK_CU(cuModuleGetFunction(&w->fn_bias_gelu_fwd, w->mod, "add_bias_gelu_fwd"));
CHECK_CU(cuModuleGetFunction(&w->fn_gelu_bwd, w->mod, "gelu_bwd"));
CHECK_CU(cuModuleGetFunction(&w->fn_res_bias, w->mod, "add_residual_bias"));
CHECK_CU(cuModuleGetFunction(&w->fn_add_bias, w->mod, "add_bias_inplace"));
CHECK_CU(cuModuleGetFunction(&w->fn_reduce_bias, w->mod, "reduce_bias_grad"));
CHECK_CU(cuModuleGetFunction(&w->fn_softmax_ce, w->mod, "softmax_ce_fwd_bwd"));
CHECK_CU(cuModuleGetFunction(&w->fn_mean_loss, w->mod, "mean_loss_kernel"));
CHECK_CU(cuModuleGetFunction(&w->fn_p2p_ring_add, w->mod, "p2p_ring_add_f32"));
CHECK_CU(cuModuleGetFunction(&w->fn_p2p_ring_copy, w->mod, "p2p_ring_copy_f32"));
CHECK_CU(cuModuleGetFunction(&w->fn_adamw, w->mod, "adamw_step"));
CHECK_CU(cuModuleGetFunction(&w->fn_inc_step, w->mod, "inc_step_kernel"));
CHECK_CU(cuStreamCreate(&w->stream, CU_STREAM_NON_BLOCKING));
CHECK_LIB(cublasCreate(&w->bh));
CHECK_LIB(cublasSetStream(w->bh, w->stream));
CHECK_CU(cuMemAlloc(&w->d_x, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_targets, B * sizeof(int)));
CHECK_CU(cuMemAlloc(&w->d_step, sizeof(int)));
CHECK_CU(cuMemAlloc(&w->d_sample_loss, B * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_loss, sizeof(float)));
for (int p = 0; p < NUM_PARAMS; p++) {
size_t sz = PARAM_COUNTS[p] * sizeof(float);
CHECK_CU(cuMemAlloc(&w->d_params[p], sz));
CHECK_CU(cuMemAlloc(&w->d_grads[p], sz));
CHECK_CU(cuMemAlloc(&w->d_grads_acc[p], sz));
CHECK_CU(cuMemAlloc(&w->d_grads_avg[p], sz));
CHECK_CU(cuMemAlloc(&w->d_m[p], sz));
CHECK_CU(cuMemAlloc(&w->d_v[p], sz));
CHECK_CU(cuMemsetD32(w->d_m[p], 0, PARAM_COUNTS[p]));
CHECK_CU(cuMemsetD32(w->d_v[p], 0, PARAM_COUNTS[p]));
}
CHECK_CU(cuMemAlloc(&w->d_w1_h, D * F * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_w2_h, F * D * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_w3_h, D * C * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_x_ln1, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_x_ln1_h, B * D * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_mean1, B * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_rstd1, B * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_h1_raw, B * F * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_h1_pre, B * F * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_h1, B * F * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_h1_h, B * F * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_h2_raw, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_res, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_x_ln2, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_x_ln2_h, B * D * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_mean2, B * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_rstd2, B * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_logits, B * C * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_dlogits, B * C * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_dlogits_h, B * C * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_dx_ln2, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_dres, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_dres_h, B * D * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_dh1, B * F * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_dh1_pre, B * F * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_dh1_pre_h, B * F * sizeof(uint16_t)));
CHECK_CU(cuMemAlloc(&w->d_dx_ln1, B * D * sizeof(float)));
CHECK_CU(cuMemAlloc(&w->d_dx, B * D * sizeof(float)));
/* Initialize identical FP32 master weights on all N GPUs via cuRAND */
curandGenerator_t gen_w = NULL;
CHECK_LIB(curandCreateGenerator(&gen_w, CURAND_RNG_PSEUDO_PHILOX4_32_10));
CHECK_LIB(curandSetSeed(gen_w, 20261126ULL));
CHECK_LIB(curandGenerateNormal(gen_w, (float *)(uintptr_t)w->d_params[0], D * F, 0.0f, 0.0625f));
CHECK_LIB(curandGenerateNormal(gen_w, (float *)(uintptr_t)w->d_params[2], F * D, 0.0f, 0.0442f));
CHECK_LIB(curandGenerateNormal(gen_w, (float *)(uintptr_t)w->d_params[4], D * C, 0.0f, 0.0625f));
CHECK_LIB(curandDestroyGenerator(gen_w));
/* Initialize distinct micro-batch inputs on each GPU via cuRAND */
curandGenerator_t gen_x = NULL;
CHECK_LIB(curandCreateGenerator(&gen_x, CURAND_RNG_PSEUDO_PHILOX4_32_10));
CHECK_LIB(curandSetSeed(gen_x, 202611260ULL + (unsigned long long)g));
CHECK_LIB(curandGenerateNormal(gen_x, (float *)(uintptr_t)w->d_x, B * D, 0.0f, 1.0f));
CHECK_LIB(curandDestroyGenerator(gen_x));
/* Zero biases & betas, set gammas = 1.0, targets, and step = 1 */
CHECK_CU(cuMemsetD32(w->d_params[1], 0, F));
CHECK_CU(cuMemsetD32(w->d_params[3], 0, D));
CHECK_CU(cuMemsetD32(w->d_params[5], 0, C));
CHECK_CU(cuMemsetD32(w->d_params[7], 0, D));
CHECK_CU(cuMemsetD32(w->d_params[9], 0, D));
CHECK_CU(cuMemcpyHtoD(w->d_params[6], ones, sizeof(ones)));
CHECK_CU(cuMemcpyHtoD(w->d_params[8], ones, sizeof(ones)));
int targets[MICRO_BATCH];
for (int b = 0; b < MICRO_BATCH; b++) {
targets[b] = (b + g * 7) % NUM_CLASSES;
}
CHECK_CU(cuMemcpyHtoD(w->d_targets, targets, sizeof(targets)));
int init_step = 1;
CHECK_CU(cuMemcpyHtoD(w->d_step, &init_step, sizeof(init_step)));
}
free(ptx);
/* Run 8 synchronous N-GPU DDP training steps */
float gpu_losses[MAX_GPUS][NUM_STEPS];
float losses[NUM_STEPS];
memset(gpu_losses, 0, sizeof(gpu_losses));
memset(losses, 0, sizeof(losses));
for (int step = 0; step < NUM_STEPS; step++) {
/* Phase 1: Forward + Backward concurrently on all N GPUs */
for (int g = 0; g < num_gpus; g++) {
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
enqueue_fwd_bwd(&workers[g]);
}
float loss_sum = 0.0f;
for (int g = 0; g < num_gpus; g++) {
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
CHECK_CU(cuStreamSynchronize(workers[g].stream));
CHECK_CU(cuMemcpyDtoH(&gpu_losses[g][step], workers[g].d_loss, sizeof(float)));
loss_sum += gpu_losses[g][step];
}
losses[step] = loss_sum / (float)num_gpus;
/* Phase 2: Direct PCIe BAR1 P2P Ring AllReduce across all 10 parameter tensors */
run_p2p_ring_allreduce(workers, num_gpus, cuCtxSetCurrent, cuStreamSynchronize);
/* Phase 3: AdamW optimizer update on all N GPUs using synchronized gradients */
for (int g = 0; g < num_gpus; g++) {
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
enqueue_adamw_update(&workers[g]);
}
for (int g = 0; g < num_gpus; g++) {
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
CHECK_CU(cuStreamSynchronize(workers[g].stream));
}
}
/* Verify final FP32 master weights: finite and bit-for-bit identical across ALL N GPUs */
uint32_t digests[MAX_GPUS];
for (int g = 0; g < num_gpus; g++) digests[g] = 2166136261u;
int finite_ok = 1;
int weight_mismatches = 0;
size_t max_elems = D * F;
float *hbuf0 = must_malloc(max_elems * sizeof(float));
float *hbufg = must_malloc(max_elems * sizeof(float));
for (int p = 0; p < NUM_PARAMS; p++) {
size_t cnt = PARAM_COUNTS[p];
CHECK_CU(cuCtxSetCurrent(workers[0].ctx));
CHECK_CU(cuMemcpyDtoH(hbuf0, workers[0].d_params[p], cnt * sizeof(float)));
for (size_t i = 0; i < cnt; i++) {
if (!isfinite(hbuf0[i])) finite_ok = 0;
}
digests[0] = fnv1a_update_floats(digests[0], hbuf0, cnt);
for (int g = 1; g < num_gpus; g++) {
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
CHECK_CU(cuMemcpyDtoH(hbufg, workers[g].d_params[p], cnt * sizeof(float)));
for (size_t i = 0; i < cnt; i++) {
if (!isfinite(hbufg[i])) finite_ok = 0;
uint32_t b0 = 0, bg = 0;
memcpy(&b0, &hbuf0[i], sizeof(b0));
memcpy(&bg, &hbufg[i], sizeof(bg));
if (b0 != bg) weight_mismatches++;
}
digests[g] = fnv1a_update_floats(digests[g], hbufg, cnt);
}
}
free(hbuf0);
free(hbufg);
int losses_finite = 1;
int strictly_decreasing = 1;
for (int step = 0; step < NUM_STEPS; step++) {
if (!isfinite(losses[step])) losses_finite = 0;
for (int g = 0; g < num_gpus; g++) {
if (!isfinite(gpu_losses[g][step])) losses_finite = 0;
}
if (step > 0 && !(losses[step] < losses[step - 1])) {
strictly_decreasing = 0;
}
}
int all_digests_equal = 1;
for (int g = 1; g < num_gpus; g++) {
if (digests[g] != digests[0]) all_digests_equal = 0;
}
int all_weights_synced = (all_digests_equal && weight_mismatches == 0);
int passed = (p2p_ring_enabled && finite_ok && losses_finite &&
strictly_decreasing && all_weights_synced);
/* Emit clean JSON */
printf("{\"workload\":\"ddp_ngpu_fp16_fp32_transformer_ffn_training\","
"\"device_count\":%d,\"micro_batch\":%d,\"global_batch\":%d,"
"\"d_model\":%d,\"d_ff\":%d,\"num_classes\":%d,\"steps\":%d,"
"\"p2p_ring_enabled\":%s,\"losses\":[",
num_gpus, MICRO_BATCH, global_batch, D_MODEL, D_FF, NUM_CLASSES, NUM_STEPS,
p2p_ring_enabled ? "true" : "false");
for (int step = 0; step < NUM_STEPS; step++) {
printf("%s%.6f", step == 0 ? "" : ",", losses[step]);
}
printf("],\"per_gpu_losses\":[");
for (int g = 0; g < num_gpus; g++) {
printf("%s[", g == 0 ? "" : ",");
for (int step = 0; step < NUM_STEPS; step++) {
printf("%s%.6f", step == 0 ? "" : ",", gpu_losses[g][step]);
}
printf("]");
}
printf("],\"loss_step_0\":%.6f,\"loss_step_7\":%.6f,"
"\"strictly_decreasing\":%s,\"weights_finite\":%s,"
"\"per_gpu_weight_digests\":[",
losses[0], losses[NUM_STEPS - 1],
strictly_decreasing ? "true" : "false",
finite_ok ? "true" : "false");
for (int g = 0; g < num_gpus; g++) {
printf("%s\"0x%08x\"", g == 0 ? "" : ",", digests[g]);
}
printf("],\"weight_mismatches\":%d,\"all_weights_synced\":%s,\"passed\":%s}\n",
weight_mismatches,
all_weights_synced ? "true" : "false",
passed ? "true" : "false");
/* Clean teardown: disable peer access around the ring, free all resources, destroy contexts */
for (int g = 0; g < num_gpus; g++) {
int next = (g + 1) % num_gpus;
int prev = (g + num_gpus - 1) % num_gpus;
CHECK_CU(cuCtxSetCurrent(workers[g].ctx));
CHECK_CU(cuCtxDisablePeerAccess(workers[next].ctx));
if (prev != next) {
CHECK_CU(cuCtxDisablePeerAccess(workers[prev].ctx));
}
}
for (int g = 0; g < num_gpus; g++) {
GpuWorker *w = &workers[g];
CHECK_CU(cuCtxSetCurrent(w->ctx));
CHECK_LIB(cublasDestroy(w->bh));
CHECK_CU(cuStreamDestroy(w->stream));
CHECK_CU(cuModuleUnload(w->mod));
for (int p = 0; p < NUM_PARAMS; p++) {
CHECK_CU(cuMemFree(w->d_params[p]));
CHECK_CU(cuMemFree(w->d_grads[p]));
CHECK_CU(cuMemFree(w->d_grads_acc[p]));
CHECK_CU(cuMemFree(w->d_grads_avg[p]));
CHECK_CU(cuMemFree(w->d_m[p]));
CHECK_CU(cuMemFree(w->d_v[p]));
}
CUdeviceptr bufs[] = {
w->d_x, w->d_targets, w->d_step, w->d_sample_loss, w->d_loss,
w->d_w1_h, w->d_w2_h, w->d_w3_h,
w->d_x_ln1, w->d_x_ln1_h, w->d_mean1, w->d_rstd1,
w->d_h1_raw, w->d_h1_pre, w->d_h1, w->d_h1_h,
w->d_h2_raw, w->d_res,
w->d_x_ln2, w->d_x_ln2_h, w->d_mean2, w->d_rstd2,
w->d_logits, w->d_dlogits, w->d_dlogits_h,
w->d_dx_ln2, w->d_dres, w->d_dres_h,
w->d_dh1, w->d_dh1_pre, w->d_dh1_pre_h,
w->d_dx_ln1, w->d_dx
};
for (size_t i = 0; i < sizeof(bufs) / sizeof(bufs[0]); i++) {
CHECK_CU(cuMemFree(bufs[i]));
}
CHECK_CU(cuCtxDestroy(w->ctx));
}
return passed ? 0 : 1;
}