// Wt.load and Gemm.i8w (see cublas.bend). Uses Bend runtime internals (e.mem, blk_loc, gpu_dev). #include #include #include #include #if BEND_CUDA #define WT_MAX 4096 static struct { CUdeviceptr ptr; uint64_t bytes; int f32; } wt_tab[WT_MAX]; static uint32_t wt_count; typedef int (*WtCreate)(void**); typedef int (*WtSgemm)(void*, int, int, int, int, int, const float*, const float*, int, const float*, int, const float*, float*, int); typedef int (*WtGemmEx)(void*, int, int, int, int, int, const void*, const void*, int, int, const void*, int, int, const void*, void*, int, int, int, int); static struct { int state; void* handle; WtGemmEx gemm; WtSgemm sgemm; const char* why; } wt_lib; static void wt_ctx(void) { CUcontext ctx; if (cuDevicePrimaryCtxRetain(&ctx, gpu_dev) != CUDA_SUCCESS || cuCtxSetCurrent(ctx) != CUDA_SUCCESS) { fprintf(stderr, "Wt: no CUDA context\n"); exit(1); } } static void wt_open(void) { if (wt_lib.state != 0) return; wt_lib.state = -1; char path[512]; const char* home = getenv("CUDA_HOME"); void* h = NULL; if (home != NULL) { snprintf(path, sizeof path, "%s/lib64/libcublas.so", home); h = dlopen(path, RTLD_NOW | RTLD_GLOBAL); } if (h == NULL) h = dlopen("/usr/local/cuda/lib64/libcublas.so", RTLD_NOW | RTLD_GLOBAL); if (h == NULL) h = dlopen("libcublas.so", RTLD_NOW | RTLD_GLOBAL); if (h == NULL) { wt_lib.why = "libcublas.so not found"; return; } WtCreate create = (WtCreate)dlsym(h, "cublasCreate_v2"); wt_lib.gemm = (WtGemmEx)dlsym(h, "cublasGemmEx"); wt_lib.sgemm = (WtSgemm)dlsym(h, "cublasSgemm_v2"); if (create == NULL || wt_lib.gemm == NULL || wt_lib.sgemm == NULL) { wt_lib.why = "cuBLAS symbols missing"; return; } wt_ctx(); if (create(&wt_lib.handle) != 0) { wt_lib.why = "cublasCreate failed"; return; } wt_lib.state = 1; } // Loading: each 64 MB chunk is read by WT_THREADS threads at once (pread) into one of two pinned staging buffers, // widened there in parallel when the weights are bf16 or fp16, and copied to the GPU asynchronously, so reading the // next chunk overlaps copying this one. #define WT_CHUNK (64ull << 20) #define WT_THREADS 16 static struct { int ready; char* buf[2]; uint32_t* wide[2]; CUstream st; CUevent ev[2]; int busy[2]; int pending; } wt_io; static void wt_io_init(void) { if (wt_io.ready) return; for (int i = 0; i < 2; i++) { if (cuMemHostAlloc((void**)&wt_io.buf[i], WT_CHUNK, 0) != CUDA_SUCCESS || cuMemHostAlloc((void**)&wt_io.wide[i], 2 * WT_CHUNK, 0) != CUDA_SUCCESS || cuEventCreate(&wt_io.ev[i], CU_EVENT_DISABLE_TIMING) != CUDA_SUCCESS) { fprintf(stderr, "Wt.load: cannot allocate pinned staging buffers\n"); exit(1); } } if (cuStreamCreate(&wt_io.st, CU_STREAM_NON_BLOCKING) != CUDA_SUCCESS) { fprintf(stderr, "Wt.load: no stream\n"); exit(1); } wt_io.ready = 1; } // waits for the weight copies still in flight (before a GEMM reads the store, or a buffer is freed) static void wt_wait(void) { if (!wt_io.pending) return; if (cuStreamSynchronize(wt_io.st) != CUDA_SUCCESS) { fprintf(stderr, "Wt.load: copy failed\n"); exit(1); } wt_io.pending = 0; } typedef struct { int fd; uint64_t off; char* dst; uint64_t n; int mode; uint32_t* wide; int ok; } WtPart; // one thread's slice of a chunk: read it, then widen it (mode 1: bf16, 2: fp16) into the F32 staging buffer static void* wt_part(void* arg) { WtPart* p = (WtPart*)arg; uint64_t got = 0; while (got < p->n) { ssize_t r = pread(p->fd, p->dst + got, p->n - got, (off_t)(p->off + got)); if (r <= 0) { p->ok = 0; return NULL; } got += (uint64_t)r; } if (p->mode == 1) { for (uint64_t i = 0; i < p->n / 2; i++) p->wide[i] = (uint32_t)((uint16_t*)p->dst)[i] << 16; } else if (p->mode == 2) { for (uint64_t i = 0; i < p->n / 2; i++) { float v = (float)((_Float16*)p->dst)[i]; memcpy(&p->wide[i], &v, 4); } } p->ok = 1; return NULL; } static void* wt_cells(Env e, Term a, uint64_t need, const char* name) { if (term_tag(a) != TAG_BUF) { fprintf(stderr, "Gemm.i8w: %s is not a 32-bit array\n", name); exit(1); } if ((1ull << blk_cls(a)) < need) { fprintf(stderr, "Gemm.i8w: %s holds %llu cells, needs %llu\n", name, (unsigned long long)(1ull << blk_cls(a)), (unsigned long long)need); exit(1); } void* p = (void*)(e.mem + blk_loc(e.mem, a)); unsigned int managed = 0; if (cuPointerGetAttribute(&managed, CU_POINTER_ATTRIBUTE_IS_MANAGED, (CUdeviceptr)(uintptr_t)p) != CUDA_SUCCESS || !managed) { fprintf(stderr, "Gemm.i8w: %s is not in CUDA managed memory\n", name); exit(1); } return p; } #endif // mode 0: int8 as is; 1: bf16 -> F32; 2: fp16 -> F32 static Term wt_load_any(Env e, Term* f, int mode) { int bf16 = mode != 0; #if BEND_CUDA uint64_t len; char* path = io_cstr(e, f[0], &len); uint64_t off = ((uint64_t)(uint32_t)f[1] << 32) | (uint32_t)f[2]; uint64_t bytes = (uint32_t)f[3]; if (wt_count >= WT_MAX) { fprintf(stderr, "Wt.load: more than %d buffers\n", WT_MAX); exit(1); } wt_ctx(); wt_io_init(); int fd = open(path, O_RDONLY); if (fd < 0) { fprintf(stderr, "Wt.load: cannot open %s\n", path); exit(1); } uint64_t dbytes = bf16 ? bytes * 2 : bytes; if (bf16 && bytes % 2 != 0) { fprintf(stderr, "Wt.load_bf16: odd byte count\n"); exit(1); } CUdeviceptr d; if (cuMemAlloc(&d, dbytes) != CUDA_SUCCESS) { fprintf(stderr, "Wt.load: cannot allocate %llu bytes on the GPU\n", (unsigned long long)dbytes); exit(1); } int b = 0; for (uint64_t at = 0; at < bytes; at += WT_CHUNK, b ^= 1) { uint64_t n = bytes - at < WT_CHUNK ? bytes - at : WT_CHUNK; if (wt_io.busy[b] && cuEventSynchronize(wt_io.ev[b]) != CUDA_SUCCESS) { fprintf(stderr, "Wt.load: copy failed\n"); exit(1); } WtPart parts[WT_THREADS]; pthread_t th[WT_THREADS]; uint64_t slice = ((n / WT_THREADS) + 4095) & ~4095ull; int used = 0; for (uint64_t s0 = 0; s0 < n && used < WT_THREADS; s0 += slice, used++) { uint64_t m = n - s0 < slice ? n - s0 : slice; parts[used] = (WtPart){fd, off + at + s0, wt_io.buf[b] + s0, m, mode, wt_io.wide[b] + s0 / 2, 0}; if (pthread_create(&th[used], NULL, wt_part, &parts[used]) != 0) { fprintf(stderr, "Wt.load: no thread\n"); exit(1); } } for (int i = 0; i < used; i++) pthread_join(th[i], NULL); for (int i = 0; i < used; i++) if (!parts[i].ok) { fprintf(stderr, "Wt.load: short read of %s at %llu\n", path, (unsigned long long)parts[i].off); exit(1); } void* src = bf16 ? (void*)wt_io.wide[b] : (void*)wt_io.buf[b]; if (cuMemcpyHtoDAsync(d + (bf16 ? at * 2 : at), src, bf16 ? n * 2 : n, wt_io.st) != CUDA_SUCCESS || cuEventRecord(wt_io.ev[b], wt_io.st) != CUDA_SUCCESS) { fprintf(stderr, "Wt.load: copy failed\n"); exit(1); } wt_io.busy[b] = 1; } wt_io.pending = 1; // the copies finish in the background; wt_wait() before anything reads the weight store close(fd); free(path); wt_tab[wt_count].ptr = d; wt_tab[wt_count].bytes = dbytes; wt_tab[wt_count].f32 = bf16; return (Term)(wt_count++); #else fprintf(stderr, "Wt.load needs a CUDA build\n"); exit(1); #endif } Term wt_load_run(Env e, Term* f, IoWork* w) { return wt_load_any(e, f, 0); } Term wt_load_bf16_run(Env e, Term* f, IoWork* w) { return wt_load_any(e, f, 1); } Term wt_load_f16_run(Env e, Term* f, IoWork* w) { return wt_load_any(e, f, 2); } Term wt_free_run(Env e, Term* f, IoWork* w) { #if BEND_CUDA uint32_t id = (uint32_t)f[0]; if (id >= wt_count || wt_tab[id].ptr == 0) { fprintf(stderr, "Wt.free: no weight buffer %u\n", id); exit(1); } wt_ctx(); wt_wait(); cuMemFree(wt_tab[id].ptr); wt_tab[id].ptr = 0; wt_tab[id].bytes = 0; #endif return term_pak(CID(Unit), 0); } Term gemm_f32w_run(Env e, Term* f, IoWork* w) { #if BEND_CUDA uint32_t id = (uint32_t)f[1], n = (uint32_t)f[3], m = (uint32_t)f[4], k = (uint32_t)f[5]; if (id >= wt_count || wt_tab[id].ptr == 0 || !wt_tab[id].f32) { fprintf(stderr, "Gemm.f32w: no F32 weight buffer %u\n", id); exit(1); } if (wt_tab[id].bytes != (uint64_t)m * k * 4) { fprintf(stderr, "Gemm.f32w: buffer %u holds %llu bytes, %u x %u needs %llu\n", id, (unsigned long long)wt_tab[id].bytes, m, k, (unsigned long long)m * k * 4); exit(1); } wt_open(); wt_wait(); if (wt_lib.state != 1) { fprintf(stderr, "Gemm.f32w: %s\n", wt_lib.why); exit(1); } float* a = wt_cells(e, f[0], (uint64_t)n * k, "A"); float* c = wt_cells(e, f[2], (uint64_t)n * m, "C"); float one = 1.0f, zero = 0.0f; int st = wt_lib.sgemm(wt_lib.handle, 1, 0, (int)m, (int)n, (int)k, &one, (const float*)(uintptr_t)wt_tab[id].ptr, (int)k, a, (int)k, &zero, c, (int)m); if (st != 0) { fprintf(stderr, "Gemm.f32w: cublasSgemm status %d\n", st); exit(1); } if (cuCtxSynchronize() != CUDA_SUCCESS) { fprintf(stderr, "Gemm.f32w: synchronize failed\n"); exit(1); } return io_tup(e, f[0], f[2]); #else fprintf(stderr, "Gemm.f32w needs a CUDA build\n"); exit(1); #endif } Term gemm_i8w_run(Env e, Term* f, IoWork* w) { #if BEND_CUDA uint32_t id = (uint32_t)f[1], n = (uint32_t)f[3], m = (uint32_t)f[4], k = (uint32_t)f[5]; if (id >= wt_count || wt_tab[id].ptr == 0 || wt_tab[id].f32) { fprintf(stderr, "Gemm.i8w: no int8 weight buffer %u\n", id); exit(1); } if (wt_tab[id].bytes != (uint64_t)m * k) { fprintf(stderr, "Gemm.i8w: buffer %u holds %llu bytes, %u x %u needs %llu\n", id, (unsigned long long)wt_tab[id].bytes, m, k, (unsigned long long)m * k); exit(1); } if (k % 4 != 0) { fprintf(stderr, "Gemm.i8w: k = %u is not a multiple of 4\n", k); exit(1); } wt_open(); wt_wait(); if (wt_lib.state != 1) { fprintf(stderr, "Gemm.i8w: %s\n", wt_lib.why); exit(1); } void* a = wt_cells(e, f[0], (uint64_t)n * k / 4, "A"); void* c = wt_cells(e, f[2], (uint64_t)n * m, "C"); int one = 1, zero = 0; int st = wt_lib.gemm(wt_lib.handle, 1, 0, (int)m, (int)n, (int)k, &one, (void*)(uintptr_t)wt_tab[id].ptr, 3, (int)k, a, 3, (int)k, &zero, c, 10, (int)m, 72, -1); if (st != 0) { fprintf(stderr, "Gemm.i8w: cublasGemmEx status %d\n", st); exit(1); } if (cuCtxSynchronize() != CUDA_SUCCESS) { fprintf(stderr, "Gemm.i8w: synchronize failed\n"); exit(1); } return io_tup(e, f[0], f[2]); #else fprintf(stderr, "Gemm.i8w needs a CUDA build\n"); exit(1); #endif } static void __attribute__((constructor)) wt_use(void) { #ifdef CID(Wt.load) io_eff(CID(Wt.load), wt_load_run); #endif #ifdef CID(Gemm.i8w) io_eff(CID(Gemm.i8w), gemm_i8w_run); #endif #ifdef CID(Wt.load_bf16) io_eff(CID(Wt.load_bf16), wt_load_bf16_run); #endif #ifdef CID(Wt.free) io_eff(CID(Wt.free), wt_free_run); #endif #ifdef CID(Wt.load_f16) io_eff(CID(Wt.load_f16), wt_load_f16_run); #endif #ifdef CID(Gemm.f32w) io_eff(CID(Gemm.f32w), gemm_f32w_run); #endif }